- #include <iostream>
- using namespace std;
- typedef struct data
- {
- float x;
- float y;
- }Data ;
- Data d[20];
- /*****************Newton插值法*************/
- float getDivDiference(int s,int t)//Define the function of get divided difference
- {
- if(t == s+1)
- {
- return (d[t].y-d[s].y)/(d[t].x-d[s].x);
- }
- else
- {
- return (getDivDiference(s+1,t)-getDivDiference(s,t-1))/(d[t].x-d[s].x);
- }
- }
- float newtonfoo(float x,int count)
- {
- int n;
- for(; ; )
- {
- cout<<"请输入n 的值(即插值次数):";
- cin>>n;
- if(n <= count -1)
- {
- break;
- }
- else
- {
- cout<<"Error ,please input another iterator value "<<endl;
- }
- }
- float t =1.0;
- float y = d[0].y;
- float yt = 0.0;
- for(int j = 1; j<= n; j++)
- {
- t=(x-d[j-1].x)*t;
- yt = getDivDiference(0,j)*t;
- y=y+yt;
- }
- return y;
- }
- /**Newton插值法(end*************/
- /*****************lagrange插值法************/
- float lagrangefoo(float x,int count)
- {
- float y =0.0;
- for(int k =0;k<count; k++)
- {
- float p=1.0;
- for(int j = 0; j<count; j++)
- {
- if(k==j)
- {
- continue;
- }
- else
- {
- p = p*(x-d[j].x)/(d[k].x-d[j].x);
- }
- }
- y = y+ p*d[k].y;
- }
- return y;
- }
- /*****lagrange插值法(end******/
- float initfooArray()
- {
- int count ;
- while (1)
- {
- cout<<"请输入弦x[i],y[i]的组数,不得超过30组:";
- cin>>count;
- if(count<=30)
- break;
- }
- for(int i= 0; i<count; i++)
- {
- cout<<"请输入第"<<i+1<<"组x的值:";
- cin>>d[i].x;
- cout<<"请输入第"<<i+1<<"组y的值:";
- cin>>d[i].y;
- }
- return count;
- }
- void help()
- { //cout<<" Define what you want do!/n";
- cout<<"*****Created by husiwen******/n";
- cout<<"--------------------------------/n";
- cout<<"** *1.Newton插值法 **/n";
- cout<<"** *2.lagrange插值法 **/n";
- cout<<"** *0.退出 **/n";
- cout<<"--------------------------------/n";
- }
- void seek()
- {
- int flag;
- cout<<"请选择你要进行的操作:";
- cin>>flag;
- while(0!=flag)
- {
- switch(flag)
- {
- case 1: //Newton插值法
- {
- cout<<" 你选择的是Newton插值法"<<endl;
- float newtonnum ,calcx,newtonResult;
- newtonnum = initfooArray();
- cout<<"请输入你要计算x的值:";
- cin>>calcx;
- newtonResult=newtonfoo(calcx,newtonnum);
- cout<<"变量x="<<calcx<<"的Newton插值结果为:";
- cout<<newtonResult<<endl;
- }
- flag = 0;
- seek();
- break;
- case 2: //lagrange插值法
- {
- cout<<" 你选择的是lagrange插值法"<<endl;
- float lagnum,calcx,lagResult;
- lagnum = initfooArray();
- cout<<"请输入你要计算x的值:";
- cin>>calcx;
- lagResult=lagrangefoo(calcx,lagnum);
- }
- flag = 0;
- seek();
- break;
- default:
- cout<<"erro/n";
- seek();// 输入错误 ,再次调用 seek 函数 提示用户输入选择操作;
- break;
- }
- }
- return ;
- }
- int main()
- {
- help();
- seek();
- return 0;
- }