RosettaCodeData/Task/Monte-Carlo-methods/Perl/monte-carlo-methods.pl

15 lines
283 B
Perl
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
sub pi {
my $nthrows = shift;
my $inside = 0;
foreach (1 .. $nthrows) {
2017-09-23 10:01:46 +02:00
my $x = rand() * 2 - 1;
my $y = rand() * 2 - 1;
2013-04-10 21:29:02 -07:00
if (sqrt($x*$x + $y*$y) < 1) {
$inside++;
}
}
return 4 * $inside / $nthrows;
}
2017-09-23 10:01:46 +02:00
printf "%9d: %07f\n", $_, pi($_) for 10**4, 10**6;