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

Sagar Shankar sagar at scubed.in
Tue Oct 18 07:28:36 CEST 2011


Hi Steven,

> 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.

Sure Steve, will do so from now on

>
> 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?

It does! I wonder why this simplification never occurred to me. Will
implement this and try it out

> 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? "))
>

Absolutely. I was just following Zelle's book and he introduces
raw_input in the 4th chapter only. I will definitely use the raw_input
method, especially as using "input" alone trips up string input

Thanks a lot for the help Steve,

Sagar


More information about the Tutor mailing list