/* --------------------------------------------------------------------- // Figure 6.33: Linear interpolation. // Figure 6.26: Instructions for linear interpolation. // --------------------------------------------------------------------- // Given two points in the form (x, f(x)), calculate the equation // of a straight line through those points. In a second program // phase, read the x-coordinates of a series of points and use the // linear equation to obtain an approximation for f(x) for each input */ #include "tools.h" void instructions( void ); void main( void ) { double x1, fx1; /* The point with the smaller x-coordinate. */ double x2, fx2; /* The point with the larger x-coordinate. */ double x, fx, slope; instructions(); /* Phase I.------------------------------------------------------------- */ do { printf( " Enter the smaller x value and f(x) for that value: " ); scanf( "%lg%lg", &x1, &fx1 ); printf( " Enter the larger x value and f(x) for that value: " ); scanf( "%lg%lg", &x2, &fx2 ); if (x1 >= x2) puts( " Error: first x-value must be < second.\n" ); } while (x1 >= x2); printf( "\n\t For p1=(%g, %g) and p2=(%g, %g)\n", x1, fx1, x2, fx2 ); slope = (fx2 - fx1) / (x2 - x1) ; printf( "\n\t f_approx(x) = %g + %g * (x - %g)\n", fx1, slope, x1 ); /* Phase II.------------------------------------------------------------ */ printf( "\n Enter x-values between %g and %g\n", x1, x2 ); printf( "\t The value of f_approx(x) will be printed for each x. \n" "\t To quit, enter an x-value outside this range.\n" ); scanf( "%lg", &x ); while (x1 <= x && x <= x2) { fx = fx1 + slope * (x - x1); printf( "\t x=%g f_approx(x)=%g\n", x, fx ); scanf( "%lg", &x ); } bye(); } /* Phase II.------------------------------------------------------------ */ void instructions( void ) { banner(); puts( "\n\n Linear Interpolation\n" " This program uses a straight line to approximate an unknown \n" " function, f(x). The user enters x and f(x) for two points. \n" " The program calculates the formula for f_approx(x), the \n" " straight line through these two points. \n" ); }