Friday, April 16, 2010

Leibniz script

I've been reading Martin Davis' Engines of Logic. I learned that when he was younger than I am now, Leibniz cleverly figured out the following is true:



π/4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11)...


The quantity on the left is pi divided by 4. Pi is the ratio of a circle's circumference to its diameter in Euclidean space. You may remember from trigonometry that π/4 radians equals 45 degrees.

The quantity on the right is an infinite series. It's meant to continue, so "... + (1/13) - (1/15) + (1/17)..." all the way up to infinity. Naturally one cannot continue to do this to infinity, though one can do it as long as he likes. In fact, the more terms you add to the equation, the closer the result comes to π/4.

Anyway, I was bored and (more importantly) drunk, so I wrote a Perl script to do just that.

$x = 1;
$total = 1;
$i = 1;
$flip = 2;

print "How many terms do you want to go out to?\n";
chomp($input = <STDIN>);

($sec,$min,$hour,$mday,$mon,$year,$wday,
$yday,$isdst)=localtime(time);
print "\nStart time:\n";
printf "%4d-%02d-%02d %02d:%02d:%02d\n",
$year+1900,$mon+1,$mday,$hour,$min,$sec;
$starttime=time;

while ($i < $input)
{ $x = (-1 * ($x + $flip)); $total = $total + (1/$x); $i = $i + 1; $flip = -1 * $flip; }

print "Finish time:\n"; ($sec,$min,$hour,$mday,$mon,$year,$wday, $yday,$isdst)=localtime(time); printf "%4d-%02d-%02d %02d:%02d:%02d\n\n", $year+1900,$mon+1,$mday,$hour,$min,$sec; $finishtime=time;

print "Operation accomplished in ", ($finishtime - $starttime), " seconds.\n\n"; print "Final term is 1/$x\n"; print "Total is $total\n";

My computer was able to calculate the result using 10,000,000 terms in 6 seconds with a result of 0.785398138397448. It did 100,000,000 terms in 61 seconds with a result of 0.785398160897331. It did 1,000,000,000 terms in 629 seconds with a result of 0.785398163147013. I have a 64-bit 2.8ghz AMD. I'd be curious to hear what kind of processor you have and how fast it did the calculation.

There might be a way to make the program run faster. I'm a beginner Perl programmer and probably didn't do it the best way.

This serves no purpose, which is why I was tempted to do it in the first place. I suppose it might serve as a "reality check" of sorts: despite appearances to the contrary, computers are nothing more than extremely fast calculators. Well, not "nothing more" exactly. Calculators aren't (usually) programmable. But computers do what they do by translating your instructions into numbers and doing binary arithmetic with them. The fact that there are such machines and that arithmetic can produce such results is perhaps worthy of thought. That seems to be Davis' point. Though if you're really interested in your computer qua calculator, I would advise you to ignore my badly written program and go find some Mersenne primes instead.

No comments: