📄 chazhi.txt
字号:
#ifndef NEWTON_DEF_
#define NEWTON_DEF_
class CNewton
{
double *f[2];
double *x;
int max;
int n;
public:
CNewton(int MaxN);//MaxN 为最大插值点数 可任意设定
~CNewton();
void InsertPoint(double X,double Y);
double GetValue(double X);
};
#endif
// file: newton.cpp
#include "newton.h"
#include "assert.h"
#include "math.h"
#ifndef NULL
#define NULL 0
#endif
CNewton::CNewton(int MaxN)
{
max=MaxN+1;
n=0;
x=new double[max];
f[0]=new double[max];
f[1]=new double[max];
assert(x!=NULL);
assert(f[0]!=NULL);
assert(f[1]!=NULL);
}
CNewton::~CNewton()
{
if(x)
delete[]x;
if(f[0])
delete[]f[0];
if(f[1])
delete[]f[1];
}
void CNewton::InsertPoint(double X,double Y)
{
int i;
double fw;
assert(n<max);
//重复点检查
for(i=0;i<n;++i)
if(fabs(X-x[i])<1e-5)
return;
//如果确保不会有重复点可删去上面语句
x[n]=X;
fw=Y;
for(i=1;i<=n;++i)
{
double tmp=fw;
fw=(fw-f[1][i-1])/(x[n]-x[n-i]);
f[1][i-1]=tmp;
}
f[0][n]=f[1][n]=fw;
n++;
}
double CNewton::GetValue(double X)
{
if(n==0)
return 0.0;
double s=f[0][n-1];
for(int i=n-2;i>=0;--i)
{
s=s*(X-x[i])+f[0][i];
}
return s;
}
// file: test cpp
#include "newton.h"
#include "iostream.h"
int main(void)
{
int n;
double x,y;
CNewton nt(20);
cout<<"输入插入点个数(n<=20)\nn=";
cin>>n;
for(int i=1;i<=n;++i)
{
cout<<"输入第"<<i<<"个点\nx=";
cin>>x;
cout<<"y=";
cin>>y;
nt.InsertPoint(x,y);
}
while(1)
{
cout<<"计算N(x)\nx=";
cin>>x;
cout<<"N("<<x<<")=\n"<<nt.GetValue(x)<<endl;
if(x==0.0)
break;
}
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -