尝试绘制函数导数的切线时出现“Subs”未定义错误

问题描述 投票:0回答:1

我已经绘制了原始函数的图形,并且我想绘制感兴趣点处的切线。

import numpy as np
from sympy import lambdify, symbols, diff, Abs

point_of_interest = 8
graphRange = [1,15]

# define the variable and the function
xsym = symbols('x')

# With a chord length of 60, plot the circle diameters
origFunction = 2 * ((60 ** 2) / (8 * Abs(xsym)) + Abs(xsym) / 2)

# define the derivative
derivative = diff(origFunction, xsym)

# define the tangent line at point of interest
tangentLine = derivative.subs(xsym, point_of_interest) * (xsym - point_of_interest) + origFunction.subs(xsym, point_of_interest)

# Convert the SymPy function to a lambda function
origF = lambdify(xsym, origFunction, "numpy")

# Generate x values
x_values = np.linspace(graphRange[0], graphRange[1], 100)

# Generate y-values for the original function
y_values = origF(x_values)

# Plot the original function
plt.plot(x_values, y_values, label='Original Function')

# THIS SECTION DOESN'T WORK YET
# Convert the SymPy function to a lambda function
diffF = lambdify(xsym, tangentLine, "numpy")

# Generate y-values for the tangent line
y_tang_values = diffF(x_values)

# Plot the tangent line
plt.plot(x_values, y_tang_values, label='Tangent Line')

#plot the point of interest
plt.plot(point_of_interest, origF(point_of_interest), 'ro', label='Point of Interest')

# Add labels and legend
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graph of Original Function and Tangent Line')
plt.legend()

# Show the plot
plt.show()

我得到的错误是这样的

回溯(最近一次调用最后一次): 文件“x:\Python Projects\Chord calc.py”,第 37 行,位于 y_tang_values = diffF(x_values) ^^^^^^^^^^^^^^^^ 文件“”,第 4 行,位于 _lambdify generated NameError:名称“Subs”未定义

我不知道如何修复此错误。

python numpy matplotlib sympy
1个回答
0
投票

目前,您正在使用一个复杂的符号,

xsym
:它没有任何假设,因此它是一般性的。

你的函数包含

Abs(xsym)
:因为
xsym
很复杂,它的导数将非常复杂:

print(Abs(xsym).diff(xsym))
# (re(x)*Derivative(re(x), x) + im(x)*Derivative(im(x), x))*sign(x)/x

将数值代入该表达式后,会出现

Subs
,稍后会出现错误。

解决方案很简单:创建一个真实的符号。替换这一行:

xsym = symbols('x')

与:

xsym = symbols('x', real=True)

然后,一切都会按预期进行。

© www.soinside.com 2019 - 2024. All rights reserved.