Jump to content

Monte Carlo methods: Difference between revisions

m
syntax highlighting fixup automation
(→‎{{header|Picat}}: Split into subsections, added {{out}}, code tag for predicates etc)
m (syntax highlighting fixup automation)
Line 29:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F monte_carlo_pi(n)
V inside = 0
L 1..n
Line 38:
R 4.0 * inside / n
 
print(monte_carlo_pi(1000000))</langsyntaxhighlight>
 
{{out}}
Line 46:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Monte Carlo methods 08/03/2017
MONTECAR CSECT
USING MONTECAR,R13 base register
Line 127:
WP DS PL16 packed decimal 16
YREGS
END MONTECAR</langsyntaxhighlight>
{{out}}
<pre>
Line 139:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "H6:REALMATH.ACT"
 
DEFINE PTR="CARD"
Line 219:
Test(1000)
Test(10000)
RETURN</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
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;</langsyntaxhighlight>
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}}
<langsyntaxhighlight lang="algol68">PROC pi = (INT throws)REAL:
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))</langsyntaxhighlight>
{{out}}
<pre>
Line 298:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">Pi: function [throws][
inside: new 0.0
do.times: throws [
Line 307:
loop [100 1000 10000 100000 1000000] 'n ->
print [pad to :string n 8 "=>" Pi n]</langsyntaxhighlight>
 
{{out}}
Line 320:
{{AutoHotkey case}}
Source: [http://www.autohotkey.com/forum/topic44657.html AutoHotkey forum] by Laszlo
<langsyntaxhighlight lang="autohotkey">
MsgBox % MontePi(10000) ; 3.154400
MsgBox % MontePi(100000) ; 3.142040
Line 333:
Return 4*p/n
}
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# --- with command line argument "throws" ---
 
Line 348:
Pi = 3.14333
 
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{trans|Java}}
<langsyntaxhighlight lang="qbasic">DECLARE FUNCTION getPi! (throws!)
CLS
PRINT getPi(10000)
Line 374:
NEXT i
getPi = 4! * inCircle / throws
END FUNCTION</langsyntaxhighlight>
{{out}}
<pre>
Line 385:
=={{header|BASIC256}}==
{{works with|basic256|1.1.4.0}}
<langsyntaxhighlight lang="basic">
# Monte Carlo Simulator
# Determine value of pi
Line 407:
next i
 
print float(4*in_c/tosses)</langsyntaxhighlight>
{{out}}
<pre>
Line 418:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> PRINT FNmontecarlo(1000)
PRINT FNmontecarlo(10000)
PRINT FNmontecarlo(100000)
Line 430:
IF RND(1)^2 + RND(1)^2 < 1 n% += 1
NEXT
= 4 * n% / t%</langsyntaxhighlight>
{{out}}
<pre>
Line 441:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#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;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
class Program {
Line 502:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 514:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include<iostream>
#include<math.h>
Line 536:
cout<<""<<4*double(hit)/double(imax)<<endl; } // Print out Pi number
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defn calc-pi [iterations]
(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))))</langsyntaxhighlight>
 
{{out}}
Line 556:
</pre>
 
<langsyntaxhighlight lang="lisp">(defn experiment
[]
(if (<= (+ (Math/pow (rand) 2) (Math/pow (rand) 2)) 1) 1 0))
Line 565:
 
(pi-estimate 10000)
</syntaxhighlight>
</lang>
 
{{out}}
Line 573:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun approximate-pi (n)
(/ (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)))</langsyntaxhighlight>
 
{{out}}
Line 590:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">def approx_pi(throws)
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</langsyntaxhighlight>
{{out}}
<pre> 1000 samples: PI = 3.1
Line 607:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.math;
 
double pi(in uint nthrows) /*nothrow*/ @safe /*@nogc*/ {
Line 620:
foreach (immutable p; 1 .. 8)
writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p));
}</langsyntaxhighlight>
{{out}}
<pre> 10: 3.200000
Line 641:
 
