Code kata: Monte Carlo method

| No Comments

Очень приблизительное вычисление числа Пи методом Монте Карло. В продолжение к 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";

Leave a comment

About this Entry

This page contains a single entry by Alex Kapranoff published on December 10, 2012 7:10 AM.

Code kata: running a DFA was the previous entry in this blog.

Code kata: решето Эратосфена is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Pages

  • about
Powered by Movable Type 5.2.6791-en-master-r6791-122a610d-20130202