如何用Python对一个函数求导?
(1)背景与介绍
如何证明自己解算出来的函数导数是正确的?
仅靠手工计算你无法确定导数的答案是否正确,不过我们可以用Python编写数学库来验证它。
(2)导数基本概念框架思维导图
导数的基本概念如下图:
(3)实例
(3.1)Ex. 1
让我们对这个函数求导,并计算当xo = 1时的导数值。
让我们来画一下函数图(如果不知道如何绘制函数图,请参照文章):
通过推算,我们知道这个函数的微分解算如下:
利用Smypy去解算,代码如下:
#!usr/bin/env python
# -*- conding:utf-8 -*-
# import the Lib
from sympy import *
import matplotlib.pyplot as plt
# define a function to caculate
# we can use the function to derivative the
# function what you want to solve
def derivative(draw = False):
"""
derivate
@para draw: Bool,plot function or not
"""
x,f = symbols("x,f")
dx = 1
# define a function which will be derivatived
f = log(1+exp(x**2))
print("the derivative of function :",diff(f,x))
if dx != None:
print("the value of derivative in xo (xo = {}):{}".format(dx,f.evalf(subs ={'x':dx})))
if draw:
ezplot = lambda expr:plot_implicit(sympify(expr))
ezplot(f)
调用求导函数 : derivative(False)
得到如下结果:
将原函数与导函数一起绘制出来如下图所示:
(3.2)Ex. 2
在默认解中我们可以得到一阶导数。当我们需要求高阶导数时,可以通过下面的代码获得更高阶次的导数:
#!usr/bin/env python
# -*- conding:utf-8 -*-
# import the Lib
from sympy import *
import matplotlib.pyplot as plt
# define a function to caculate
# we can use the function to derivative the
# function what you want to solve
def derivative(draw = False):
"""
derivate
@para draw: Bool,plot function or not
"""
x,f = symbols("x,f")
dx = 1
# define a function which will be derivatived
n = 2
f = x**3
print("the derivative ({}) of function :{}".format(n,diff(f,x,n)))
if dx != None:
print("the value of derivative in xo (xo = {}):{}".format(dx,f.evalf(subs ={'x':dx})))
if draw:
ezplot = lambda expr:plot_implicit(sympify(expr))
ezplot(f)
例如,对 y = x^3
函数求二阶导数:
(4)迷惑的情况
我试图在 Sympy 代码中显示求导后的函数图,但失败了。
if draw:
ezplot = lambda expr:plot_implicit(sympify(expr))
ezplot(f)
你会发现画布上什么都没有。显然,我的代码有很多问题,所以如果大佬有其他正确的写法,可以在评论中提交你正确的代码。