数值分析 Lab 2 的 C++ 程序示例

 Lab 2.  Lagrange Polynomial 


        Given a set of sample points of a certain function f , use Lagrange polynomial to approximate function values at some given points   a1a2 ,…,am                .
Input
There are several sets of inputs.  For each set:
 The 1st line contains an integer 20 >= n >=0  which is the degree of Lagrange polynomial.   n = -1 signals the end of file.
 The 2nd line contains n+1 distinct real numbers                                                                xi  
 The 3rd line contains n+1 real numbers                                                                            f(xi)                   .
 The last line of a test case consists of an integer m > 0 and m real numbers         ai        .
The numbers are separated by spaces and new lines.

Output (♦represents a space)
For each ai , you are supposed to print the function value at this point in the following format:
               fprintf(outfile, "f(%6.3f)♦=♦%12.8e/n", a, f );
The outputs of two test cases must be seperated by a blank line.

Sample Input
7
0.5♦0.7♦0.9♦1.1♦1.3♦1.5♦1.7♦1.9
0.48♦0.64♦0.78♦0.89♦0.96♦1.00♦0.99♦0.95
5♦0.74♦1.6♦0.55♦1.2♦1.85
1
0.0♦1.0
0.0♦1.0
1♦0.5
–1

Sample Output
f(♦0.740) =6.68735821e–001
f(♦1.600) =1.00341309e+000
f(♦0.550) =5.26938820e–001
f(♦1.200) =9.29135742e–001
f(♦1.850) =9.52078056e–001
 
f(♦0.500) =5.00000000e–001


My answer:

 Lagrange.h

class  CLagrange  
{
private:
    
double LagrangeCoe(int StepIndex,int ApproxIndex);
public:
    
void Output(FILE *fp);
    unsigned 
char GetResult();
    
void Dispose();
    unsigned 
char ReadNext(FILE *fp);
    CLagrange();
    
virtual ~CLagrange();
private:
    
double *m_pXVal;        //x values read from file(the number of x is m_ValNum)
    double *m_pYVal;        //y=f(x) values read from file( m_ValNum)
    int m_ValNum;
    

    
double *m_pApproxXVal;    //x valuse will be esitmated
    double *m_pApproxYVal;    //saved the estimated f(x).
    int m_ApproxNum;        // the number of x will be esitmated

}
;

 Lagrange.cpp

#include  " Lagrange.h "
#define  DELPOINT(p)  if(p != NULL)delete p,p=NULL;
#define  DELARRAYPOINT(p) if (p != NULL) delete [] p ,p=NULL;
//
//  Construction/Destruction
//
//  yxf
CLagrange::CLagrange()
{
    m_ApproxNum
=-1;
    m_pApproxXVal 
= NULL;
    m_pApproxYVal 
= NULL;

    m_pXVal 
= NULL;
    m_pYVal 
= NULL;
    m_ValNum 
= -1;
}


CLagrange::
~ CLagrange()
{
    Dispose();
}


/*--------------------------------------------
return 
    0 for the end of this file
    -1 for file error
    1 for read value ok
description:
    read a group of x and f(x) from file  in.txt
    first read n degree from the first line of file(when n == -1 denoted the end of file return 0 )
    the next line has n+1 numbers which denoted as x
    the next line has n+1 numbers which denoted as f(x)
    the next line first number is how many real numbers 
    need to be estimate by lagrange algorithm. 
    then read the last number and estimated the f(x)

-----------------------------------------------
*/

unsigned 
char   CLagrange::ReadNext(FILE  * fp)
{    
    
int ret,i;
    
double tmp=0;
    
char c=0;
    Dispose();                            
//destroy memory

    
if(fp == NULL)return -1;            //file error 
    ret = fscanf(fp,"%d ",&m_ValNum);
                            
    
if( ret == EOF) return -1;            //file end. but has error
    if( m_ValNum == -1 )return 0;        //file end

    m_ValNum 
++;                        //degree of Lagrange polynomial + 1 is the X Value Number


    m_pXVal 
= new double[m_ValNum];
    m_pYVal 
= new double[m_ValNum ]; //allocate space
    
//read x Value;
    for(i = 0; i < m_ValNum; i++)fscanf(fp,"%lf",&m_pXVal[i]);
    
    fscanf(fp,
"%*[^ ] ");//go to the next line
    
// read f(x)
    for(i = 0;i < m_ValNum; i++)fscanf(fp,"%lf",&m_pYVal[i]);
    
    fscanf(fp,
"%*[^ ] ");//go to the next line
    fscanf(fp,"%d ",&m_ApproxNum);// read the number of the points that will be approximated.
    m_pApproxXVal = new double[m_ApproxNum];//allocate memory
    m_pApproxYVal = new double[m_ApproxNum];
    
//read the points that will be approximated
    for(i = 0; i< m_ApproxNum ; i ++)fscanf(fp,"%lf",&m_pApproxXVal[i]);
    
//read ok return 1
    fscanf(fp,"%*[^ ] ");//go to the next line
    return 1;

}

