I have heard that python can do infinite sums. For instance if I want to evaluate the infinite sum:
1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...
How should I go about? I am a newbie to python. So I would appreciate if someone could write out the entire code and if I need to include/import something.
For instance, in wolfram alpha if I input Summation (-1)^(n-1)/(2*n-1) from n=1 to infinity
it gives the answer as 0.785395
. I want the answer computed to a desired accuracy say, as in the case of wolfram alpha upto 6 digits.
Further, I was looking at this post here and tried to mimic that but it gives me the following errors:
`NameError: name 'Infinity' is not defined`
`NameError: name 'Inf' is not defined`
Thanks, Adhvaitha
The sum of infinite for an arithmetic series is undefined since the sum of terms leads to ±∞. The sum to infinity for a geometric series is also undefined when |r| > 1.
The Python sum() function calculates the total of all numerical values in an iterable. sum() works with both integers and floating-point numbers. The sum() function has an optional parameter to add a number to the total. alculating the sum of a list is a common operation in Python.
While it still is finite, you can approximate that series using the fractions
and decimal
modules:
from fractions import Fraction
from decimal import Decimal
repetitions = 100
d = 1
r = Fraction(1, d)
for n in range(repetitions):
r += Fraction(1, d) - Fraction(1, d + 2)
d += 4
print(Decimal(r.numerator)/Decimal(r.denominator))
I think this comes closest to what you want to do.
Python has unlimited precision integers, but not unlimited precision floats. There are packages you can use that provide that, though.
And nothing can "complete" an infinite sum, since it involves an infinite number of steps. You'll need to find a closed form for the sum, and then evaluate that, or accept an approximation achieved by terminating the infinite sum when a precision criterion is met.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With