0

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?

TGFoxy
  • 39
  • 5

2 Answers2

4

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.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Should note that you **should not** use list comprehensions here - use generators that save on memory. – Krish Jun 03 '20 at 17:32
  • Yup -- this example is a generator because there are no square brackets (`[]`). See https://stackoverflow.com/questions/364802/how-exactly-does-a-generator-comprehension-work – Samwise Jun 03 '20 at 18:19
2
n = 1
s = 0
while True:
    s  += 1/n**2
    n += 1
    print(s, end="\r")

Press Ctrl + C when you're happy! :)

RobC
  • 22,977
  • 20
  • 73
  • 80
najeem
  • 1,841
  • 13
  • 29