0

my teacher gave this assignment asking to estimate pi at different values of "i". i can get the first value of 4.0000 just fine but when i try for 101 i get 0.5024. Im honestly drawing a total blank here and the other questions on this site use a slightly different equation for estimation

here's my code:

num = 1

def m(i):  
    answer = 0  
    for k in range(num):   
        answer+=((-1)**(i+1)/(2*i-1))  
    return answer  

and the question:

m(i) = 4*(1-1/3+1/5-1/7+1/9-1/11+⋯+〖(-1)〗^(i+1)/(2*i-1))

Your task: Write a function that returns m(i) for a given i and write a test program that displays the following table

i    m(i)
1    4.0000 
101  3.1515  
201  3.1466  
301  3.1449  
401  3.1441  
501  3.1436  
601  3.1433  
701  3.1430  
801  3.1428  
901  3.1427  

any help is appreciated and please excuse my inability to format on here (i'm new)

3 Answers 3

3

Look closely at your iteration:

for k in range(num):   
    answer+=((-1)**(i+1)/(2*i-1))  

You're iterating over k, but k appears nowhere in the loop body. That can't be right.

Sign up to request clarification or add additional context in comments.

Comments

1

To add to Jakob's answer, your for loop starts at k=0, to estimate pi you have to start at k=1.

I.e. change for k in range(num): to for k in range(1,num + 1):

Comments

0

This seems to produce the correct result:

def m(num):  
    answer = 0          
    for i in range(num):
        answer+=(-1)**i*1/(2.0*i+1.0)       
    return answer  

for i in [1,101,201,301,401,501,601,701,801,901]:
    print i,"%.4f" % (4*m(i))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.