Happy PI Day
3.1415926535...
How could one miss this? It's PI day today. Here's a slow converging approximation of PI:
[weiqi@gao] $ cat PI.java
public class PI {
public static void main(String[] args) {
double sum = 0.0d;
for (int i = 1; i < 64000; i++) {
sum += 6.0/(i*i);
}
System.out.println(Math.sqrt(sum));
}
}
[weiqi@gao] $ javac PI.java
[weiqi@gao] $ java PI
3.1415525815597167
Update: Kyle Cordes, in a trackback, expresses the above algorithm in one line of Ruby:
ruby -e "print (1..64000).inject(0.0) { | sum, i | sum + 6.0 / (i*i) } ** 0.5"
3.141577732895
This is indeed shorter than the Java code but not necessarily easier to comprehend. For example, what does ".inject() {| | }" do?
The clearest expression I can think of is in Mathematica:
In[1] := N[Sqrt[Sum[6/n^2, {n, 1, Infinity}]]] Out[1] = 3.14159
The equivalent python code is almost as elegent:
python -c "print sum(6.0/(i*i) for i in range(1, 64000))**0.5" 3.14157773266
Slightly longer, but still shorter than the Ruby code is Common Lisp
clisp -x -q '(sqrt (loop for x from 1 to 64000 sum (/ 6.0 (* x x))))' 3.141363
And the shortest of them all, (drum roll...) belongs to Perl (of course)
perl -e '(∑n=1∞6/n2)½'
Just kidding. :)
Re: Happy PI Day
>> For example, what does ".inject() {| | }" do?
The funny thing about this is that I knew what "inject" meant from having used it in another language, thought of it immediately when I saw your post, and was pleased to see that Ruby had it.
Inject is a common and useful idiom. A great meta-point of this is that if Ruby (or many other "programmable" programming languages) didn't have such an idiom, it could be added. There are people who object to doing so, but I find that to be pretty silly - the essence of programming is building abstractions.
Of all the examples you showed, I like the Python one the best - this is a great use of the "list comprehension" idea.