15个版本 (8个重大变更)
0.9.1 | 2024年4月16日 |
---|---|
0.8.1 | 2023年10月20日 |
0.7.1 | 2023年5月31日 |
0.6.0 | 2023年1月20日 |
0.2.0 | 2021年7月26日 |
#48 in 数学
1,150 每月下载量
在 10 个crate中使用了 10 (9 个直接)
240KB
5.5K SLoC
num-dual
广义、递归、标量和向量(超)对偶数,用于自动和精确计算(偏)导数。包括Python绑定。
安装和使用
Python
可以直接从PyPI安装python包
pip install num_dual
Rust
将以下内容添加到您的 Cargo.toml
[dependencies]
num-dual = "0.7"
示例
Python
计算标量值函数的一阶和二阶导数。
from num_dual import second_derivative
import numpy as np
def f(x):
return np.exp(x) / np.sqrt(np.sin(x)**3 + np.cos(x)**3)
f, df, d2f = second_derivative(f, 1.5)
print(f'f(x) = {f}')
print(f'df/dx = {df}')
print(f'd2f/dx2 = {d2f}')
Rust
此示例定义了一个泛型函数,可以使用任何(超)对偶数调用,并自动计算导数。
use num_dual::*;
fn f<D: DualNum<f64>>(x: D, y: D) -> D {
x.powi(3) * y.powi(2)
}
fn main() {
let (x, y) = (5.0, 4.0);
// Calculate a simple derivative using dual numbers
let x_dual = Dual64::from(x).derivative();
let y_dual = Dual64::from(y);
println!("{}", f(x_dual, y_dual)); // 2000 + [1200]ε
// or use the provided function instead
let (_, df) = first_derivative(|x| f(x, y.into()), x);
println!("{df}"); // 1200
// Calculate a gradient
let (value, grad) = gradient(|v| f(v[0], v[1]), SMatrix::from([x, y]));
println!("{value} {grad}"); // 2000 [1200, 1000]
// Calculate a Hessian
let (_, _, hess) = hessian(|v| f(v[0], v[1]), SMatrix::from([x, y]));
println!("{hess}"); // [[480, 600], [600, 250]]
// for x=cos(t) and y=sin(t) calculate the third derivative w.r.t. t
let (_, _, _, d3f) = third_derivative(|t| f(t.cos(), t.sin()), 1.0);
println!("{d3f}"); // 7.358639755305733
}
文档
Python
要使以下命令生效,您必须已安装该软件包(请参阅:从源安装)。
cd docs
make html
在您的浏览器中打开 _build/html/index.html
。
进一步阅读
如果您想了解更多关于对偶数和自动微分主题的信息,我们在此为您列出了一些有用的资源
- 关于超对偶数的初始论文:Fike, J. 和 Alonso, J., 2011
- 关于自动微分的所有主题的网站:autodiff.org
- 我们关于方程状态建模中对偶数的论文:Rehner, P. 和 Bauer, G., 2021
引用我们
如果您发现 num-dual
对您自己的科学研究有用,请考虑引用此库的出版物。
@ARTICLE{rehner2021,
AUTHOR={Rehner, Philipp and Bauer, Gernot},
TITLE={Application of Generalized (Hyper-) Dual Numbers in Equation of State Modeling},
JOURNAL={Frontiers in Chemical Engineering},
VOLUME={3},
YEAR={2021},
URL={https://www.frontiersin.org/article/10.3389/fceng.2021.758090},
DOI={10.3389/fceng.2021.758090},
ISSN={2673-2718}
}
依赖关系
~2.7–9MB
~83K SLoC