拉格朗日N次插值多项式代码

本文通过一个具体的数学实例介绍了拉格朗日插值法的应用过程,包括如何利用已知的正弦值来估算未知角度的正弦值,并提供了完整的C++代码实现。

// lagrange.cpp: 主项目文件。
//    sin30o = 0.5; sin60o = sqrt(3)/2≈0.86603,求sin50o=? 
#include <stdafx.h>
#include 
<iostream>

using namespace std;

double Lagrange(int n, double x_var, double *x, double *y);
bool   CheckValid(int n, double *x);

int main( )
{
    
double x[ 2= 3060};
    
double y[ 2= {0.50.86603};

    
double x_var = 50;
    
double res   = 0.0f;

    
if(!CheckValid(1,x) ){
        cout 
<<"输入的插值节点的x值必须互异!"<<endl;
    }


    res 
= Lagrange( 1,x_var,x,y);

    
//printf("the result is : %3.5f ",res);
    cout << "the result is :" << res ;
    getchar();

    
return 0;
}



/*检查当i!=j时是否有x[i] == x[j]的情况,如果有则不符合算法条件*/
bool CheckValid(int n, double *x){
    
int i;
    
int j;

    
for(i = 0; i <= n ; i++){

        
for( j = 1; j<= n; j++){

            
if ( i == j){

                
continue;

            }
else{

                
if(x[i] == x[j])        
                
return false;    

            }
//end of else
        }
//end of if        
    }
// end of for(i)
    return true;
}


/*
 * n: 插值次(阶)数;
 * x_var:待求结果对应的x值;
 *数组*x,*y 为已知插值节点(xi,yi)
 
*/

double Lagrange(int n, double x_var, double *x, double *y)
{
    
/*
    * Local variables definition
    
*/

    
int                  i; 
    
int                  j;
    
double tempi = 0.0f;
    
double tempj = 0.0f;

    
for ( i = 0; i <= n; i++ ){

        tempj 
= 1.0f;

        
for ( j = 0; j <= n; j++ ){
            
if ( j == i){
                
continue;
            }
else{
                tempj 
*= ( x_var - x[j])*1.0/( x[i] - x[j] );
            }

        }
/* end of for(j)*/

        tempi 
+= tempj * y[i];

    }
/* end of for(i) */

    
return tempi;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值