Number changing when inserted into list [duplicate]

☆樱花仙子☆ 提交于 2019-12-13 17:11:37

问题


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", working_weight
cells[working_cell_position][4] = working_weight
print "part b", working_weight, cells[working_cell_position][4], cells[working_cell_position]

and what it prints is this:

part a 62.4
part b 62.4 62.4 [6, 6, '', '', 62.400000000000006]

So if you didn't quite get it, basically I have the variable working_weight which is 62.4, but when I insert it into a list, it changes it to 62.400000000000006, yet if I only print that number from the list it prints as 62.4 still. If anyone could help, or suggest a solution to fix this it would be greatly appreciated.


回答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.




回答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')



回答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__?



来源:https://stackoverflow.com/questions/22429955/number-changing-when-inserted-into-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!