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?

0


a source to share


3 answers


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

      

+11


a source


You write:

var=decimal.Decimal(1/i)

      



which is odd since the "i" is undefined at this point. What about:

one = decimal.Decimal( "1" )
total = decimal.Decimal( "0" )
for i in range( 1, 31 ):
    total += one / decimal.Decimal( "%d" % i )

      

+3


a source


Your mistake is that decimal.Decimal(4)

it is not a function, but an object.


BTW: It looks like Fractions (Python 2.6) is what you really need.

+2


a source







All Articles