np.arange与浮点参数无法正常工作 [英] np.arange does not work as expected with floating point arguments

查看:257
本文介绍了np.arange与浮点参数无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试一下:

import numpy as np
np.arange(0,3*0.1,0.1)

输出将是: array([0.,0.1,0.2,0.3])

Output will be: array([ 0. , 0.1, 0.2, 0.3])

这是不可思议的,因为对于np.arange,值是在半开间隔内生成的值(开始,停止)".我尝试了其他数字,发现只有3的倍数会触发这种现象:

This is incredible because for np.arange 'Values are generated within the half-open interval [start, stop)'. I tried other numbers and found only the multiples of 3 would trigger such phenomenon:

np.arange(0,2*0.1,0.1).shape
# 2
np.arange(0,3*0.1,0.1).shape
# 4
np.arange(0,4*0.1,0.1).shape
# 4
np.arange(0,5*0.1,0.1).shape
# 5
np.arange(0,6*0.1,0.1).shape
# 7

我现在很困惑.有人可以帮我吗?

I'm so confused now. Can somebody help me?

推荐答案

问题出在你的端点:3 * 0.1,它不等于0.3(请记住,Python和NumPy使用

The problem is your endpoint: 3 * 0.1, which is not considered equal to 0.3 (remember that Python and NumPy use floating point arithmetic where some numbers, i.e. 0.1, cannot be represented exactly).

>>> 3 * 0.1
0.30000000000000004
>>> 0.3  
0.3  # or more exactly 0.299999999999999988897769753748...
>>> 3 * 0.1 == 0.3
False

所以包含0.3并不奇怪,因为端点(非常小)更大.

So it's not really surprising that 0.3 is included because the endpoint is (very slightly) bigger.

请注意, numpy.arange 也包含公式,结果数组中将包含多少个元素:

Note that the numpy.arange also contains the formula how many elements will be in the result array:

ceil((stop - start)/step

>>> (3 * 0.1 - 0)/0.1
3.0000000000000004
>>> ceil(_)
4

浮点数运算非常棘手,尤其是在比较浮点数是否相等时.为什么不创建整数数组并按除法创建所需的float数组呢?

Floating point math is tricky, especially when comparing floats for equality. Why not just create an integer array and create the desired float array by division:

>>> import numpy as np
>>> np.arange(0, 3, 1) / 10
array([0. , 0.1, 0.2])

或者 numpy.linspace 为浮点值提供更多选项的函数:

Or the numpy.linspace function which offers more options for floating point values:

>>> import numpy as np
>>> np.linspace(0.0, 3 * 0.1, 3, endpoint=False)
array([0. , 0.1, 0.2])

这篇关于np.arange与浮点参数无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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