在学习期末考试时,我遇到了这个问题,但似乎无法解决这个问题。问题本身如下所示。任何有关如何解决此问题的帮助将不胜感激。
以下是我解决的类似问题的代码。我希望它可以作为解决这个问题的基础
#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();
}
这是实际的问题:
最佳答案
好吧,对于您来说,您说的是在x = 1
处计算这些差异,但实际上是在x = 0.5
处进行计算。
仅仅说“它不起作用”是不够的。您期待什么,而您得到什么呢?
关于c - C中的中心差近似,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4432477/