===More Functional Style===
<langsyntaxhighlight lang="d">void main() {
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));
}</langsyntaxhighlight>
{{out}}
<pre> 10: 3.200000
Line 663:
From example at [https://www.dartlang.org/ Dart Official Website]
 
<langsyntaxhighlight lang="dart">
import 'dart:async';
import 'dart:html';
Line 714:
bool get isInsideUnitCircle => x * x + y * y <= 1;
}
</syntaxhighlight>
</lang>
{{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.
 
<langsyntaxhighlight lang="e">def pi(n) {
var inside := 0
for _ ? (entropy.nextFloat() ** 2 + entropy.nextFloat() ** 2 < 1) in 1..n {
Line 729:
}
return inside * 4 / n
}</langsyntaxhighlight>
 
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</langsyntaxhighlight>
Output:
3.1292
Line 774:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule MonteCarlo do
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)</langsyntaxhighlight>
 
{{out}}
Line 800:
=={{header|Erlang}}==
===With inline test===
<syntaxhighlight lang="erlang">
<lang ERLANG>
-module(monte).
-export([main/1]).
Line 818:
 
main(N) -> io:format("PI: ~w~n", [ monte(N) ]).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 830:
</pre>
===With test in a function===
<syntaxhighlight lang="erlang">
<lang ERLANG>
-module(monte2).
-export([main/1]).
Line 851:
 
main(N) -> io:format("PI: ~w~n", [ monte(N) ]).
</syntaxhighlight>
</lang>
{{out}}
<pre>Xcoord
Line 865:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM RANDOM_PI
 
Line 889:
MONTECARLO(1000000->RES) PRINT(RES)
MONTECARLO(10000000->RES) PRINT(RES)
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>
Line 900:
 
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function map MonteCarloPI (n,plot=false) ...
$ X:=random(1,n);
Line 915:
3.14159265359
>MonteCarloPI(10000,true):
</syntaxhighlight>
</lang>
 
[[File:Test.png]]
Line 922:
There is some support and test expressions.
 
<langsyntaxhighlight lang="fsharp">
let print x = printfn "%A" x
 
Line 942:
MonteCarloPiGreco 10000 |> print
MonteCarloPiGreco 100000 |> print
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 953:
Since Factor lets the user choose the range of the random generator, we use 2^32.
 
<langsyntaxhighlight lang="factor">USING: kernel math math.functions random sequences ;
 
: 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 ;</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="factor">10000 pi .
3.1412</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class MontyCarlo
{
Line 991:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,024:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">MODULE Simulation
IMPLICIT NONE
Line 1,058:
END DO
END PROGRAM MONTE_CARLO</langsyntaxhighlight>
 
{{out}}
Line 1,069:
</pre>
{{works with|Fortran|2008 and later}}
<langsyntaxhighlight lang="fortran">
program mc
integer :: n,i
Line 1,086:
pi = 4.d0 * dble( count( hypot(x(1,:),x(2,:)) <= 1.d0 ) ) / n
end function
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 23-10-2016
' compile with: fbc -s console
 
Line 1,121:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{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">
<lang Futhark>
import "futlib/math"
 
Line 1,188:
let inside = reduce (+) 0 bs
in 4.0f32*f32(inside)/f32(n)
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
'''Using standard library math/rand:'''
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,224:
fmt.Println(getPi(10000000))
fmt.Println(getPi(100000000))
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,269:
fmt.Println(getPi(10000000))
fmt.Println(getPi(100000000))
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad
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)</langsyntaxhighlight>
{{Out}}
<pre>Example:
Line 1,296:
Or, using foldM, and dropping sqrt:
 
<langsyntaxhighlight lang="haskell">import Control.Monad (foldM, (>=>))
import System.Random (randomRIO)
import Data.Functor ((<&>))
Line 1,318:
mapM_
(monteCarloPi >=> print)
[1000, 10000, 100000, 1000000]</langsyntaxhighlight>
{{Out}}
For example:
Line 1,327:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">FUNCTION Pi(samples)
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</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
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</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,368:
=={{header|J}}==
'''Explicit Solution:'''
<langsyntaxhighlight lang="j">piMC=: monad define "0
4* y%~ +/ 1>: %: +/ *: <: +: (2,y) ?@$ 0
)</langsyntaxhighlight>
 
'''Tacit Solution:'''
<langsyntaxhighlight lang="j">piMCt=: (0.25&* %~ +/@(1 >: [: +/&.:*: _1 2 p. 0 ?@$~ 2&,))"0</langsyntaxhighlight>
 
'''Examples:'''
<langsyntaxhighlight lang="j"> piMC 1e6
3.1426
piMC 10^i.7
4 2.8 3.24 3.168 3.1432 3.14256 3.14014</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class MC {
public static void main(String[] args) {
System.out.println(getPi(10000));
Line 1,407:
return 4.0 * inCircle / numThrows;
}
}</langsyntaxhighlight>
{{out}}
3.1396
Line 1,415:
3.14168604
{{works with|Java|8+}}
<langsyntaxhighlight lang="java">package montecarlo;
 
import java.util.stream.IntStream;
Line 1,458:
return (4.0 * inCircle) / numThrows;
}
}</langsyntaxhighlight>
{{out}}
3.1556
Line 1,468:
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight JavaScriptlang="javascript">function mcpi(n) {
var x, y, m = 0;
 
Line 1,487:
console.log(mcpi(100000));
console.log(mcpi(1000000));
console.log(mcpi(10000000));</langsyntaxhighlight>
<pre>3.168
3.1396
Line 1,496:
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 1,534:
);
});
})();</langsyntaxhighlight>
{{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:
<langsyntaxhighlight lang="sh"># In case gojq is used, trim leading 0s:
function prng {
cat /dev/urandom | tr -cd '0-9' | fold -w 10 | sed 's/^0*\(.*\)*\(.\)*$/\1\2/'
}
 
prng | jq -nMr -f program.jq</langsyntaxhighlight>
 
'''program.jq'''
<langsyntaxhighlight lang="jq">def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
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))" )</langsyntaxhighlight>
{{out}}
<pre>
Line 1,595:
=={{header|Jsish}}==
From Javascript ES5 entry, with PRNG seeded during unit testing for reproducibility.
<langsyntaxhighlight lang="javascript">/* Monte Carlo methods, in Jsish */
function mcpi(n) {
var x, y, m = 0;
Line 1,626:
mcpi(1000000) ==> 3.142124
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,633:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Printf
 
function monteπ(n)
Line 1,643:
p = monteπ(n)
println("$(lpad(n, 9)): π ≈ $(lpad(p, 10)), pct.err = ", @sprintf("%2.5f%%", abs(p - π) / π))
end</langsyntaxhighlight>
 
{{out}}
Line 1,654:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> sim:{4*(+/{~1<+/(2_draw 0)^2}'!x)%x}
 
sim 10000
Line 1,660:
 
sim'10^!8
4 2.8 3.4 3.072 3.1212 3.14104 3.14366 3.1413</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
fun mcPi(n: Int): Double {
Line 1,685:
n *= 10
}
}</langsyntaxhighlight>
Sample output:
{{out}}
Line 1,700:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
for pow = 2 to 6
n = 10^pow
Line 1,717:
end function
</langsyntaxhighlight>
 
{{out}}
Line 1,730:
=={{header|Locomotive Basic}}==
 
<langsyntaxhighlight lang="locobasic">10 mode 1:randomize time:defint a-z
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</langsyntaxhighlight>
 
[[File:Monte Carlo, 200 points, Locomotive BASIC.png]]
Line 1,751:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">
to square :n
output :n * :n
Line 1,768:
show sim 100000 10000 ; 3.145
show sim 1000000 10000 ; 3.140828
</syntaxhighlight>
</lang>
 
=={{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?)
<langsyntaxhighlight LSLlang="lsl">integer iMIN_SAMPLE_POWER = 0;
integer iMAX_SAMPLE_POWER = 6;
default {
Line 1,794:
llOwnerSay("Done.");
}
}</langsyntaxhighlight>
{{out}}
<pre>Estimating Pi (3.141593)
Line 1,807:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function MonteCarlo ( n_throws )
math.randomseed( os.time() )
 
Line 1,823:
print( MonteCarlo( 100000 ) )
print( MonteCarlo( 1000000 ) )
print( MonteCarlo( 10000000 ) )</langsyntaxhighlight>
{{out}}
<pre>3.1436
Line 1,832:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
We define a function with variable sample size:
<langsyntaxhighlight Mathematicalang="mathematica">MonteCarloPi[samplesize_Integer] := N[4Mean[If[# > 1, 0, 1] & /@ Norm /@ RandomReal[1, {samplesize, 2}]]]</langsyntaxhighlight>
Example (samplesize=10,100,1000,....10000000):
<langsyntaxhighlight Mathematicalang="mathematica">{#, MonteCarloPi[#]} & /@ (10^Range[1, 7]) // Grid</langsyntaxhighlight>
gives back:
<pre>10 3.2
Line 1,844:
10000000 3.14134</pre>
 
<langsyntaxhighlight Mathematicalang="mathematica">monteCarloPi = 4. Mean[UnitStep[1 - Total[RandomReal[1, {2, #}]^2]]] &;
monteCarloPi /@ (10^Range@6)</langsyntaxhighlight>
 
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:
<langsyntaxhighlight Wolframlang="wolfram Languagelanguage">MonkeyDartsPi[numberOfThrows_] := (
xyCoordinates = RandomReal[{0, 1}, {numberOfThrows, 2}];
InsideCircle = Length[Select[Total[xyCoordinates^2, {2}],#<=1&]] ;
4*N[InsideCircle / Length[xyCoordinates],1+Log10[numberOfThrows]])</langsyntaxhighlight>
 
We do several runs with a larger number of throws each time, increasing by powers of 10.
<langsyntaxhighlight Wolframlang="wolfram Languagelanguage">Grid[Table[{n, MonkeyDartsPi[n]}, {n, 10^Range[7]} ], Alignment -> Left]</langsyntaxhighlight>
 
We see that as the number of throws increases, we get closer to the value of Pi:
Line 1,875:
 
Minimally Vectorized:
<langsyntaxhighlight MATLABlang="matlab">function piEstimate = monteCarloPi(numDarts)
 
%The square has a sides of length 2, which means the circle has radius
Line 1,891:
 
end
</syntaxhighlight>
</lang>
 
Completely Vectorized:
<langsyntaxhighlight MATLABlang="matlab">function piEstimate = monteCarloPi(numDarts)
piEstimate = 4*sum( sum(rand(numDarts,2).^2,2) <= 1 )/numDarts;
 
end</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight MATLABlang="matlab">>> monteCarloPi(7000000)
 
ans =
 
3.141512000000000</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight Maximalang="maxima">load("distrib");
approx_pi(n):= block(
[x: random_continuous_uniform(0, 1, n),
Line 1,917:
4*cin/n);
float(approx_pi(100));</langsyntaxhighlight>
 
=={{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 / С/П</langsyntaxhighlight>
 
''Example:'' for n = ''1000'' the output is ''3.152''.
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import math, random
 
randomize()
Line 1,957:
for n in [10e4, 10e6, 10e7, 10e8]:
echo pi(n)</langsyntaxhighlight>
{{out}}
<pre>3.15336
Line 1,965:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let get_pi throws =
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</langsyntaxhighlight>
Example:
# get_pi 10000;;
Line 1,991:
=={{header|Octave}}==
 
<langsyntaxhighlight lang="octave">function p = montepi(samples)
in_circle = 0;
for samp = 1:samples
Line 2,006:
disp(montepi(l));
l *= 10;
endwhile</langsyntaxhighlight>
 
Since it runs slow, I've stopped it at the second iteration, obtaining:
Line 2,014:
=== Much faster implementation ===
 
<langsyntaxhighlight lang="octave">
function result = montepi(n)
result = sum(rand(1,n).^2+rand(1,n).^2<1)/n*4;
endfunction
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">MonteCarloPi(tests)=4.*sum(i=1,tests,norml2([random(1.),random(1.)])<1)/tests;</langsyntaxhighlight>
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}}
<langsyntaxhighlight lang="pascal">Program MonteCarlo(output);
 
uses
Line 2,055:
writeln (10**i, ' samples give ', MC_Pi(i):7:5, ' as pi.');
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>:> ./MonteCarlo
Line 2,066:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub pi {
my $nthrows = shift;
my $inside = 0;
Line 2,079:
}
 
printf "%9d: %07f\n", $_, pi($_) for 10**4, 10**6;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,087:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,112:
 
=={{header|PHP}}==
<syntaxhighlight lang="php"><?
<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);
?></langsyntaxhighlight>
{{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.</langsyntaxhighlight>
 
===List comprehension===
This is simpler, but slightly slower than using <code>while</code> loop.
<langsyntaxhighlight Picatlang="picat">sim2(N, F) = sum([apply(F) : _I in 1..N]).</langsyntaxhighlight>
 
===Recursion===
<langsyntaxhighlight Picatlang="picat">sim_rec(N,F) = S =>
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).</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight Picatlang="picat">go =>
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).</langsyntaxhighlight>
 
{{out}}
Line 2,179:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de carloPi (Scl)
(let (Dim (** 10 Scl) Dim2 (* Dim Dim) Pi 0)
(do (* 4 Dim)
Line 2,188:
 
(for N 6
(prinl (carloPi N)) )</langsyntaxhighlight>
{{out}}
<pre>3.4
Line 2,199:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<langsyntaxhighlight lang="powershell">function Get-Pi ($Iterations = 10000) {
$InCircle = 0
for ($i = 0; $i -lt $Iterations; $i++) {
Line 2,215:
| Add-Member -PassThru NoteProperty Pi $Pi `
| Add-Member -PassThru NoteProperty "% Difference" $Diff
}</langsyntaxhighlight>
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}}==
<langsyntaxhighlight PureBasiclang="purebasic">OpenConsole()
Procedure.d MonteCarloPi(throws.d)
Line 2,253:
 
PrintN("Press any key"): Repeat: Until Inkey() <> ""
</syntaxhighlight>
</lang>
{{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):
<langsyntaxhighlight lang="python">>>> import random, math
>>> 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</langsyntaxhighlight>
 
===As a program using a function===
<langsyntaxhighlight lang="python">
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>
</lang>
 
===Faster implementation using Numpy===
<langsyntaxhighlight lang="python">
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>
</lang>
 
=={{header|Quackery}}==
Line 2,318:
{{trans|Forth}}
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "bigrat.qky" loadfile ] now!
 
[ [ 64 bit ] constant
Line 2,332:
swap 20 point$ echo$ cr ] is trials ( n --> )
 
' [ 10 100 1000 10000 100000 1000000 ] witheach trials</langsyntaxhighlight>
 
{{out}}
Line 2,344:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r"># nice but not suitable for big samples!
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))</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang 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)))</langsyntaxhighlight>
{{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:
<langsyntaxhighlight lang="racket">#lang racket
(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)))</langsyntaxhighlight>
 
[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" perl6line>my @random_distances = ([+] rand**2 xx 2) xx *;
 
sub approximate_pi(Int $n) {
Line 2,465:
say "$_ iterations: ", approximate_pi $_
for 100, 1_000, 10_000;
</syntaxhighlight>
</lang>
{{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" perl6line>my @pi = ([\+] 4 * (1 > [+] rand**2 xx 2) xx *) Z/ 1 .. *;
say @pi[10, 1000, 10_000];</langsyntaxhighlight>
 
=={{header|REXX}}==
A specific─purpose commatizer function is included to format the number of iterations.
<langsyntaxhighlight 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.*/
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 _</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 2,531:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
decimals(8)
see "monteCarlo(1000) = " + monteCarlo(1000) + nl
Line 2,544:
t = (4 * n) / t
return t
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,553:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def approx_pi(throws)
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</langsyntaxhighlight>
{{out}}
<pre> 1000 samples: PI = 3.2
Line 2,569:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">extern crate rand;
 
use rand::Rng;
Line 2,601:
println!("{:9}: {:<11} dev: {:.5}%", samples, estimate, deviation);
}
}</langsyntaxhighlight>
{{out}}
<pre>Real pi: 3.141592653589793
Line 2,612:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object MonteCarlo {
private val random = new scala.util.Random
 
Line 2,638:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>10000 simulations; pi estimation: 3.1492
Line 2,647:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 2,672:
writeln(" 10000000: " <& pi( 10000000) digits 5);
writeln("100000000: " <& pi(100000000) digits 5);
end func;</langsyntaxhighlight>
 
{{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">
<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>
</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).
 
<syntaxhighlight lang="sequencel">
<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>
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func monteCarloPi(nthrows) {
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))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,761:
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">program define mcdisk
clear all
quietly set obs `1'
Line 2,777:
 
. mcdisk 100000000
3.1416253</langsyntaxhighlight>
 
=={{header|Swift}}==
{{trans|JavaScript}}
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
func mcpi(sampleSize size:Int) -> Double {
Line 2,806:
println(mcpi(sampleSize: 1000000))
println(mcpi(sampleSize: 10000000))
println(mcpi(sampleSize: 100000000))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,819:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc pi {samples} {
set i 0
set inside 0
Line 2,833:
foreach runs {1e2 1e4 1e6 1e8} {
puts "$runs => [pi $runs]"
}</langsyntaxhighlight>
result
<pre>PI is approx 3.141592653589793
Line 2,843:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
#import flo
 
mcp "n" = times/4. div\float"n" (rep"n" (fleq/.5+ sqrt+ plus+ ~~ sqr+ minus/.5+ rand)?/~& plus/1.) 0.</langsyntaxhighlight>
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:
<langsyntaxhighlight Ursalalang="ursala">#cast %eL
 
pis = mcp* <10,100,1000,10000,100000,1000000></langsyntaxhighlight>
{{out}}
<pre><
Line 2,879:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
 
Line 2,902:
Fmt.print("$9d -> $10.8f -> $6.4f", n, pi, err)
n = n * 10
}</langsyntaxhighlight>
 
{{out}}
Line 2,918:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Ran=1, CrLf=9;
code real RlOut=48;
 
Line 2,938:
RlOut(0, MontePi( 1_000_000)); CrLf(0);
RlOut(0, MontePi(100_000_000)); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 2,949:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn monty(n){
inCircle:=0;
do(n){
Line 2,956:
}
4.0*inCircle/n
}</langsyntaxhighlight>
Or, in a more functional style (using a reference for state info):
<langsyntaxhighlight lang="zkl">fcn monty(n){
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;
}</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.