#!/usr/bin/perl
# This is a quick program to calculate pi using the Monte Carlo method.
# I recomend inputting a value for $cycles greater that 1000.
# I am working on a detailed explanation of how and why this works.
# I will add it as soon as I'm done.
use strict;
open(PI, ">>pi.dat") || die "pi.dat";
my ($i, $j, $yespi, $pi) = 1;
my $cycles = 1;
srand;
while ($j <= 100000) {
$cycles = $j;
while ($i <= $cycles) {
my ($x, $y, $cdnt) = 1;
$x = rand;
$y = rand;
$cdnt = $x**2 + $y**2;
if ($cdnt <= 1) {
++$yespi;
}
$i=$i + 10;
$pi = ($yespi / ($cycles / 10)) * 4; # since I add 10 every time.
print PI "$cycles $pi\n";
}
$j = $j + 10;
}
close(PI) || die "pi.dat";