Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1,6 +1,22 @@
A '''Monte Carlo Simulation''' is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess."
A '''Monte Carlo Simulation''' is a way of approximating the value of a function
where calculating the actual value is difficult or impossible. <br>
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."
A simple Monte Carlo Simulation can be used to calculate the value for π. If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be π/4. So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately π/4.
A simple Monte Carlo Simulation can be used to calculate the value for π.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be π/4.
Write a function to run a simulation like this with a variable number of random points to select. Also, show the results of a few different sample sizes.
For software where the number π is not built-in, we give π to a couple of digits: 3.141592653589793238462643383280
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately π/4.
Write a function to run a simulation like this, with a variable number
of random points to select. <br>
Also, show the results of a few different sample sizes.
For software where the number π is not built-in,
we give π to a couple of digits:
3.141592653589793238462643383280

View file

@ -16,7 +16,7 @@ double pi(double tolerance)
}
val = (double) hit / sampled;
error = val * sqrt(val * (1 - val) / sampled) * 4;
error = sqrt(val * (1 - val) / sampled) * 4;
val *= 4;
/* some feedback, or user gets bored */

View file

@ -1,14 +1,14 @@
import std.stdio, std.random, std.math;
double pi(in int nthrows) {
int inside;
foreach (i; 0 .. nthrows)
if (hypot(uniform(0, 1.0), uniform(0, 1.0)) <= 1)
double pi(in uint nthrows) /*nothrow*/ @safe /*@nogc*/ {
uint inside;
foreach (immutable i; 0 .. nthrows)
if (hypot(uniform01, uniform01) <= 1)
inside++;
return 4.0 * inside / nthrows;
}
void main() {
foreach (p; 1 .. 8)
foreach (immutable p; 1 .. 8)
writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p));
}

View file

@ -1,9 +1,9 @@
import std.stdio, std.random, std.math, std.algorithm, std.range;
enum isIn = (int) => hypot(uniform(0, 1.0), uniform(0, 1.0)) <= 1;
enum pi = (in int n) => 4.0 * n.iota.count!isIn / n;
void main() {
import std.stdio, std.random, std.math, std.algorithm, std.range;
immutable isIn = (int) => hypot(uniform01, uniform01) <= 1;
immutable pi = (in int n) => 4.0 * n.iota.count!isIn / n;
foreach (immutable p; 1 .. 8)
writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p));
}

View file

