np.ceil 在 python 中不起作用

np.ceil in python doesn't work

我实际上在 python 中遇到 "np.ceil" 的一些问题。

import numpy as np

x_start = 0
y_start = 0
x_end = 2
y_end = 1
x_step = 0.4
y_step = 0.3

x_segment = int(np.ceil((x_end-x_start)/x_step))
y_segment = int(np.ceil((y_end-y_start)/y_step))

print "N. x: " + str(x_segment)
print "N. y: " + str(y_segment)

matrix = np.zeros((y_segment, x_segment), dtype=int)

import matplotlib.pyplot as plt
import matplotlib.patches as patches

def frange(x, y, jump):
  while x < y:
    yield x
    x += jump
for y in frange(y_start, y_end, y_step):
    print "***"
    for x in frange(x_start, x_end, x_step):
        count = 0
        print "(" + str(x) + "; " + str(y) + ")   m[" + str(y_segment - int(np.ceil(y/y_step)) - 1) + "][" + str(int(np.ceil(x/x_step)))+"]" + " | x/x_step: " + str(x/x_step) + " | np.ceil(x/x_step): " + str(int(np.ceil(x/x_step)))

我应该得到类似的东西:

...
***
(0; 0)   m[3][0] | x/x_step: 0.0 | np.ceil(x/x_step): 0
(0.4; 0)   m[3][1] | x/x_step: 1.0 | np.ceil(x/x_step): 1
(0.8; 0)   m[3][2] | x/x_step: 2.0 | np.ceil(x/x_step): 2
(1.2; 0)   m[3][3] | x/x_step: 3.0 | np.ceil(x/x_step): 3
(1.6; 0)   m[3][4] | x/x_step: 4.0 | np.ceil(x/x_step): 4
***
...

但是数字“3”被替换为“4”。

***
(0; 0)   m[3][0] | x/x_step: 0.0 | np.ceil(x/x_step): 0
(0.4; 0)   m[3][1] | x/x_step: 1.0 | np.ceil(x/x_step): 1
(0.8; 0)   m[3][2] | x/x_step: 2.0 | np.ceil(x/x_step): 2
(1.2; 0)   m[3][4] | x/x_step: 3.0 | np.ceil(x/x_step): 4
(1.6; 0)   m[3][4] | x/x_step: 4.0 | np.ceil(x/x_step): 4
***

你知道为什么吗?我该如何修复我的代码?谢谢!

简答:浮点数不精确问题

长答案:

frange 似乎有一些浮动精度问题。看看当你通过 frange:

时会发生什么

如果您只打印原始浮点数:

>>> [x for x in frange(x_start, x_end, x_step)]
[0, 0.4, 0.8, 1.2000000000000002, 1.6]

出于某种原因,1.2 不完全是 1.2。当你这样做时:

np.ceil(1.2000000000000002/x_step)

你得到 4.0(换句话说,np.ceil 正常工作)。

想要的本质上是np.ceil(1.2/x_step),等于3.0

我建议在应用 np.ceil()

之前使用 np.round() 或类似的东西来四舍五入你的 x