Reputation: 39
I am messing about and wanted to use python to evaluate the following series
1/1^2 + 1/2^2 + 1/3^2 + .....
Any suggestions on how to do this?
Upvotes: 0
Views: 240
Reputation: 1921
n = 1
s = 0
while True:
s += 1/n**2
n += 1
print(s, end="\r")
Press Ctrl + C when you're happy! :)
Upvotes: 2
Reputation: 71424
Computers do math pretty fast. Just give it a big number:
>>> sum(1/n**2 for n in range(1, 1000000))
1.64493306684777
If you want it to be within a specific level of precision, you could make this a little more complicated by iterating until the difference in successive answers gets below a certain threshold. If you don't care about the exact precision or the exact runtime, just pick a number that's arbitrarily "big enough" but not so big that it'll take "too long". I just arbitrarily said "a million" in the above example, which makes it accurate to more decimal places than you're likely to care about and still takes well under a second.
Upvotes: 4