插入到列表中时编号改变 [英] Number changing when inserted into list

查看:143
本文介绍了插入到列表中时编号改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只会粘贴部分代码,因为它很长,但我想知道是否有人可能知道这个问题的潜在原因。所以我在这里有这样的代码:

pre $ c $ print $打印part a,working_weight
cells [working_cell_position] [4] = working_weight
printpart b,working_weight,cells [working_cell_position] [4],cells [working_cell_position]



$ p
$ b $ $ $ $ $ $ $ $ $ $ $ $ $' ,'','','62.400000000000006]

所以如果你不太明白,有变量 working_weight 它是 62.4 ,但是当我将它插入到列表中时,它将它更改为 62.400000000000006 ,但是如果我只从列表中打印这个数字,它仍会打印为 62.4 。如果有人可以帮忙,或建议一个解决方案来解决这个问题,将不胜感激。

解决方案

这是因为 float 在几乎每种语言中本质上都是不精确的,因为它们不能在最低级别以64位二进制表示。你的代码发生了什么事,与如何将它放入 list 或类似的东西没有任何关系。



如果你想保留一个精确的小数,你应该使用 decimal.Decimal

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

这个 code>然后就可以对其执行操作,就像任何 float


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.

解决方案

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.

这篇关于插入到列表中时编号改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