Python中舍入浮点数的问题 [英] Problems with Rounding Floats in Python
本文介绍了Python中舍入浮点数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
np.round出现问题,np.around不能正确舍入.我不能包含代码,因为当我手动设置值(相对于使用我的数据)时,返回有效,但这是输出:
I'm having a problem with np.round, np.around where it is not rounding properly. I can't include code, because when I do it manually set the value (as opposed to use the my data), the return works, but here is the output:
In [177]: a
Out[177]: 0.0099999998
In [178]: np.round(a,2)
Out[178]: 0.0099999998
In [179]: np.round(a,1)
Out[179]: 0.0
我想念什么? a的dtype是float32,我需要更改吗?
What am I missing? The dtype of a is float32, do I need to change this?
推荐答案
尝试创建np.float32(0.01)
,您将看到答案.您将获得已经可以达到的精度.
Try creating np.float32(0.01)
and you will see your answer. You are getting the precision you can already.
>>> import numpy as np
>>> x = 0.01
>>> epsilon = 0.01 - np.float32(0.01)
>>> for n in np.arange(x - 10*epsilon, x + 10*epsilon, epsilon):
... print(repr(np.float32(n)))
...
0.0099999979
0.0099999979
0.0099999979
0.0099999988
0.0099999988
0.0099999988
0.0099999988
0.0099999998
0.0099999998
0.0099999998
0.0099999998
0.0099999998
0.010000001
0.010000001
0.010000001
0.010000001
0.010000002
0.010000002
0.010000002
0.010000002
这篇关于Python中舍入浮点数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文