在下面的代码中,y1和y2应该相等,但不相等. vectorize()或dot()可能存在错误吗?
In the code below, y1 and y2 ought to be equal but they aren't. Could there be a bug in vectorize() or dot()?
import numpy as np interval = np.arange(0, 30, 0.1) y1 = [- 1.57 * max(0, x - 10) - 0.72 * max(0, 15 - x) - 1.09 * max(0, 20 - x) for x in interval] def fun(x, pivot, truth): if truth: return max(0, x - pivot) else: return max(0, pivot - x) pivots = [10, 15, 20] truths = [ 1, 0, 0] coeffs = [-1.57, -0.72, -1.09] y2 = [np.dot(np.vectorize(fun)(x, pivots, truths), coeffs) for x in interval] import matplotlib.pyplot as plt plt.plot(interval, y1, interval, y2) plt.show()y1和y2的图形:
Graphs of y1 and y2:
推荐答案为了应用正确的转换规则,numpy偶尔将您的函数与前哨值(numpy.int64)一起使用,以检查其输出的数据类型(如果输出的是整数0,因为那是max返回的,则它假定计算结果应全部为整数,并对其他结果进行四舍五入,但是,如果将函数更改为始终通过在max中使用0.0返回浮点数,则: >
In order to apply proper casting rules numpy uses your function occasionally with sentinel values (numpy.int64) to check what kind of data it outputs, if it outputs the integer 0 because thats what max returned then it assumes the result of the calculation should all be integers and rounds the other results off, however if you change the function to always return floats by using 0.0 in max:
def fun(x, pivot, truth): if truth: return max(0.0, x - pivot) else: return max(0.0, pivot - x)然后,对numpy应用的检查将始终导致浮点结果,并且不应用四舍五入.
Then the checks that numpy applies will always result in float results and no rounding will be applied.
更多推荐
NumPy vectorize()或dot()似乎有问题
发布评论