分段二次插值c語言
A. 用c語言實現拉格朗日插值、牛頓插值、等距結點插值演算法
#include<stdio.h>
#include<stdlib.h>
#include<iostream.h>
typedef struct data
{
float x;
float y;
}Data;//變數x和函數值y的結構
Data d[20];//最多二十組數據
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次插值):";//獲得插值次數
cin>>n;
if(n<=count-1)// 插值次數不得大於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;//判斷是否為同一個數
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]的組數,不得超過20組:";//要求用戶輸入數據組數
cin>>count;
if(count<=20)
break;//檢查輸入的是否合法
system("cls");
}
//獲得各組數據
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<<"你選擇了牛頓插值計算方法,其結果為:";
y=Newton(x,count);break;//調用相應的處理函數
}
if(choice==1)
{
cout<<"你選擇了拉格朗日插值計算方法,其結果為:";
y=lagrange(x,count);break;//調用相應的處理函數
}
if(choice==0)
break;
system("cls");
cout<<"輸入錯誤!!!!"<<endl;
}
cout<<x<<" , "<<y<<endl;//輸出最終結果
}
B. 用C語言求分段函數值
#include<stdio.h>
intmain()
{doublex,y;
scanf("%lf",&x);
if(x<0)y=x*x-1;
elseif(x<1)y=x*x;
elsey=x*x+1;
printf("%g",y);
return0;
}
C. 求雙線性插值法的C語言程序!幫幫忙!拜託各位了!
ab
t
cd
就是兩次線性插值,先在x方向插出t上下方的_t1、_t2,然後再用它們插出t來
floattest(floatx,floaty)
{
float_t1,_t2,t;
_t1=a+(b-a)*(x-ax)/(bx-ax);
_t2=c+(d-c)*(x-cx)/(dx-cx);
t=_t1+(_t2-_t1)*(y-ay);
returnt;
}
D. c語言分段函數怎麼寫
#include"stdio.h"
#include"math.h"
intmain(intargc,char*argv[]){
doublex,y;
printf("Inputx(R:)... x=");
scanf("%lf",&x);
if(x<5)
y=-x+3.5;
elseif(x>=5&&x<10)
y=20-3.5*pow(x+3,7);//這里看著像7,是幾就把7改成幾
else
y=-3.5+sin(x);
printf("y=%g (x==%g) ",y,x);
return0;
}
運行樣例: