c 2b 2b program to find eigenvalues of a matrix

Solutions on MaxInterview for c 2b 2b program to find eigenvalues of a matrix by the best coders in the world

showing results for - "c 2b 2b program to find eigenvalues of a matrix"
Valerio
01 Sep 2020
1
2#include<iostream>
3#include<iomanip>
4#include<stdio.h>
5#include<math.h>
6
7#define SIZE 10
8
9using namespace std;
10
11int main()
12{
13	 float a[SIZE][SIZE], x[SIZE],x_new[SIZE];
14	 float temp, lambda_new, lambda_old, error;
15	 int i,j,n, step=1;
16
17     /* Setting precision and writing floating point values in fixed-point notation. */
18     cout<< setprecision(3)<< fixed;
19
20	 /* Inputs */
21	 /* Reading order of square matrix */
22	 cout<<"Enter Order of Matrix: ";
23	 cin>>n;
24
25     /* Reading tolerable error */
26	 cout<<"Enter Tolerable Error: ";
27	 cin>>error;
28
29	 /* Reading Square Matrix of Order n */
30	 cout<<"Enter Coefficient of Matrix: "<< endl;
31	 for(i=1;i<=n;i++)
32	 {
33		  for(j=1;j<=n;j++)
34		  {
35			   cout<<"a["<< i<<"]"<< j<<"]= ";
36               cin>>a[i][j];
37		  }
38	 }
39
40	 /* Reading Intial Guess Vector */
41	 cout<<"Enter Initial Guess Vector: "<< endl;
42	 for(i=1;i<=n;i++)
43	 {
44		  cout<<"x["<< i<<"]= ";
45		  cin>>x[i];
46	 }
47
48	 /* Initializing Lambda_Old */
49	 lambda_old = 1;
50	 /* Multiplication */
51
52	 /* Setting label for repetition */
53	 up:
54	 for(i=1;i<=n;i++)
55	 {
56		  temp = 0.0;
57		  for(j=1;j<=n;j++)
58		  {
59		   	temp = temp + a[i][j]*x[j];
60		  }
61		  x_new[i] = temp;
62	 }
63
64	 /* Replacing x by x_new */
65	 for(i=1;i<=n;i++)
66	 {
67	  	x[i] = x_new[i];
68	 }
69
70	 /* Finding largest value from x*/
71	 lambda_new = fabs(x[1]);
72	 for(i=2;i<=n;i++)
73	 {
74		  if(fabs(x[i])>lambda_new)
75		  {
76		   	lambda_new = fabs(x[i]);
77		  }
78	 }
79
80	 /* Normalization */
81	 for(i=1;i<=n;i++)
82	 {
83	  	x[i] = x[i]/lambda_new;
84	 }
85
86	 /* Display */
87	 cout<< endl<< endl<<"STEP-"<< step<< endl;
88	 cout<<"Eigen Value = "<< lambda_new<< endl;
89	 cout<<"Eigen Vector: "<< endl;
90	 cout<<"[";
91	 for(i=1;i<=n;i++)
92	 {
93	  	cout<< x[i]<<"\t";
94	 }
95     cout<<"\b\b\b]"; /* \b is for backspace */
96
97	 /* Checking Accuracy */
98	 if(fabs(lambda_new-lambda_old)>error)
99	 {
100		  lambda_old=lambda_new;
101		  step++;
102		  goto up;
103	 }
104
105	 return(0);
106}
107
108