aboutsummaryrefslogtreecommitdiff
path: root/Perl/pi.pl
diff options
context:
space:
mode:
authorSyndamia <kamen.d.mladenov@protonmail.com>2020-09-18 22:07:30 +0300
committerSyndamia <kamen.d.mladenov@protonmail.com>2020-09-18 22:07:30 +0300
commit24e6f3d1c93aacfd2606f5625029e4e26b37cff0 (patch)
tree09ef8f132a898732d453b86e76e267427effb117 /Perl/pi.pl
parent2c63f2b94833bcf6d92aad883fffe4cc61e009ef (diff)
downloadalgorithms-24e6f3d1c93aacfd2606f5625029e4e26b37cff0.tar
algorithms-24e6f3d1c93aacfd2606f5625029e4e26b37cff0.tar.gz
algorithms-24e6f3d1c93aacfd2606f5625029e4e26b37cff0.zip
Added a pi estimation script
Diffstat (limited to 'Perl/pi.pl')
-rw-r--r--Perl/pi.pl36
1 files changed, 36 insertions, 0 deletions
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);
+}