You are on page 1of 2

#include <iostream>

#include <stdio.h>
#include <math.h>
#include <iomanip>

using namespace std;

double InterpolateLagrangePolynomial (double x, double* x_values, double* y_values, int size)


{
double lagrange_pol = 0;
double basics_pol;

for (int k = 0; k < size; k++)


{
basics_pol = 1;
for (int i = 0; i < size; i++)
{
if (k == i) continue;
basics_pol *= (x - x_values[i])/(x_values[k] - x_values[i]);
}
lagrange_pol += basics_pol*y_values[k];
}
return lagrange_pol;
}

double testF(double x)
{
return 1/(5+2*x); // for example
}

int main(void)
{
const int size = 10;

double x_values[size];
double y_values[size];

// Generate the points


double a = 0, b = 2, step = (b-a)/size;
int i;
double xx,z1,z2,r1,r2,r;

for (i=0,xx=a ; i < size; i++, xx += step)


{
x_values[i] = xx;
y_values[i] = testF(xx);
}

cout<<"Introduceti o valoare din intervalul ["<<a<<","<<b<<"]: "; cin>>z1;


cout<<"Introduceti o valoare din afara intervalui ["<<a<<","<<b<<"]: "; cin>>z2;
r1=InterpolateLagrangePolynomial(z1 , x_values, y_values, size);
r2=InterpolateLagrangePolynomial(z2 , x_values, y_values, size);

cout<<" Xi | f(Xi) | L(Xi) | Diferenta absoluta "<<endl;


cout<<"--------------------------------------------------------------------"<<endl;
for(i=0;i<size;i++)
{ r=InterpolateLagrangePolynomial(x_values[i] , x_values, y_values, size);
cout<<setw(15)<<x_values[i]<<"|"<<setw(15)<<y_values[i]<<"|"<<setw(15)<<r<<"|
"<<fabs(y_values[i]-r)<<endl;
}

r1=InterpolateLagrangePolynomial(z1 , x_values, y_values, size);


r2=InterpolateLagrangePolynomial(z2 , x_values, y_values, size);
cout<<"--------------------------------------------------------------------"<<endl;
cout<<setw(15)<<z1<<"|"<<setw(15)<<testF(z1)<<"|"<<setw(15)<<r1<<"| "<<fabs(testF(z1)-
r1)<<endl;
cout<<setw(15)<<z2<<"|"<<setw(15)<<testF(z2)<<"|"<<setw(15)<<r2<<"| "<<fabs(testF(z2)-
r2)<<endl;
return 0;
}

You might also like