Compute pi by using Gregory series

• (2 Pages)
• 1
• 2

16 Replies - 4105 Views - Last Post: 02 October 2012 - 01:17 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=293586&amp;s=d49269e89b74ea9e1b48194dd38a99a4&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#16 q81101

Reputation: 0
• Posts: 28
• Joined: 28-September 12

Re: Compute pi by using Gregory series

Posted 02 October 2012 - 12:39 PM

This is what mine look like:

http://postimage.org/image/rsqnz28tn/

#17 baavgai

• Dreaming Coder

Reputation: 6082
• Posts: 13,169
• Joined: 16-October 07

Re: Compute pi by using Gregory series

Posted 02 October 2012 - 01:17 PM

Hmm, was unaware integer math was no longer integer math in Python 3. Thanks for the info.

Here's how it would work in either system:
```>>> def pi1():
...     sum = 0.0
...     for i in range(1, 100000 +1):
...             n  = ( (-1) ** (i + 1) / (2.0 * i - 1) )
...             sum += n * 4.0
...             if(i % 10000 == 0):
...                     print("pi is {0}".format(sum))
...
>>>
>>> pi1()
pi is 3.14149265359
pi is 3.14154265359
pi is 3.14155932026
pi is 3.14156765359
pi is 3.14157265359
pi is 3.14157598692
pi is 3.14157836788
pi is 3.14158015359
pi is 3.14158154248
pi is 3.14158265359
>>>

```

I prefer the iterative approach.

So, by way of example:
```>>> def pi2():
...     sum, n, d = 1.0, 1.0, 1.0
...     for i in range(1, 100000 +1):
...             n, d = -n, d + 2.0
...             sum += n / d
...             if(i % 10000 == 0):
...                     print("pi is {0}".format(sum * 4))
...
>>>
>>> pi2()
pi is 3.14169264359
pi is 3.14164265109
pi is 3.14162598581
pi is 3.14161765296
pi is 3.14161265319
pi is 3.14160931998
pi is 3.1416069391
pi is 3.14160515343
pi is 3.14160376458
pi is 3.14160265349
>>>

```