Tutorial :Unable to make an iterable decimal function in Python



Question:

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?


Solution:1

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  


Solution:2

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 )  


Solution:3

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »