Skip to content

Commit 2eb30cb

Browse files
Nic Hartleyjiegillet
Nic Hartley
authored andcommitted
Add Monte Carlo implementation in Factor (#434)
* added Monte Carlo * added USING statements so this can be run with no errors * added pi calculation * removed timing stuff * add error * aagh forgot again
1 parent b5c6600 commit 2eb30cb

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
USING: locals random math.ranges math.functions ;
2+
3+
:: monte-carlo ( n in-shape?: ( x y -- ? ) -- % )
4+
n <iota> [ drop random-unit random-unit in-shape? call ] count n /
5+
; inline
6+
7+
! Use the monte-carlo approximation to calculate pi
8+
: monte-carlo-pi ( n -- pi-approx )
9+
[ ! in-circle check
10+
[ 2 ^ ] bi@ + ! get the distance from the center
11+
1 < ! see if it's less than the radius
12+
]
13+
monte-carlo 4 * >float
14+
;
15+
16+
USING: math.constants ;
17+
10000000 monte-carlo-pi ! Approximate pi
18+
dup . ! Print the approximation
19+
pi - pi / 100 * >float abs . ! And the error margin
20+
21+

contents/monte_carlo_integration/monte_carlo_integration.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ each point is tested to see whether it's in the circle or not:
7171
[import:1-4, lang:"ruby"](code/ruby/monte_carlo.rb)
7272
{% sample lang="f90" %}
7373
[import:1-8, lang:"fortran"](code/fortran/monte_carlo.f90)
74+
{% sample lang="factor" %}
75+
[import:9-12 lang:"factor"](code/factor/monte_carlo.factor)
7476
{% sample lang="emojic" %}
7577
[import:23-27, lang:"emojicode"](code/emojicode/monte_carlo.emojic)
7678
{% sample lang="php" %}
@@ -155,6 +157,8 @@ Feel free to submit your version via pull request, and thanks for reading!
155157
[import, lang:"ruby"](code/ruby/monte_carlo.rb)
156158
{% sample lang="f90" %}
157159
[import, lang:"fortran"](code/fortran/monte_carlo.f90)
160+
{% sample lang="factor" %}
161+
[import, lang:"factor"](code/factor/monte_carlo.factor)
158162
{% sample lang="emojic" %}
159163
[import, lang:"emojicode"](code/emojicode/monte_carlo.emojic)
160164
{% sample lang="php" %}

0 commit comments

Comments
 (0)