# 蒙地卡羅法求 PI

## 解法

from '/lib/math' import random
from '/lib/math' import pow

N = 50001
(sum = iterate(0, N)
.select(_ -> pow(random(), 2) + pow(random(), 2) < 1)
.length())

println('PI = {0}'.format(4 * sum / (N - 1)))

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 50001

int main(void) {
srand(time(NULL));

int sum = 0;

int i;
for(i = 1; i < N; i++) {
double x = (double) rand() / RAND_MAX;
double y = (double) rand() / RAND_MAX;
if((x * x + y * y) < 1) {
sum++;
}
}

printf("PI = %f\n", (double) 4 * sum / (N - 1));

return 0;
}

• Java
import static java.lang.Math.*;
public class MonteCarlo {
public static void main(String[] args) {
final int N = 50001;
int sum = 0;
for(int i = 1; i < N; i++) if(pow(random(), 2) + pow(random(), 2) < 1) {
sum++;
}
System.out.printf("PI = %f%n", 4.0 * sum / (N - 1));
}
}

from random import random
N = 50001
print("PI =", 4 * len([1 for i in range(1, N)
if random() ** 2 + random() ** 2 < 1]) / (N - 1))

• Scala
import java.lang.Math._
val N = 50000
printf("PI = %f%n", 4.0 * (for(i <- 1 to N
if(pow(random(), 2) + pow(random(), 2) < 1)) yield 1).size / N)

N = 50000
print "PI = ", 4.0 * (1...N).map {
rand ** 2 + rand ** 2 < 1 ? 1 : 0 }.reduce(:+) / N

Array.prototype.reduce = function(init, f) {
var value = init;
for(var i = 0; i < this.length; i++) {
value = f(value, this[i]);
}
return value;
};

function range(n) {
var r = [];
for(var i = 0; i < n; i++) {
r[i] = i;
}
return r;
}

var n = 50000;
print(4 * range(n).map(function() {
var x = Math.random();
var y = Math.random();
return x * x + y * y < 1 ? 1 : 0;
}).reduce(0, function(ac, elem) {
return ac + elem;
}) / n);

import System.Random

rand gen n= take n \\$ randomRs (0.0, 1.0) gen::[Float]

main = do
gen1 <- getStdGen
gen2 <- newStdGen
let n = 50000
ic = length [1 | (x, y) <-
zip (rand gen1 n) (rand gen2 n), (x ** 2 + y ** 2) < 1]
print (4 * fromIntegral ic / fromIntegral n)