迭代法求解非線性方程組
阿新 • • 發佈:2019-02-15
#include<iostream>
#include<math.h>
using namespace std;
int M;//允許迭代最大次數
double E;//允許的誤差
/*
針對式子:
x^2-10x+y^2+23=0
xy^2+x-10y^2+2=0
*/
//計算範數||X-Y||的值
double getNorm(double *x, double *y){
double sum = 0;
for (int i = 0; i < 2; i++)
sum += abs(x[i] - y[i]);
return sum;
}
int main() {
double *X0 = new double[2];//初始迭代向量
double *D = new double[2];//迭代向量
X0[0] = 3.8;
X0[1] = 0.9;
printf("請輸入允許迭代的最大次數:");
cin >> M;
printf("請輸入允許的最大誤差:");
cin >> E;
int k = 0;
while (true) {
if (k > M) {
printf("達到迭代次數,當前值為:\n");
printf("X1 = %f\n", D[0]);
printf("X2 = %f\n", D[1]);
break;
}
D[0] = (pow(X0[0],2)+pow(X0[1],2)+23) / 10;
double temp = (X0[0] * pow(X0[1], 2) + X0[0] + 2) / 10;
D[1] = pow(temp,0.5);
if (getNorm(D, X0) < E) {
cout << "迭代法的結果為:" << endl;
printf("X1 = %f\n",D[0]);
printf("X2 = %f\n", D[1]);
break;
}
X0[0] = D[0];
X0[1] = D[1];
k++;
}
system("pause");
}
#include<math.h>
using namespace std;
int M;//允許迭代最大次數
double E;//允許的誤差
/*
針對式子:
x^2-10x+y^2+23=0
xy^2+x-10y^2+2=0
*/
//計算範數||X-Y||的值
double getNorm(double *x, double *y){
double sum = 0;
for (int i = 0; i < 2; i++)
sum += abs(x[i] - y[i]);
return sum;
}
int main() {
double *X0 = new double[2];//初始迭代向量
double *D = new double[2];//迭代向量
X0[0] = 3.8;
X0[1] = 0.9;
printf("請輸入允許迭代的最大次數:");
cin >> M;
printf("請輸入允許的最大誤差:");
cin >> E;
int k = 0;
while (true) {
if (k > M) {
printf("達到迭代次數,當前值為:\n");
printf("X1 = %f\n", D[0]);
printf("X2 = %f\n", D[1]);
break;
}
D[0] = (pow(X0[0],2)+pow(X0[1],2)+23) / 10;
double temp = (X0[0] * pow(X0[1], 2) + X0[0] + 2) / 10;
D[1] = pow(temp,0.5);
if (getNorm(D, X0) < E) {
cout << "迭代法的結果為:" << endl;
printf("X1 = %f\n",D[0]);
printf("X2 = %f\n", D[1]);
break;
}
X0[0] = D[0];
X0[1] = D[1];
k++;
}
system("pause");
}