Last active
January 18, 2018 07:34
-
-
Save rijesha/d74802badf35c47cb6651cddc05dade6 to your computer and use it in GitHub Desktop.
Probabilistically Calculating pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Probabilistically Calculating pi with C# | |
using System; | |
using System.Math; | |
class MainClass { | |
public static void Main (string[] args) { | |
int total_iterations = 100000000; | |
int count_inside_quarter_circle = 0; | |
var r = new Random(); | |
for (int i = 0; i < total_iterations; i++){ | |
double x = r.NextDouble(); | |
double y = r.NextDouble(); | |
if (Sqrt(Pow(x,2) + Pow(y,2)) < 1) | |
count_inside_quarter_circle++; | |
} | |
Console.WriteLine((double)4*count_inside_quarter_circle/total_iterations); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(*Probabilistically Calculating pi with OCaml*) | |
let f x = float_of_int x in | |
let hyp a b = sqrt((a *. a ) +. (b *. b)) in | |
let randcheck () = hyp (Random.float 1.0) (Random.float 1.0) < 1.0 in | |
let total_iterations = 1000000 in | |
let count_inside_quarter_circle = ref 0 in | |
for i = 1 to total_iterations do | |
let a = if (randcheck ()) then 1 else 0 in | |
count_inside_quarter_circle := !count_inside_quarter_circle + a; | |
done; | |
print_string (string_of_float ( 4.0 *. ( (f !count_inside_quarter_circle) /. (f total_iterations) )));; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Probabilistically Calculating pi with python | |
from math import * | |
from random import * | |
total_iterations = 1000000 | |
count_inside_quarter_circle = 0 | |
for i in range(total_iterations): | |
x = random() | |
y = random() | |
if sqrt(pow(x,2) + pow(y,2)) < 1: | |
count_inside_quarter_circle = count_inside_quarter_circle + 1 | |
print(4*count_inside_quarter_circle/total_iterations) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment