numpy.diff的输出错误 [英] Output of numpy.diff is wrong

查看:175
本文介绍了numpy.diff的输出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题: 我正在尝试使用numpy计算(数字)导数,但是我发现函数numpy.diff返回的值(以及numpy.gradient)中存在一些问题.我发现这些值是完全错误的! 这是一个代码示例:

here's my problem: I am trying to use numpy to compute (numerical) derivatives, but I am finding some problems in the value the function numpy.diff returns (and numpy.gradient as well). What I find is that the values are totally wrong! here's a code sample:

import numpy as np
x = np.linspace(-5, 5, 1000)
y = x**2
yDiff = np.diff(y)
print y[0], yDiff[0]

此脚本的输出为:

25.0 -0.0999998997997

在第一个值正确的地方,第二个恰好比它应该的那个小100倍(考虑近似值)! 我做了不同的尝试,这不是与函数边界有关的问题,这100个因素似乎是系统性的... 这可以与np.diff正在执行的某些规范化相关吗?也许我只是在不注意的情况下错过了重要的事情? 感谢您的帮助

where the first value is right, the second is exactly 100 times smaller than the one it should be (considering approximations)! I have made different attempts and this is not a problem related to the boundaries of the function, and this 100 factor seems systematic... Can this be related to some normalization np.diff is doing? Or perhaps I am just missing something important without noticing? Thanks for the help

推荐答案

np.diff不会计算导数,而只是计算有限差分.您必须自己解决间距问题.试试

np.diff doesn't calculate the derivative it just calulates finite differences; you have to account for the spacing yourself. Try

np.diff(y) / (x[1] - x[0])

顺便说一句,np.linspace具有一个retstep关键字,在这种情况下很方便:

Btw., np.linspace has a retstep keyword that is convenient in this context:

x, dx = np.linspace(-5, 5, 100, retstep=True)
...
np.diff(y) / dx

这篇关于numpy.diff的输出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