Can't do an iterable decimal function in Python
I want to calculate the amount
1/1 + 1/2 + 1/3 + ... + 1/30
I am running the code unsuccessfully
import decimal
import math
var=decimal.Decimal(1/i)
for i in range(1,31):
print(sum(var))
I am getting the error
'Decimal' object is not iterable
How can you make an iterative function in Python?
a source to share
What you want is this:
print(sum(decimal.Decimal(1) / i for i in range(1, 31)))
The reason your code is not working is because you are trying to iterate over one instance Decimal
(using sum
). Also, your definition var
is wrong. Perhaps your intention was something like this:
var = lambda i: decimal.Decimal(str(1.0 / i))
(Note that using str
, Decimal
does not allow floating point argument). But even then, your loop will fail, because using sum
within a loop is inherently flawed. sum
should be used after the cycle has created all the fractions you want to sum. So it will either:
print(sum(var(i) for i in range(1,31)))
print(sum(map(var, range(1, 31))))
For completeness, another way to do it:
one = decimal.Decimal(1) unitFractions = (one / i for i in itertools.count(1)) print(sum(itertools.islice(unitFractions, 30)))
However, as gs mentioned , fractions provides an alternative method that gives a fractional answer:
>>> unitFractions = (fractions.Fraction(1, i) for i in itertools.count(1))
>>> print(sum(itertools.islice(unitFractions, 30)))
9304682830147/2329089562800
a source to share