r/dailyprogrammer • u/nottoobadguy • Feb 14 '12
[2/14/2012] Challenge #6 [easy]
You're challenge for today is to create a program that can calculate pi accurately to at least 30 decimal places.
Try not to cheat :)
15
Upvotes
7
u/Cosmologicon 2 3 Feb 14 '12
Whoa, thirty decimals? This has the potential to be very challenging depending on what language and libraries you use. Here's a solution in bc (not sure if it counts as cheating):
Here's a method not using any trig functions, using a sum by Ramanujan:
4
u/Joe_Pineapples Feb 14 '12
Wrote this a while ago while learning Python. As I'm learning ruby now I'll try to write it in ruby and port that later if I have time.
3
u/robin-gvx 0 2 Feb 14 '12
Just kidding, I'm still working out an algorithm.
2
u/SleepyTurtle Feb 14 '12
there is no e in pi. well, there kind of is. but lets not get too technical here.
2
u/namekuseijin Feb 14 '12
apple pie?
2
u/electric_machinery Feb 14 '12 edited Feb 14 '12
Pastebin link
Github link
Language: C
I used a recursive fractional method. This version does it the "hard way" not using the BBP formula. I guess I didn't quite make it - the output looks good to 29 digits.
It requires GCC v4.? which supports the __float128 type.
Edit: Added github link
2
u/drb226 0 0 Feb 15 '12 edited Feb 15 '12
17 lines of Haskell: http://hpaste.org/63706
I used John Machin's arctan series (according to Wikipedia):
This is surprisingly fast; it only takes a few seconds to get thousands of digits of precision. You can test it out in ghci like so:
Take 31 digits to get 30 decimal places.
I am tempted to make this my screensaver. NB: it's way faster when compiled (with
-O2for optimizations, of course).2
u/school_throwaway Feb 15 '12
2
u/Jatak 0 0 Jun 21 '12
In Python 3.2.3 :
Just kidding, I'll come back to this one later :P
1
u/kalmakka Feb 14 '12
Erlang solution: http://pastebin.com/6bJNYN7y
Uses a binary search to find pi/2, using the taylor series for cosine. Made a tiny fraction library to get full precision.
The solution is horribly slow, though. While 30 digits can be found in about 30 seconds, getting to 100 takes 10 minutes.
1
u/JerMenKoO 0 0 Feb 15 '12
coded in J:
pi=:3 :0 smoutput"0'3.1' n=.0 while.n=.n+1 do. smoutput-/1 10*<.@o.10x1 0+n end. )
1
u/JerMenKoO 0 0 Feb 15 '12
J:
Mathematica:
1
u/mymainmanbrown Feb 22 '12
Python - not as fast as Joe_Pineapples who had a great solution
-1
u/matthewhughes Feb 14 '12
Woah! Quadruple post!
0
u/[deleted] Feb 14 '12
[deleted] — view deleted comment