0

I am trying to do the calculation

formula

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.

Community
  • 1
  • 1
kalenpw
  • 695
  • 3
  • 10
  • 34
  • If you're using code from a Python 3 textbook in Python 2, skim any of the articles on the key differences. The [What's New in Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) or any of the others. Being aware of the differences upfront will save you hours of headscratching... – smci Oct 14 '16 at 05:13

2 Answers2

3

If you use Python 2.x, then in the expression: 1/(i**4), the integer devision is used, as result for i=1, it equals to 1 and for all other i>1, it gets 0.

Just add floating point to 1: 1./(i**4), this should fix the problem.

PS In Python 3.x, your code should work as expected, because operator / is defined on floating point numbers, while operator // is defined for integers.

Slava
  • 827
  • 5
  • 13
  • 1
    Yeah this was done in 2.7, I should have included that in the question. Thanks for the tidbit on it working in 3 I will have to start using 3 more often. – kalenpw Oct 14 '16 at 04:44
2

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
lycuid
  • 2,555
  • 1
  • 18
  • 28
  • Ah, thank you that did the trick. Didn't know about sum or needing to include a float. Thanks for the quick answer I will accept it in 7 minutes – kalenpw Oct 14 '16 at 04:42
  • @kalenpw: Note that even so you're not getting the full precision of the `Decimal` type since you're only converting a `float` to `Decimal` (*after* the calculation). If you want high precision, you need to do `s += Decimal(1)/Decimal(i**4)`. – Tim Pietzcker Oct 14 '16 at 05:27