Monte Carlo methods: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Picat}}: Split into subsections, added {{out}}, code tag for predicates etc) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 29:
=={{header|11l}}==
<
V inside = 0
L 1..n
Line 38:
R 4.0 * inside / n
print(monte_carlo_pi(1000000))</
{{out}}
Line 46:
=={{header|360 Assembly}}==
<
MONTECAR CSECT
USING MONTECAR,R13 base register
Line 127:
WP DS PL16 packed decimal 16
YREGS
END MONTECAR</
{{out}}
<pre>
Line 139:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<
DEFINE PTR="CARD"
Line 219:
Test(1000)
Test(10000)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Monte_Carlo_methods.png Screenshot from Atari 8-bit computer]
Line 231:
=={{header|Ada}}==
<
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
Line 253:
Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo;</
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.
Line 271:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<
BEGIN
INT inside := 0;
Line 286:
print ((" 1 000 000:",pi ( 1 000 000),new line));
print ((" 10 000 000:",pi ( 10 000 000),new line));
print (("100 000 000:",pi (100 000 000),new line))</
{{out}}
<pre>
Line 298:
=={{header|Arturo}}==
<
inside: new 0.0
do.times: throws [
Line 307:
loop [100 1000 10000 100000 1000000] 'n ->
print [pad to :string n 8 "=>" Pi n]</
{{out}}
Line 320:
{{AutoHotkey case}}
Source: [http://www.autohotkey.com/forum/topic44657.html AutoHotkey forum] by Laszlo
<
MsgBox % MontePi(10000) ; 3.154400
MsgBox % MontePi(100000) ; 3.142040
Line 333:
Return 4*p/n
}
</syntaxhighlight>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# --- with command line argument "throws" ---
Line 348:
Pi = 3.14333
</syntaxhighlight>
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{trans|Java}}
<
CLS
PRINT getPi(10000)
Line 374:
NEXT i
getPi = 4! * inCircle / throws
END FUNCTION</
{{out}}
<pre>
Line 385:
=={{header|BASIC256}}==
{{works with|basic256|1.1.4.0}}
<
# Monte Carlo Simulator
# Determine value of pi
Line 407:
next i
print float(4*in_c/tosses)</
{{out}}
<pre>
Line 418:
=={{header|BBC BASIC}}==
<
PRINT FNmontecarlo(10000)
PRINT FNmontecarlo(100000)
Line 430:
IF RND(1)^2 + RND(1)^2 < 1 n% += 1
NEXT
= 4 * n% / t%</
{{out}}
<pre>
Line 441:
=={{header|C}}==
<
#include <stdlib.h>
#include <math.h>
Line 476:
printf("Pi is %f\n", pi(3e-4)); /* set to 1e-4 for some fun */
return 0;
}</
=={{header|C sharp|C#}}==
<
class Program {
Line 502:
}
}
}</
{{out}}
Line 514:
=={{header|C++}}==
<
#include<iostream>
#include<math.h>
Line 536:
cout<<""<<4*double(hit)/double(imax)<<endl; } // Print out Pi number
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(loop [x (rand) y (rand) in 0 total 1]
(if (< total iterations)
Line 545:
(double (* (/ in total) 4)))))
(doseq [x (take 5 (iterate #(* 10 %) 10))] (println (str (format "% 8d" x) ": " (calc-pi x))))</
{{out}}
Line 556:
</pre>
<
[]
(if (<= (+ (Math/pow (rand) 2) (Math/pow (rand) 2)) 1) 1 0))
Line 565:
(pi-estimate 10000)
</syntaxhighlight>
{{out}}
Line 573:
=={{header|Common Lisp}}==
<
(/ (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))
(format t "~%~8d -> ~f" n (approximate-pi n)))</
{{out}}
Line 590:
=={{header|Crystal}}==
{{trans|Ruby}}
<
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
4.0 * times_inside / throws
Line 597:
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
puts "%8d samples: PI = %s" % [n, approx_pi(n)]
end</
{{out}}
<pre> 1000 samples: PI = 3.1
Line 607:
=={{header|D}}==
<
double pi(in uint nthrows) /*nothrow*/ @safe /*@nogc*/ {
Line 620:
foreach (immutable p; 1 .. 8)
writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p));
}</
{{out}}
<pre> 10: 3.200000
Line 641:
===More Functional Style===
<
import std.stdio, std.random, std.math, std.algorithm, std.range;
Line 649:
foreach (immutable p; 1 .. 8)
writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p));
}</
{{out}}
<pre> 10: 3.200000
Line 663:
From example at [https://www.dartlang.org/ Dart Official Website]
<
import 'dart:async';
import 'dart:html';
Line 714:
bool get isInsideUnitCircle => x * x + y * y <= 1;
}
</syntaxhighlight>
{{out}}
The script give in reality an output formatted in HTML
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.
<
var inside := 0
for _ ? (entropy.nextFloat() ** 2 + entropy.nextFloat() ** 2 < 1) in 1..n {
Line 729:
}
return inside * 4 / n
}</
Some sample runs:
Line 752:
=={{header|EasyLang}}==
<syntaxhighlight lang="text">func mc n . .
for i range n
x = randomf
Line 766:
call mc 100000
call mc 1000000
call mc 10000000</
Output:
3.1292
Line 774:
=={{header|Elixir}}==
<
def pi(n) do
count = Enum.count(1..n, fn _ ->
Line 787:
Enum.each([1000, 10000, 100000, 1000000, 10000000], fn n ->
:io.format "~8w samples: PI = ~f~n", [n, MonteCarlo.pi(n)]
end)</
{{out}}
Line 800:
=={{header|Erlang}}==
===With inline test===
<syntaxhighlight lang="erlang">
-module(monte).
-export([main/1]).
Line 818:
main(N) -> io:format("PI: ~w~n", [ monte(N) ]).
</syntaxhighlight>
{{out}}
<pre>
Line 830:
</pre>
===With test in a function===
<syntaxhighlight lang="erlang">
-module(monte2).
-export([main/1]).
Line 851:
main(N) -> io:format("PI: ~w~n", [ monte(N) ]).
</syntaxhighlight>
{{out}}
<pre>Xcoord
Line 865:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM RANDOM_PI
Line 889:
MONTECARLO(1000000->RES) PRINT(RES)
MONTECARLO(10000000->RES) PRINT(RES)
END PROGRAM</
{{out}}
<pre>
Line 900:
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang="euler math toolbox">
>function map MonteCarloPI (n,plot=false) ...
$ X:=random(1,n);
Line 915:
3.14159265359
>MonteCarloPI(10000,true):
</syntaxhighlight>
[[File:Test.png]]
Line 922:
There is some support and test expressions.
<
let print x = printfn "%A" x
Line 942:
MonteCarloPiGreco 10000 |> print
MonteCarloPiGreco 100000 |> print
</syntaxhighlight>
{{out}}
<pre>
Line 953:
Since Factor lets the user choose the range of the random generator, we use 2^32.
<
: limit ( -- n ) 2 32 ^ ; inline
: in-circle ( x y -- ? ) limit [ sq ] tri@ [ + ] [ <= ] bi* ;
: rand ( -- r ) limit random ;
: pi ( n -- pi ) [ [ drop rand rand in-circle ] count ] keep / 4 * >float ;</
Example use:
<
3.1412</
=={{header|Fantom}}==
<
class MontyCarlo
{
Line 991:
}
}
</syntaxhighlight>
{{out}}
Line 1,024:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
IMPLICIT NONE
Line 1,058:
END DO
END PROGRAM MONTE_CARLO</
{{out}}
Line 1,069:
</pre>
{{works with|Fortran|2008 and later}}
<
program mc
integer :: n,i
Line 1,086:
pi = 4.d0 * dble( count( hypot(x(1,:),x(2,:)) <= 1.d0 ) ) / n
end function
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,121:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre> Mumber of throws Ratio (Pi) Error
Line 1,139:
Since Futhark is a pure language, random numbers are implemented using Sobol sequences.
<syntaxhighlight lang="futhark">
import "futlib/math"
Line 1,188:
let inside = reduce (+) 0 bs
in 4.0f32*f32(inside)/f32(n)
</syntaxhighlight>
=={{header|Go}}==
'''Using standard library math/rand:'''
<
import (
Line 1,224:
fmt.Println(getPi(10000000))
fmt.Println(getPi(100000000))
}</
{{out}}
<pre>
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.
<
import (
Line 1,269:
fmt.Println(getPi(10000000))
fmt.Println(getPi(100000000))
}</
=={{header|Haskell}}==
<
import System.Random
Line 1,284:
let dist :: Double
dist = sqrt (rand_x * rand_x + rand_y * rand_y)
return (if dist < 1 then 1 else 0)</
{{Out}}
<pre>Example:
Line 1,296:
Or, using foldM, and dropping sqrt:
<
import System.Random (randomRIO)
import Data.Functor ((<&>))
Line 1,318:
mapM_
(monteCarloPi >=> print)
[1000, 10000, 100000, 1000000]</
{{Out}}
For example:
Line 1,327:
=={{header|HicEst}}==
<
inside = 0
DO i = 1, samples
Line 1,338:
WRITE(ClipBoard) Pi(1E5) ! 3.14204
WRITE(ClipBoard) Pi(1E6) ! 3.141672
WRITE(ClipBoard) Pi(1E7) ! 3.1412856</
=={{header|Icon}} and {{header|Unicon}}==
<
every t := 10 ^ ( 5 to 9 ) do
printf("Rounds=%d Pi ~ %r\n",t,getPi(t))
Line 1,354:
incircle +:= 1
return 4 * incircle / rounds
end</
{{libheader|Icon Programming Library}}
Line 1,368:
=={{header|J}}==
'''Explicit Solution:'''
<
4* y%~ +/ 1>: %: +/ *: <: +: (2,y) ?@$ 0
)</
'''Tacit Solution:'''
<
'''Examples:'''
<
3.1426
piMC 10^i.7
4 2.8 3.24 3.168 3.1432 3.14256 3.14014</
=={{header|Java}}==
<
public static void main(String[] args) {
System.out.println(getPi(10000));
Line 1,407:
return 4.0 * inCircle / numThrows;
}
}</
{{out}}
3.1396
Line 1,415:
3.14168604
{{works with|Java|8+}}
<
import java.util.stream.IntStream;
Line 1,458:
return (4.0 * inCircle) / numThrows;
}
}</
{{out}}
3.1556
Line 1,468:
=={{header|JavaScript}}==
===ES5===
<
var x, y, m = 0;
Line 1,487:
console.log(mcpi(100000));
console.log(mcpi(1000000));
console.log(mcpi(10000000));</
<pre>3.168
3.1396
Line 1,496:
===ES6===
<
"use strict";
Line 1,534:
);
});
})();</
{{Out}} For example:
<pre>1000 samples: 3.064
Line 1,549:
jq does not have a built-in PRNG so we will use /dev/urandom
as a source of entropy by invoking jq as follows:
<
function prng {
cat /dev/urandom | tr -cd '0-9' | fold -w 10 | sed 's/^0*\(.*\)*\(.\)*$/\1\2/'
}
prng | jq -nMr -f program.jq</
'''program.jq'''
<
def percent: "\(100000 * . | round / 1000)%";
Line 1,580:
| ($p | mcPi) as $mcpi
| ((($pi - $mcpi)|length) / $pi) as $error
| "\($p|lpad(10)) \($mcpi|lpad(10)) \($error|percent|lpad(6))" )</
{{out}}
<pre>
Line 1,595:
=={{header|Jsish}}==
From Javascript ES5 entry, with PRNG seeded during unit testing for reproducibility.
<
function mcpi(n) {
var x, y, m = 0;
Line 1,626:
mcpi(1000000) ==> 3.142124
=!EXPECTEND!=
*/</
{{out}}
Line 1,633:
=={{header|Julia}}==
<
function monteπ(n)
Line 1,643:
p = monteπ(n)
println("$(lpad(n, 9)): π ≈ $(lpad(p, 10)), pct.err = ", @sprintf("%2.5f%%", abs(p - π) / π))
end</
{{out}}
Line 1,654:
=={{header|K}}==
<
sim 10000
Line 1,660:
sim'10^!8
4 2.8 3.4 3.072 3.1212 3.14104 3.14366 3.1413</
=={{header|Kotlin}}==
<
fun mcPi(n: Int): Double {
Line 1,685:
n *= 10
}
}</
Sample output:
{{out}}
Line 1,700:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
for pow = 2 to 6
n = 10^pow
Line 1,717:
end function
</
{{out}}
Line 1,730:
=={{header|Locomotive Basic}}==
<
20 input "How many samples";n
30 u=n/100+1
Line 1,745:
140 print "Computed value of pi:"pi2!
150 print "Difference to real value of pi: ";
160 print using "+#.##%"; (pi2!-pi)/pi*100</
[[File:Monte Carlo, 200 points, Locomotive BASIC.png]]
Line 1,751:
=={{header|Logo}}==
<
to square :n
output :n * :n
Line 1,768:
show sim 100000 10000 ; 3.145
show sim 1000000 10000 ; 3.140828
</syntaxhighlight>
=={{header|LSL}}==
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?)
<
integer iMAX_SAMPLE_POWER = 6;
default {
Line 1,794:
llOwnerSay("Done.");
}
}</
{{out}}
<pre>Estimating Pi (3.141593)
Line 1,807:
=={{header|Lua}}==
<
math.randomseed( os.time() )
Line 1,823:
print( MonteCarlo( 100000 ) )
print( MonteCarlo( 1000000 ) )
print( MonteCarlo( 10000000 ) )</
{{out}}
<pre>3.1436
Line 1,832:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
We define a function with variable sample size:
<
Example (samplesize=10,100,1000,....10000000):
<
gives back:
<pre>10 3.2
Line 1,844:
10000000 3.14134</pre>
<
monteCarloPi /@ (10^Range@6)</
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:
We create a function ''MonkeyDartsPi'', which can take a variable number of throws as input:
<
xyCoordinates = RandomReal[{0, 1}, {numberOfThrows, 2}];
InsideCircle = Length[Select[Total[xyCoordinates^2, {2}],#<=1&]] ;
4*N[InsideCircle / Length[xyCoordinates],1+Log10[numberOfThrows]])</
We do several runs with a larger number of throws each time, increasing by powers of 10.
<
We see that as the number of throws increases, we get closer to the value of Pi:
Line 1,875:
Minimally Vectorized:
<
%The square has a sides of length 2, which means the circle has radius
Line 1,891:
end
</syntaxhighlight>
Completely Vectorized:
<
piEstimate = 4*sum( sum(rand(numDarts,2).^2,2) <= 1 )/numDarts;
end</
{{out}}
<
ans =
3.141512000000000</
=={{header|Maxima}}==
<
approx_pi(n):= block(
[x: random_continuous_uniform(0, 1, n),
Line 1,917:
4*cin/n);
float(approx_pi(100));</
=={{header|MAXScript}}==
Line 1,938:
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П0 П1 0 П4 СЧ x^2 ^ СЧ x^2 +
1 - x<0 15 КИП4 L0 04 ИП4 4 *
ИП1 / С/П</
''Example:'' for n = ''1000'' the output is ''3.152''.
=={{header|Nim}}==
<
randomize()
Line 1,957:
for n in [10e4, 10e6, 10e7, 10e8]:
echo pi(n)</
{{out}}
<pre>3.15336
Line 1,965:
=={{header|OCaml}}==
<
let rec helper i count =
if i = throws then count
Line 1,976:
else
helper (i+1) count
in float (4 * helper 0 0) /. float throws</
Example:
# get_pi 10000;;
Line 1,991:
=={{header|Octave}}==
<
in_circle = 0;
for samp = 1:samples
Line 2,006:
disp(montepi(l));
l *= 10;
endwhile</
Since it runs slow, I've stopped it at the second iteration, obtaining:
Line 2,014:
=== Much faster implementation ===
<
function result = montepi(n)
result = sum(rand(1,n).^2+rand(1,n).^2<1)/n*4;
endfunction
</syntaxhighlight>
=={{header|PARI/GP}}==
<
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}}==
{{libheader|Math}}
<
uses
Line 2,055:
writeln (10**i, ' samples give ', MC_Pi(i):7:5, ' as pi.');
end.
</syntaxhighlight>
{{out}}
<pre>:> ./MonteCarlo
Line 2,066:
=={{header|Perl}}==
<
my $nthrows = shift;
my $inside = 0;
Line 2,079:
}
printf "%9d: %07f\n", $_, pi($_) for 10**4, 10**6;</
{{out}}
<pre>
Line 2,087:
=={{header|Phix}}==
<!--<
<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>
Line 2,100:
<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>
<!--</
{{out}}
<pre>
Line 2,112:
=={{header|PHP}}==
<syntaxhighlight lang="php"><?
$loop = 1000000; # loop to 1,000,000
$count = 0;
Line 2,121:
}
echo "loop=".number_format($loop).", count=".number_format($count).", pi=".($count/$loop*4);
?></
{{out}}
<pre>loop=1,000,000, count=785,462, pi=3.141848</pre>
Line 2,128:
Some general Monte Carlo simulators. <code>N</code> is the number of runs, <code>F</code> is the simulation function.
===Using while loop===
<syntaxhighlight lang="text">
sim1(N, F) = C =>
C = 0,
Line 2,135:
C := C + apply(F),
I := I + 1
end.</
===List comprehension===
This is simpler, but slightly slower than using <code>while</code> loop.
<
===Recursion===
<
sim_rec(N,N,F,0,S).
sim_rec(0,_N,_F,S,S).
sim_rec(C,N,F,S0,S) :-
S1 = S0 + apply(F),
sim_rec(C-1,N,F,S1,S).</
===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.
<
foreach(N in 0..7)
sim_pi(10**N)
Line 2,166:
% The simulation function:
% returns 1 if success, 0 otherwise
pi_f() = cond(frand()**2 + frand()**2 <= 1, 1, 0).</
{{out}}
Line 2,179:
=={{header|PicoLisp}}==
<
(let (Dim (** 10 Scl) Dim2 (* Dim Dim) Pi 0)
(do (* 4 Dim)
Line 2,188:
(for N 6
(prinl (carloPi N)) )</
{{out}}
<pre>3.4
Line 2,199:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<
$InCircle = 0
for ($i = 0; $i -lt $Iterations; $i++) {
Line 2,215:
| Add-Member -PassThru NoteProperty Pi $Pi `
| Add-Member -PassThru NoteProperty "% Difference" $Diff
}</
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 $_ }
Line 2,229:
=={{header|PureBasic}}==
<
Procedure.d MonteCarloPi(throws.d)
Line 2,253:
PrintN("Press any key"): Repeat: Until Inkey() <> ""
</syntaxhighlight>
{{out}}
<pre>'built-in' #PI = 3.14159265358979310000
Line 2,268:
One use of the "sum" function is to count how many times something is true (because True = 1, False = 0):
<
>>> throws = 1000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
Line 2,283:
for q in [0,1]]) < 1
for p in xrange(throws)) / float(throws)
3.1415666400000002</
===As a program using a function===
<
from random import random
from math import hypot
Line 2,304:
for n in [10**4, 10**6, 10**7, 10**8]:
print "%9d: %07f" % (n, pi(n))
</syntaxhighlight>
===Faster implementation using Numpy===
<
import numpy as np
n = input('Number of samples: ')
print np.sum(np.random.rand(n)**2+np.random.rand(n)**2<1)/float(n)*4
</syntaxhighlight>
=={{header|Quackery}}==
Line 2,318:
{{trans|Forth}}
<
[ [ 64 bit ] constant
Line 2,332:
swap 20 point$ echo$ cr ] is trials ( n --> )
' [ 10 100 1000 10000 100000 1000000 ] witheach trials</
{{out}}
Line 2,344:
=={{header|R}}==
<
monteCarloPi <- function(samples) {
x <- runif(samples, -1, 1) # for big samples, you need a lot of memory!
Line 2,370:
print(monteCarloPi(1e4))
print(monteCarloPi(1e5))
print(monteCarlo2Pi(1e7))</
=={{header|Racket}}==
<
(define (in-unit-circle? x y) (<= (sqrt (+ (sqr x) (sqr y))) 1))
Line 2,404:
;; 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)))
(printf "exact = ~a~%inexact = ~a~%(pi - guess) = ~a~%" mc (exact->inexact mc) (- pi mc)))</
{{out}}
<pre>1000000 samples of 10000000: 785763 passed -> 785763/250000
Line 2,421:
A little more Racket-like is the use of an iterator (in this case '''for/fold'''),
which is clearer than an inner function:
<
(define (in-unit-circle? x y) (<= (sqrt (+ (sqr x) (sqr y))) 1))
;; Good idea made in another task that:
Line 2,448:
;; 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)))
(printf "exact = ~a~%inexact = ~a~%(pi - guess) = ~a~%" mc (exact->inexact mc) (- pi mc)))</
[Similar output]
Line 2,456:
{{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>.
<syntaxhighlight lang="raku"
sub approximate_pi(Int $n) {
Line 2,465:
say "$_ iterations: ", approximate_pi $_
for 100, 1_000, 10_000;
</syntaxhighlight>
{{out}}
<pre>Monte-Carlo π approximation:
Line 2,474:
We don't really need to write a function, though. A lazy list would do:
<syntaxhighlight lang="raku"
say @pi[10, 1000, 10_000];</
=={{header|REXX}}==
A specific─purpose commatizer function is included to format the number of iterations.
<
numeric digits 20 /*use 20 decimal digits to handle args.*/
parse arg times chunk digs r? . /*does user want a specific number? */
Line 2,512:
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 _</
{{out|output|text= when using the default input:}}
<pre>
Line 2,531:
=={{header|Ring}}==
<
decimals(8)
see "monteCarlo(1000) = " + monteCarlo(1000) + nl
Line 2,544:
t = (4 * n) / t
return t
</syntaxhighlight>
Output:
<pre>
Line 2,553:
=={{header|Ruby}}==
<
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
4.0 * times_inside / throws
Line 2,560:
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
puts "%8d samples: PI = %s" % [n, approx_pi(n)]
end</
{{out}}
<pre> 1000 samples: PI = 3.2
Line 2,569:
=={{header|Rust}}==
<
use rand::Rng;
Line 2,601:
println!("{:9}: {:<11} dev: {:.5}%", samples, estimate, deviation);
}
}</
{{out}}
<pre>Real pi: 3.141592653589793
Line 2,612:
=={{header|Scala}}==
<
private val random = new scala.util.Random
Line 2,638:
}
}
}</
{{out}}
<pre>10000 simulations; pi estimation: 3.1492
Line 2,647:
=={{header|Seed7}}==
<
include "float.s7i";
Line 2,672:
writeln(" 10000000: " <& pi( 10000000) digits 5);
writeln("100000000: " <& pi(100000000) digits 5);
end func;</
{{out}}
Line 2,685:
=={{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
<syntaxhighlight lang="sequencel">
import <Utilities/Random.sl>;
import <Utilities/Conversion.sl>;
Line 2,709:
result when n < 0 else
monteCarloHelper(n - 1, yRand.Generator, newResult);
</syntaxhighlight>
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">
import <Utilities/Random.sl>;
import <Utilities/Conversion.sl>;
Line 2,739:
result when n < 0 else
monteCarloHelper(n - 1, yRand.Generator, newResult);
</syntaxhighlight>
=={{header|Sidef}}==
<
4 * (^nthrows -> count_by {
hypot(1.rand(2) - 1, 1.rand(2) - 1) < 1
Line 2,750:
for n in [1e2, 1e3, 1e4, 1e5, 1e6] {
printf("%9d: %07f\n", n, monteCarloPi(n))
}</
{{out}}
<pre>
Line 2,761:
=={{header|Stata}}==
<
clear all
quietly set obs `1'
Line 2,777:
. mcdisk 100000000
3.1416253</
=={{header|Swift}}==
{{trans|JavaScript}}
<
func mcpi(sampleSize size:Int) -> Double {
Line 2,806:
println(mcpi(sampleSize: 1000000))
println(mcpi(sampleSize: 10000000))
println(mcpi(sampleSize: 100000000))</
{{out}}
<pre>
Line 2,819:
=={{header|Tcl}}==
<
set i 0
set inside 0
Line 2,833:
foreach runs {1e2 1e4 1e6 1e8} {
puts "$runs => [pi $runs]"
}</
result
<pre>PI is approx 3.141592653589793
Line 2,843:
=={{header|Ursala}}==
<
#import flo
mcp "n" = times/4. div\float"n" (rep"n" (fleq/.5+ sqrt+ plus+ ~~ sqr+ minus/.5+ rand)?/~& plus/1.) 0.</
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
Line 2,864:
* The result of the division is quadrupled by <code>times/4.</code>.
test program:
<
pis = mcp* <10,100,1000,10000,100000,1000000></
{{out}}
<pre><
Line 2,879:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<
import "/fmt" for Fmt
Line 2,902:
Fmt.print("$9d -> $10.8f -> $6.4f", n, pi, err)
n = n * 10
}</
{{out}}
Line 2,918:
=={{header|XPL0}}==
<
code real RlOut=48;
Line 2,938:
RlOut(0, MontePi( 1_000_000)); CrLf(0);
RlOut(0, MontePi(100_000_000)); CrLf(0);
]</
{{out}}
Line 2,949:
=={{header|zkl}}==
<
inCircle:=0;
do(n){
Line 2,956:
}
4.0*inCircle/n
}</
Or, in a more functional style (using a reference for state info):
<
4.0 * (1).pump(n,Void,fcn(r){
x:=(0.0).random(1); y:=(0.0).random(1);
Line 2,964:
r
}.fp(Ref(0)) ).value/n;
}</
{{out}}
<pre>
|