最近項目里總是要對很龐大的公式求導,很煩人,手工求導容易出錯。
當然MATLAB是個好選擇,不過當它要錢的時候,您可能就不這么認為了。
于是,實現了一個可以
編譯期求導(不用擔心運行時負擔)的小型庫,還不完全,僅支持多項式,sin,cos,pow,exp,log等函數求導。
后期的表達式優化做的不是很好。
下面是一些測試代碼,完整的源碼在
http://www.boostpro.com/vault/index.php?action=downloadfile&filename=[math]AD.zip實現部分很復雜,請多多指教。
只有1個函數, d(...)
支持高階,多元求導。
d(exp, var)(value1, value2, ...)
exp內可以有多個變量,var表示要對其求導的變量,value表示求導以后用于計算表達式的變量的值。
比如:
d(d(x*x*x, x),x)(3.0) 表示對x*x*x求二階導數在x=3.0時候的值。
d(d(x*x*y, x), y)(3.0, 4.0) 表示d(x*x*y)/(dxdy)在x=3.0,y=4.0的值。
d(d(x*x*x, x) +d(y*x, y), y) (2.0) 則表示 (d(x*x*x)/dx + d(y*x)/dy)/dy == 0。
可以直接用cout把求導后的表達式輸出,不用給變量給值。
cout<<d(x*x, x) // 結果是:2*x
這里沒有用任何迭代,是直接對表達式求導的。返回值是求導后的表達式,本質是一個仿函數。可以用boost::function保存起來使用。
例如:
boost::function<double (double)> df = d(pow(x, const_<10>::type()), x); //df 參數為1個double,返回double
然后就可以在任何地方使用 df 了:
double res = df(3.0) // res == pow(3, 9)
1
#include "ad.h"
2
#include <iostream>
3
#include <iterator>
4
5
using namespace std;
6
7
int main()
8

{
9
variable<0>::type x;
10
variable<1>::type y;
11
12
double res[14];
13
14
res[0] = d(pow(x, const_<10>::type()), x)(2.0);
15
16
res[1] = d(x * x * x, x)(2.0);
17
res[2] = d(x + x + x, x)(2.0);
18
res[3] = d(x - x - x, x)(2.0);
19
res[4] = d(x / x, x)(2.0);
20
21
res[5] = d(pow(x, var(3.0)), x)(2.0);
22
res[6] = d(pow(var(3.0), x), x)(2.0);
23
res[7] = d(pow(x, x), x)(2.0);
24
25
res[8] = d(log(x), x)(2.0);
26
res[9] = d(exp(x), x)(2.0);
27
28
res[10] = d(sin(x), x)(2.0);
29
res[11] = d(cos(x), x)(2.0);
30
31
res[12] = d(d(sin(x) * cos(y), x), y)(2.0, 3.0);
32
33
res[13] = (d(log(x) + x, x) * x)(2.0);
34
35
copy(res, res + 14, ostream_iterator<double>(cout, "\n"));
36
37
cout<<d(pow(x, const_<10>::type()), x)<<endl;
38
39
cout<<d(x * x * x, x)<<endl;
40
cout<<d(x + x + x, x)<<endl;
41
cout<<d(x - x - x, x)<<endl;
42
cout<<d(x / x / x, x)<<endl;
43
44
cout<<d(pow(x, var(3.0)), x)<<endl;
45
cout<<d(pow(var(3.0), x), x)<<endl;
46
cout<<d(pow(x, x), x)<<endl;
47
48
cout<<d(log(x), x)<<endl;
49
cout<<d(exp(x), x)<<endl;
50
51
cout<<d(sin(x), x)<<endl;
52
cout<<d(cos(x), x)<<endl;
53
54
cout<<d(d(sin(x) * cos(y), x), y)<<endl;
55
56
cout<<(d(log(x) + x, x) * x)<<endl;
57
58
return 0;
59
}
60
輸出結果如下:
1
512
2
12
3
3
4
-1
5
0
6
12
7
9.88751
8
6.77259
9
0.5
10
7.38906
11
-0.416147
12
0.909297
13
-0.0587266
14
3
15
pow(x,9)
16
(((x+x)*x)+(x*x))
17
3
18
-1
19
(-1/(x*x))
20
(pow(x,3)*(3*(1/x)))
21
(pow(3,x)*log(3))
22
(pow(x,x)*(log(x)+1))
23
(1/x)
24
exp(x)
25
cos(x)
26
sin(x)
27
(cos(x)*sin(y))
28
(((1/x)+1)*x)
29
posted on 2009-05-01 23:50
尹東斐 閱讀(2586)
評論(6) 編輯 收藏 引用