牛顿插值

//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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值