NumPy linspace舍入错误

ajw*_*ood 5 python floating-point numpy

有人可以解释这个四舍五入的问题numpy.linspace吗?

import numpy as np

np.linspace(0, 1, 6) == np.around( np.linspace(0, 1, 6), 10 )
# array([ True,  True,  True, False,  True,  True], dtype=bool)
Run Code Online (Sandbox Code Playgroud)

这是我到达这里的方式......

import numpy as np

## Two ways of defining the same thing
A = np.array([ 0., 0.2, 0.4, 0.6, 0.8, 1. ])
B = np.linspace(0, 1, 6)

## A and B appear to be the same
A # array([ 0., 0.2, 0.4, 0.6, 0.8, 1. ])
B # array([ 0., 0.2, 0.4, 0.6, 0.8, 1. ])


## They're not
A == B # array([ True, True, True, False, True, True], dtype=bool)
A - B  # array([ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -1.11022302e-16, 0.00000000e+00, 0.00000000e+00])


## Gotta round to get my expected result
C = np.round( np.linspace( 0, 1, 6 ), 10 )
C      # array([ 0., 0.2, 0.4, 0.6, 0.8, 1. ])
A == C # array([ True, True, True, True, True, True], dtype=bool)
Run Code Online (Sandbox Code Playgroud)

我定义的方式B看起来很无辜...这个四舍五入的问题是什么东西可以咬我们所有的地方?

Jai*_*ime 6

它不漂亮,但它的浮点方式,你将不得不学习与它一起生活.这是你奇怪的结果来自:

>>> a = np.float(1)
>>> a /= 5
>>> a
0.2
>>> a*3
0.6000000000000001
Run Code Online (Sandbox Code Playgroud)

你必须np.allclose帮助你处理这类事情,但如果你对浮点数比较没有纪律,那么是的,它会一遍又一遍地咬你.