can't solve an exercise-help me with it

Michael J. Fromberger Michael.J.Fromberger at Clothing.Dartmouth.EDU
Thu Jan 12 00:34:12 EST 2006

In article <43c5e027$0$2459$edfadb0f at>,
 "hossam" <nono at> wrote:

> I'm studying python newly and have an exercise that is difficult for me as a 
> beginner.Here it is :
> "Write a program that approximates the value of pi by summing the terms of 
> this series:
> 4/1-4/3+4/5-4/7+4/9-4/11+.... The program should prompt the user for n, the 
> number of terms to sum and then output the sum of the first n terms of this 
> series."
> any help would be appreciated.
> benni

The series you're describing is basically expanding the Taylor series 
for 4 * atan(1), where

              oo     -1
   atan(1) =  SUM   ------
             i = 0  2i + 1

(or in LaTeX:  \sum_{i=0}^{\infty}\frac{-1^i}{2i+1})

To enumerate the terms of this series, you can treat i as a counter, and 
compute the numerator and denominator either directly or from their 
previous values.  The sum can be accumulated into a separate variable.  
So, for instance,

. sum = 0. ; num = 1. ; den = 1.
. for i in xrange(n):
.   sum += num / den
.   num = -num
.   den += 2
. pi = 4 * sum   # approximately...

Keep in mind that this approximation for atan(1) converges very slowly, 
so you will need to do quite a lot of terms before it will converge (you 
need about a thousand terms to get 2 significant figures after the 
decimal point).  You might have better results using Machin's formula, 

  atan(1) = 4 * atan(1/5) - atan(1/239)

Or, pi = 16 * atan(1/5) - 4 * atan(1/239).  The Taylor series will 
converge more quickly for atan(1/5) and atan(1/239).

(LaTeX: \mathrm{atan}(x) = \sum_{i=0}^\infty\frac{(-1^i)x^i}{2i+1})


Michael J. Fromberger             | Lecturer, Dept. of Computer Science  | Dartmouth College, Hanover, NH, USA

More information about the Python-list mailing list