Jump to content

Monte Carlo methods: Difference between revisions

(PureBasic)
Line 243:
 
=={{header|D}}==
D V.2.
<lang d>
<lang d>import std.stdio:, writeflnstd.random, std.math;
import std.random: rand;
 
double pi(int nthrows) {
int inside;
forforeach (int i; i0 <.. nthrows; i++) {
doubleif r1(uniform(0,1.0) =^^ rand2 + uniform(0,1.0) /^^ cast(double2 <= 1)uint.max;
double r2 = rand() / cast(double)uint.max;
if (r1*r1 + r2*r2 <= 1.0)
inside++;
}
return 4.0 * inside / nthrows;
}
 
void main() {
foreach (p; 1 .. 9)
for (int n = 10_000; n <= 100_000_000; n *= 10)
writefln("%9d11s: %07f", n10 ^^ p, pi(n10 ^^ p));
}</lang d>
}
</lang>
 
Sample output:
<pre>
100000 10: 32.137760400000
1000000 100: 3.143508200000
10000000 1000: 3.140836136000
100000000 10000: 3.141666170000
100000: 3.141680
</pre>
1000000: 3.141884
For much faster results you can use the pseudorandom generator of Tango, or another one like R250-521.
10000000: 3.141182
100000000: 3.141838</pre>
 
=={{header|E}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.