你能帮我解决这个问题吗?
代码:-
import numpy as np
def test(numList):
yesList=[]
for num in numList:
print num, "start here"
for i in np.arange(2.0,3.0,0.1):
print i
if num==i: yesList.append(num)
return yesList
打印测试([2.1,2.3,3.0])
输出:-
2.1 start here
2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
2.3 start here
2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
3.0 start here
2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
[2.1]
我希望它打印 [2.1,2.3]
但它只给我 [2.1]
,如图所示。
最佳答案
简单的回答是,您正在使用浮点(不精确)数字并期望得到精确的结果,但这最终会失败。长答案要复杂得多,但首先请看 this site's floating-point FAQ 中的第一项。 : Is floating point math broken? (这是一个 JavaScript 问题,但它同样适用于所有语言。)
关于python - 循环 float 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11928557/