kalenpw - 8 months ago 56
Python Question

# Python 2 decimal division unexpected results

I am trying to do the calculation

$\sum_{n=1}^{\10} \frac{1}{n^4}$

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.

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:

``````1.08203658
``````
Source (Stackoverflow)