Advertisement
Guest User

Untitled

a guest
Dec 18th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. #include<iostream>
  2. #include<fstream>
  3. #include<math.h>
  4. using namespace std;
  5.  
  6. class Jacobi{
  7. private:
  8. double** a;
  9. double eps;
  10. int n;
  11. double abs(double var){
  12. if(var >= 0){return var;}
  13. else{return (-1)*var;}
  14. }
  15. int sign(double var) {
  16. if (var > 0) return 1;
  17. if (var < 0) return -1;
  18. return 0;
  19. }
  20. void rotation(int i, int j){
  21. double cos = 0, sin = 0;
  22.  
  23. if (a[i][i] == a[j][j]){
  24. cos = sqrt((double)2)/2;
  25. sin = sqrt((double)2)/2;
  26. }else{
  27. double x = -2*a[i][j], y = a[i][i] - a[j][j];
  28. cos = sqrt(0.5 * (1 + (abs(y) / sqrt(x*x + y*y))));
  29. sin = (sign(x*y)*abs(x)) / (2 * cos*sqrt(x*x + y*y));
  30. }
  31. for (int m = 0; m < n; m++) {
  32. if (m != i && m != j) {
  33. double aim = a[i][m];
  34. a[i][m] = cos*a[i][m] - sin*a[j][m];
  35. a[m][i] = a[i][m];
  36. a[j][m] = sin*aim + cos*a[j][m];
  37. a[m][j] = a[j][m];
  38. }
  39. }
  40. double aii = a[i][i], ajj = a[j][j], aij = a[i][j];
  41. a[i][i] = cos*cos*aii - 2*sin*cos*aij + sin*sin*ajj;
  42. a[j][j] = sin*sin*aii + 2*sin*cos*aij + cos*cos*ajj;
  43. a[i][j] = (cos*cos - sin*sin)*aij + cos*sin*(aii - ajj);
  44. a[j][i] = a[i][j];
  45. }
  46. void findMax(int* k, int* l){
  47. double res = 0;
  48. for (int i = 0; i < n; i++) {
  49. for (int j = 0; j < n; j++){
  50. if ((i != j)&&(abs(a[i][j]) > abs(res))) {
  51. res = a[i][j];
  52. *k = i;
  53. *l = j;
  54. }
  55. }
  56. }
  57. }
  58. public:
  59. Jacobi(){}
  60. void input(){
  61. ifstream fin;
  62. fin.open("input.txt");
  63. if(fin.is_open()){
  64. if(!fin.eof()){
  65. fin >> n;
  66. }
  67. /////
  68. a = new double*[n];
  69. for(int i = 0; i < n; i++){
  70. a[i] = new double[n];
  71. }
  72. /////
  73. for(int i = 0; i < n; i++){
  74. for(int j = 0; j < n; j++){
  75. if(!fin.eof()){
  76. fin >> a[i][j];
  77. }
  78. }
  79. }
  80. if(!fin.eof()){
  81. fin >> eps;
  82. }
  83. }else{cout << "reading error" << endl;}
  84. fin.close();
  85. }
  86. void solve(){
  87. int i=0, j=0;
  88. while (abs(a[i][j]) > eps){
  89. findMax(&i, &j);
  90. rotation(i, j);
  91. }
  92. }
  93. void output(){
  94. for(int i = 0; i < n; i++){
  95. for(int j = 0; j < n; j++){
  96. cout << a[i][j] << ' ';
  97. }
  98. cout << endl;
  99. }
  100. cout << endl;
  101. for(int i = 0; i < n; i++){
  102. cout << a[i][i] << endl;
  103. }
  104. }
  105. };
  106. int main(){
  107. Jacobi a;
  108. a.input();
  109. a.solve();
  110. a.output();
  111. system("pause");
  112. return 0;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement