在SciPy中如何计算边界导数?

2024-03-28 11:06:20 发布

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

我有一个脚本,在不同的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=0和{}绘制dy/dx?在

^{pr2}$

实际上,我需要计算每个(x,y)曲线在x=0边界处的斜率(如下所示),然后根据z绘制斜率。在

enter image description here


Tags: importnumpy脚本forreturnmatplotlibdefas
2条回答

你把描述中的变量弄混了。假设你在变量(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)和{}使用this。在

必须使用^{}函数:

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()

截图:

enter image description here

相关问题 更多 >