/* Linear Interpolation (15 points) ^ |........... f(x1) | /. | / . p=f(x)|.......* | /. . | / . . f(x0) | / . . |.... . . | . . . --------------------> x0 x x1 Linear interpolation is a common method for estimating the value of a function at a point x for which no data is availalbe, but data exists for points located on either side of x on the horizontal axis. Given two points x0 and x1 and the value of the function evaluated at these points f(x0) and f(x1) using linear intepolation one can estimate the value of the function p=f(x) at another point x that lies between x0 and x1. The interpolation formula is as follows: (x - x0) (x1 - x) p = f(x) = ---------- f(x1) + ---------- f(x0) (x1 - x0) (x1 - x0) In other words, the estimation is performed by fitting a straight line between the points (x0, f(x0)) and (x1, f(x1)) and using this line to estiamte the values of the function in the interval (x1, x1). Note that we don't even need to know the analytical form of the function; we only need to know its values at two points. SAMPLE RUN #1: Please enter x0: 1 Please enter f(x0): 1 Please enter x1: 3 Please enter f(x1): 3 Please enter x: 2 The interpolated value of the function at x=2 is equal to 2 SAMPLE RUN #2: Please enter x0: -1 Please enter f(x0): -2 Please enter x1: 2 Please enter f(x1): 4 Please enter x: 1.5 The interpolated value of the function at x=1.5 is equal to 3 */ #include #include #include double linearInterpolation(double x0, double f_x0, double x1, double f_x1, double x) { double result = (x - x0)/(x1-x0)*f_x1 + (x1-x)/(x1-x0)*f_x0; return result; } int main(void) { double x0, x1; double f_x0, f_x1; double x; double p; printf("Please enter x0: "); scanf("%lf", &x0); printf("Please enter f(x0): "); scanf("%lf", &f_x0); printf("Please enter x1: "); scanf("%lf", &x1); printf("Please enter f(x1): "); scanf("%lf", &f_x1); printf("\nPlease enter x: "); scanf("%lf", &x); double res = linearInterpolation(x0, f_x0, x1, f_x1, x); printf("\nThe interpolated value of the function at x=%g is equal to %g\n\n", x, res); system("pause"); }