/* Kincaid and Cheney Programming Problem 6.2#1 Polynomial approximation of degree n Written December 2012 by Eric Olson for Math 701 */ #include #include void divdif(int n,double x[n+1],double c[n+1]){ for(int k=1;k<=n;k++) for(int i=n;i>=k;i--) { c[i]=(c[i-1]-c[i])/(x[i-k]-x[i]); } } double interp(int n,double x[n+1],double c[n+1],double z){ double y=0; for(int i=n;i>0;i--) y=(z-x[i-1])*(y+c[i]); return y+c[0]; } double f(double x){ return 1/(1+x*x); } int main(){ int n; scanf("%d",&n); printf("# Kincaid and Cheney Programming Problem 6.2#1\n" "# Polynomial approximation of degree %d\n\n",n); double x[n+1],c[n+1]; double a=-5,b=5,h=(b-a)/n; for(int i=0;i<=n;i++){ x[i]=a+h*i; c[i]=f(x[i]); } divdif(n,x,c); h=(b-a)/30; printf("#%17s %18s %18s %18s\n","z","f(z)","Pn(z)","f(z)-Pn(z)"); for(int i=0;i<=30;i++){ double z=a+h*i, y=f(z), p=interp(n,x,c,z); printf("%18.10e %18.10e %18.10e %18.10e\n",z,y,p,y-p); } exit(0); }