Monte Carlo methods: Difference between revisions

Content added Content deleted
(→‎{{header|Picat}}: Split into subsections, added {{out}}, code tag for predicates etc)
m (syntax highlighting fixup automation)
Line 29: Line 29:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F monte_carlo_pi(n)
<syntaxhighlight lang="11l">F monte_carlo_pi(n)
V inside = 0
V inside = 0
L 1..n
L 1..n
Line 38: Line 38:
R 4.0 * inside / n
R 4.0 * inside / n


print(monte_carlo_pi(1000000))</lang>
print(monte_carlo_pi(1000000))</syntaxhighlight>


{{out}}
{{out}}
Line 46: Line 46:


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Monte Carlo methods 08/03/2017
<syntaxhighlight lang="360asm">* Monte Carlo methods 08/03/2017
MONTECAR CSECT
MONTECAR CSECT
USING MONTECAR,R13 base register
USING MONTECAR,R13 base register
Line 127: Line 127:
WP DS PL16 packed decimal 16
WP DS PL16 packed decimal 16
YREGS
YREGS
END MONTECAR</lang>
END MONTECAR</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 139: Line 139:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
{{libheader|Action! Real Math}}
<lang Action!>INCLUDE "H6:REALMATH.ACT"
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"


DEFINE PTR="CARD"
DEFINE PTR="CARD"
Line 219: Line 219:
Test(1000)
Test(1000)
Test(10000)
Test(10000)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Monte_Carlo_methods.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Monte_Carlo_methods.png Screenshot from Atari 8-bit computer]
Line 231: Line 231:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;


Line 253: Line 253:
Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo;</lang>
end Test_Monte_Carlo;</syntaxhighlight>
The implementation uses built-in uniformly distributed on [0,1] random numbers.
The implementation uses built-in uniformly distributed on [0,1] random numbers.
Note that the accuracy of the result depends on the quality of the pseudo random generator: its circle length and correlation to the function being simulated.
Note that the accuracy of the result depends on the quality of the pseudo random generator: its circle length and correlation to the function being simulated.
Line 271: Line 271:


