首页 > 解决方案 > 如何从python求解导数方程

问题描述

我是 sympy 方法的新手,我想根据用户的输入计算二项式方程的导数。

from scipy.misc import derivative 
import sympy as sp
x = sp.Symbol("x")

sign = input("What is the operator of the equation? ")
a = int(input("What is the value of a? "))
expo = int(input("What is the value of exponent for x? "))
b = int(input("What is the value of b? "))


if sign == '-':
    ans = sp.diff(a * x ** expo - b,x)
    print (ans)

elif sign == '+':
    ans = sp.diff(a * x ** expo + b,x)
    print (ans)

def f(x):
    if sign == '-':
        ans = sp.diff(a * x ** expo - b,x)
        return ans

    elif sign == '+':
        ans = sp.diff(a * x ** expo + b,x)
        return ans

print (derivative(f,2.0))

我遇到了函数 f(x) 的错误。使用这个函数,它将显示上述方程的导数。例如等式是 (6x^2 - 2)。x = 3 的值

f'(x) = 12x -> 这应该显示为答案

f(3) = 36 -> 这应该显示为函数 f(x) 的答案

标签: python

解决方案


import sympy as sp
x = sp.Symbol("x")

sign = input("What is the operator of the equation? ")
a = int(input("What is the value of a? "))
expo = int(input("What is the value of exponent for x? "))
b = int(input("What is the value of b? "))


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,3)) # prints the derivative evaluated at x=3

推荐阅读