python - 如何使用 matplotlib 绘制导数?

标签 python matplotlib math plot sympy

我在绘制导数时遇到问题。以我的等式为例:

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

enter image description here

关于python - 如何使用 matplotlib 绘制导数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68951190/

相关文章:

python - 在 Python 中与另一个命令行程序交互

python - 使用 Python 更改网格厚度的极坐标图

python - 更清晰的代码来绕过在 Python 中打印 Int 值

相当于 Sinatra 的 Python

python - 如何为seaborn热图中的值分配颜色

python - 如何在matplotlib中将 'underbar'放在字母(下划线字符)下面?

math - 在 switch case 语句中检测 2 个变量值的 4 个排列

python - 四次方程求解器的实现不起作用

java - 困难的公式

python - 如何在 Pandas 中删除左右字符串中的所有 '0'