{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>PROC pi = (INT throws)REAL:
<syntaxhighlight lang="algol68">PROC pi = (INT throws)REAL:
BEGIN
BEGIN
INT inside := 0;
INT inside := 0;
Line 286: Line 286:
print ((" 1 000 000:",pi ( 1 000 000),new line));
print ((" 1 000 000:",pi ( 1 000 000),new line));
print ((" 10 000 000:",pi ( 10 000 000),new line));
print ((" 10 000 000:",pi ( 10 000 000),new line));
print (("100 000 000:",pi (100 000 000),new line))</lang>
print (("100 000 000:",pi (100 000 000),new line))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 298: Line 298:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>Pi: function [throws][
<syntaxhighlight lang="rebol">Pi: function [throws][
inside: new 0.0
inside: new 0.0
do.times: throws [
do.times: throws [
Line 307: Line 307:
loop [100 1000 10000 100000 1000000] 'n ->
loop [100 1000 10000 100000 1000000] 'n ->
print [pad to :string n 8 "=>" Pi n]</lang>
print [pad to :string n 8 "=>" Pi n]</syntaxhighlight>


{{out}}
{{out}}
Line 320: Line 320:
{{AutoHotkey case}}
{{AutoHotkey case}}
Source: [http://www.autohotkey.com/forum/topic44657.html AutoHotkey forum] by Laszlo
Source: [http://www.autohotkey.com/forum/topic44657.html AutoHotkey forum] by Laszlo
<lang autohotkey>
<syntaxhighlight lang="autohotkey">
MsgBox % MontePi(10000) ; 3.154400
MsgBox % MontePi(10000) ; 3.154400
MsgBox % MontePi(100000) ; 3.142040
MsgBox % MontePi(100000) ; 3.142040
Line 333: Line 333:
Return 4*p/n
Return 4*p/n
}
}
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# --- with command line argument "throws" ---
# --- with command line argument "throws" ---


Line 348: Line 348:
Pi = 3.14333
Pi = 3.14333


</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
{{trans|Java}}
{{trans|Java}}
<lang qbasic>DECLARE FUNCTION getPi! (throws!)
<syntaxhighlight lang="qbasic">DECLARE FUNCTION getPi! (throws!)
CLS
CLS
PRINT getPi(10000)
PRINT getPi(10000)
Line 374: Line 374:
NEXT i
NEXT i
getPi = 4! * inCircle / throws
getPi = 4! * inCircle / throws
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 385: Line 385:
=={{header|BASIC256}}==
=={{header|BASIC256}}==
{{works with|basic256|1.1.4.0}}
{{works with|basic256|1.1.4.0}}
<lang basic>
<syntaxhighlight lang="basic">
# Monte Carlo Simulator
# Monte Carlo Simulator
# Determine value of pi
# Determine value of pi
Line 407: Line 407:
next i
next i


print float(4*in_c/tosses)</lang>
print float(4*in_c/tosses)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 418: Line 418:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> PRINT FNmontecarlo(1000)
<syntaxhighlight lang="bbcbasic"> PRINT FNmontecarlo(1000)
PRINT FNmontecarlo(10000)
PRINT FNmontecarlo(10000)
PRINT FNmontecarlo(100000)
PRINT FNmontecarlo(100000)
Line 430: Line 430:
IF RND(1)^2 + RND(1)^2 < 1 n% += 1
IF RND(1)^2 + RND(1)^2 < 1 n% += 1
NEXT
NEXT
= 4 * n% / t%</lang>
= 4 * n% / t%</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 441: Line 441:


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <math.h>
#include <math.h>
Line 476: Line 476:
printf("Pi is %f\n", pi(3e-4)); /* set to 1e-4 for some fun */
printf("Pi is %f\n", pi(3e-4)); /* set to 1e-4 for some fun */
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


class Program {
class Program {
Line 502: Line 502:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 514: Line 514:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<syntaxhighlight lang="cpp">
#include<iostream>
#include<iostream>
#include<math.h>
#include<math.h>
Line 536: Line 536:
cout<<""<<4*double(hit)/double(imax)<<endl; } // Print out Pi number
cout<<""<<4*double(hit)/double(imax)<<endl; } // Print out Pi number
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(defn calc-pi [iterations]
<syntaxhighlight lang="lisp">(defn calc-pi [iterations]
(loop [x (rand) y (rand) in 0 total 1]
(loop [x (rand) y (rand) in 0 total 1]
(if (< total iterations)
(if (< total iterations)
Line 545: Line 545:
(double (* (/ in total) 4)))))
(double (* (/ in total) 4)))))


(doseq [x (take 5 (iterate #(* 10 %) 10))] (println (str (format "% 8d" x) ": " (calc-pi x))))</lang>
(doseq [x (take 5 (iterate #(* 10 %) 10))] (println (str (format "% 8d" x) ": " (calc-pi x))))</syntaxhighlight>


{{out}}
{{out}}
Line 556: Line 556:
</pre>
</pre>


<lang lisp>(defn experiment
<syntaxhighlight lang="lisp">(defn experiment
[]
[]
(if (<= (+ (Math/pow (rand) 2) (Math/pow (rand) 2)) 1) 1 0))
(if (<= (+ (Math/pow (rand) 2) (Math/pow (rand) 2)) 1) 1 0))
Line 565: Line 565:


(pi-estimate 10000)
(pi-estimate 10000)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 573: Line 573:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun approximate-pi (n)
<syntaxhighlight lang="lisp">(defun approximate-pi (n)
(/ (loop repeat n count (<= (abs (complex (random 1.0) (random 1.0))) 1.0)) n 0.25))
(/ (loop repeat n count (<= (abs (complex (random 1.0) (random 1.0))) 1.0)) n 0.25))


(dolist (n (loop repeat 5 for n = 1000 then (* n 10) collect n))
(dolist (n (loop repeat 5 for n = 1000 then (* n 10) collect n))
(format t "~%~8d -> ~f" n (approximate-pi n)))</lang>
(format t "~%~8d -> ~f" n (approximate-pi n)))</syntaxhighlight>


{{out}}
{{out}}
Line 590: Line 590:
=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>def approx_pi(throws)
<syntaxhighlight lang="ruby">def approx_pi(throws)
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
4.0 * times_inside / throws
4.0 * times_inside / throws
Line 597: Line 597:
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
puts "%8d samples: PI = %s" % [n, approx_pi(n)]
puts "%8d samples: PI = %s" % [n, approx_pi(n)]
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre> 1000 samples: PI = 3.1
<pre> 1000 samples: PI = 3.1
Line 607: Line 607:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.random, std.math;
<syntaxhighlight lang="d">import std.stdio, std.random, std.math;


double pi(in uint nthrows) /*nothrow*/ @safe /*@nogc*/ {
double pi(in uint nthrows) /*nothrow*/ @safe /*@nogc*/ {
Line 620: Line 620:
foreach (immutable p; 1 .. 8)
foreach (immutable p; 1 .. 8)
writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p));
writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 10: 3.200000
<pre> 10: 3.200000
Line 641: Line 641:


===More Functional Style===
===More Functional Style===
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.random, std.math, std.algorithm, std.range;
import std.stdio, std.random, std.math, std.algorithm, std.range;


Line 649: Line 649:
foreach (immutable p; 1 .. 8)
foreach (immutable p; 1 .. 8)
writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p));
writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 10: 3.200000
<pre> 10: 3.200000
Line 663: Line 663:
From example at [https://www.dartlang.org/ Dart Official Website]
From example at [https://www.dartlang.org/ Dart Official Website]


<lang dart>
<syntaxhighlight lang="dart">
import 'dart:async';
import 'dart:async';
import 'dart:html';
import 'dart:html';
Line 714: Line 714:
bool get isInsideUnitCircle => x * x + y * y <= 1;
bool get isInsideUnitCircle => x * x + y * y <= 1;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
The script give in reality an output formatted in HTML
The script give in reality an output formatted in HTML
Line 723: Line 723:
This computes a single quadrant of the described square and circle; the effect should be the same since the other three are symmetric.
This computes a single quadrant of the described square and circle; the effect should be the same since the other three are symmetric.


<lang e>def pi(n) {
<syntaxhighlight lang="e">def pi(n) {
var inside := 0
var inside := 0
for _ ? (entropy.nextFloat() ** 2 + entropy.nextFloat() ** 2 < 1) in 1..n {
for _ ? (entropy.nextFloat() ** 2 + entropy.nextFloat() ** 2 < 1) in 1..n {
Line 729: Line 729:
}
}
return inside * 4 / n
return inside * 4 / n
}</lang>
}</syntaxhighlight>


Some sample runs:
Some sample runs:
Line 752: Line 752:


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<lang>func mc n . .
<syntaxhighlight lang="text">func mc n . .
for i range n
for i range n
x = randomf
x = randomf
Line 766: Line 766:
call mc 100000
call mc 100000
call mc 1000000
call mc 1000000
call mc 10000000</lang>
call mc 10000000</syntaxhighlight>
Output:
Output:
3.1292
3.1292
Line 774: Line 774:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule MonteCarlo do
<syntaxhighlight lang="elixir">defmodule MonteCarlo do
def pi(n) do
def pi(n) do
count = Enum.count(1..n, fn _ ->
count = Enum.count(1..n, fn _ ->
Line 787: Line 787:
Enum.each([1000, 10000, 100000, 1000000, 10000000], fn n ->
Enum.each([1000, 10000, 100000, 1000000, 10000000], fn n ->
:io.format "~8w samples: PI = ~f~n", [n, MonteCarlo.pi(n)]
:io.format "~8w samples: PI = ~f~n", [n, MonteCarlo.pi(n)]
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 800: Line 800:
=={{header|Erlang}}==
=={{header|Erlang}}==
===With inline test===
===With inline test===
<syntaxhighlight lang="erlang">
<lang ERLANG>
-module(monte).
-module(monte).
-export([main/1]).
-export([main/1]).
Line 818: Line 818:


main(N) -> io:format("PI: ~w~n", [ monte(N) ]).
main(N) -> io:format("PI: ~w~n", [ monte(N) ]).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 830: Line 830:
</pre>
</pre>
===With test in a function===
===With test in a function===
<syntaxhighlight lang="erlang">
<lang ERLANG>
-module(monte2).
-module(monte2).
-export([main/1]).
-export([main/1]).
Line 851: Line 851:


main(N) -> io:format("PI: ~w~n", [ monte(N) ]).
main(N) -> io:format("PI: ~w~n", [ monte(N) ]).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Xcoord
<pre>Xcoord
Line 865: Line 865:


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM RANDOM_PI
PROGRAM RANDOM_PI


Line 889: Line 889:
MONTECARLO(1000000->RES) PRINT(RES)
MONTECARLO(1000000->RES) PRINT(RES)
MONTECARLO(10000000->RES) PRINT(RES)
MONTECARLO(10000000->RES) PRINT(RES)
END PROGRAM</lang>
END PROGRAM</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 900: Line 900:


=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function map MonteCarloPI (n,plot=false) ...
>function map MonteCarloPI (n,plot=false) ...
$ X:=random(1,n);
$ X:=random(1,n);
Line 915: Line 915:
3.14159265359
3.14159265359
>MonteCarloPI(10000,true):
>MonteCarloPI(10000,true):
</syntaxhighlight>
</lang>


[[File:Test.png]]
[[File:Test.png]]
Line 922: Line 922:
There is some support and test expressions.
There is some support and test expressions.


<lang fsharp>
<syntaxhighlight lang="fsharp">
let print x = printfn "%A" x
let print x = printfn "%A" x


Line 942: Line 942:
MonteCarloPiGreco 10000 |> print
MonteCarloPiGreco 10000 |> print
MonteCarloPiGreco 100000 |> print
MonteCarloPiGreco 100000 |> print
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 953: Line 953:
Since Factor lets the user choose the range of the random generator, we use 2^32.
Since Factor lets the user choose the range of the random generator, we use 2^32.


<lang factor>USING: kernel math math.functions random sequences ;
<syntaxhighlight lang="factor">USING: kernel math math.functions random sequences ;


: limit ( -- n ) 2 32 ^ ; inline
: limit ( -- n ) 2 32 ^ ; inline
: in-circle ( x y -- ? ) limit [ sq ] tri@ [ + ] [ <= ] bi* ;
: in-circle ( x y -- ? ) limit [ sq ] tri@ [ + ] [ <= ] bi* ;
: rand ( -- r ) limit random ;
: rand ( -- r ) limit random ;
: pi ( n -- pi ) [ [ drop rand rand in-circle ] count ] keep / 4 * >float ;</lang>
: pi ( n -- pi ) [ [ drop rand rand in-circle ] count ] keep / 4 * >float ;</syntaxhighlight>


Example use:
Example use:


<lang factor>10000 pi .
<syntaxhighlight lang="factor">10000 pi .
3.1412</lang>
3.1412</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class MontyCarlo
class MontyCarlo
{
{
Line 991: Line 991:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,024: Line 1,024:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>MODULE Simulation
<syntaxhighlight lang="fortran">MODULE Simulation
IMPLICIT NONE
IMPLICIT NONE
Line 1,058: Line 1,058:
END DO
END DO
END PROGRAM MONTE_CARLO</lang>
END PROGRAM MONTE_CARLO</syntaxhighlight>


{{out}}
{{out}}
Line 1,069: Line 1,069:
</pre>
</pre>
{{works with|Fortran|2008 and later}}
{{works with|Fortran|2008 and later}}
<lang fortran>
<syntaxhighlight lang="fortran">
program mc
program mc
integer :: n,i
integer :: n,i
Line 1,086: Line 1,086:
pi = 4.d0 * dble( count( hypot(x(1,:),x(2,:)) <= 1.d0 ) ) / n
pi = 4.d0 * dble( count( hypot(x(1,:),x(2,:)) <= 1.d0 ) ) / n
end function
end function
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' version 23-10-2016
<syntaxhighlight lang="freebasic">' version 23-10-2016
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,121: Line 1,121:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre> Mumber of throws Ratio (Pi) Error
<pre> Mumber of throws Ratio (Pi) Error
Line 1,139: Line 1,139:
Since Futhark is a pure language, random numbers are implemented using Sobol sequences.
Since Futhark is a pure language, random numbers are implemented using Sobol sequences.


<syntaxhighlight lang="futhark">
<lang Futhark>
import "futlib/math"
import "futlib/math"


Line 1,188: Line 1,188:
let inside = reduce (+) 0 bs
let inside = reduce (+) 0 bs
in 4.0f32*f32(inside)/f32(n)
in 4.0f32*f32(inside)/f32(n)
</syntaxhighlight>
</lang>


=={{header|Go}}==
=={{header|Go}}==
'''Using standard library math/rand:'''
'''Using standard library math/rand:'''
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,224: Line 1,224:
fmt.Println(getPi(10000000))
fmt.Println(getPi(10000000))
fmt.Println(getPi(100000000))
fmt.Println(getPi(100000000))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,236: Line 1,236:


For very careful Monte Carlo studies, you might consider the subrepository rand library. The random number generator there has some advantages such as better known statistical properties and better use of memory.
For very careful Monte Carlo studies, you might consider the subrepository rand library. The random number generator there has some advantages such as better known statistical properties and better use of memory.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,269: Line 1,269:
fmt.Println(getPi(10000000))
fmt.Println(getPi(10000000))
fmt.Println(getPi(100000000))
fmt.Println(getPi(100000000))
}</lang>
}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Monad
<syntaxhighlight lang="haskell">import Control.Monad
import System.Random
import System.Random


Line 1,284: Line 1,284:
let dist :: Double
let dist :: Double
dist = sqrt (rand_x * rand_x + rand_y * rand_y)
dist = sqrt (rand_x * rand_x + rand_y * rand_y)
return (if dist < 1 then 1 else 0)</lang>
return (if dist < 1 then 1 else 0)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Example:
<pre>Example:
Line 1,296: Line 1,296:
Or, using foldM, and dropping sqrt:
Or, using foldM, and dropping sqrt:


<lang haskell>import Control.Monad (foldM, (>=>))
<syntaxhighlight lang="haskell">import Control.Monad (foldM, (>=>))
import System.Random (randomRIO)
import System.Random (randomRIO)
import Data.Functor ((<&>))
import Data.Functor ((<&>))
Line 1,318: Line 1,318:
mapM_
mapM_
(monteCarloPi >=> print)
(monteCarloPi >=> print)
[1000, 10000, 100000, 1000000]</lang>
[1000, 10000, 100000, 1000000]</syntaxhighlight>
{{Out}}
{{Out}}
For example:
For example:
Line 1,327: Line 1,327:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>FUNCTION Pi(samples)
<syntaxhighlight lang="hicest">FUNCTION Pi(samples)
inside = 0
inside = 0
DO i = 1, samples
DO i = 1, samples
Line 1,338: Line 1,338:
WRITE(ClipBoard) Pi(1E5) ! 3.14204
WRITE(ClipBoard) Pi(1E5) ! 3.14204
WRITE(ClipBoard) Pi(1E6) ! 3.141672
WRITE(ClipBoard) Pi(1E6) ! 3.141672
WRITE(ClipBoard) Pi(1E7) ! 3.1412856</lang>
WRITE(ClipBoard) Pi(1E7) ! 3.1412856</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
every t := 10 ^ ( 5 to 9 ) do
every t := 10 ^ ( 5 to 9 ) do
printf("Rounds=%d Pi ~ %r\n",t,getPi(t))
printf("Rounds=%d Pi ~ %r\n",t,getPi(t))
Line 1,354: Line 1,354:
incircle +:= 1
incircle +:= 1
return 4 * incircle / rounds
return 4 * incircle / rounds
end</lang>
end</syntaxhighlight>


{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
Line 1,368: Line 1,368:
=={{header|J}}==
=={{header|J}}==
'''Explicit Solution:'''
'''Explicit Solution:'''
<lang j>piMC=: monad define "0
<syntaxhighlight lang="j">piMC=: monad define "0
4* y%~ +/ 1>: %: +/ *: <: +: (2,y) ?@$ 0
4* y%~ +/ 1>: %: +/ *: <: +: (2,y) ?@$ 0
)</lang>
)</syntaxhighlight>


'''Tacit Solution:'''
'''Tacit Solution:'''
<lang j>piMCt=: (0.25&* %~ +/@(1 >: [: +/&.:*: _1 2 p. 0 ?@$~ 2&,))"0</lang>
<syntaxhighlight lang="j">piMCt=: (0.25&* %~ +/@(1 >: [: +/&.:*: _1 2 p. 0 ?@$~ 2&,))"0</syntaxhighlight>


'''Examples:'''
'''Examples:'''
<lang j> piMC 1e6
<syntaxhighlight lang="j"> piMC 1e6
3.1426
3.1426
piMC 10^i.7
piMC 10^i.7
4 2.8 3.24 3.168 3.1432 3.14256 3.14014</lang>
4 2.8 3.24 3.168 3.1432 3.14256 3.14014</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class MC {
<syntaxhighlight lang="java">public class MC {
public static void main(String[] args) {
public static void main(String[] args) {
System.out.println(getPi(10000));
System.out.println(getPi(10000));
Line 1,407: Line 1,407:
return 4.0 * inCircle / numThrows;
return 4.0 * inCircle / numThrows;
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
3.1396
3.1396
Line 1,415: Line 1,415:
3.14168604
3.14168604
{{works with|Java|8+}}
{{works with|Java|8+}}
<lang java>package montecarlo;
<syntaxhighlight lang="java">package montecarlo;


import java.util.stream.IntStream;
import java.util.stream.IntStream;
Line 1,458: Line 1,458:
return (4.0 * inCircle) / numThrows;
return (4.0 * inCircle) / numThrows;
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
3.1556
3.1556
Line 1,468: Line 1,468:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
<lang JavaScript>function mcpi(n) {
<syntaxhighlight lang="javascript">function mcpi(n) {
var x, y, m = 0;
var x, y, m = 0;


Line 1,487: Line 1,487:
console.log(mcpi(100000));
console.log(mcpi(100000));
console.log(mcpi(1000000));
console.log(mcpi(1000000));
console.log(mcpi(10000000));</lang>
console.log(mcpi(10000000));</syntaxhighlight>
<pre>3.168
<pre>3.168
3.1396
3.1396
Line 1,496: Line 1,496:


===ES6===
===ES6===
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 1,534: Line 1,534:
);
);
});
});
})();</lang>
})();</syntaxhighlight>
{{Out}} For example:
{{Out}} For example:
<pre>1000 samples: 3.064
<pre>1000 samples: 3.064
Line 1,549: Line 1,549:
jq does not have a built-in PRNG so we will use /dev/urandom
jq does not have a built-in PRNG so we will use /dev/urandom
as a source of entropy by invoking jq as follows:
as a source of entropy by invoking jq as follows:
<lang sh># In case gojq is used, trim leading 0s:
<syntaxhighlight lang="sh"># In case gojq is used, trim leading 0s:
function prng {
function prng {
cat /dev/urandom | tr -cd '0-9' | fold -w 10 | sed 's/^0*\(.*\)*\(.\)*$/\1\2/'
cat /dev/urandom | tr -cd '0-9' | fold -w 10 | sed 's/^0*\(.*\)*\(.\)*$/\1\2/'
}
}


prng | jq -nMr -f program.jq</lang>
prng | jq -nMr -f program.jq</syntaxhighlight>


'''program.jq'''
'''program.jq'''
<lang jq>def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
<syntaxhighlight lang="jq">def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;


def percent: "\(100000 * . | round / 1000)%";
def percent: "\(100000 * . | round / 1000)%";
Line 1,580: Line 1,580:
| ($p | mcPi) as $mcpi
| ($p | mcPi) as $mcpi
| ((($pi - $mcpi)|length) / $pi) as $error
| ((($pi - $mcpi)|length) / $pi) as $error
| "\($p|lpad(10)) \($mcpi|lpad(10)) \($error|percent|lpad(6))" )</lang>
| "\($p|lpad(10)) \($mcpi|lpad(10)) \($error|percent|lpad(6))" )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,595: Line 1,595:
=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript ES5 entry, with PRNG seeded during unit testing for reproducibility.
From Javascript ES5 entry, with PRNG seeded during unit testing for reproducibility.
<lang javascript>/* Monte Carlo methods, in Jsish */
<syntaxhighlight lang="javascript">/* Monte Carlo methods, in Jsish */
function mcpi(n) {
function mcpi(n) {
var x, y, m = 0;
var x, y, m = 0;
Line 1,626: Line 1,626:
mcpi(1000000) ==> 3.142124
mcpi(1000000) ==> 3.142124
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 1,633: Line 1,633:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>using Printf
<syntaxhighlight lang="julia">using Printf


function monteπ(n)
function monteπ(n)
Line 1,643: Line 1,643:
p = monteπ(n)
p = monteπ(n)
println("$(lpad(n, 9)): π ≈ $(lpad(p, 10)), pct.err = ", @sprintf("%2.5f%%", abs(p - π) / π))
println("$(lpad(n, 9)): π ≈ $(lpad(p, 10)), pct.err = ", @sprintf("%2.5f%%", abs(p - π) / π))
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,654: Line 1,654:


=={{header|K}}==
=={{header|K}}==
<lang K> sim:{4*(+/{~1<+/(2_draw 0)^2}'!x)%x}
<syntaxhighlight lang="k"> sim:{4*(+/{~1<+/(2_draw 0)^2}'!x)%x}


sim 10000
sim 10000
Line 1,660: Line 1,660:


sim'10^!8
sim'10^!8
4 2.8 3.4 3.072 3.1212 3.14104 3.14366 3.1413</lang>
4 2.8 3.4 3.072 3.1212 3.14104 3.14366 3.1413</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.0
<syntaxhighlight lang="scala">// version 1.1.0


fun mcPi(n: Int): Double {
fun mcPi(n: Int): Double {
Line 1,685: Line 1,685:
n *= 10
n *= 10
}
}
}</lang>
}</syntaxhighlight>
Sample output:
Sample output:
{{out}}
{{out}}
Line 1,700: Line 1,700:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
for pow = 2 to 6
for pow = 2 to 6
n = 10^pow
n = 10^pow
Line 1,717: Line 1,717:
end function
end function
</lang>
</syntaxhighlight>


{{out}}
{{out}}
Line 1,730: Line 1,730:
=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==


<lang locobasic>10 mode 1:randomize time:defint a-z
<syntaxhighlight lang="locobasic">10 mode 1:randomize time:defint a-z
20 input "How many samples";n
20 input "How many samples";n
30 u=n/100+1
30 u=n/100+1
Line 1,745: Line 1,745:
140 print "Computed value of pi:"pi2!
140 print "Computed value of pi:"pi2!
150 print "Difference to real value of pi: ";
150 print "Difference to real value of pi: ";
160 print using "+#.##%"; (pi2!-pi)/pi*100</lang>
160 print using "+#.##%"; (pi2!-pi)/pi*100</syntaxhighlight>


[[File:Monte Carlo, 200 points, Locomotive BASIC.png]]
[[File:Monte Carlo, 200 points, Locomotive BASIC.png]]
Line 1,751: Line 1,751:


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>
<syntaxhighlight lang="logo">
to square :n
to square :n
output :n * :n
output :n * :n
Line 1,768: Line 1,768:
show sim 100000 10000 ; 3.145
show sim 100000 10000 ; 3.145
show sim 1000000 10000 ; 3.140828
show sim 1000000 10000 ; 3.140828
</syntaxhighlight>
</lang>


=={{header|LSL}}==
=={{header|LSL}}==
To test it yourself; rez a box on the ground, and add the following as a New Script.
To test it yourself; rez a box on the ground, and add the following as a New Script.
(Be prepared to wait... LSL can be slow, but the Servers are typically running thousands of scripts in parallel so what do you expect?)
(Be prepared to wait... LSL can be slow, but the Servers are typically running thousands of scripts in parallel so what do you expect?)
<lang LSL>integer iMIN_SAMPLE_POWER = 0;
<syntaxhighlight lang="lsl">integer iMIN_SAMPLE_POWER = 0;
integer iMAX_SAMPLE_POWER = 6;
integer iMAX_SAMPLE_POWER = 6;
default {
default {
Line 1,794: Line 1,794:
llOwnerSay("Done.");
llOwnerSay("Done.");
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Estimating Pi (3.141593)
<pre>Estimating Pi (3.141593)
Line 1,807: Line 1,807:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function MonteCarlo ( n_throws )
<syntaxhighlight lang="lua">function MonteCarlo ( n_throws )
math.randomseed( os.time() )
math.randomseed( os.time() )


Line 1,823: Line 1,823:
print( MonteCarlo( 100000 ) )
print( MonteCarlo( 100000 ) )
print( MonteCarlo( 1000000 ) )
print( MonteCarlo( 1000000 ) )
print( MonteCarlo( 10000000 ) )</lang>
print( MonteCarlo( 10000000 ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>3.1436
<pre>3.1436
Line 1,832: Line 1,832:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
We define a function with variable sample size:
We define a function with variable sample size:
<lang Mathematica>MonteCarloPi[samplesize_Integer] := N[4Mean[If[# > 1, 0, 1] & /@ Norm /@ RandomReal[1, {samplesize, 2}]]]</lang>
<syntaxhighlight lang="mathematica">MonteCarloPi[samplesize_Integer] := N[4Mean[If[# > 1, 0, 1] & /@ Norm /@ RandomReal[1, {samplesize, 2}]]]</syntaxhighlight>
Example (samplesize=10,100,1000,....10000000):
Example (samplesize=10,100,1000,....10000000):
<lang Mathematica>{#, MonteCarloPi[#]} & /@ (10^Range[1, 7]) // Grid</lang>
<syntaxhighlight lang="mathematica">{#, MonteCarloPi[#]} & /@ (10^Range[1, 7]) // Grid</syntaxhighlight>
gives back:
gives back:
<pre>10 3.2
<pre>10 3.2
Line 1,844: Line 1,844:
10000000 3.14134</pre>
10000000 3.14134</pre>


<lang Mathematica>monteCarloPi = 4. Mean[UnitStep[1 - Total[RandomReal[1, {2, #}]^2]]] &;
<syntaxhighlight lang="mathematica">monteCarloPi = 4. Mean[UnitStep[1 - Total[RandomReal[1, {2, #}]^2]]] &;
monteCarloPi /@ (10^Range@6)</lang>
monteCarloPi /@ (10^Range@6)</syntaxhighlight>


A less elegant way to solve the problem, is to imagine a (well-trained) monkey, throwing a number of darts at a dartboard.
A less elegant way to solve the problem, is to imagine a (well-trained) monkey, throwing a number of darts at a dartboard.
Line 1,852: Line 1,852:


We create a function ''MonkeyDartsPi'', which can take a variable number of throws as input:
We create a function ''MonkeyDartsPi'', which can take a variable number of throws as input:
<lang Wolfram Language>MonkeyDartsPi[numberOfThrows_] := (
<syntaxhighlight lang="wolfram language">MonkeyDartsPi[numberOfThrows_] := (
xyCoordinates = RandomReal[{0, 1}, {numberOfThrows, 2}];
xyCoordinates = RandomReal[{0, 1}, {numberOfThrows, 2}];
InsideCircle = Length[Select[Total[xyCoordinates^2, {2}],#<=1&]] ;
InsideCircle = Length[Select[Total[xyCoordinates^2, {2}],#<=1&]] ;
4*N[InsideCircle / Length[xyCoordinates],1+Log10[numberOfThrows]])</lang>
4*N[InsideCircle / Length[xyCoordinates],1+Log10[numberOfThrows]])</syntaxhighlight>


We do several runs with a larger number of throws each time, increasing by powers of 10.
We do several runs with a larger number of throws each time, increasing by powers of 10.
<lang Wolfram Language>Grid[Table[{n, MonkeyDartsPi[n]}, {n, 10^Range[7]} ], Alignment -> Left]</lang>
<syntaxhighlight lang="wolfram language">Grid[Table[{n, MonkeyDartsPi[n]}, {n, 10^Range[7]} ], Alignment -> Left]</syntaxhighlight>


We see that as the number of throws increases, we get closer to the value of Pi:
We see that as the number of throws increases, we get closer to the value of Pi:
Line 1,875: Line 1,875:


Minimally Vectorized:
Minimally Vectorized:
<lang MATLAB>function piEstimate = monteCarloPi(numDarts)
<syntaxhighlight lang="matlab">function piEstimate = monteCarloPi(numDarts)


%The square has a sides of length 2, which means the circle has radius
%The square has a sides of length 2, which means the circle has radius
Line 1,891: Line 1,891:


end
end
</syntaxhighlight>
</lang>


Completely Vectorized:
Completely Vectorized:
<lang MATLAB>function piEstimate = monteCarloPi(numDarts)
<syntaxhighlight lang="matlab">function piEstimate = monteCarloPi(numDarts)
piEstimate = 4*sum( sum(rand(numDarts,2).^2,2) <= 1 )/numDarts;
piEstimate = 4*sum( sum(rand(numDarts,2).^2,2) <= 1 )/numDarts;


end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
<lang MATLAB>>> monteCarloPi(7000000)
<syntaxhighlight lang="matlab">>> monteCarloPi(7000000)


ans =
ans =


3.141512000000000</lang>
3.141512000000000</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang Maxima>load("distrib");
<syntaxhighlight lang="maxima">load("distrib");
approx_pi(n):= block(
approx_pi(n):= block(
[x: random_continuous_uniform(0, 1, n),
[x: random_continuous_uniform(0, 1, n),
Line 1,917: Line 1,917:
4*cin/n);
4*cin/n);
float(approx_pi(100));</lang>
float(approx_pi(100));</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
Line 1,938: Line 1,938:


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>П0 П1 0 П4 СЧ x^2 ^ СЧ x^2 +
<syntaxhighlight lang="text">П0 П1 0 П4 СЧ x^2 ^ СЧ x^2 +
1 - x<0 15 КИП4 L0 04 ИП4 4 *
1 - x<0 15 КИП4 L0 04 ИП4 4 *
ИП1 / С/П</lang>
ИП1 / С/П</syntaxhighlight>


''Example:'' for n = ''1000'' the output is ''3.152''.
''Example:'' for n = ''1000'' the output is ''3.152''.


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import math, random
<syntaxhighlight lang="nim">import math, random


randomize()
randomize()
Line 1,957: Line 1,957:
for n in [10e4, 10e6, 10e7, 10e8]:
for n in [10e4, 10e6, 10e7, 10e8]:
echo pi(n)</lang>
echo pi(n)</syntaxhighlight>
{{out}}
{{out}}
<pre>3.15336
<pre>3.15336
Line 1,965: Line 1,965:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let get_pi throws =
<syntaxhighlight lang="ocaml">let get_pi throws =
let rec helper i count =
let rec helper i count =
if i = throws then count
if i = throws then count
Line 1,976: Line 1,976:
else
else
helper (i+1) count
helper (i+1) count
in float (4 * helper 0 0) /. float throws</lang>
in float (4 * helper 0 0) /. float throws</syntaxhighlight>
Example:
Example:
# get_pi 10000;;
# get_pi 10000;;
Line 1,991: Line 1,991:
=={{header|Octave}}==
=={{header|Octave}}==


<lang octave>function p = montepi(samples)
<syntaxhighlight lang="octave">function p = montepi(samples)
in_circle = 0;
in_circle = 0;
for samp = 1:samples
for samp = 1:samples
Line 2,006: Line 2,006:
disp(montepi(l));
disp(montepi(l));
l *= 10;
l *= 10;
endwhile</lang>
endwhile</syntaxhighlight>


Since it runs slow, I've stopped it at the second iteration, obtaining:
Since it runs slow, I've stopped it at the second iteration, obtaining:
Line 2,014: Line 2,014:
=== Much faster implementation ===
=== Much faster implementation ===


<lang octave>
<syntaxhighlight lang="octave">
function result = montepi(n)
function result = montepi(n)
result = sum(rand(1,n).^2+rand(1,n).^2<1)/n*4;
result = sum(rand(1,n).^2+rand(1,n).^2<1)/n*4;
endfunction
endfunction
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>MonteCarloPi(tests)=4.*sum(i=1,tests,norml2([random(1.),random(1.)])<1)/tests;</lang>
<syntaxhighlight lang="parigp">MonteCarloPi(tests)=4.*sum(i=1,tests,norml2([random(1.),random(1.)])<1)/tests;</syntaxhighlight>
A hundred million tests (about a minute) yielded 3.14149000, slightly more precise (and round!) than would have been expected. A million gave 3.14162000 and a thousand 3.14800000.
A hundred million tests (about a minute) yielded 3.14149000, slightly more precise (and round!) than would have been expected. A million gave 3.14162000 and a thousand 3.14800000.


=={{header|Pascal}}==
=={{header|Pascal}}==
{{libheader|Math}}
{{libheader|Math}}
<lang pascal>Program MonteCarlo(output);
<syntaxhighlight lang="pascal">Program MonteCarlo(output);


uses
uses
Line 2,055: Line 2,055:
writeln (10**i, ' samples give ', MC_Pi(i):7:5, ' as pi.');
writeln (10**i, ' samples give ', MC_Pi(i):7:5, ' as pi.');
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>:> ./MonteCarlo
<pre>:> ./MonteCarlo
Line 2,066: Line 2,066:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub pi {
<syntaxhighlight lang="perl">sub pi {
my $nthrows = shift;
my $nthrows = shift;
my $inside = 0;
my $inside = 0;
Line 2,079: Line 2,079:
}
}


printf "%9d: %07f\n", $_, pi($_) for 10**4, 10**6;</lang>
printf "%9d: %07f\n", $_, pi($_) for 10**4, 10**6;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,087: Line 2,087:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100</span>
Line 2,100: Line 2,100:
<span style="color: #000000;">N</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">10</span>
<span style="color: #000000;">N</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">10</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,112: Line 2,112:


=={{header|PHP}}==
=={{header|PHP}}==
<syntaxhighlight lang="php"><?
<lang PHP><?
$loop = 1000000; # loop to 1,000,000
$loop = 1000000; # loop to 1,000,000
$count = 0;
$count = 0;
Line 2,121: Line 2,121:
}
}
echo "loop=".number_format($loop).", count=".number_format($count).", pi=".($count/$loop*4);
echo "loop=".number_format($loop).", count=".number_format($count).", pi=".($count/$loop*4);
?></lang>
?></syntaxhighlight>
{{out}}
{{out}}
<pre>loop=1,000,000, count=785,462, pi=3.141848</pre>
<pre>loop=1,000,000, count=785,462, pi=3.141848</pre>
Line 2,128: Line 2,128:
Some general Monte Carlo simulators. <code>N</code> is the number of runs, <code>F</code> is the simulation function.
Some general Monte Carlo simulators. <code>N</code> is the number of runs, <code>F</code> is the simulation function.
===Using while loop===
===Using while loop===
<lang>
<syntaxhighlight lang="text">
sim1(N, F) = C =>
sim1(N, F) = C =>
C = 0,
C = 0,
Line 2,135: Line 2,135:
C := C + apply(F),
C := C + apply(F),
I := I + 1
I := I + 1
end.</lang>
end.</syntaxhighlight>


===List comprehension===
===List comprehension===
This is simpler, but slightly slower than using <code>while</code> loop.
This is simpler, but slightly slower than using <code>while</code> loop.
<lang Picat>sim2(N, F) = sum([apply(F) : _I in 1..N]).</lang>
<syntaxhighlight lang="picat">sim2(N, F) = sum([apply(F) : _I in 1..N]).</syntaxhighlight>


===Recursion===
===Recursion===
<lang Picat>sim_rec(N,F) = S =>
<syntaxhighlight lang="picat">sim_rec(N,F) = S =>
sim_rec(N,N,F,0,S).
sim_rec(N,N,F,0,S).
sim_rec(0,_N,_F,S,S).
sim_rec(0,_N,_F,S,S).
sim_rec(C,N,F,S0,S) :-
sim_rec(C,N,F,S0,S) :-
S1 = S0 + apply(F),
S1 = S0 + apply(F),
sim_rec(C-1,N,F,S1,S).</lang>
sim_rec(C-1,N,F,S1,S).</syntaxhighlight>


===Test===
===Test===
Of the three different MC simulators, <code>sim_rec/2</code> (using recursion) is slightly faster than the other two (<code>sim1/2</code> and <code>sim2/2</code>) which have about the same speed.
Of the three different MC simulators, <code>sim_rec/2</code> (using recursion) is slightly faster than the other two (<code>sim1/2</code> and <code>sim2/2</code>) which have about the same speed.
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
foreach(N in 0..7)
foreach(N in 0..7)
sim_pi(10**N)
sim_pi(10**N)
Line 2,166: Line 2,166:
% The simulation function:
% The simulation function:
% returns 1 if success, 0 otherwise
% returns 1 if success, 0 otherwise
pi_f() = cond(frand()**2 + frand()**2 <= 1, 1, 0).</lang>
pi_f() = cond(frand()**2 + frand()**2 <= 1, 1, 0).</syntaxhighlight>


{{out}}
{{out}}
Line 2,179: Line 2,179:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de carloPi (Scl)
<syntaxhighlight lang="picolisp">(de carloPi (Scl)
(let (Dim (** 10 Scl) Dim2 (* Dim Dim) Pi 0)
(let (Dim (** 10 Scl) Dim2 (* Dim Dim) Pi 0)
(do (* 4 Dim)
(do (* 4 Dim)
Line 2,188: Line 2,188:


(for N 6
(for N 6
(prinl (carloPi N)) )</lang>
(prinl (carloPi N)) )</syntaxhighlight>
{{out}}
{{out}}
<pre>3.4
<pre>3.4
Line 2,199: Line 2,199:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
{{works with|PowerShell|2}}
<lang powershell>function Get-Pi ($Iterations = 10000) {
<syntaxhighlight lang="powershell">function Get-Pi ($Iterations = 10000) {
$InCircle = 0
$InCircle = 0
for ($i = 0; $i -lt $Iterations; $i++) {
for ($i = 0; $i -lt $Iterations; $i++) {
Line 2,215: Line 2,215:
| Add-Member -PassThru NoteProperty Pi $Pi `
| Add-Member -PassThru NoteProperty Pi $Pi `
| Add-Member -PassThru NoteProperty "% Difference" $Diff
| Add-Member -PassThru NoteProperty "% Difference" $Diff
}</lang>
}</syntaxhighlight>
This returns a custom object with appropriate properties which automatically enables a nice tabular display:
This returns a custom object with appropriate properties which automatically enables a nice tabular display:
<pre>PS Home:\> 10,100,1e3,1e4,1e5,1e6 | ForEach-Object { Get-Pi $_ }
<pre>PS Home:\> 10,100,1e3,1e4,1e5,1e6 | ForEach-Object { Get-Pi $_ }
Line 2,229: Line 2,229:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>OpenConsole()
<syntaxhighlight lang="purebasic">OpenConsole()
Procedure.d MonteCarloPi(throws.d)
Procedure.d MonteCarloPi(throws.d)
Line 2,253: Line 2,253:


PrintN("Press any key"): Repeat: Until Inkey() <> ""
PrintN("Press any key"): Repeat: Until Inkey() <> ""
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>'built-in' #PI = 3.14159265358979310000
<pre>'built-in' #PI = 3.14159265358979310000
Line 2,268: Line 2,268:


One use of the "sum" function is to count how many times something is true (because True = 1, False = 0):
One use of the "sum" function is to count how many times something is true (because True = 1, False = 0):
<lang python>>>> import random, math
<syntaxhighlight lang="python">>>> import random, math
>>> throws = 1000
>>> throws = 1000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
Line 2,283: Line 2,283:
for q in [0,1]]) < 1
for q in [0,1]]) < 1
for p in xrange(throws)) / float(throws)
for p in xrange(throws)) / float(throws)
3.1415666400000002</lang>
3.1415666400000002</syntaxhighlight>


===As a program using a function===
===As a program using a function===
<lang python>
<syntaxhighlight lang="python">
from random import random
from random import random
from math import hypot
from math import hypot
Line 2,304: Line 2,304:
for n in [10**4, 10**6, 10**7, 10**8]:
for n in [10**4, 10**6, 10**7, 10**8]:
print "%9d: %07f" % (n, pi(n))
print "%9d: %07f" % (n, pi(n))
</syntaxhighlight>
</lang>


===Faster implementation using Numpy===
===Faster implementation using Numpy===
<lang python>
<syntaxhighlight lang="python">
import numpy as np
import numpy as np


n = input('Number of samples: ')
n = input('Number of samples: ')
print np.sum(np.random.rand(n)**2+np.random.rand(n)**2<1)/float(n)*4
print np.sum(np.random.rand(n)**2+np.random.rand(n)**2<1)/float(n)*4
</syntaxhighlight>
</lang>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 2,318: Line 2,318:
{{trans|Forth}}
{{trans|Forth}}


<lang Quackery> [ $ "bigrat.qky" loadfile ] now!
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now!


[ [ 64 bit ] constant
[ [ 64 bit ] constant
Line 2,332: Line 2,332:
swap 20 point$ echo$ cr ] is trials ( n --> )
swap 20 point$ echo$ cr ] is trials ( n --> )


' [ 10 100 1000 10000 100000 1000000 ] witheach trials</lang>
' [ 10 100 1000 10000 100000 1000000 ] witheach trials</syntaxhighlight>


{{out}}
{{out}}
Line 2,344: Line 2,344:


=={{header|R}}==
=={{header|R}}==
<lang R># nice but not suitable for big samples!
<syntaxhighlight lang="r"># nice but not suitable for big samples!
monteCarloPi <- function(samples) {
monteCarloPi <- function(samples) {
x <- runif(samples, -1, 1) # for big samples, you need a lot of memory!
x <- runif(samples, -1, 1) # for big samples, you need a lot of memory!
Line 2,370: Line 2,370:
print(monteCarloPi(1e4))
print(monteCarloPi(1e4))
print(monteCarloPi(1e5))
print(monteCarloPi(1e5))
print(monteCarlo2Pi(1e7))</lang>
print(monteCarlo2Pi(1e7))</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define (in-unit-circle? x y) (<= (sqrt (+ (sqr x) (sqr y))) 1))
(define (in-unit-circle? x y) (<= (sqrt (+ (sqr x) (sqr y))) 1))
Line 2,404: Line 2,404:
;; to see how it looks as a decimal we can exact->inexact it
;; to see how it looks as a decimal we can exact->inexact it
(let ((mc (monte-carlo 10000000 1000000 random-point-in-2x2-square in-unit-circle? passed:samples->pi)))
(let ((mc (monte-carlo 10000000 1000000 random-point-in-2x2-square in-unit-circle? passed:samples->pi)))
(printf "exact = ~a~%inexact = ~a~%(pi - guess) = ~a~%" mc (exact->inexact mc) (- pi mc)))</lang>
(printf "exact = ~a~%inexact = ~a~%(pi - guess) = ~a~%" mc (exact->inexact mc) (- pi mc)))</syntaxhighlight>
{{out}}
{{out}}
<pre>1000000 samples of 10000000: 785763 passed -> 785763/250000
<pre>1000000 samples of 10000000: 785763 passed -> 785763/250000
Line 2,421: Line 2,421:
A little more Racket-like is the use of an iterator (in this case '''for/fold'''),
A little more Racket-like is the use of an iterator (in this case '''for/fold'''),
which is clearer than an inner function:
which is clearer than an inner function:
<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define (in-unit-circle? x y) (<= (sqrt (+ (sqr x) (sqr y))) 1))
(define (in-unit-circle? x y) (<= (sqrt (+ (sqr x) (sqr y))) 1))
;; Good idea made in another task that:
;; Good idea made in another task that:
Line 2,448: Line 2,448:
;; to see how it looks as a decimal we can exact->inexact it
;; to see how it looks as a decimal we can exact->inexact it
(let ((mc (monte-carlo/2 10000000 1000000 random-point-in-unit-square in-unit-circle? passed:samples->pi)))
(let ((mc (monte-carlo/2 10000000 1000000 random-point-in-unit-square in-unit-circle? passed:samples->pi)))
(printf "exact = ~a~%inexact = ~a~%(pi - guess) = ~a~%" mc (exact->inexact mc) (- pi mc)))</lang>
(printf "exact = ~a~%inexact = ~a~%(pi - guess) = ~a~%" mc (exact->inexact mc) (- pi mc)))</syntaxhighlight>


[Similar output]
[Similar output]
Line 2,456: Line 2,456:
{{works with|rakudo|2015-09-24}}
{{works with|rakudo|2015-09-24}}
We'll consider the upper-right quarter of the unitary disk centered at the origin. Its area is <math>\pi \over 4</math>.
We'll consider the upper-right quarter of the unitary disk centered at the origin. Its area is <math>\pi \over 4</math>.
<lang perl6>my @random_distances = ([+] rand**2 xx 2) xx *;
<syntaxhighlight lang="raku" line>my @random_distances = ([+] rand**2 xx 2) xx *;


sub approximate_pi(Int $n) {
sub approximate_pi(Int $n) {
Line 2,465: Line 2,465:
say "$_ iterations: ", approximate_pi $_
say "$_ iterations: ", approximate_pi $_
for 100, 1_000, 10_000;
for 100, 1_000, 10_000;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Monte-Carlo π approximation:
<pre>Monte-Carlo π approximation:
Line 2,474: Line 2,474:
We don't really need to write a function, though. A lazy list would do:
We don't really need to write a function, though. A lazy list would do:


<lang perl6>my @pi = ([\+] 4 * (1 > [+] rand**2 xx 2) xx *) Z/ 1 .. *;
<syntaxhighlight lang="raku" line>my @pi = ([\+] 4 * (1 > [+] rand**2 xx 2) xx *) Z/ 1 .. *;
say @pi[10, 1000, 10_000];</lang>
say @pi[10, 1000, 10_000];</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
A specific─purpose commatizer function is included to format the number of iterations.
A specific─purpose commatizer function is included to format the number of iterations.
<lang rexx>/*REXX program computes and displays the value of pi÷4 using the Monte Carlo algorithm*/
<syntaxhighlight lang="rexx">/*REXX program computes and displays the value of pi÷4 using the Monte Carlo algorithm*/
numeric digits 20 /*use 20 decimal digits to handle args.*/
numeric digits 20 /*use 20 decimal digits to handle args.*/
parse arg times chunk digs r? . /*does user want a specific number? */
parse arg times chunk digs r? . /*does user want a specific number? */
Line 2,512: Line 2,512:
exit 0 /*stick a fork in it, we're all done. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: procedure; arg _; do k=length(_)-3 to 1 by -3; _=insert(',',_,k); end; return _</lang>
commas: procedure; arg _; do k=length(_)-3 to 1 by -3; _=insert(',',_,k); end; return _</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 2,531: Line 2,531:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
decimals(8)
decimals(8)
see "monteCarlo(1000) = " + monteCarlo(1000) + nl
see "monteCarlo(1000) = " + monteCarlo(1000) + nl
Line 2,544: Line 2,544:
t = (4 * n) / t
t = (4 * n) / t
return t
return t
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,553: Line 2,553:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def approx_pi(throws)
<syntaxhighlight lang="ruby">def approx_pi(throws)
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
4.0 * times_inside / throws
4.0 * times_inside / throws
Line 2,560: Line 2,560:
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
puts "%8d samples: PI = %s" % [n, approx_pi(n)]
puts "%8d samples: PI = %s" % [n, approx_pi(n)]
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre> 1000 samples: PI = 3.2
<pre> 1000 samples: PI = 3.2
Line 2,569: Line 2,569:


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>extern crate rand;
<syntaxhighlight lang="rust">extern crate rand;


use rand::Rng;
use rand::Rng;
Line 2,601: Line 2,601:
println!("{:9}: {:<11} dev: {:.5}%", samples, estimate, deviation);
println!("{:9}: {:<11} dev: {:.5}%", samples, estimate, deviation);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Real pi: 3.141592653589793
<pre>Real pi: 3.141592653589793
Line 2,612: Line 2,612:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object MonteCarlo {
<syntaxhighlight lang="scala">object MonteCarlo {
private val random = new scala.util.Random
private val random = new scala.util.Random


Line 2,638: Line 2,638:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>10000 simulations; pi estimation: 3.1492
<pre>10000 simulations; pi estimation: 3.1492
Line 2,647: Line 2,647:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";


Line 2,672: Line 2,672:
writeln(" 10000000: " <& pi( 10000000) digits 5);
writeln(" 10000000: " <& pi( 10000000) digits 5);
writeln("100000000: " <& pi(100000000) digits 5);
writeln("100000000: " <& pi(100000000) digits 5);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 2,685: Line 2,685:
=={{header|SequenceL}}==
=={{header|SequenceL}}==
First solution is serial due to the use of random numbers. Will always give the same result for a given n and seed
First solution is serial due to the use of random numbers. Will always give the same result for a given n and seed
<syntaxhighlight lang="sequencel">
<lang sequenceL>
import <Utilities/Random.sl>;
import <Utilities/Random.sl>;
import <Utilities/Conversion.sl>;
import <Utilities/Conversion.sl>;
Line 2,709: Line 2,709:
result when n < 0 else
result when n < 0 else
monteCarloHelper(n - 1, yRand.Generator, newResult);
monteCarloHelper(n - 1, yRand.Generator, newResult);
</syntaxhighlight>
</lang>


The second solution will run in parallel. It will also always give the same result for a given n and seed. (Note, the function monteCarloHelper is the same in both versions).
The second solution will run in parallel. It will also always give the same result for a given n and seed. (Note, the function monteCarloHelper is the same in both versions).


<syntaxhighlight lang="sequencel">
<lang sequenceL>
import <Utilities/Random.sl>;
import <Utilities/Random.sl>;
import <Utilities/Conversion.sl>;
import <Utilities/Conversion.sl>;
Line 2,739: Line 2,739:
result when n < 0 else
result when n < 0 else
monteCarloHelper(n - 1, yRand.Generator, newResult);
monteCarloHelper(n - 1, yRand.Generator, newResult);
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func monteCarloPi(nthrows) {
<syntaxhighlight lang="ruby">func monteCarloPi(nthrows) {
4 * (^nthrows -> count_by {
4 * (^nthrows -> count_by {
hypot(1.rand(2) - 1, 1.rand(2) - 1) < 1
hypot(1.rand(2) - 1, 1.rand(2) - 1) < 1
Line 2,750: Line 2,750:
for n in [1e2, 1e3, 1e4, 1e5, 1e6] {
for n in [1e2, 1e3, 1e4, 1e5, 1e6] {
printf("%9d: %07f\n", n, monteCarloPi(n))
printf("%9d: %07f\n", n, monteCarloPi(n))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,761: Line 2,761:


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>program define mcdisk
<syntaxhighlight lang="stata">program define mcdisk
clear all
clear all
quietly set obs `1'
quietly set obs `1'
Line 2,777: Line 2,777:


. mcdisk 100000000
. mcdisk 100000000
3.1416253</lang>
3.1416253</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


func mcpi(sampleSize size:Int) -> Double {
func mcpi(sampleSize size:Int) -> Double {
Line 2,806: Line 2,806:
println(mcpi(sampleSize: 1000000))
println(mcpi(sampleSize: 1000000))
println(mcpi(sampleSize: 10000000))
println(mcpi(sampleSize: 10000000))
println(mcpi(sampleSize: 100000000))</lang>
println(mcpi(sampleSize: 100000000))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,819: Line 2,819:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc pi {samples} {
<syntaxhighlight lang="tcl">proc pi {samples} {
set i 0
set i 0
set inside 0
set inside 0
Line 2,833: Line 2,833:
foreach runs {1e2 1e4 1e6 1e8} {
foreach runs {1e2 1e4 1e6 1e8} {
puts "$runs => [pi $runs]"
puts "$runs => [pi $runs]"
}</lang>
}</syntaxhighlight>
result
result
<pre>PI is approx 3.141592653589793
<pre>PI is approx 3.141592653589793
Line 2,843: Line 2,843:


=={{header|Ursala}}==
=={{header|Ursala}}==
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import flo
#import flo


mcp "n" = times/4. div\float"n" (rep"n" (fleq/.5+ sqrt+ plus+ ~~ sqr+ minus/.5+ rand)?/~& plus/1.) 0.</lang>
mcp "n" = times/4. div\float"n" (rep"n" (fleq/.5+ sqrt+ plus+ ~~ sqr+ minus/.5+ rand)?/~& plus/1.) 0.</syntaxhighlight>
Here's a walk through.
Here's a walk through.
* <code>mcp "n" = </code>... defines a function named <code>mcp</code> in terms of a dummy variable <code>"n"</code>, which will be the number of iterations used in the simulation
* <code>mcp "n" = </code>... defines a function named <code>mcp</code> in terms of a dummy variable <code>"n"</code>, which will be the number of iterations used in the simulation
Line 2,864: Line 2,864:
* The result of the division is quadrupled by <code>times/4.</code>.
* The result of the division is quadrupled by <code>times/4.</code>.
test program:
test program:
<lang Ursala>#cast %eL
<syntaxhighlight lang="ursala">#cast %eL


pis = mcp* <10,100,1000,10000,100000,1000000></lang>
pis = mcp* <10,100,1000,10000,100000,1000000></syntaxhighlight>
{{out}}
{{out}}
<pre><
<pre><
Line 2,879: Line 2,879:
{{trans|Kotlin}}
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "random" for Random
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 2,902: Line 2,902:
Fmt.print("$9d -> $10.8f -> $6.4f", n, pi, err)
Fmt.print("$9d -> $10.8f -> $6.4f", n, pi, err)
n = n * 10
n = n * 10
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,918: Line 2,918:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>code Ran=1, CrLf=9;
<syntaxhighlight lang="xpl0">code Ran=1, CrLf=9;
code real RlOut=48;
code real RlOut=48;


Line 2,938: Line 2,938:
RlOut(0, MontePi( 1_000_000)); CrLf(0);
RlOut(0, MontePi( 1_000_000)); CrLf(0);
RlOut(0, MontePi(100_000_000)); CrLf(0);
RlOut(0, MontePi(100_000_000)); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,949: Line 2,949:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn monty(n){
<syntaxhighlight lang="zkl">fcn monty(n){
inCircle:=0;
inCircle:=0;
do(n){
do(n){
Line 2,956: Line 2,956:
}
}
4.0*inCircle/n
4.0*inCircle/n
}</lang>
}</syntaxhighlight>
Or, in a more functional style (using a reference for state info):
Or, in a more functional style (using a reference for state info):
<lang zkl>fcn monty(n){
<syntaxhighlight lang="zkl">fcn monty(n){
4.0 * (1).pump(n,Void,fcn(r){
4.0 * (1).pump(n,Void,fcn(r){
x:=(0.0).random(1); y:=(0.0).random(1);
x:=(0.0).random(1); y:=(0.0).random(1);
Line 2,964: Line 2,964:
r
r
}.fp(Ref(0)) ).value/n;
}.fp(Ref(0)) ).value/n;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>