From 24e6f3d1c93aacfd2606f5625029e4e26b37cff0 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Fri, 18 Sep 2020 22:07:30 +0300 Subject: Added a pi estimation script --- Perl/pi.pl | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Perl/pi.pl diff --git a/Perl/pi.pl b/Perl/pi.pl new file mode 100644 index 0000000..263b312 --- /dev/null +++ b/Perl/pi.pl @@ -0,0 +1,36 @@ +#!/usr/bin/perl +#!/data/data/com.termux/files/usr/bin/perl + +if (grep(/^$ARGV[0]$/, ('h', '-h', '--help'))) { + print "m.pl MAX_VALUE TOTAL_PAIRS\n"; + exit; +} + +($max_val, $total) = (shift // 120, shift // 500); + +print "PI estimate: " . est_pi($max_val, $total) . " with $total numbers between 0 and $max_val.\n"; + +sub est_pi($$) { + my ($MAX_VAL, $TOTAL) = @_; + my $total_coprime; + + foreach (1 .. $TOTAL) { + my $gcd = gcd_iter(rnd_int($MAX_VAL), rnd_int($MAX_VAL)); + + $total_coprime += ($gcd == 1); + } + + return sqrt(6/($total_coprime/$TOTAL)); +} + +sub rnd_int($) { + return int(rand(shift) + 0.5); +} + +sub gcd_iter($$) { + my ($u, $v) = @_; + while ($v) { + ($u, $v) = ($v, $u % $v); + } + return abs($u); +} -- cgit v1.2.3