我试着画一个分段函数的导数。在
{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
首先,} guesses the output dtype by calling the underlying function on the first element of the input 。这意味着导数计算中的一些
f
有时返回一个int,如果没有指定显式输出数据类型,^{f
结果被强制为整数,从而忽略了结果。在不能只对一个不处理数组的函数调用
numpy.vectorize
,并假设一切都会解决。您仍然需要注意诸如dtype和文档中的其他异常,而且它永远不会像编写用于自然处理矢量化操作的函数那样快。在另一个问题是,正如documentation中明确指出的那样
scipy.misc.derivative
使用中心差分公式,默认间距为1。这个步长比图中的“摆动”要大得多。必须指定较小的步长才能获得有用的导数结果。在相关问题 更多 >
编程相关推荐