// ConsoleAppSorSolu.cpp : 定义控制台应用程序的入口点。
//
/*
*函数功能:SOR迭代法,雅可比,高斯-赛德尔
*函数原形:bool SorSolution(float &x1,float &x2,float &x3,float acc);
*参数:float &x1,float &x2,float &x3,float acc,前三个参数就是方程的要求解的未知数,最后一个数精度
*返回值:bool型变量,表征函数成功计算与否
*时间复杂度:O(1)
*备注:无
*日期:2014/12/2
*原创:是
*作者:EbowTang
*Email:tangyibiao520@163.com
*/
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
bool SorSolution(float &x1,float &x2,float &x3,float acc);
int main()
{
float x1=0.0,x2=1.0,x3=2.0;
char ans='n';
cout<<"该方程为:"<<endl;
cout<<"9*x1-8.6*x2-1.32*x3=7.2"<<endl;
cout<<"-1.9*x1+10*x2-1.63*x3=8.4"<<endl;
cout<<"-x1-x2+15*x3=13.698"<<endl;
do
{
cout<<"/*******************SOR迭代法,华丽的分割线(此时w=2)*******************/"<<endl;
cout<<"请输入解的精确度:"<<endl;
float accuracy;
cin>>accuracy;
if (SorSolution(x1,x2,x3,accuracy))
{
cout<<"方程组的解为:"<<endl;
cout<<"x1 = "<<x1<<", x2 = "<<x2<<", x3 = "<<x3<<endl;
}
else
{
cout<<"该方程是发散的,无解!"<<endl;
}
cout<<"是否继续?(y/n)";
cin>>ans;
} while (ans=='y');
return 0;
}
/***********求解线性方程组的解******************/
bool SorSolution(float &x1,float &x2,float &x3,float acc)
{
float newX1=x1,newX2=x2,newX3=x3; //新值初始化
float oldX1=1.0,oldX2=2.0,oldX3=3.0; //旧值初始化
int count = 0;
double w=2;//w>1(w>0)时为超松弛迭代法,否则为低松弛
/*判断x1,x2,x3,如果都达到精度要求acc,则停止循环*/
while (fabs(newX1-oldX1)>acc && fabs(newX2-oldX2)>acc&& fabs(newX3-oldX3)>acc)
{
oldX1 = newX1; //将新值赋值给老值
oldX2 = newX2;
oldX3 = newX3;
newX1 = (1-w)*newX1+w*((8.6/9)*oldX2+(1.32/9)*oldX3+(7.2/9));
newX2 = (1-w)*newX2+w*(0.19*oldX1+0.163*oldX3+0.84);
newX3 = (1-w)*newX3+w*((1.0/15)*oldX1+(1.0/15)*oldX2+13.698/15);
/***************************雅可比迭代形式*******************************
newX1 = (8.6/9)*oldX2+(1.32/9)*oldX3+(7.2/9);
newX2 = 0.19*oldX1+0.163*oldX3+0.84;
newX3 = (1.0/15)*oldX1+(1.0/15)*oldX2+13.698/15;
************************************************************************/
/***************************高斯赛德尔迭代形式****************************
newX1 = (8.6/9)*oldX2+(1.32/9)*oldX3+(7.2/9);
newX2 = 0.19*newX1+0.163*oldX3+0.84;
newX3 = (1.0/15)*newX1+(1.0/15)*newX2+13.698/15;
************************************************************************/
count++;
if (count>1000)
return false;
}
x1 = newX1; //达到精度要求则赋值并返回真
x2 = newX2;
x3 = newX3;
cout<<"共迭代了:"<<count<<"次"<<endl;
return true;
}