【问题标题】:Weird behavior of np.gradient with increased resolution分辨率提高的 np.gradient 的奇怪行为
【发布时间】:2022-01-13 05:35:30
【问题描述】:

我想在同一个图上绘制 cos(x) 和它的导数 -sin(x)。 我的做法如下:

import numpy as np    
x = np.linspace(0,10,20) #x values: 0-10, 20 values
f = np.cos(x) # function
df = np.gradient(f) # derivative

# plot
plt.plot(f, label ="function")
plt.plot(df, label ="derivative")
plt.legend()

您已经可以看到导数的幅度存在问题。它应该是 1,但大约是 0.5。

如果我现在将分辨率从 20 点增加到 50 点,则导数的幅度下降得更多:

100 分:

1000 分:

有人知道发生了什么吗?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    这是因为假设两个连续值之间的默认间距为 1。有关详细信息,请参阅this answer

    在您的示例中,当您使用 np.linspace 时,可以通过编程方式找到间距

    sp = np.diff(x)[0]
    

    或者更好(感谢@Kraigolas!)

    # form the array *and* get the spacing in one shot
    x, sp = np.linspace(0, 10, 20, retstep=True)
    

    那么,

    x, sp = np.linspace(0, 10, 2000, retstep=True)
    f = np.cos(x)
    
    df = np.gradient(f, sp) # change is here!
    
    # plot
    plt.plot(f, label ="function")
    plt.plot(df, label ="derivative")
    plt.legend()
    

    给予

    其他点数类似。

    【讨论】:

    • np.linspace 也接受参数retstep,因此可以写成x, sp = np.linspace(0, 10, 2000, retstep=True)
    • @Kraigolas 哦,谢谢!您介意我将其添加到答案中吗(并注明出处)?
    • 没关系,乐于助人!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 2020-06-04
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多