为什么Scipy.misc.导数给出错误答案Python

2024-05-15 05:53:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着画一个分段函数的导数。在

{1美元^

我算出了导数存在的数学,一切都应该是好的,我想看看在“奇点”发生了什么,但我得到:

“x=0”处的奇点

与我的期望相反:

我期望的那种结果

我的代码:

from scipy.misc import derivative as deriv
import numpy as np
import pylab as pyl


def f(x):  # Define piecewise function
    if x != 0:
        h = np.power(x, -1)
        return x**2 * np.sin(h)
    elif x == 0:
        return 0


vf = np.vectorize(f)  # Vectorize function to use "deriv"

x = np.linspace(-1, 1, num=10 ** 5)  # Make 'x' continuous parameter
x = np.sort(np.append(x, [0]))  # Make sure 'x' contains '0'


def d(x): return deriv(vf, x)  # Define derivative of 'f' respect to 'x'


print('0, ' + str(d(0)))  # Derivative at '0'

pyl.plot(x, vf(x), 'b-')  # Plot functions
pyl.plot(x, d(x), 'C4')
pyl.scatter(0, d(0), c='r0')

pyl.grid()

pyl.show()  # Display graphically

Tags: toimportmakereturndefasnpfunction
1条回答
网友
1楼 · 发布于 2024-05-15 05:53:15

首先,f有时返回一个int,如果没有指定显式输出数据类型,^{} guesses the output dtype by calling the underlying function on the first element of the input。这意味着导数计算中的一些f结果被强制为整数,从而忽略了结果。在

不能只对一个不处理数组的函数调用numpy.vectorize,并假设一切都会解决。您仍然需要注意诸如dtype和文档中的其他异常,而且它永远不会像编写用于自然处理矢量化操作的函数那样快。在


另一个问题是,正如documentation中明确指出的那样

scipy.misc.derivative(func, x0, dx=1.0, n=1, args=(), order=3)

Find the n-th derivative of a function at a point.

Given a function, use a central difference formula with spacing dx to compute the n-th derivative at x0.

scipy.misc.derivative使用中心差分公式,默认间距为1。这个步长比图中的“摆动”要大得多。必须指定较小的步长才能获得有用的导数结果。在

相关问题 更多 >

    热门问题