大学里的数值分析实验-拉格朗日-欧拉-改进的欧拉-牛顿插-二分-四阶-迭代
拉格朗日-#include <iostream>
using namespace std;
int main()
{
float x,y,z,X[50],Y[50];
int j,m,n;
cout<<"请输入要计算的x,x=";
cin>>x;
cout<<"请输入插值节点个数n,n=";
cin>>n;
cout<<"请输入"<<n+1<<"组X,Y的值"<<endl;
for(j=0;j<=n;j++)
cin>>X[j]>>Y[j];
y=0;
for(m=0;m<=n;m++)
{
z=1;
for(j=0;j<=n;j++)
if(j!=m)
z=z*(x-X[j])/(X[m]-X[j]);
y=y+z*Y[m];
}
cout<<"拉格朗日插值的结果为:"<<endl;
cout<<"当x="<<x<<"时, y="<<y<<endl;
return 0;
}
欧拉-
#include<iostream.h>
int main()
{
double x0,y0,a,b,h,x,y,Y;
int n,i;
cout<<"请输入初始值"<<endl;
cin>>x0>>y0;
cout<<"请输入取值范围"<<endl;
cin>>a>>b;
cout<<"请输入步长"<<endl;
cin>>h;
x=x0,y=y0;
n=(b-a)/h;
cout<<"结果为:"<<endl;
for(i=1;i<n+1;i++)
{
Y=y+h*(y-2*(x+(i-1)*h)/y);
cout<<i*h<<" ";
cout<<Y<<endl;
y=Y;
}
return 0;
}
改进
的欧拉-
#include<iostream>
using namespace std;
float f(float x,float y);
int main()
{
float x0,y0,a,b,x1,y1,yp,yc,h;
int i,n;
cout<<"请输入已知的一组x0,y0的值:";
cin>>x0>>y0;
cout<<"请输入步长h, h=";
cin>>h;
cout<<"请输入定义域(两端的数值):";
cin>>a>>b;
n=(b-a)/h;
cout<<" n"<<" Xn"<<" Yn"<<endl;
for(i=1;i<=n+1;i++)
{
yp=y0+h*f(x0,y0);
x1=x0+h;
yc=y0+h*f(x1,yp);
y1=(yp+yc)/2;
cout.width(2);
cout<<i;
cout.width(6);
cout<<x1;
cout.width(10);
cout<<y1;
cout<<endl;
x0=x1;
y0=y1;
}
return 0;
}
float f(float x,float y)
{
float z;
z=y-2*x/y;
return z;
}
牛顿插-
#include<iostream.h>
int main()
{
int i,n,j;
float X[100],Y[100],a,b[100]={0},x,y;
cout<<"请输入节点总数n:"<<endl;
cin>>n;
cout<<"请输入要求的x的值:"<<endl;
cin>>x;
for(i=0;i<=n;i++)
{
cout<<"请输入第"<<i+1<<"组x、y的值:"<<endl;
cin>>X[i]>>Y[i];
}
y=Y[0];
for(i=0;i<=n;i++)
{
for(j=0;j<=n;j++)
{
a=1.0;
if(j!=i)
{
a=a*(X[i]-X[j]);
}
}
b[i+1]=b[i]+Y[i]/a;
}
for(i=0;i<n;i++)
{
y=y+b[i+1]*(x-X[i]);
}
cout<<"所求的函数值为:"<<y<<endl;
return 0;
}
二分-
#include<iostream.h>
float f(float X);
int main()
{
float a,b,x;
cout<<"请输入估计实根所在的区间。"<<endl;
cin>>a>>b;
while ((a-b)*(a-b)>=0.000025)
{
x=(a+b)/2;
if (f(x)*f(a)>0)
a=x;
else b=x;
}
cout<<x;
return 0;
}
float f(float X)
{
float z;
z=X*X*X-X-1;
return z;
}
四阶-
#include<iostream.h>
int main()
{
double x0,y0,a,b,k1,k2,k3,k4,xn,yn,h,Y;
int i,n;
cout<<"请输入初值:"<<endl;
cin>>x0>>y0;
cout<<"请输入范围:"<<endl;
cin>>a>>b;
cout<<"请输入步长:"<<endl;
cin>>h;
n=(b-a)/h;
xn=x0;
yn=y0;
cout<<"结果为:"<<endl;
for(i=1;i<n+1;i++)
{
k1=yn-2*xn/yn;
k2=yn+h*k1/2-(2*xn+h)/(yn+h*k1/2);
k3=yn+h*k2/2-(2*xn+h)/(yn+h*k2/2);
k4=yn+h*k3-2*(xn+h)/(yn+h*k3);
Y=yn+h*(k1+2*k2+2*k3+k4)/6;
cout<<i*h<<" ";
cout<<Y<<endl;
xn=i*h;
yn=Y;
}
return 0;
}
迭代
#include<iostream.h>
#include<math.h>
double f(double X);
int main()
{
double a,b,c;
cout<<"请输入估计实根。"<<endl;
cin>>a;
b=f(a);
while ((a-b)*(a-b)>=0.000000000001)
{
b=f(b);
c=b;
a=b;
}
cout<<c;
return 0;
}
double f(double X)
{
double z;
z=pow(X+1,1.0/3);
return z;
}