如何使用 Numpy 计算导数? [英] How do I compute derivative using Numpy?

查看:44
本文介绍了如何使用 Numpy 计算导数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何计算一个函数的导数,例如

How do I calculate the derivative of a function, for example

y = x2+1

使用numpy?

比方说,我想要 x = 5 处的导数值...

Let's say, I want the value of derivative at x = 5...

推荐答案

您有四个选择

  1. 有限差异
  2. 自动导数
  3. 符号微分
  4. 手动计算导数.

有限差分不需要外部工具,但容易出现数值错误,如果您处于多变量情况,可能需要一段时间.

Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.

如果您的问题足够简单,则符号微分是理想的.如今,符号方法变得非常健壮.SymPy 是一个很好的项目,可以很好地与 NumPy 集成.查看自动换行或lambdify 函数或查看Jensen 关于类似问题的博文.

Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.

自动导数非常酷,不容易出现数字错误,但确实需要一些额外的库(为此谷歌,有一些不错的选择).这是最强大但也是最复杂/最难设置的选择.如果你很好地限制自己使用 numpy 语法,那么 Theano 可能是一个不错的选择.

Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy syntax then Theano might be a good choice.

这是一个使用 SymPy 的例子

Here is an example using SymPy

In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2⋅x

In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2.  2.  2.  2.  2.]

这篇关于如何使用 Numpy 计算导数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