views:

265

answers:

3

I want to calculate the sum of

1/1 + 1/2 + 1/3 + ... + 1/30

I run the code unsuccessfully

import decimal
import math
var=decimal.Decimal(1/i)

for i in range(1,31):
   print(sum(var))

I get the error

'Decimal' object is not iterable

How can you make the iterable function in Python?

+11  A: 

What you want is this:

print(sum(decimal.Decimal(1) / i for i in range(1, 31)))

The reason your code doesn't work, is that you try to iterate over one Decimal instance (through the use of sum). Furthermore, your definition of var is invalid. Your intention was probably something like this:

var = lambda i: decimal.Decimal(str(1.0 / i))

(Note the use of str, Decimal does not permit a floating point argument). But even then your loop would not work, because the use of sum inside the loop is inherently flawed. sum should be used after the loop has created all fractions that you want to sum. So that would be either of:

print(sum(var(i) for i in range(1,31)))
print(sum(map(var, range(1, 31))))

For completeness, yet another way to do this is the following:

one = decimal.Decimal(1)
unitFractions = (one / i for i in itertools.count(1))
print(sum(itertools.islice(unitFractions, 30)))

However, as mentioned by gs, the fractions provides an alternative method that yields a fractional answer:

>>> unitFractions = (fractions.Fraction(1, i) for i in itertools.count(1))
>>> print(sum(itertools.islice(unitFractions, 30)))
9304682830147/2329089562800
Stephan202
Thank you for your answer!
Masi
+3  A: 

You write:

var=decimal.Decimal(1/i)

which is weird since 'i' is not defined at that point. How about:

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

Your mistake is, that decimal.Decimal(4) isn't a function, but an object.


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

Georg
I agree about Fraction. Decimal is just supposed to represent finite base-10 decimals. It won't represent stuff like 1/3 precisely. So why use it? Fraction is what you want to do arithmetic with fractions.
newacct