Организация математических операций в С++
Функция void ERROR_MATRIX(dim):
Это функция-член, которая вызывается для фиксации некоторых ошибок при создании матриц и работе с ними, таких как отсутствие памяти, несогласованность размеров матриц при операции умножения, попытки вычислить отрицательную степень матрицы и т.п.
Листинг модуля с определением и реализацией класса матриц
// файл tmatr.cpp
#include
#include
#include
#include
typedef unsigned char dim;
template
typedef Matrix Vector;
private:
VARTYPE *matr; // указатель на массив матрицы
dim m,n; // размеры матрицы
public:
// конструкторы и деструкторы:
Matrix() { matr=(VARTYPE*)0; m=n=0; }
Matrix(dim,dim=1); // Обычный конструктор
Matrix(const
Matrix
~Matrix() { delete [ ]matr; }
// доступ к элементам матрицы
dim size_row() { return m; } // число строк
dim size_col() { return n; } // число столбцов
VARTYPE& operator() (dim x) const { return (*this)(x,0); } // элементу
// перегруженные операции и функции:
Matrix
Matrix
Matrix
Matrix
VARTYPE determ(); // определитель матрицы
VARTYPE vmodul(); // модуль вектора
Matrix& Gauss(dim,dim); // преобразование по Гауссу
// (для получ. обратной и единичной матрицы)
// (для получ. верхнетреугольной матрицы)
Matrix minor(dim,dim); // возвращает указ. минор матрицы
Vector line(dim i) // возвращает вектор-строку матрицы
{ return extract(1,n,i,0); }
Vector column(dim j) // возвращает вектор-столбец матрицы
{ return extract(m,1,0,j); }
VARTYPE& operator() (dim,dim) const; // доступ к
Matrix
// безусловное приравнивание матриц
Matrix
Matrix
Matrix
void swap_line(dim, dim); //обмен строками матрицы
void swap_column(dim, dim); // обмен столбцами матрицы
friend
Matrix
friend Matrix
friend Matrix
friend Matrix
operator*(const double&,const Matrix
friend Matrix
operator*(const Matrix
friend ostream&
operator<<(ostream&,Matrix
// потоковый вывод матрицы
friend int
operator>>(istream&,Matrix
// потоковый ввод существ. матрицы
// 0 - без. ошибок, 1 - была ошибка
dim read(ifstream&); // файловое чтение и запись матрицы
dim write(ofstream&); // в ее внутреннем, двоичном представлении.
friend
VARTYPE operator %(const Matrix
//Функция ошибок
void ERROR_MATRIX(dim) const;
};
// Реализация класса матриц
template
Matrix
{
m=M;
n=N;
matr=new VARTYPE[m*n];
if(!matr) ERROR_MATRIX(1);
setmem(matr,sizeof(VARTYPE)*m*n,0);
}
template
Matrix
{
m=M_Obj.m;
n=M_Obj.n;
matr=new VARTYPE[m*n];
if(!matr) ERROR_MATRIX(1);
movmem(M_Obj.matr, matr, sizeof(VARTYPE)*m*n);
}
template
Matrix
{
m=M_Obj.m;
n=M_Obj.n;
matr=new VARTYPE[m*n];
if(!matr) ERROR_MATRIX(1);
movmem(M_Obj.matr,matr,sizeof(VARTYPE)*m*n);
return *this;
}
//Диагональ?
template
Matrix
{
for(int i=0,j;i if(i==j)
(*this)(i,j)=f; else (*this)(i,j)=0; return *this; } template Matrix { if (q>0) { for(Matrix M=*this; q>1;
q--) M=M*(*this); return M; } if (q!=-1)
ERROR_MATRIX(3); //
вычисление
обратной метoдом
преобразований
Гаусса if
(n!=m) ERROR_MATRIX(4); Matrix M(m,2*n); M.insert(*this); for(int i=0;i M(i,i+M.m)=1; for(i=0;i M.Gauss(i,i); return
M.extract(M.m,M.m,0,M.m); } template Matrix {
Matrix for(int i=0, j; i for(j=0; j A(j,i)=(*this)(i,j); return A; } template VARTYPE
Matrix { if
(n!=m) ERROR_MATRIX(4); if (n==1) return (*this)(0,0); for(int i=0; i if ((*this)(i,0)) { static Matrix M <<= *this; VARTYPE
d=M(i,0)*(i%2?-1:1); return
d*M.Gauss(i,0).minor(i,0).determ(); } return 0.0; } template VARTYPE
Matrix { VARTYPE d=0; if (n!=1)
ERROR_MATRIX(9); static Matrix M <<= *this; for(int i=0; i d=d+M(i,0)*M(i,0); return sqrt(d); } template Matrix { Matrix if (!A(M,N))
ERROR_MATRIX(5); for(int i=0,j;i for(j=0;j if (i!=M && j!=N)
A(i,j)-=A(M,j)*A(i,N)/A(M,N); for(j=0;j if (j!=N) A(M,j)/=A(M,N); for(i=0;i A(i,N)=0; A(M,N)=1; return *this; } template Matrix { //
строки y и столбца
x Matrix for(int
i=0,in=0,j,jn;i if (i!=M) { for(j=0,jn=0;j if (j!=N)
A(in,jn++)=(*this)(i,j); in++; } return A; } template
Matrix { if (M+A.m>m ||
N+A.n>n) ERROR_MATRIX(6); for(int i=0, j; i for(j=0; j (*this)(i+M,j+N)=A(i,j); return
*this; } template
Matrix { if (M+LM>m ||
N+LN>n) ERROR_MATRIX(7); Matrix for(int i=0, j; i for(j=0; j A(i,j)=(*this)(i+M,j+N); return A; } template VARTYPE&
Matrix { return *(matr+n*M+N); } template Matrix { Matrix for(int i=0,j; i for(j=0; j C(i,j)+=B(i,j); return C; } template Matrix { Matrix for(int i=0, j; i for(j=0;j C(i,j)-=B(i,j); return C; } template Matrix { Matrix if (A.n!=B.m) { if(A.m==3 &&
A.n==1 && B.m==3 && B.n==1) { C(0)=A(1)*B(2)-A(2)*B(1); C(1)=A(2)*B(0)-A(0)*B(2); C(2)=A(0)*B(1)-A(1)*B(0); } else A.ERROR_MATRIX(2); } else { for(int
i=0,j,k;i for(j=0;j for(k=0;k C(i,j)+=A(i,k)*B(k,j); } return C; } template
Matrix { Matrix for(int
i=0,j;i for(j=0;j B(i,j)*=f; return B; } template
Matrix { Matrix for(int
i=0,j;i for(j=0;j B(i,j)*=f; return
B; } template Matrix { delete [] matr; m=M; n=N; if (N && M) {
matr=new VARTYPE[m*n]; if (!matr)
ERROR_MATRIX(1);
setmem(matr,sizeof(VARTYPE)*m*n,0); } else { m=n=0;
matr=(VARTYPE*)0; } return *this; } template ostream&
operator<<(ostream &out,Matrix { for(int
i=0,j;i {
for(j=0;j out << A(i,j)<<
" "; out< } return out; } template int operator>>(istream
&inp,Matrix { for(int
i=0,j;i for(j=0;j>A(i,j)) ) return 1; return 0; } template void
Matrix { if (L1==L2) return; double b; for(int j=0;j { b=(*this)(L1,j); (*this)(L1,j)=(*this)(L2,j); (*this)(L2,j)=b; } } template void
Matrix { if (C1==C2) return; double b; for(int i=0;i { b=(*this)(i,C1); (*this)(i,C1)=(*this)(i,C2); (*this)(i,C2)=b; } } template dim
Matrix { (finp.get(m)).get(n);
delete []matr; matr=new VARTYPE[m*n]; if(!matr)
ERROR_MATRIX(1); setmem(matr,sizeof(VARTYPE)*m*n,0); finp.read((char
*)matr,sizeof(VARTYPE)*m*n); return finp.fail(); } template dim
Matrix { (fout.put(m)).put(n); (fout.write((char
*)matr,sizeof(VARTYPE)*m*n))< } template VARTYPE operator%(const
Matrix { if(A.n!=1 || B.n!=1)
A.ERROR_MATRIX(9); if(A.m!=B.m)
A.ERROR_MATRIX(0); VARTYPE scalarmul = 0; for(int i=0; i scalarmul =
scalarmul+A(i)*B(i); return scalarmul; } template void
Matrix { static char *message[]
= {
"Матрицы
должны иметь
одинаковую
размерность", //0 "Не
выделена
память!", //1 "Матрицы
не согласованы
для умножения", //2 "Степень
должна быть
больше нуля
или -1", //3 "Матрица
должна быть
квадратной", //4 "Нулевой
ведущий элемент
в преобразовании
Гаусса", //5 "Вставка
невозможна
из-за перекрытия
базовой матрицы", //6
"Извлекаемая
матрица выходит
за границы
базовой", //7 "Выход
за границы.
Попытка доступа
к несущ. элементу", //8 "Это
не вектор!"}; //9 cerr<<"ERROR:
"<< message[E] << endl; exit(1); }
Демонстративно
- тестирующая
программа: #include
#include
#include
#include
"tmatr.cpp" int
main() {
clrscr();
Matrix
Matrix
double d;
A(0,0)=1.1; A(0,1)=2.2; A(0,2)=3.3;
A(1,0)=2.4; A(1,1)=1.1; A(1,2)=4.4;
A(2,0)=1.3; A(2,1)=2.1; A(2,2)=4.1;
B(0,0)=2; B(0,1)=7; B(0,2)=2;
B(1,0)=4; B(1,1)=8; B(1,2)=1;
B(2,0)=6; B(2,1)=4; B(2,2)=1;
V(0)=2.1; V(1)=3.31; V(2)=1.4;
H(0)=1.1; H(1)=2.1; H(2)=3.1; //******************************
C=A+B;
cout<<"A:n"<
cout<<"B:n"<
cout<<"C=A+B:n"<
cout<<"Press any key...n";
getch();
clrscr(); //******************************
C=A-B;
cout<<"A:n"<
cout<<"B:n"<
cout<<"C=A-B:n"<
cout<<"Press any key...n";
getch();
clrscr(); //****************************** //******************************
X=V+H;
cout<<"V:n"<
cout<<"H:n"<
cout<<"X=V+H:n"<
cout<<"Press any key...n";
getch();
clrscr(); //******************************
X=V-H;
cout<<"V:n"<
cout<<"H:n"<
cout<<"X=V-H:n"<
cout<<"Press any key...n";
getch();
clrscr();
C=A*V;
cout<<"A:n"<
cout<<"V:n"<
cout<<"C=A*V:n"<
cout<<"Press any key...n";
getch();
clrscr(); //******************************
Matrix
D(0,0)=1; D(0,1)=2; D(0,2)=3;
D(1,0)=2; D(1,1)=5; D(1,2)=6;
D(2,0)=7; D(2,1)=3; D(2,2)=9;
ofstream fout("test.mtr");
if(!fout)
{
cout<<"file not openn";
return 1;
}
D.write(fout);
fout.close();
ifstream fin("test.mtr");
if(!fin)
{
cout<<"file not openn";
return 1;
}
E.read(fin); //й су«їtЎ«ј
уїсС
cout<<"D:n";
cout<
cout<<"E:n";
cout<
fin.close();
cout<<"Press any key...n";
getch();
clrscr();
//************************************
C=A^-1;
cout<<"A:n"<
cout<<"C=A^-1:n"<
cout<<"Press any key...n";
getch();
clrscr();
//****************************
// A*X=V X=(A^-1)*V
X=(A^-1)*V;
cout<<"A^-1:n"<<(A^-1)<
cout<<"V:n"<
cout<<"X:n"<
cout<<"Press any key...n";
getch();
clrscr(); //************************************
d=A.determ();
cout<<"determinant of A = "<
d=V.vmodul();
cout<<"modul of V = "<
cout<<"Press any key...n";
getch();
clrscr(); //************************************
V(0)=4; V(1)=3; V(2)=2;
U(0)=1; U(1)=2; U(2)=3;
d=V%U;
cout<<"scalar product V*U= "<<
d<
cout<<"Press any key...n";
getch();
clrscr(); //************************************
C=!A;