Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<fstream>
- #include<math.h>
- using namespace std;
- class Jacobi{
- private:
- double** a;
- double eps;
- int n;
- double abs(double var){
- if(var >= 0){return var;}
- else{return (-1)*var;}
- }
- int sign(double var) {
- if (var > 0) return 1;
- if (var < 0) return -1;
- return 0;
- }
- void rotation(int i, int j){
- double cos = 0, sin = 0;
- if (a[i][i] == a[j][j]){
- cos = sqrt((double)2)/2;
- sin = sqrt((double)2)/2;
- }else{
- double x = -2*a[i][j], y = a[i][i] - a[j][j];
- cos = sqrt(0.5 * (1 + (abs(y) / sqrt(x*x + y*y))));
- sin = (sign(x*y)*abs(x)) / (2 * cos*sqrt(x*x + y*y));
- }
- for (int m = 0; m < n; m++) {
- if (m != i && m != j) {
- double aim = a[i][m];
- a[i][m] = cos*a[i][m] - sin*a[j][m];
- a[m][i] = a[i][m];
- a[j][m] = sin*aim + cos*a[j][m];
- a[m][j] = a[j][m];
- }
- }
- double aii = a[i][i], ajj = a[j][j], aij = a[i][j];
- a[i][i] = cos*cos*aii - 2*sin*cos*aij + sin*sin*ajj;
- a[j][j] = sin*sin*aii + 2*sin*cos*aij + cos*cos*ajj;
- a[i][j] = (cos*cos - sin*sin)*aij + cos*sin*(aii - ajj);
- a[j][i] = a[i][j];
- }
- void findMax(int* k, int* l){
- double res = 0;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++){
- if ((i != j)&&(abs(a[i][j]) > abs(res))) {
- res = a[i][j];
- *k = i;
- *l = j;
- }
- }
- }
- }
- public:
- Jacobi(){}
- void input(){
- ifstream fin;
- fin.open("input.txt");
- if(fin.is_open()){
- if(!fin.eof()){
- fin >> n;
- }
- /////
- a = new double*[n];
- for(int i = 0; i < n; i++){
- a[i] = new double[n];
- }
- /////
- for(int i = 0; i < n; i++){
- for(int j = 0; j < n; j++){
- if(!fin.eof()){
- fin >> a[i][j];
- }
- }
- }
- if(!fin.eof()){
- fin >> eps;
- }
- }else{cout << "reading error" << endl;}
- fin.close();
- }
- void solve(){
- int i=0, j=0;
- while (abs(a[i][j]) > eps){
- findMax(&i, &j);
- rotation(i, j);
- }
- }
- void output(){
- for(int i = 0; i < n; i++){
- for(int j = 0; j < n; j++){
- cout << a[i][j] << ' ';
- }
- cout << endl;
- }
- cout << endl;
- for(int i = 0; i < n; i++){
- cout << a[i][i] << endl;
- }
- }
- };
- int main(){
- Jacobi a;
- a.input();
- a.solve();
- a.output();
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement