【python与高等数学专题 二】使用Python的sympy库求解N阶导函数及对应点的导数值

如何用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)

你会发现画布上什么都没有。显然,我的代码有很多问题,所以如果大佬有其他正确的写法,可以在评论中提交你正确的代码。

(4)原文链接

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值