雅克比迭代法求解线性方程组的C语言程序?
来源:学生作业帮 编辑:大师作文网作业帮 分类:综合作业 时间:2024/11/12 00:29:48
雅克比迭代法求解线性方程组的C语言程序?
void Solve ( double dCoef [] ,double dY [] ,unsigned int iOrder ,double dErr)
{//用Jacobi迭代法解方程组,dCoef[]系数阵,Y[]向量,iOrder给出方程阶数,dErr给出精度
\x05double res [Max];\x05//方程解
\x05double res2[Max];\x05//保存上一阶方程解
\x05if ( Max < iOrder )
\x05{
\x05\x05printf ("最多支持%d阶方程组.",Max);
\x05\x05return;
\x05}
\x05for ( unsigned int i = 0 ; i < iOrder ; res2 [i++] = 0.0 );\x05//初始解向量 (0,0...)
\x05
\x05while ( true )
\x05{
\x05\x05bool bStopIterative = true;\x05
\x05\x05for (unsigned int i = 0 ; i < iOrder ; ++i)
\x05\x05{
\x05\x05\x05double dSum2 = 0;
\x05\x05\x05for (unsigned int j = 0 ; j < iOrder ; j++)
\x05\x05\x05{//求第二项
\x05\x05\x05\x05if ( j == i ) continue;
\x05\x05\x05\x05dSum2 += dCoef [i * iOrder + j] * res2 [j];
\x05\x05\x05}
\x05\x05\x05res[i] = 1/dCoef[i * iOrder + i] * ( dY[i] - dSum2 );
\x05\x05\x05
\x05\x05\x05if ( abs ( res2[i] - res [i] ) > dErr )
\x05\x05\x05\x05bStopIterative = false;
\x05\x05}
\x05\x05
\x05\x05if ( bStopIterative )
\x05\x05\x05break;
\x05\x05for (unsigned int i = 0 ; i < iOrder ; i++ )
\x05\x05\x05res2[ i ] = res[ i ];
\x05}
\x05//输出结果
\x05for (unsigned int i = 0 ; i < iOrder ; i++)
\x05\x05printf ("x%d = %lf\n",i+1 ,res[i]);
}
int main(int argc,char* argv[])
{
\x05double a[] =
\x05{
\x05\x058,-3,2,
\x05\x054,11,-1,
\x05\x052,1,4
\x05};
\x05double b[3] =
\x05{
\x05\x0520,33,12
\x05};
\x05Solve ( a ,b ,15 ,1e-10);
\x05getchar();
\x05return 0;
}
{//用Jacobi迭代法解方程组,dCoef[]系数阵,Y[]向量,iOrder给出方程阶数,dErr给出精度
\x05double res [Max];\x05//方程解
\x05double res2[Max];\x05//保存上一阶方程解
\x05if ( Max < iOrder )
\x05{
\x05\x05printf ("最多支持%d阶方程组.",Max);
\x05\x05return;
\x05}
\x05for ( unsigned int i = 0 ; i < iOrder ; res2 [i++] = 0.0 );\x05//初始解向量 (0,0...)
\x05
\x05while ( true )
\x05{
\x05\x05bool bStopIterative = true;\x05
\x05\x05for (unsigned int i = 0 ; i < iOrder ; ++i)
\x05\x05{
\x05\x05\x05double dSum2 = 0;
\x05\x05\x05for (unsigned int j = 0 ; j < iOrder ; j++)
\x05\x05\x05{//求第二项
\x05\x05\x05\x05if ( j == i ) continue;
\x05\x05\x05\x05dSum2 += dCoef [i * iOrder + j] * res2 [j];
\x05\x05\x05}
\x05\x05\x05res[i] = 1/dCoef[i * iOrder + i] * ( dY[i] - dSum2 );
\x05\x05\x05
\x05\x05\x05if ( abs ( res2[i] - res [i] ) > dErr )
\x05\x05\x05\x05bStopIterative = false;
\x05\x05}
\x05\x05
\x05\x05if ( bStopIterative )
\x05\x05\x05break;
\x05\x05for (unsigned int i = 0 ; i < iOrder ; i++ )
\x05\x05\x05res2[ i ] = res[ i ];
\x05}
\x05//输出结果
\x05for (unsigned int i = 0 ; i < iOrder ; i++)
\x05\x05printf ("x%d = %lf\n",i+1 ,res[i]);
}
int main(int argc,char* argv[])
{
\x05double a[] =
\x05{
\x05\x058,-3,2,
\x05\x054,11,-1,
\x05\x052,1,4
\x05};
\x05double b[3] =
\x05{
\x05\x0520,33,12
\x05};
\x05Solve ( a ,b ,15 ,1e-10);
\x05getchar();
\x05return 0;
}