Skip to content Skip to sidebar Skip to footer

Number Changing When Inserted Into List

I'm only going to paste part of my code since it's very long, but I was wondering if any one might know potential causes of this problem. So I have this code here: print 'part a',

Solution 1:

This is because floats are inherently imprecise in pretty much every language, as they cannot be represented easily in 64-bit binary at the lowest level. What is happening to your code has nothing to do with how it is put into the list or anything like that.

If you want to keep a precise decimal you should use decimal.Decimal.

>>> from decimal import Decimal
>>> working_weight = Decimal(str(working_weight))
>>> working_weight
Decimal('62.4')

This Decimal can then have operations performed on it like any float.


Solution 2:

Floating point math is tough, that's the problem. If you have decimals, use decimal.Decimal.

from decimal import Decimal

a = Decimal("30")
b = Decimal("32.4")
print(a+b)
# Decimal ('62.4')

Solution 3:

It's hard to say for sure without having a reproducible problem, but one way to get something similar is for example

import numpy
a = numpy.array([62.4], numpy.float)
print a[0]      # outputs 62.4
print [a[0]]    # outputs [62.399999999999999]

where is working_height coming from? What is working_height.__class__?


Post a Comment for "Number Changing When Inserted Into List"