拉格朗日插值法

拉格朗日插值法
   
     
#include " iostream "
#include
" math.h "
using namespace std;
int n;
int main()
{
int N;
double x[ 3 ] = { 0.2 , 0.3 , 0.4 }, y[ 3 ] = { 1.2214 , 1.3499 , 1.4918 }, Y = 0 , X1 = 0.285 ,b,m;
int i,j,k;
for (k = 0 ;k < 3 ;k ++ )
{
double p = 1 ;
for (j = 0 ;j < 3 ;j ++ )
{
if (j == k) continue ;
else
{
p
= p * (X1 - x[j]) / (x[k] - x[j]);
}

}
Y
= Y + p * y[k];
}
/* X1=0.285时的近似值 */
printf(
" e(%.3lf)=%.6lf\n " ,X1,Y);
cout
<< " Please Input N value( 2 or 3 ) " << endl << " N= " ;
while (cin >> N)
{

if (N == 2 || N == 3 )
{
double x[ 3 ] = { 0.2 , 0.3 , 0.4 }, y[ 3 ] = { 1.2214 , 1.3499 , 1.4918 }, Y = 0 , X = 0.285 ;
for (k = 0 ;k < N;k ++ )
{
double p = 1 ;
for (j = 0 ;j < N;j ++ )
{

if (j == k) continue ;
else
p
= p * (X - x[j]) / (x[k] - x[j]);
}
Y
= Y + p * y[k];
}
printf(
" L(%d)=%.6lf\n " , N - 1 ,Y);
double X2;Y = 0 ;

m
= 1 ;
if (N == 2 ) X2 = 0.3 ;
else X2 = 0.4 ;
for (k = 0 ;k < N;k ++ )
{
double p = 1 ;
for (j = 0 ;j < N;j ++ )
{
if (j == k) continue ;
else
{
p
= p * (X2 - x[j]) / (x[k] - x[j]);
}

}
Y
= Y + p * y[k];
m
*= (X1 - x[k]);
}
/* N==2或N==3的截断误差 */
printf(
" R%d(%.6lf)<%.5lf\n " ,N - 1 ,X1,fabs(Y * m / 6 ));
// cout<<"Please Input N value(2 or 3)"<<endl<<"N=";
}
else
{
cout
<< " error! " << endl;
}
cout
<< " Please Input N value( 2 or 3 ) " << endl << " N= " ;
}
}

同有兴趣的朋友共勉!

你可能感兴趣的:(值)