0
我在为决赛学习时遇到了这个问题,而且我似乎无法使其发挥作用。这个问题本身如下所示。任何关于如何解决这个问题的帮助将不胜感激。C中的中心差分近似值
下面是我解决类似问题的代码。我希望它可以作为一个基础上解决这一问题
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
using namespace std;
double f(double x)
{
return (cos(x));
}
/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Numerical Differentiation Formulae (n-th derivative)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
void dnf_dxn (int n, double x, double h, double& fd, double& cd)
{
if(n==1)
// Approximation to the 1st Derivative of f at x
{
// 1st order forward differencing
fd = (f(x+h) - f(x))/h;
// 2nd order centered differencing
cd = (f(x+h) - f(x-h))/(2*h);
}
else if(n==2)
// Approximation to the 2nd Derivative of f at x
{
// 1st order forward differencing
fd = (f(x+2*h) - 2*f(x+h) + f(x))/(h*h);
// 2nd order centered differencing
cd = (f(x+h) - 2*f(x) + f(x-h))/(h*h);
}
else if(n==3)
// Approximation to the 3rd Derivative of f at x
{
// 1st order forward differencing
fd = (f(x+3*h) - 3*f(x+2*h) + 3*f(x+h) - f(x))/(h*h*h);
// 2nd order centered differencing
cd = (f(x+2*h) - 2*f(x+h) + 2*f(x-h) - f(x-2*h))/(2*h*h*h);
}
else
{
printf("Only derivatives of orders 1, 2 and 3 are implemented. \n");
getchar();
exit(1);
}
}
/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
NUM_DIFF M A I N P R O G R A M
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
int main()
{
printf("\n Numerical Differentiation of f(x)=cos(x) at x=1 \n \n");
printf(" Derivative of order 1, 2 and 3 using forward \n");
printf(" and centered difference approximations (h=0.01): \n \n");
double x = 0.5;
double h = 0.01;
int n;
double fd, cd, exact, cd_error, fd_error;
double true_fx = - sin(x);
double true_fxx = - cos(x);
double true_fxxx = sin(x);
printf("Derivative Stepsize Differencing Result Abs Error \n");
for(n=1; n<4; n++)
{
dnf_dxn (n, x, h, fd, cd);
if(n==1)
{ exact = true_fx; }
else if(n==2)
{ exact = true_fxx; }
else
{ exact = true_fxxx; }
fd_error = abs(exact - fd);
cd_error = abs(exact - cd);
printf(" %i %4.2f Forward %10.7f %10.3e \n",
n, h, fd, fd_error);
printf(" Centered %10.7f %10.3e \n",
cd, cd_error);
}
printf("\n \n <Press the RETURN key to exit num_diff.cpp> \n \n");
getchar();
}
下面是实际的问题:
对不起,上面的代码来自不同的问题,但它与我所问的有关,因此变量和方程的差异。我应该更清楚一点。 我的问题是,用正确的替换变量和方程后,我不知道接下来要做什么。关于h的一点让我完全失去了。 – David 2010-12-13 19:49:45