Monte Carlo methods: Difference between revisions

Content added Content deleted
No edit summary
Line 1,983:
100000000: 3.14159
</pre>
 
=={{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
<lang sequenceL>
import <Utilities/Random.sl>;
import <Utilities/Conversion.sl>;
 
main(args(2)) := monteCarlo(stringToInt(args[1]), stringToInt(args[2]));
 
monteCarlo(n, seed) :=
let
totalHits := monteCarloHelper(n, seedRandom(seed), 0);
in
(totalHits / intToFloat(n))*4.0;
 
monteCarloHelper(n, generator, result) :=
let
xRand := getRandom(generator);
x := xRand.Value/(generator.RandomMax + 1.0);
yRand := getRandom(xRand.Generator);
y := yRand.Value/(generator.RandomMax + 1.0);
newResult := result + 1 when x^2 + y^2 < 1.0 else
result;
in
result when n < 0 else
monteCarloHelper(n - 1, yRand.Generator, newResult);
</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).
 
<lang sequenceL>
import <Utilities/Random.sl>;
import <Utilities/Conversion.sl>;
 
main(args(2)) := monteCarlo(stringToInt(args[1]), stringToInt(args[2]));
 
chunks := 100;
monteCarlo3(n, seed) :=
let
newSeeds := getRandomSequence(seedRandom(seed), chunks).Value;
totalHits := monteCarloHelper(n / chunks, seedRandom(newSeeds), 0);
in
(sum(totalHits) / intToFloat((n / chunks)*chunks))*4.0;
 
monteCarloHelper(n, generator, result) :=
let
xRand := getRandom(generator);
x := xRand.Value/(generator.RandomMax + 1.0);
yRand := getRandom(xRand.Generator);
y := yRand.Value/(generator.RandomMax + 1.0);
newResult := result + 1 when x^2 + y^2 < 1.0 else
result;
in
result when n < 0 else
monteCarloHelper(n - 1, yRand.Generator, newResult);
</lang>
 
=={{header|Sidef}}==