Suppose we are given a set of tabulated values for y versus x, i.e.,
\(\begin{array}{c c c c c} y_0 & y_1 & y_2 & \cdots & y_n\\x_0 & x_1 & x_2 & \cdots & x_n\end{array}\)
and we wish to obtain a value of y at some specified value of x that lies between two of the tabulated values. This problem is commonly solved by interpolation, i.e., by passing a polynomial y(x) through n points such that \(y(x_0)=y_0\), \(y(x_1) =y_1\), \(\cdots\) ,\(y(x_n) =y_n\) and then evaluating y at the desired value of x.
A common way to carry out the interpolation is to use the Lagrange form of the interpolation polynomial. To do this we write
\(y(x)=f_0(x)y_0 + f_1(x)y_1 + \cdots + f_n(x)y_n\)
wheref \(f_i(x)\) is a polynomial such that
\(f_i(x)=\frac{(x-x_0)(x-x_1)\cdots(x-x_{i-1})(x-x_{i+1})\cdots(x-x_n)}{(x_i-x_0)(x_i-x_1)\cdots(x_i-x_{i-1})(x_i-x_{i+1})\cdots(x_i-x_n)}\)
Notice that \(f_i(x_i) = 1\) and \(f_i(x_j) = 0\), where \(x_j\) is a tabulated value of x different from \(x_i\). Therefore we are assured that \(y(x_i)=y_i\).
Write a C program to read in N pairs of data, where N does not exceed 10, and then obtain an interpolated value of y at one or more specified values of x. Use the program to obtain interpolated values of y at x = 13.7,x = 37.2, x = 112 and x = 147 from the data listed below.
\(\begin{array}{c c}x= & y = \\ 0 & 0.21073\\20 & 0.45482\\30 & 0.49011\\40 & 0.50563\\50 & 0.49245\\60 & 0.47220\\80 & 0.43433\\120 & 0.33824\\180 & 0.19390\end{array}\)
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void main()
{
double X[SIZE], Y[SIZE], newx, numerator, denominator, newy;
int i, j, N;
do {
printf("Enter the dimension: ");
scanf("%d", &N);
} while (N <= 0 || N > SIZE);
// reading the array in ascending order
for (i = 0; i < N; i++)
{
printf("Enter X[%d]: ", i);
scanf("%lf", &X[i]);
printf("Enter Y[%d]: ", i);
scanf("%lf", &Y[i]);
}
printf("Enter X: ");
scanf("%lf", &newx);
newy=0;
for(i=0; i<N; i++)
{
numerator=1;
denominator=1;
for(j=0; j<N; j++)
{
if(j!=i)
{
numerator=numerator*(newx-X[j]);
denominator=denominator*(X[i]-X[j]);
}
}
newy=newy+((numerator/denominator)*Y[i]);
}
printf("\n\n for x = %lf, y=%lf\n",newx,newy);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
UVA 1112 - Mice and Maze