Python 如何写出函数的导数

Python 如何写出函数的导数,python,sympy,Python,Sympy,我必须用python写一个等式。 方程为f(x)=(3+2x)e-x 计算f'(x)的x=2和f'(x)=极限(i->0){[f(x+i)-f(x-i)]/2i}的i=10^-n其中n=2,3,4,然后对其进行积分。 对于这个问题,我尝试了python程序 import math from math import exp import sympy as sp x = sp.Symbol('x') sp.diff((3+2*x)*math.exp(-x),x) from scipy.misc im

我必须用python写一个等式。 方程为
f(x)=(3+2x)e-x
计算
f'(x)
x=2
f'(x)=极限(i->0){[f(x+i)-f(x-i)]/2i}
i=10^-n
其中
n=2,3,4
,然后对其进行积分。 对于这个问题,我尝试了python程序

import math
from math import exp
import sympy as sp
x = sp.Symbol('x')
sp.diff((3+2*x)*math.exp(-x),x)
from scipy.misc import derivative
def f(x):
    return (3+2*x)*math.exp(-x)
def d(x):
    return derivative (f,x)
def d(x):
    h=1./1000.
    rise=f(x+h)-f(x-h)
    run=2*h
    slop = rise/run
    return slop
def integral(startingx, endingx, number of rectangles):
    width = (endingx-startingx)/number of rectangles
    runningsum = 0
    for i in range(number of rectangles):
        height = f(startingx + i*width)
        area= height*width
        runningSum += area
        return runningSum
print (f)
print (derivative(f,2))
print (integral)

下面的sympy代码以符号方式计算导数和积分。请注意,您不能在符号计算中使用Python的数学库或其他库(如scipy和numpy)中的函数。如果需要生成用于数值计算的函数,Sympy有一个函数
lambdify()
。Symphy的
subs
命令可以用特定值替换变量<代码>简化()对于以更简单的形式编写公式非常有用

将sympy作为sp导入
x=sp.Symbol('x')
def f(x):
返回(3+2*x)*sp.exp(-x)
定义d(x):
返回sp.diff(f(x),x)
通过公式(x,eps)得出的def导数:
回报率(f(x+eps)-f(x-eps))/(2*eps)
印刷品(“f(x):”,f(x))
打印(“导数:”,d(x).simplify()
打印(“x=2时的导数:”,d(x).subs(x,2).simplify())
打印(“x=2时的导数:”,d(x).subs(x,2).evalf())
print(“f(x)的积分):”,sp.integrate(f(x)).simplify()
对于范围(2,5)内的n:
每股收益=10**(-n)
打印(“通过公式推导的公式,每股收益=10^-%d:%n,通过公式推导的公式(2,每股收益))
输出:

f(x): (2*x + 3)*exp(-x)
derivative: -(2*x + 1)*exp(-x)
derivative at x=2 : -5*exp(-2)
derivative at x=2 evaluated: -0.676676416183063
the integral of f(x): -(2*x + 5)*exp(-x)
derivative_via_formula, eps=10^-2: -0.676678671737280
derivative_via_formula, eps=10^-3: -0.676676438738810
derivative_via_formula, eps=10^-4: -0.676676416409006

symphy
不会区分普通Python函数;您必须定义一个表示数学函数的
sympy
对象。澄清:您的目标是以数字方式进行计算,还是以符号方式进行计算?您在某些地方使用了
sympy
,但在其他地方定义了数值导数和积分。您所说的“积分”是什么意思?你到底想积分什么?在你使用Symphy的地方,你不能使用
math.exp
scipy.derivative
。Josh Karpel,我的目标是做导数,用数值方法积分函数。这个答案有用吗?