Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wallis' formula for pi

def wallis(n):
    pi = 0.0

    for i in range(n):
        left = (2 * i)/(2 * i - 1)
        right = (2 * i)/(2 * i + 1)
        total = left * right
        pi = pi + total

    return pi

print wallis(1000)
print wallis(10000)
print wallis(100000)

I copied the formula exactly but I keep getting 0 as the output. Can someone please tell me what I am doing wrong. Python 2.7.

The link to the formula is here

like image 386
ShadyBears Avatar asked Apr 21 '26 21:04

ShadyBears


2 Answers

Python is doing integer division, and truncates the decimals. This is because both values to division are integers. Convert one of the numbers to a float to get a floating point value in return.

left = float(2 * i)/(2 * i - 1)
right = float(2 * i)/(2 * i + 1)

OR, as @kindall points out, you can change the constants to floats directly and avoid the call to the float function:

left = (2.0 * i)/(2 * i - 1) # just 2. works, too
right = (2.0 * i)/(2 * i + 1)

If/when you switch to python 3.x, you won't need to do this. In fact, you need to explicitly request integer division with //.

As per a comment by @Serdalis, you could also add from __future__ import division at the top of your file to get the same behavior as python 3.x (i.e. you won't need to add the float in your equation.)

like image 167
SethMMorton Avatar answered Apr 23 '26 11:04

SethMMorton


Apart from problem highlighted by @SethMMorton your formula is wrong. First it is a product not sum, second it gives pi/2 not pi. At last there is no reason to loop from 0.

def wallis(n):
    pi = 2.
    for i in xrange(1, n):
        left = (2. * i)/(2. * i - 1.)
        right = (2. * i)/(2. * i + 1.)
        pi = pi * left * right
    return pi
like image 40
zero323 Avatar answered Apr 23 '26 11:04

zero323



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!