数值方法代码.docxVIP

  • 6
  • 0
  • 约2.53万字
  • 约 35页
  • 2017-08-05 发布于重庆
  • 举报
数值方法代码

数值方法代码-二分法,迭代法,牛顿法,高斯消元法,高斯先列主元消元法,高斯全主元消元法,标度化列住院消元法,直接三角分解法,道立特分解法,改进的平方根法,平方根法,雅克比法,高斯赛德尔迭代法,牛顿插值法,拉格朗日插值法,最小二乘法,牛顿科茨公式,数值积分梯形公式 1.二分法 #includeiostream.h #include stdio.h #include math.h //调用fabs函数。 double f(double x) //定义函数F(x)。 { return 2*x*x*x-x-1; } void main() { double a,b,w,x; cout请输入方程根的区间[a,b]及误差w:; cinabw; x=(a+b)/2; while(fabs(f(x))wfabs(a-b)w){ //用while循环控制中值折算的条件。 if(f(x)*f(b)0) a=x; //进行二分,缩小求值范围。 else if(f(a)*f(x)0) b=x; x=(a+b)/2; } coutxendl; } 2.迭代法 #includeiostream.h #include stdio.h #include math.h //调用fabs函数。 double f(double x) //定义函数F(x)。 { return 2*x*x*x-x-1; } void main() { double a,b,w,x; cout请输入方程根的区间[a,b]及误差w:; cinabw; x=(a+b)/2; while(fabs(f(x))wfabs(a-b)w){ //用while循环控制中值折算的条件。 if(f(x)*f(b)0) a=x; //进行二分,缩小求值范围。 else if(f(a)*f(x)0) b=x; x=(a+b)/2; } coutxendl; } 3.牛顿法 #include iostream #include cmath #include iomanip #include stdio.h using namespace std; typedef double (*pFun)(double x); double getIterativeValue(double x) { return pow((x+1)/2,(double)1.0/3); } double Solve(pFun f,double x,double e,int n) { double res; while(n--) { res = f(x); if(fabs(res - x) e) { printf(第%d次次迭代以后返回值为:%0.7lf \n,10-n,res); break; } else x = res; printf(第%d次迭代以后x值为:%0.7lf\n ,10-n,x); } return res; } int main() { cout setprecision(7); double x,e; cout 输入初值和精度: endl; cin x e; cout Solve(getIterativeValue,x,e,10) endl; return 0; } 4.高斯消元法 #include stdio.h #include stdlib.h #define N 10 //矩阵大小范围 /* * 使用已经求出的x,向前计算x(供getx()调用) * float a[][] 系数矩阵 * float x[] 方程组解 * int i 解的序号 * int n 矩阵大小 * return 公式中需要的和 */ float getm(float a[N][N], float x[N], int i, int n) { float m = 0; int r; for(r=i+1; rn; r++) { m += a[i][r] * x[r]; } return m; } /* * 解方程组,计算x * float a[][] 系数矩阵 * float b[] 右端项 * float x[]

文档评论(0)

1亿VIP精品文档

相关文档