0

I am trying to calculate the value for Pi using Taylor Series. Below is the code that I have, but when I run the program I get a list of 1's and 0's.

Here is my code:

from math import *
import numpy as np

n= 100
x= 1
series = []

for i in range(0,n):
    value = (x**(2*i+1)*(-1)**i)/(2*i+1)
    series.append(value)

print series    
Nathan Neven
  • 37
  • 1
  • 2
  • 11
  • As a note, when using range to index a for loop, for memory purposes, it is typically better to use `xrange` rather than `range`. This link talks about it more: http://stackoverflow.com/questions/135041/should-you-always-favor-xrange-over-range. Also, for both `range` and `xrange`, the default lower index is 0 so you can replace `range(0,n)` with `range(n)` (or better `xrange(n)`). – Steven C. Howell Mar 13 '15 at 00:46

2 Answers2

1

The error message is telling you all you need to know. You are trying to divide two lists even though you might not think it looks like it. [] in Python indicate a list, even though they can be used as brackets in real math. All you have to do is change

value = [x**(2*i+1)*(-1)**i]/[2*i+1]

to

value = (x**(2*i+1)*(-1)**i)/(2*i+1)
michaelpri
  • 3,521
  • 4
  • 30
  • 46
0

I believe you're running into the same issue as this one, which is trying to divide one list by another list. Take a look at the suggestions there and I think you'll find your answer.

Community
  • 1
  • 1
trmiller
  • 183
  • 5