// destroy the memory allocated by function ReadNext(FILE *fp)
void  CLagrange::Dispose()
{
    DELARRAYPOINT(m_pApproxXVal);
    DELARRAYPOINT(m_pApproxYVal);
    DELARRAYPOINT(m_pXVal);
    DELARRAYPOINT(m_pYVal);
}


unsigned 
char  CLagrange::GetResult()
{
    
    
int i,j;
    
for( i = 0; i < m_ApproxNum ; i++)
    
{
        m_pApproxYVal[i] 
= 0.0;//init
        for(j = 0; j < m_ValNum ; j++)
        
{
            
//denote the formula 2.9 P26
            m_pApproxYVal[i] += (LagrangeCoe(j,i) * m_pYVal[j] );    
        }

    }

    
return 1;
}

/*-----------------------------------------------------------
The Lagrange coefficient polynomials for degree m_ValNum-1. 
denote  the book P26 formula 2.8 
StepIndex is k   and m_pApproxXVal[ApproxIndex] is the x 
-----------------------------------------------------------
*/

double  CLagrange::LagrangeCoe( int  StepIndex,  int  ApproxIndex)
{
    
double Ret=1.0,tmp=1.0;
    
int i;
    
for(i=0;i<m_ValNum;i++)
    
{
        
if(i!=StepIndex)tmp *= (m_pApproxXVal[ApproxIndex]-m_pXVal[i]);
    }

    
for(i = 0; i < m_ValNum; i ++)
    
{
        
if( i != StepIndex) Ret *= (m_pXVal[StepIndex] - m_pXVal[i]);
    }

    
return tmp / Ret;

}

/*------------------------------------------------------------------
print the result to the screen and in the file
----------------------------------------------------------------------
*/

void  CLagrange::Output(FILE  * fp)
{
    
int i;

    printf(
" ********************************************************************** ");
    printf(
"                          Read Value                                   ");
    printf(
"X   :");
    
for(i=0 ; i < m_ValNum ; i++)printf("%6.3f ",m_pXVal[i]);
    printf(
" ");
    printf(
"f(x):");
    
for(i=0 ; i < m_ValNum ; i++)printf("%6.3f ",m_pYVal[i]);
    printf(
" ");
    printf(
"                       Approximated Value                               ");
    
for(i = 0; i < m_ApproxNum ; i ++)printf("f(%6.3f) = %12.8e ",m_pApproxXVal[i],m_pApproxYVal[i]);


    
//print the result to file
    if(fp == NULL)return ;
    
for(i = 0; i < m_ApproxNum ; i ++)
    fprintf(fp, 
"f(%6.3f) = %12.8e ", m_pApproxXVal[i],m_pApproxYVal[i] );


}

 Exe2.cpp

#include  " Lagrange.h "
/*******************************************************
for english instruction:
http://mathworld.wolfram.com/LagrangeInterpolatingPolynomial.html
http://math.fullerton.edu/mathews/numerical/la.htm
http://private.codecogs.com/d-ox/maths/interpolation/lagrange.php
***********************************************************
*/

#include 
< direct.h >

int  main( int  argc,  char *  argv[])
{
    CLagrange lag;
    
char CurDir[256];
    
char InFileName[256];
    
char OutFileName[256];

    
// you may use ".//in.txt" for current directory file
    
// i use getcwd get current directory for clearly.
    getcwd(CurDir,256);//get current directory
    sprintf(InFileName,"%s/in.txt",CurDir);
    sprintf(OutFileName,
"%s/out.txt",CurDir);

    printf(
"Current Directory:    %s ",CurDir);
    printf(
"Input File name  :    %s ",InFileName);
    printf(
"Output File name :    %s",OutFileName);



    
//open file
    FILE *fpIn= fopen(InFileName,"r");
    FILE 
*fpOut = fopen(OutFileName,"wb+");
    
if(fpIn == NULL || fpOut == NULL)
    
{
        printf(
"open file error ");
        
return 0;
    }

    
// ReadNext return 0 if end of file -1 if error
    while(lag.ReadNext(fpIn)>0)
    
{
        lag.GetResult();    
//get the result 
        lag.Output(fpOut);    //out put the result
        fprintf(fpOut," ");
    }

    fclose(fpIn);
    fclose(fpOut);
    printf(
" ********************************************************************** ");
    
    getchar();
// i am not familial with winxp .
                
//in my win2000 if i don't use this  function
                
// the dos windows only flashed and disappeared immediately
    return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值