//newton.h
#ifndef NEWTON_H_INCLUDED
#define NEWTON_H_INCLUDED
#define INITSIZE 20
#define APPENEDSIZE 20
typedef struct
{
double x;
double y;
}Point;
class Newton
{
private:
int pointNum;
int arrLength;
Point *pointArr;
double *f;
double *tmpf;
void appened();
public:
Newton();
~Newton();
void clear();
inline int getPointNum()const{return pointNum;}
inline void getPoint(int pos,double &x,double &y)const
{
x=pointArr[pos].x;
y=pointArr[pos].y;
}
bool insertPoint(double x,double y);
double Pn(double x)const;
};
#endif // NEWTON_H_INCLUDED
//newton.cpp
#include"newton.h"
#include<string.h>
Newton::Newton()
{
pointNum=0;
arrLength=INITSIZE;
pointArr=new Point[arrLength];
f=new double[arrLength];
tmpf=new double[arrLength];
}
Newton::~Newton()
{
delete pointArr;
delete f;
delete tmpf;
}
void Newton::appened()
{
int lt=arrLength;
Point *tmp=pointArr;
arrLength+=APPENEDSIZE;
pointArr=new Point[arrLength];
memcpy(pointArr,tmp,lt*sizeof(Point));
delete tmp;
double *tf=f;
f=new double[arrLength];
memcpy(f,tf,lt*sizeof(double));
delete tf;
tf=tmpf;
tmpf=new double[arrLength];
memcpy(tmpf,tf,lt*sizeof(double));
delete tf;
}
void Newton::clear()
{
pointNum=0;
arrLength=INITSIZE;
delete pointArr;
delete f;
pointArr=new Point[arrLength];
f=new double[arrLength];
}
bool Newton::insertPoint(double x,double y)
{
for(int i=0;i<pointNum;i++)
if(pointArr[i].x==x)
return false;
pointArr[pointNum].x=x;
pointArr[pointNum].y=y;
double fc=y;
double tmp;
for(int i=1;i<=pointNum;i++)
{
tmp=fc;
fc=(fc-tmpf[i-1])/(pointArr[pointNum].x-pointArr[pointNum-i].x);
tmpf[i-1]=tmp;
}
tmpf[pointNum]=fc;
f[pointNum]=fc;
pointNum++;
if(pointNum==arrLength)
appened();
return true;
}
double Newton::Pn(double x)const
{
double ret=f[0];
double product=1.0;
for(int i=1;i<pointNum;i++)
{
product*=(x-pointArr[i-1].x);
ret+=f[i]*product;
}
return ret;
}
//实例main.cpp,对fx=sin(x)进行插值
#include<stdio.h>
#include<math.h>
#include"newton.h"
int main()
{
Newton N;
for(double i=0.0;i<=1.0;i+=0.2)
N.insertPoint(i,sin(i)); //添加插值节点
for(double i=0.0;i<1.0;i+=0.05)
printf("%-5f:%-5f--%-5f\n",i,sin(i),N.Pn(i));//分别输出sin(i)和牛顿插值的结果
return 0;
}