如何计算SciPy边界处的导数?

How to calculate derivatives at the boundary in SciPy?

我有一个脚本在各种 z 处绘制一组 (x,y) 曲线。

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,1,100)
z = np.linspace(0,30,30)

def y(z, x):
    return z**(1-x)

for i in z:
    plt.plot(x, y(i,x))

如何在 x=0z 处绘制 dy/dx

plt.plot(z, dy/dx at x=0)

事实上,我需要计算每条 (x,y) 曲线(如下所示)在 x=0 边界处的斜率,然后根据 z.[=22= 绘制斜率]

您混淆了描述中的变量。我假设您在变量 (x,z) 中有一个函数 y。所以你需要计算 dy/dx 和 dy/dz.

您有几个选项来计算导数,包括符号计算(使用 SymPY)或简单的有限差分计算(容易出现数值错误)参见:How do I compute derivative using Numpy?

但是,你不能绘制这个导数,因为你是在一个点 (x=0,z=0) 计算它,因此结果是一个浮点数,而不是一个函数。要制作您想要的情节,您需要计算一般符号导数 (dydx) 并制作您建议的情节。要得到点 (0,0) 的结果,只需 dydx(0,0).

顺便说一下,dydz = (1-x)z**(-x)dydx = -ln(z)*z**(1-x) 使用 this

您必须使用derivative函数:

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.

Parameters:

func : function Input function.

x0 : float The point at which n-th derivative is found.

dx : float, optional Spacing.

n : int,optional Order of the derivative. Default is 1.

args : tuple, optional Arguments order : int, optional Number of points to use, must be odd.

你的情况:

import numpy as np
import matplotlib.pyplot as plt

from scipy.misc import derivative

x = np.linspace(0,1,100)
z = np.linspace(0,30,30)

x0 = 0

def y(z, x):
    return z**(1-x)

dydx = [derivative(lambda x : y(zi, x) , x0) for zi in z]

plt.plot(z, dydx)

plt.show()

截图: