我已经画出了我的原始函数,我想画出关注点的切线.

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=DIFF(X_VALUES) ^^ 文件"",第4行,in_lambdify已生成 NameError:未定义名称‘Subs’

我不知道该怎么做才能修复这个错误.

推荐答案

目前,你使用的是一个复杂的符号,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)

然后,一切都将按预期进行.

enter image description here

Python相关问答推荐

如何从同一类的多个元素中抓取数据?

取相框中一列的第二位数字

在Python中,什么表达相当于0x1.0p-53?

如何才能将每个组比上一组增加N %?

如何在Python中增量更新DF

如何知道标志是否由用户传递或具有默认值?

为什么基于条件的过滤会导致pandas中的空数据框架?

如何使用Selenium访问svg对象内部的元素

更改Seaborn条形图中的x轴日期时间限制

通过交换 node 对链接列表进行 Select 排序

添加包含中具有任何值的其他列的计数的列

用gekko解决的ADE方程系统突然不再工作,错误消息异常:@错误:模型文件未找到.& &

在Pandas 日历中插入一行

重新匹配{ }中包含的文本,其中文本可能包含{{var}

用Python解密Java加密文件

基于字符串匹配条件合并两个帧

如何在Raspberry Pi上检测USB并使用Python访问它?

如何在UserSerializer中添加显式字段?

如何在turtle中不使用write()来绘制填充字母(例如OEG)

调用decorator返回原始函数的输出