NumPy vectorize()或dot()似乎有问题

编程入门 行业动态 更新时间:2024-10-23 02:09:01
本文介绍了NumPy vectorize()或dot()似乎有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在下面的代码中,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()似乎有问题

本文发布于:2023-11-03 12:43:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555162.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NumPy   vectorize   dot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!