当前位置:文档之家› 数值方法C++代码大全上(包括二分法迭代法牛顿法等等)

数值方法C++代码大全上(包括二分法迭代法牛顿法等等)

#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)
1.
#include<iostream.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:";
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;
cin>>a>>b>>w;
x=(a+b)/2;
while(fabs(f(x))>w&&fabs(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;
}
cout<<x<<endl;
printf("请连续输入矩阵值:");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
scanf("%f", &a[i][j]);
}
printf("请输入右端项:");
for(i=0; i<n; i++)
{
scanf("%f", &b[i]);
}
/*显示原始矩阵*/
printf("\n原始矩阵\n");
else //计算其他x值(对于公式中的求和部分,需要调用getm()函数)
result = float((b[i]-getm(a,x,i,n))/a[i][i]);
return result;
}
void main()
{
//float a[N][N] = {{2,1,1},{1,3,2},{1,2,2}};
cout << Solve(getIterativeValue,x,e,10) << endl;
system("pause");
return 0;
}
3.
#include <iostream>
#include <cmath>
#include <iomanip>
#include <stdio.h>
using namespace std;
}
2.
#include <iostream>
#include <cmath>
#include <iomanip>
#include <stdio.h>
using namespace std;
typedef double (*pFun)(double x);
double getIterativeValue(double x)
break;
}
else
x = res;
outPrint("第%d次迭代以后x值为:%0.7lf\n ",10-n,x);
}
return res;
}
int main()
{
cout << setprecision(7);
double x,e;
cout << "输入初值和精度:" << endl;
cin >> x >> e;
//float b[N] = {4,6,5};
float a[N][N]; //系数矩阵
float b[N]; //右端项
float x[N]; //方程组解
int i,j,k;
int n=N; //矩阵大小
/*用户手工输入矩阵*/
printf("请输入系数矩阵的大小:");
scanf("%d", &n);
* loat a[N][N], float b[N], float x[N], int i, int n)
{
float result;
if(i==n-1) //计算最后一个x的值
result = float(b[n-1]/a[n-1][n-1]);
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
printf("%f ",a[i][j]);
{
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)
{
outPrint("第%d次次迭代以后返回值为:%0.7lf \n",10-n,res);
{
float m = 0;
int r;
for(r=i+1; r<n; r++)
{
m += a[i][r] * x[r];
}
return m;
}
/*
*解方程组,计算x
* float a[][]系数矩阵
* float b[]右端项
* float x[]方程组解
* int i解的序号
* int n矩阵大小
}
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>
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;
相关主题