10个重要的算法C语言实现源代码

包括拉格朗日,牛顿插值,高斯,龙贝格,牛顿迭代,牛顿-科特斯,雅克比,秦九昭,幂法,高斯塞德尔 。都是经典的数学算法,希望能开托您的思路。


1.拉格朗日插值多项式 ,用于离散数据的拟合
<font color="#000000" size="3">C/C++ code
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
float lagrange(float *x,float *y,float xx,int n)     /*拉格朗日插值算法*/
{ int i,j;
   float *a,yy=0.0;    /*a作为临时变量,记录拉格朗日插值多项式*/
   a=(float *)malloc(n*sizeof(float));
   for(i=0;i<=n-1;i++)
   { a=y;
     for(j=0;j<=n-1;j++)
     if(j!=i) a*=(xx-x[j])/(x-x[j]);
     yy+=a;
   }
free(a);
return yy;
}
main()
{ int i,n;
float x[20],y[20],xx,yy;
printf("Input n:");
scanf("%d",&n);
if(n>=20) {printf("Error!The value of n must in (0,20)."); getch();return 1;}
if(n<=0) {printf("Error! The value of n must in (0,20)."); getch(); return 1;}
for(i=0;i<=n-1;i++)
{ printf("x[%d]:",i);
    scanf("%f",&x);
}
printf("\n");
for(i=0;i<=n-1;i++)
{ printf("y[%d]:",i);scanf("%f",&y);}
printf("\n");
printf("Input xx:");
scanf("%f",&xx);
yy=lagrange(x,y,xx,n);
printf("x=%f,y=%f\n",xx,yy);
getch();
}
</font>








2.牛顿插值多项式,用于离散数据的拟合
<font color="#000000" size="3">C/C++ code
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void difference(float *x,float *y,int n)
{ float *f;
int k,i;
f=(float *)malloc(n*sizeof(float));
for(k=1;k<=n;k++)
{ f[0]=y[k];
    for(i=0;i<k;i++)
      f[i+1]=(f-y)/(x[k]-x);
    y[k]=f[k];
}
return;
}
main()
{ int i,n;
float x[20],y[20],xx,yy;
printf("Input n:");
scanf("%d",&n);
if(n>=20) {printf("Error! The value of n must in (0,20)."); getch(); return 1;}
if(n<=0) {printf("Error! The value of n must in (0,20).");getch(); return 1;}
for(i=0;i<=n-1;i++)
{ printf("x[%d]:",i);
    scanf("%f",&x);
}
   printf("\n");
for(i=0;i<=n-1;i++)
{ printf("y[%d]:",i);scanf("%f",&y);}
printf("\n");
difference(x,(float *)y,n);
printf("Input xx:");
scanf("%f",&xx);
yy=y[20];
for(i=n-1;i>=0;i--) yy=yy*(xx-x)+y;
printf("NewtonInter(%f)=%f",xx,yy);
getch();
}</font>






3.高斯列主元消去法,求解其次线性方程组
<font color="#000000" size="3">C/C++ code
#include<stdio.h>
#include <math.h>
#define N 20
int main()
{ int n,i,j,k;
int mi,tmp,mx;
float a[N][N],b[N],x[N];
printf("\nInput n:");
scanf("%d",&n);
if(n>N)
{ printf("The input n should in(0,N)!\n");
    getch();
    return 1;
}
if(n<=0)
{ printf("The input n should in(0,N)!\n");
    getch();
    return 1;
}
printf("Now input a(i,j),i,j=0...%d:\n",n-1);
for(i=0;i<n;i++)
{ for(j=0;j<n;j++)
    scanf("%f",&a[j]);}
pri
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值