Skip to content

Examples


Estimating Pi, π, with Monte Carlo

  • Check out page 3 of this document (PDF) for more info.
  • Increase the number of iterations or samples to obtain a more precise value.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
let number_of_iterations = 25;
let number_of_samples = 500;
let radius = 200;
let radius_squared = power(radius, 2);
let sample_space = linspace(0, radius, 10000);
let pi = 0;

for(let i = 0; i < number_of_iterations; i = i + 1) {
    let x_array = random_choose(sample_space, number_of_samples);
    let y_array = random_choose(sample_space, number_of_samples);

    let count = 0;
    for(let k = 0; k < number_of_samples; k = k + 1) {
        let distance_squared = power(x_array[k], 2) + power(y_array[k], 2);
        if (distance_squared <= radius_squared) {
            // Inside circle
            count = count + 1;
        }
    }
    pi = pi + count / number_of_samples;
    println 4 * pi /number_of_iterations;
}

Using FFT for polynomial multiplication

Laziness strikes again

Placeholder


Fibonacci (Slow)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fn fibonacci_slow(n) {
    if (n <= 1) {
        return n;
    }
    return fib(n - 2) + fib(n - 1);
}

for (let i = 0; i < 20; i = i + 1) {
    println fibonacci_slow(i);
}

Fibonacci (Fast)

1
2
3
4
5
6
7
8
let a = 0;
let temp = 0;

for (let b = 1; a < 10000; b = temp + b) {
    println a;
    temp = a;
    a = b;
}