http://qs321.pair.com?node_id=159377

A friend was talking about computing PI, so wrote this script to compute it.

#!/usr/bin/perl -w #Compute pi. Based on Leibniz's algorithm that # pi = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11... use strict; my $pi = 4; my $next_digits = get_leibniz(); for ( 1 .. 100000 ) { my ( $subtract, $add ) = &$next_digits; $pi = $pi - $subtract + $add; } print $pi; sub get_leibniz { my $index = 1; my $sub = sub { $index += 2; my $first = 4/$index; $index += 2; my $second = 4/$index; return ($first, $second); }; return $sub; }

I can reduce that down to this:

$p=4;$n=l();for(1..100000){($s,$a)=&$n;$p=$p-$s+$a}print$p; sub l{$i=1;sub{$i+=2;$f=4/$i;$i+=2;$q=4/$i;($f,$q)}}

112 strokes. Admittedly, I'm rotten at golf. Any takers? No trig functions allowed :)

Update: I took four strokes off by eliminating a space and three superfluous semi-colons. Also, my answer is only correct to 5 digits. I could increase the second value in the for range, but that takes too long. Hadn't really thought about dealing with accuracy. Hmm...

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.