?? 新建 文本文檔 (5).txt
字號:
牛頓和拉格朗日插值算法http://www.diybl.com/ 2007-2-13 網(wǎng)絡 點擊:873 [ 評論 ]
-
-
文章搜索: 【點擊打包該文章】
【到本站論壇,與同行交流】
/*近日瀏覽文章時發(fā)現(xiàn)在這個網(wǎng)站上有好幾篇問關(guān)于牛頓插值和拉格朗日插值的文章。本人正好寫了這個代碼,將它公布,希望對一些朋友有幫助。如程序中有什么問題請與我聯(lián)系。QQ:421404493 E-mail:wbaobao#zj.com*/
//編譯平臺:2000+vc6.0
//實驗一
//作者:計算機科學與技術(shù)02級2班 寶寶 421404493
#include<stdio.h>
#include<stdlib.h>
#include<iostream.h>
typedef struct data
{
float x;
float y;
}Data;//變量x和函數(shù)值y的結(jié)構(gòu)
Data d[20];//最多二十組數(shù)據(jù)
float f(int s,int t)//牛頓插值法,用以返回插商
{
if(t==s+1)
return (d[t].y-d[s].y)/(d[t].x-d[s].x);
else
return (f(s+1,t)-f(s,t-1))/(d[t].x-d[s].x);
}
float Newton(float x,int count)
{
int n;
while(1)
{
cout<<"請輸入n值(即n次插值):";//獲得插值次數(shù)
cin>>n;
if(n<=count-1)// 插值次數(shù)不得大于count-1次
break;
else
system("cls");
}
//初始化t,y,yt。
float t=1.0;
float y=d[0].y;
float yt=0.0;
//計算y值
for(int j=1;j<=n;j++)
{
t=(x-d[j-1].x)*t;
yt=f(0,j)*t;
//cout<<f(0,j)<<endl;
y=y+yt;
}
return y;
}
float lagrange(float x,int count)
{
float y=0.0;
for(int k=0;k<count;k++)//這兒默認為count-1次插值
{
float p=1.0;//初始化p
for(int j=0;j<count;j++)
{//計算p的值
if(k==j)continue;//判斷是否為同一個數(shù)
p=p*(x-d[j].x)/(d[k].x-d[j].x);
}
y=y+p*d[k].y;//求和
}
return y;//返回y的值
}
void main()
{
float x,y;
int count;
while(1)
{
cout<<"請輸入x[i],y[i]的組數(shù),不得超過20組:";//要求用戶輸入數(shù)據(jù)組數(shù)
cin>>count;
if(count<=20)
break;//檢查輸入的是否合法
system("cls");
}
//獲得各組數(shù)據(jù)
for(int i=0;i<count;i++)
{
cout<<"請輸入第"<<i+1<<"組x的值:";
cin>>d[i].x;
cout<<"請輸入第"<<i+1<<"組y的值:";
cin>>d[i].y;
system("cls");
}
cout<<"請輸入x的值:";//獲得變量x的值
cin>>x;
while(1)
{
int choice=3;
cout<<"請您選擇使用哪種插值法計算:"<<endl;
cout<<" (0):退出"<<endl;
cout<<" (1):Lagrange"<<endl;
cout<<" (2):Newton"<<endl;
cout<<"輸入你的選擇:";
cin>>choice;//取得用戶的選擇項
if(choice==2)
{
cout<<"你選擇了牛頓插值計算方法,其結(jié)果為:";
y=Newton(x,count);break;//調(diào)用相應的處理函數(shù)
}
if(choice==1)
{
cout<<"你選擇了拉格朗日插值計算方法,其結(jié)果為:";
y=lagrange(x,count);break;//調(diào)用相應的處理函數(shù)
}
if(choice==0)
break;
system("cls");
cout<<"輸入錯誤!!!!"<<endl;
}
cout<<x<<" , "<<y<<endl;//輸出最終結(jié)果
}
#include <iostream>
using namespace std;
typedef struct{
double x;
double y;
}data;
int main()
{
const int n=3; //插值次數(shù)
data *p=new data[n];
for(int i=0;i!=n;++i,++p)
cin >> p->x >> p->y;
p-=n;
double s=0,x=0;
cout << "x = ";
cin >> x;
for (int i=0;i!=n;++i) {
data *q=p; //X[i]
double h=0,b=0;
data *m=p+i; //X[k]
for (int j=0;j!=n;++j,++q){
if (q==m) {continue;}
if (!h&&!b) {
h=x-q->x;
b=m->x-q->x;
}
else {
h*=(x-q->x);
b*=(m->x-q->x);
}
}
if (!s) s=(m->y)*(h/b);
else s+=(m->y)*(h/b);
}
cout << "result:"<<s;
system("pause");
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -