[Tutor] A better way to estimate the value of Pi?

Steven D'Aprano steve at pearwood.info
Mon Oct 17 13:06:25 CEST 2011


Sagar Shankar wrote:
> Hi, this is my first question to this group. I'm a beginner to computer
> science and programming in Python. Am currently using John Zelle's book -
> Python Programming: An introduction to computer science to teach myself.

Hi Sagar, and welcome.

Can I ask you to please post code using plain text rather than HTML 
email (also known as "rich text"), as HTML email messes up the 
formatting? In this case, I can reverse-engineer the correct formatting, 
so no harm done other than a waste of time, but that won't always be so 
easy.


> In the book, there is an exercise to create a program that approximates the
> value of Pi by using the series [image: image.png]
> 
> Now, the only way I've been able to figure out how to do this is by creating
> pairs of 4/x - 4/x+2 and calculating the series. The problem is that the
> exercise asks to prompt the user for the number of terms to sum, and then
> output the sum. So if an user inputs just 1, then his answer should be 4/1,
> whereas in my version it will 4/1-4/3

The series looks like:

4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 +- ...

Three things stand out:

(1) The *numerator* of each term is always 4.

(2) The *denominator* of the terms are 1, 3, 5, ... or to put it another 
way, the term in position i has denominator 2*i+1 (starting with i=0).

(3) The *sign* of the terms are +1, -1, +1, -1, +1, ... If you remember 
your high school maths, (-1)**0 = +1, (-1)**1 = -1, (-1)**2 = +1, etc. 
So the term in position i has denominator (-1)**i.

Putting those three things together, the term in position i (starting 
with i=0) has value 4.0*(-1)**i/(2*i+1).

Does that help?


One other thing:

> import math
> seed = input("Please enter the number of pairs to calculate: ")

In Python 2, you shouldn't use input() for user input. It was a design 
mistake, which has now been fixed in Python 3, but in Python 2 you 
should use raw_input() instead.

The problem with input() is that it takes the user's input and *executes 
it as code*, which could have all sorts of bad side-effects starting 
with errors and just getting worse:

 >>> name = input("What is your name? ")
What is your name? Steven
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<string>", line 0, in ?
NameError: name 'Steven' is not defined

Instead, you should say this:


seed = int(raw_input("How many terms would you like? "))



-- 
Steven



More information about the Tutor mailing list