我编写了一个简单的程序来使用函数指针计算函数的一阶和二阶导数。我的程序计算正确答案(或多或少),但对于某些函数,准确性低于我想要的。
这是我要区分的功能:
float f1(float x) {
return (x * x);
}
这些是使用中心有限差分法的导数函数:
// Function for calculating the first derivative.
float first_dx(float (*fx)(float), float x) {
float h = 0.001;
float dfdx;
dfdx = (fx(x + h) - fx(x - h)) / (2 * h);
return dfdx;
}
// Function for calculating the second derivative.
float second_dx(float (*fx)(float), float x) {
float h = 0.001;
float d2fdx2;
d2fdx2 = (fx(x - h) - 2 * fx(x) + fx(x + h)) / (h * h);
return d2fdx2;
}
主功能:
int main() {
pc.baud(9600);
float x = 2.0;
pc.printf("**** Function Pointers ****\r\n");
pc.printf("Value of f(%f): %f\r\n", x, f1(x));
pc.printf("First derivative: %f\r\n", first_dx(f1, x));
pc.printf("Second derivative: %f\r\n\r\n", second_dx(f1, x));
}
这是程序的输出:
**** Function Pointers ****
Value of f(2.000000): 4.000000
First derivative: 3.999948
Second derivative: 1.430511
我对一阶导数的准确性感到满意,但我认为二阶导数太远了(它应该等于 ~2.0)。
我对浮点数的表示方式以及它们有时不准确的原因有基本的了解,但是如何使二阶导数结果更准确?我是否可以使用比中心有限差分法更好的方法,或者有什么方法可以使用当前方法获得更好的结果?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句