kalenpw kalenpw - 1 year ago 115
Python Question

Python 2 decimal division unexpected results

I am trying to do the calculation


Using the python decimal module with the following code:

from decimal import *
getcontext().prec = 9
sum = Decimal(0)
for i in range(1,11):
sum += Decimal(1/(i**4))
print sum

however, this outputs 1, not a very small fraction like I would expect. I can't find much information here https://docs.python.org/2/library/decimal.html about what is wrong with the code. My guess is sum is not being used as a Decimal in the loop, but I am unsure how to resolve that.

Answer Source

First of all, don't use sum as a variable name, as it is a built-in.
And its sort of necessary to provide at least one float for arithmetic if you expect a float-type answer, here:

s = Decimal(0)

for i in range(1,11):
  s += Decimal(1./(i**4)) # dividing 1. or 1.0 instead of just 1
print s

this gives:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download