简体   繁体   中英

How can you approximate the value of an infinite series in python?

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?

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.

n = 1
s = 0
while True:
    s  += 1/n**2
    n += 1
    print(s, end="\r")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM