python - 循环 float 范围

标签 python numpy floating-point

你能帮我解决这个问题吗?

代码:-

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/

相关文章:

c++ - clang 是否有 _ExtFloat 就像它有 _ExtInt 一样?

algorithm - 哪种浮点比较更准确,为什么?

c++ - 将 (ASCII) 字符字符串转换为 float - C/C++ 和 Matlab

python - wxPython 中的分组事件

python - Django 测试客户端 post() 返回 302,尽管 View 的 post() 出错

python - 打印列表时避免链式数字

python - (Python) 当 <a> 标记之间有两个文本时如何使用 driver.find_element_by_link_text

python - 使用 Python 将列中的值从 float 舍入到整数

python - 什么是 [Sci/Num]Python 相当于 Matlabs "norminv"(正态逆累积分布函数)

python - 矩阵的距离矩阵