feat: 前向自动微分纯头文件库

This commit is contained in:
mayge
2026-04-01 02:39:40 +08:00
parent 2ff32f5c89
commit 58aedec43c
10 changed files with 180 additions and 0 deletions

40
tests/basic.cpp Normal file
View File

@@ -0,0 +1,40 @@
#include <iostream>
#include "forwardad.hpp"
#include "types/dual.hpp"
using namespace forwardad;
// 一阶测试函数
Dual f(Dual x) {
return x + x*x + pow(x,3);
}
// 二阶测试函数
Dual g(Dual x, Dual y) {
return exp(x) * log(y);
}
// 高阶测试函数
Dual h(Dual x, Dual y, Dual z) {
return pow(x, 3) + pow(y, 2) + z + cos(x * y * z);
}
int main() {
std::cout << "Testing f(x) = x^2 + sin(x) at x=2.0\n";
auto r = diff(f, 2.0);
std::cout << "value = " << r.value << "\n";
std::cout << "grad = " << r.gradient[0] << "\n";
std::cout << "\nTesting g(x,y) = exp(x)*log(y) at (x,y)=(1.0, 2.0)\n";
auto r2 = diff(g, 1.0, 2.0);
std::cout << "value = " << r2.value << "\n";
std::cout << "grad = (" << r2.gradient[0] << ", " << r2.gradient[1] << ")\n";
std::cout << "\nTesting h(x,y,z) = x^3 + y^2 + z + cos(x*y*z) at (x,y,z)=(1.0, 2.0, 3.0)\n";
auto r3 = diff(h, 1.0, 2.0, 3.0);
std::cout << "value = " << r3.value << "\n";
std::cout << "grad = (" << r3.gradient[0] << ", " << r3.gradient[1] << ", " << r3.gradient[2] << ")\n";
return 0;
}