我实际上在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.round()
之前,我建议使用x
或类似的东西来围绕你的np.ceil()
值