/*T Math/CS 466/666 Midterm Solutions \medskip\noindent Problem 1(iv). Consider the approximation $$ f''(x)\approx {f(x+h)-2f(x)+f(x-h)\over h^2}. $$ Let $f(x)=\sin(x^2)$. Write or modify a computer program to create a table showing the approximation and the errors in the approximation when $x=2$ and $h=2^{-n}$ for $n=0,1,\ldots,30.$ */ #include #include double f(double x){ return sin(x*x); } double ddf(double x){ /*T Always set this to $f''(x)$ where $f(x)$ is defined above. Since $f'(x)=2x\cos(x^2)$ then the exact second derivative is $f''(x)=2\cos(x^2)-4x^2\sin(x^2)$. */ double xx=x*x; return 2*cos(xx)-4*xx*sin(xx); } double addf(double x,double h){ return (f(x+h)-2*f(x)+f(x-h))/(h*h); } int main(){ printf("Math/CS 466/666 Midterm\nProblem 1(iv)\n\n"); double h=1,x=2; printf("%3s %22s %22s %22s\n","n","h","approximation","error"); for(int n=0;n<=30;n++,h/=2){ printf("%3d %22.14e %22.14e %22.14e\n", n,h,addf(x,h),addf(x,h)-ddf(x)); } return 0; }