@ -2,7 +2,7 @@ import System.Random
import Control.Monad
get_pi throws = do results <- replicateM throws one_trial
return (4 * fromIntegral (foldl' (+) 0 results) / fromIntegral throws)
return (4 * fromIntegral (foldl (+) 0 results) / fromIntegral throws)
where
one_trial = do rand_x <- randomRIO (-1, 1)
rand_y <- randomRIO (-1, 1)

View file

@ -0,0 +1,44 @@
package montecarlo;
import java.util.stream.IntStream;
import java.util.stream.DoubleStream;
import static java.lang.Math.random;
import static java.lang.Math.hypot;
import static java.lang.System.out;
public interface MonteCarlo {
public static void main(String... arguments) {
IntStream.of(
10000,
100000,
1000000,
10000000,
100000000
)
.mapToDouble(MonteCarlo::pi)
.forEach(out::println)
;
}
public static double range() {
//a square with a side of length 2 centered at 0 has
//x and y range of -1 to 1
return (random() * 2) - 1;
}
public static double pi(int numThrows){
long inCircle = DoubleStream.generate(
//distance from (0,0) = hypot(x, y)
() -> hypot(range(), range())
)
.limit(numThrows)
.unordered()
.parallel()
//circle with diameter of 2 has radius of 1
.filter(d -> d < 1)
.count()
;
return (4.0 * inCircle) / numThrows;
}
}

View file

@ -1,8 +1,8 @@
load(distrib);
load("distrib");
approx_pi(n):= block(
[x: random_continuous_uniform(0, 1, n),
y: random_continuous_uniform(0, 1, n),
r, cin: 0],
r, cin: 0, listarith: true],
r: x^2 + y^2,
for r0 in r do if r0<1 then cin: cin + 1,
4*cin/n);

View file

@ -1,10 +1,9 @@
sub approximate_pi (Int $sample_size) {
my Int $in = 0;
(rand - 1/2)**2 + (rand - 1/2)**2 < 1/4 and ++$in
for ^$sample_size;
return 4 * $in / $sample_size;
my @random_distances := ([+] rand**2 xx 2) xx *;
sub approximate_pi(Int $n) {
4 * @random_distances[^$n].grep(* < 1) / $n
}
say 'n = 100: ', approximate_pi 100;
say 'n = 1,000: ', approximate_pi 1_000;
say 'n = 10,000: ', approximate_pi 10_000;
say "Monte-Carlo π approximation:";
say "$_ iterations: ", approximate_pi $_
for 100, 1_000, 10_000;

View file

@ -1,6 +1,2 @@
sub approximate_pi (Int $sample_size) {
$sample_size R/ [+]
4 xx grep 0 ..^ 1/4,
(rand - 1/2)**2 + (rand - 1/2)**2 xx
$sample_size;
}
my @pi := ([\+] 4 * (1 > [+] rand**2 xx 2) xx *) Z/ 1 .. *;
say @pi[10, 1000, 10_000];

View file

@ -1,9 +0,0 @@
my @random_distances := ([+] rand**2 xx 2) xx *;
sub approximate_pi(Int $n) {
4 * @random_distances[^$n].grep(* < 1) / $n
}
say "Monte-Carlo π approximation:";
say "$_ iterations: ", approximate_pi $_
for 100, 1_000, 10_000;

View file

@ -1,4 +1,4 @@
import numpy as np
n = input('Number of samples: ')
print np.sum(np.random.rand(n)**2+np.random.rand(n)<1)/float(n)*4
print np.sum(np.random.rand(n)**2+np.random.rand(n)**2<1)/float(n)*4

View file

@ -1,36 +1,33 @@
/*REXX program uses the Monte Carlo method to compute pi÷4 */
/*REXX program computes pi÷4 using the Monte Carlo algorithm. */
parse arg times chunks . /*does user want a specific num? */
if times=='' then times=1000000000 /*one billion should do it. */
if chunks=='' then chunks=10000 /*do Monte Carle in 10k chunks. */
if times=='' then times=1000000000 /*one billion should do it. */
if chunks=='' then chunks=10000 /*do Monte Carlo in 10k chunks. */
limit=10000-1 /*REXX random gens only integers.*/
limitSq=limit**2 /*...so, instead of 1, use lim**2*/
limitSq=limit**2 /*···so, instead of 1, use lim**2*/
!=0 /*number of "pi hits" so far. */
accur=0 /*accuracy of the Monte Carlo pi.*/
if 1=='f1'x then piChar='pi' /*if EBCDIC, then use literal. */
else piChar='e3'x /*if ASCII, then use symbol. */
if 1=='f1'x then piChar='pi' /*if EBCDIC, then use literal. */
else piChar='e3'x /*if ASCII, then use pi symbol.*/
pi=3.14159265358979323846264338327950288419716939937511 /*da real McCoy*/
numeric digits length(pi) /*at least, we'll use these digs.*/
say 'real pi='pi"+" /*might was well brag about it. */
say /*just for the eyeballs. */
do j=1 for times%chunks
do chunks /*do Monte Carlo, chunk-at-a-time*/
if random(0,limit)**2+random(0,limit)**2<=limitSq then !=!+1
end
do j=1 for times%chunks
do chunks /*do Monte Carlo, chunk-at-a-time*/
if random(0,limit)**2 + random(0,limit)**2 <=limitSq then !=!+1
end /*chunks*/
reps=chunks*j /*compute number of repetitions. */
piX=4*!/reps /*let's see how this puppy does. */
_=compare(piX,pi) /*compare apples & ...crabapples.*/
if _<=accur then iterate /*if not better accuracy, pout. */
_=compare(piX,pi) /*compare apples & ···crabapples.*/
if _<=accur then iterate /*if not better accuracy, pout. */
say right(comma(reps),20) 'repetitions: Monte Carlo' piChar,
"is accurate to" _-1 'places.' /*subtract 1 for dec point.*/
accur=_ /*use this accuracy for baseline.*/
end /*j*/
end /*j*/
exit /*stick a fork in it, we're done.*/
/*────────────────────────────────COMMA subroutine──────────────────────*/
comma: procedure; parse arg _,c,p,t; arg ,cu; c=word(c ",",1)
if cu=='BLANK' then c=' '; o=word(p 3,1); p=abs(o); t=word(t 999999999,1)
if \datatype(p,'W') | \datatype(t,'W')|p==0|arg()>4 then return _; n=_'.9'
#=123456789; k=0; if o<0 then do; b=verify(_,' '); if b==0 then return _
e=length(_) - verify(reverse(_),' ') + 1; end; else do; b=verify(n,#,"M")
e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end
do j=e to b by -p while k<t; _=insert(c,_,j); k=k+1; end; return _
/*────────────────────────────────COMMA subroutine────────────────────────────────────────────────────────────────────────────────────*/
comma: procedure; parse arg _,c,p,t; arg ,cu; c=word(c ",",1); if cu=='BLANK' then c=' '; o=word(p 3,1); p=abs(o); t=word(t 999999999,1)
if \datatype(p,'W') | \datatype(t,'W') | p==0 | arg()>4 then return _; n=_'.9'; #=123456789; k=0; if o<0 then do; b=verify(_,' ')
if b==0 then return _; e=length(_) - verify(reverse(_),' ') + 1; end; else do;
b=verify(n,#,"M"); e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end; do j=e to b by -p while k<t; _=insert(c,_,j); k=k+1; end; return _