Code kata: Monte Carlo method

  • Posted on
  • by

Очень приблизительное вычисление числа Пи методом Монте Карло. В продолжение к http://friendfeed.com/kkapp/b5d3658c.

#! /usr/bin/perl
use strict;
use warnings;

my $EPS = 0.001;

sub mt_pi {
	my $radius = shift;

	my ($prev, $cur) = (0, 100);
	my ($count, $count_in) = (0, 0);

	do {
		$prev = $cur;

		for (1 .. 500000) {
			my ($x, $y) = map
				{ rand $radius * 2 - $radius } 0..1;
			++$count;

			if (sqrt($x*$x + $y*$y) <= $radius) {
				++$count_in;
			}
		}

		$cur = 4 * $count_in / $count;
	} while (abs($prev - $cur) > $EPS);

	return $cur;
}

print mt_pi(1), "\n";