我在绘制导数时遇到问题。以我的等式为例:
x 的值 = 3
f(x) = 6x^2 - 2
f'(x) = 12x
f(3) = 36
from scipy.misc import derivative
import matplotlib.pyplot as plt
import numpy as np
import sympy as sp
x = sp.Symbol("x")
ex = int(input("What is the value of x in f(x)? "))
coef = int(input("What is the coefficient of the first value? "))
if coef == 1:
a = int(input("\nWhat is the value of the first coefficient in the equation? ")) #6
sign = input("What is the operator of the equation? [+] or [-] ") #-
expo = int(input("What is the value of exponent for the variable x? ")) #2
ask = input("Does the 2nd value for the equation has constant? [Y] / [N]: ").upper() #y
if ask == 'Y': #this will be the accepted condition for my example equation
b = int(input("What is the value of constant? "))
if sign == '-':
f = a * x ** expo - b
elif sign == '+':
f = a * x ** expo + b
derivative = sp.diff(f,x) # derivative of the function
print (derivative) #prints the derivative as a function of x
print (derivative.subs(x,ex)) # prints the derivative evaluated at x=3
plt.plot((derivative.subs(x,ex)))
plt.plot(derivative)
plt.show()
我收到一个错误,导数不能接受 float 。我对每个输入都做了评论,以便人们了解我的程序是如何工作的。
Error:
Message=can't convert expression to float
Source=D:\VB\Calculus\Calculus\Calculus.py
StackTrace:
File "D:\VB\Calculus\Calculus\Calculus.py", line 24, in <module> (Current frame)
plt.plot(derivative)
最佳答案
matplotlib.pyplot.plot
需要数组才能绘制它们的点,但您要向其传递一个 sympy
对象。
为了绘制 sympy
对象,您应该使用 sympy.plotting.plot
:
(我简化了您的代码以使要点清晰)
import matplotlib.pyplot as plt
from sympy.plotting import plot
import sympy as sp
x = sp.Symbol("x")
ex = 3
a = 6
expo = 2
b = 2
f = a*x**expo - b
derivative = sp.diff(f, x)
plot(derivative, ylabel = "f'(x)")
关于python - 如何使用 matplotlib 绘制导数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68951190/