matlab还没学精通,正好好久没写代码了,借此温习温习。
//Jacobi.cpp
#include "Jacobi.h"
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
using std::vector;
vector<double> matrix_A;
vector<double> vector_b;
Jacobi::Jacobi()
{
cout << "输入方阵维数:";
cin >> order;
std::cout << order << "阶矩阵构造成功" << endl;
}
void Jacobi::input_matrix_A()
{ //由于数组在编译阶段就已经分配内存,维度必须是常量,故此处用向量来存储矩阵
//初始化为order*order个int元素,没个元素都被初始化为0
double elemt = 0;
for (int i = 0; i <= order * order - 1; i++)
{
cout << "输入第" << i + 1 << "个元素" << endl;
cin >> elemt;
matrix_A.push_back(elemt);
}
pointer_A = &matrix_A[0];
cout << "输入的矩阵为" << endl;
output_matrix(pointer_A);
}
void Jacobi::input_vector_b()
{
double element;
for (int i = 0; i < order; i++)
{
cout << "请输入第" << i + 1 << "个b元素" << endl;
cin >> element;
vector_b.push_back(element);//构造成Ax-b=0
}
pointer_b = &vector_b[0];
cout << "输入的列向量为" << endl;
output_vector(pointer_b);
}
void Jacobi::structure_iterator()
{
for (int i = 0; i <= order - 1; i++)
{
int denominator = pointer_A[i * order + i];
pointer_b[i] = (pointer_b[i]) / denominator;
for (int j = 0; j <= order - 1; j++)
{
pointer_A[i * order + j] = -(pointer_A[i * order + j]) / denominator;
}
pointer_A[i * order + i] = 0;
}
cout << "绝对误差限";
double e;
cin >> e;
vector<double> vector_xk(order, 0);
int n = 0,k=0;//n为满足绝对误差的解的个数,k为迭代次数
do
{
n = 0;
vector<double> vector_xk1(order, 0);//每次都初始化k+1
for (int i = 0; i < order; i++)
{
for (int j = 0; j < order; j++)
{
vector_xk1[i] += (vector_xk[j] * pointer_A[i * order + j]);
}
vector_xk1[i] += pointer_b[i];
}
for (int i = 0; i < order; i++)
{
if (abs(vector_xk[i]-vector_xk1[i]) < e)
{
n++;
}
}
vector_xk = vector_xk1;
k++;
cout << "k=" << k << endl;
output_vector(&vector_xk[0]);
} while (n<order);
}
void Jacobi::output_matrix(double* p)
{
double* pointer = p;
for (int i = 0; i <= order - 1; i++)
{
for (int j = 0; j <= order - 1; j++)
{
cout << pointer[i * order + j] << "\t";
}
cout << endl;
}
}
void Jacobi::output_vector(double* q)
{
double* pointer = q;
for (int i = 0; i < order; i++)
{
cout << pointer[i] << "\t";
}
cout << endl;
}```
```cpp
//Jacobi.h
#ifndef _JACOBI_H_
#define _JACOBI_H_
class Jacobi
{
public:
void input_matrix_A(); //输入系数矩阵A
void input_vector_b();//输入AX=b中的向量b
void structure_iterator();//构造迭代公式
void output_matrix(double* p);//输出矩阵
void output_vector(double* q);//输出向量
Jacobi();
private:
double* pointer_A = 0;//指向系数矩阵的指针
double* pointer_b = 0;//指向b的指针
int order = 0; //矩阵阶数
};
#endif