static void B5() { WriteLine("\n Problem B5\n"); int n = 5; matrix A = rand_sym_mat(n); matrix B = A.copy(); matrix C = A.copy(); WriteLine($"Random symmetric matrix A with size {n}"); WriteLine("We find all eigenvalues with cyclic routine"); jcbi_cycl test_cycl = new jcbi_cycl(B); test_cycl.Eigvals.print("Eigenvalues found by cyclic routine, low to high"); WriteLine("\nNow we use the value-by-value routine to calculate eigenvalues from last to first"); WriteLine("We do this by changing the calculation of " + "rotation angle theta to 0.5*Atan2(-Apq, App-Aqq)\n"); bool invert = true; int evalnum = n; bool vbv = true; jcbi_cycl test_vbv = new jcbi_cycl(C, vbv, evalnum, invert); test_vbv.Eigvals.print("Eigenvalues value-by-value, in order of calculation"); }
static void B2() { WriteLine("\n Problem B2\n"); int n = 8; matrix A = rand_sym_mat(n); matrix B = A.copy(); WriteLine("Random symmetric matrix A with size {0}", n); WriteLine("Perform eigenvalue by eigenvalue calculation for first 4 values"); int evalnum = 4; bool val_by_val = true; jcbi_cycl test_vbv = new jcbi_cycl(B, val_by_val, evalnum); Write("Found eigenvalues = "); for (int i = 0; i < evalnum; i++) { Write(" {0:g3} ", test_vbv.Eigvals[i]); } Write("\n"); ((test_vbv.V).T * A * test_vbv.V - test_vbv.D).print("V.T*A*V - D = ", "{0,10:f6}"); WriteLine("\n Total rotations used = {0}", test_vbv.Rotations); B.print("\n Matrix copy used, after value by value operations = ", "{0,10:f6}"); matrix C = A.copy(); WriteLine("\nSimilar calculation with cyclic sweeps"); jcbi_cycl test_cycl = new jcbi_cycl(C); test_cycl.Eigvals.print("Found eigenvalues = "); (test_cycl.V.T * A * test_cycl.V - test_cycl.D).print("V.T*A*V - D = ", "{0,10:f6}"); WriteLine("\n Total rotations used = {0}", test_cycl.Rotations); C.print("\n Matrix copy used, after cyclic sweeps = ", "{0,10:f6}"); }
public static void Main(){ // for(int n=2;n<50;n+=5){ for(int n=2;n<50;n+=10){ vector e=new vector(n); matrix V=new matrix(n,n); var rnd = new Random(1); matrix A = new matrix(n,n); for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ A[i,j]=(rnd.NextDouble()); A[j,i]=A[i,j]; } } matrix Alow=A.copy(); matrix Ahigh=A.copy(); matrix Vlow=V.copy(); matrix Vhigh=V.copy(); vector elow=e.copy(); vector ehigh=e.copy(); //for plotting: // matrix B=A.copy(); var sweeps=jacobi.cyclic(A,e,V); // matrix VTAV = V.T*B*V; // VTAV.printfloat("Should be diagional:"); var lowest=jacobi.lowest(Alow,elow,1,Vlow); //only the one lowest eigenvalue // matrix VTAVlow = Vlow.T*B*Vlow; // VTAVlow.printfloat("Should be diagional:"); var highest=jacobi.highest(Ahigh,ehigh,1,Vhigh); //only the one highest eigenvalue // matrix VTAVhigh = Vhigh.T*B*Vhigh; // VTAVhigh.printfloat("Should be diagional:"); WriteLine($"{n} {sweeps} {lowest} {highest}"); } }//Main
public static void Main() { //now test highest EV int n = 5; matrix A = new matrix(n, n); matrix V = new matrix(n, n); vector e = new vector(n); var rand = new Random(1); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { A[i, j] = 2 * (rand.NextDouble() - 0.5); A[j, i] = A[i, j]; } } //2 highest EV matrix AA2 = A.copy(); string order = "high"; int count = jacobiB.jacobirow(AA2, e, 2, V, order); e.print("First 2 values should be highest EVs"); //full diag matrix Vh = new matrix(n, n); vector eh = new vector(n); matrix AAh = A.copy(); int counth = jacobiB.jacobirow(AAh, eh, n, Vh); eh.print("all eigenvalues"); }
public static void Main() { WriteLine(); WriteLine("Create a matrix and diagonalize it via the cyclic, value-by-value and" + " classic method."); var rand = new Random(); int n = 5; // Create a random matrix matrix A = new matrix(n, n); for (int i = 0; i < n; i++) { A[i, i] = 2 - 4 * rand.NextDouble(); for (int j = i + 1; j < n; j++) { A[i, j] = 2 - 3.32 * rand.NextDouble(); A[j, i] = A[i, j]; } } // Print the random matrix. WriteLine("\nSetting up a random symmetric matrix:"); A.print(); WriteLine(); // Diagonalize it via the three different methods matrix Acopy = A.copy(); matrix AcopyII = A.copy(); matrix V = new matrix(n, n); vector e = new vector(n); vector eRot = new vector(n); vector eClassic = new vector(n); int sweeps = jacobi.cycle(A, e, V); int entries = (n * n - n) / 2; int rotations = jacobi.findEigenvalue(Acopy, eRot, V, n, true); int rotationsClassic = jacobi.classic(AcopyII, eClassic, V); WriteLine("The cyclic method used {0} operations", sweeps * entries); WriteLine("The value-by-value method used {0} operations", rotations); WriteLine("The classic method used {0} operations", rotationsClassic); WriteLine("\nAfter cyclic diagonalization the matrix looks like:"); A.print(); WriteLine("\nAfter value-by-value diagonalization the matrix looks like:"); Acopy.print(); WriteLine("\nAfter classic Jacobi diagonalization the matrix looks like:"); AcopyII.print(); Write("\n\n"); WriteLine("The found eigenvalues are:"); WriteLine("E(cyclic)\t\tE(val_by_val)\t\tE(classic)"); for (int j = 0; j < n; j++) { WriteLine("{0}\t{1}\t{2}", e[j], eRot[j], eClassic[j]); } }
static void B4() { WriteLine("\n Problem B4\n"); WriteLine("See PlotB4r.svg and PlotB4t.svg for results"); int l = 50; // max matrix size int k = 5; // number of tries for each avg Stopwatch sw = new Stopwatch(); var timewriter = new System.IO.StreamWriter("out.b4time.txt"); var rotwriter = new System.IO.StreamWriter("out.b4rot.txt"); vector tvbv = new vector(l); vector tcyc = new vector(l); vector rvbv = new vector(l); vector rcyc = new vector(l); for (int i = 0; i < l; i++) { tvbv[i] = 0; tcyc[i] = 0; rvbv[i] = 0; rcyc[i] = 0; for (int j = 0; j < k; j++) { matrix A = rand_sym_mat(i + 1); sw.Reset(); matrix B = A.copy(); bool vbv = true; int evalnum = l; sw.Start(); jcbi_cycl test_vbv = new jcbi_cycl(B, vbv, evalnum); sw.Stop(); tvbv[i] += sw.Elapsed.TotalMilliseconds; rvbv[i] += test_vbv.Rotations; matrix C = A.copy(); sw.Reset(); sw.Start(); jcbi_cycl test_cyc = new jcbi_cycl(C); sw.Stop(); tcyc[i] += sw.Elapsed.TotalMilliseconds; rcyc[i] += test_cyc.Rotations; } tvbv[i] = tvbv[i] / k; tcyc[i] = tcyc[i] / k; rvbv[i] = rvbv[i] / k; rcyc[i] = rcyc[i] / k; timewriter.WriteLine($"{i} {tvbv[i]} {tcyc[i]}"); rotwriter.WriteLine($"{i} {rvbv[i]} {rcyc[i]}"); } timewriter.Close(); rotwriter.Close(); }
public static void Main(string[] args) { int n = 5; //size of real symmetric matrix matrix A = new matrix(n, n); var rnd = new Random(1); for (int i = 0; i < n; i++) /* Construction of a random vector */ { for (int j = 0; j < n; j++) { A[i, j] = (rnd.NextDouble() * 10); A[j, i] = A[i, j]; /* We make sure that the matrix is symmetric */ } } A.print("Random symmetric matrix, A:"); matrix V = new matrix(n, n); vector e = new vector(n); matrix B = A.copy(); /* We make a copy of A */ int sweeps = jacobi.cyclic(A, e, V); /* We use the jacobi matlib for the implementation of the cyclic sweeps: public static int cyclic(matrix A, vector e, matrix V=null){...} */ WriteLine($"\nNumber of sweeps: {sweeps}"); matrix D = (V.T * B * V); // D.print("\nEigenvalue-decomposition, V^T*A*V (should be diagonal):"); D.printfloat("\nEigenvalue-decomposition, V^T*A*V (should be diagonal):"); /* using my print2 to get 0's instead of values with e.g. "e-16"*/ e.print("\nEigenvalues:\n"); }
public givens(matrix A) { R = A.copy(); n = A.size1; m = A.size2; // Loop over the columns of the matrix for (int q = 0; q < m; q++) { // Loop over the rows of the matrix that lie under the diagonal for (int p = q + 1; p < n; p++) { double theta = Atan2(R[p, q], R[q, q]); // Loop to recalculate the relevant entries in the matrix // This runs over all columns in the two rows p and q, which are // the only ones affected. for (int k = q; k < m; k++) { double xq = R[q, k]; double xp = R[p, k]; R[q, k] = xq * Cos(theta) + xp * Sin(theta); R[p, k] = -xq *Sin(theta) + xp * Cos(theta); } // Store the angle that made R[p,q] = 0 in the spot instead of zero R[p, q] = theta; } } }
static void Main() { WriteLine("Exam problem 21: \nTwo-sided Jacobi algorithm for Singular Value Decomposition (SVD) \n");; int n = 7; WriteLine($"Generating Random {n}x{n} matrix"); matrix A = randomMatrix(n, n), U = new matrix(n, n), V = new matrix(n, n); matrix D = A.copy(); A.print("Matrix A generated:"); WriteLine("Making composition..."); int sweeps = twoSidedJacobiSVD(D, U, V); WriteLine($"Procedure done!\nNo. of sweeps: {sweeps}.\nNow A --> U*D*V^T, where"); D.print("D: "); U.print("U: "); V.print("V: "); matrix R = (U * D) * V.transpose(); R.print("Test that UDV^T = A"); A.print("A, for reference"); matrix UUt = U * U.transpose(), VVt = V * V.transpose(); UUt.print("Test U*U^T = 1"); VVt.print("Test V*V^T = 1"); }
public qr_decomp_GS(matrix A) { int n = A.size1; int m = A.size2; q = A.copy(); r = new matrix(m, m); vector qi = new vector(n); vector qj = new vector(n); for (int i = 0; i < m; i++) { qi = q.col_toVector(i); r[i, i] = Sqrt(qi.dot(qi)); for (int k = 0; k < n; k++) { q[k, i] = q[k, i] / r[i, i]; } for (int j = i + 1; j < m; j++) { qi = q.col_toVector(i); qj = q.col_toVector(j); r[i, j] = qi.dot(qj); for (int k = 0; k < n; k++) { q[k, j] = q[k, j] - q[k, i] * r[i, j]; } } } }
public static int Main() { Random rand = new Random(); // Creating the inverse of a matrix Write("Inverse of matrix\n"); matrix A = new matrix(10, 10); for (int i = 0; i < A.size1; i++) { for (int j = 0; j < A.size2; j++) { A[i, j] = rand.NextDouble() * 9.99; if (A[i, j] > 5.0) { A[i, j] *= -1; } } } Write("A=\n"); print2(A); matrix Q = A.copy(); matrix R = new matrix(A.size1, A.size2); matrix.qr_gs_decomp(Q, R); matrix B = qr_gs_inverse(Q, R); Write("\nA*B=\n"); print2(A * B); return(0); }
static void Main() { /// Test on random matrix /// WriteLine("/////////////// Part A - Test on random matrix ///////////////"); int n = 5; var rand = new Random(1); matrix A = new matrix(n, n); vector e = new vector(n); matrix V = new matrix(n, n); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { A[i, j] = rand.NextDouble(); A[j, i] = A[i, j]; } } A.print($"random {n}x{n} matrix"); WriteLine(); matrix B = A.copy(); int sweeps = jacobi.cyclic(B, e, V); WriteLine($"Number of sweeps in jacobi={sweeps}"); WriteLine(); matrix D = (V.T * A * V); (D).print("Should be a diagonal matrix V.T*B*V="); WriteLine(); e.print("Eigenvalues should equal the diagonal elements above"); vector D_diagonal = new vector(n); for (int i = 0; i < n; i++) { D_diagonal[i] = D[i, i]; } if (D_diagonal.approx(e)) { WriteLine("Eigenvalues agree \tTest passed"); } else { WriteLine("Test failed"); } WriteLine(); matrix A2 = (V * D * V.T); (A2).print("Check that V*D*V.T=A"); if (A2.approx(A)) { WriteLine("V*D*V.T = A \tTest passed"); } else { WriteLine("V*D*V.T != A \tTest failed"); } }
//constructor public gi_rot(matrix A1) { matrix a = A1.copy(); int row = a.size1; int col = a.size2; for (int n = 0; n < col; n++) { for (int n1 = n + 1; n1 < row; n1++) { double the = Atan2(a[n1, n], a[n, n]); //a[n]=a[n1]*Cos(the)+a[n]*Sin(the); //a[n1]=(-1)*a[n1]*Sin(the)+a[n]*Cos(the); //a[n, n1]=the; for (int n2 = n; n2 < col; n2++) { double an_n2 = a[n, n2]; double an1_n2 = a[n1, n2]; a[n, n2] = an_n2 * Cos(the) + an1_n2 * Sin(the); a[n1, n2] = (-1) * an_n2 * Sin(the) + an1_n2 * Cos(the); } //end for a[n1, n] = the; } //end for } //end for A = a; } //end constructor...
public CholeskyDecomposition(matrix B) { matrix A = B.copy(); int size = A.cols; L = new matrix(size, size); for (int i = 0; i < size; i++) { for (int k = 0; k < (i + 1); k++) { double sum = 0; for (int j = 0; j < k; j++) { sum += L[i, j] * L[k, j]; } if (i == k) { // Do this to prevent NaN and +-Infinity if (A[i, i] - sum <= 0) { throw new CholeskyException("Bad Cholesky"); } L[i, k] = Math.Sqrt(A[i, i] - sum); } else { L[i, k] = 1 / L[k, k] * (A[i, k] - sum); } } } }
// Comparison of time and rotations needed to calculate the lowest // eigenvalue for the cyclic and single value method. static void probB5() { Write("\n\nProblem B.5:\n"); int n = 7; matrix A1 = matrixHelp.makeRandSymMatrix(n); matrix A2 = A1.copy(); Write("Finding the largest eigenvalue of the matrix:\n"); A1.print(); matrix V1 = new matrix(n, n); matrix V2 = new matrix(n, n); vector e1 = new vector(n); vector e2 = new vector(n); int rot1 = jacobi.cyclic(A1, e1, V1); int rot2 = jacobi.values(A2, e2, 1, V2, true); Write("\n"); Write($"Largest found by cyclic jacobi: {e1[n-1]}\n"); Write($"Largest found by single row jacobi: {e2[0]}\n"); Write("\nThe single row method was changed by changing the calculation of the rotation angle theta to: 0.5*Atan2(-Apq, App-Aqq)\n"); }
public static void Main() { int n = 3; matrix A = new matrix(n, n); matrix V = new matrix(n, n); vector e = new vector(n); var rand = new Random(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { A[i, j] = rand.NextDouble() * 10; A[j, i] = A[i, j]; } } A.print("Symmetric matrix A:"); matrix Ao = new matrix(n, n); Ao = A.copy(); int count = jacobi.cycsweep(A, e, V); WriteLine($"Number of sweeps: {count}"); V.print("Eigenvectors"); A.print("new A"); e.print("Eigenvalues"); (V.T * Ao * V).print("V^T*A*V diagonal, test"); }
}//constructor public diagJacobi(matrix x, int firstN, bool eigVec = false, bool largestFirst = false) { a = x.copy(); if (largestFirst) { a = -1 * a; } if (eigVec) { v = new matrix(a.size1, a.size1); v.set_identity(); } l = new vector(a.size1); for (int i = 0; i < a.size1; i++) { l[i] = a[i, i]; } bool changed; sweeps = 0; rotations = 0; for (int r = 0; r < firstN; r++) { do { changed = this.rowSweep(r); sweeps++; } while(changed); } if (largestFirst) { a = -1 * a; l = -1 * l; } }//constructor
public static void Main() { // First part of A int n = 5; // Size of quadratic matrix M. var rnd = new Random(1); Console.WriteLine("Part A1"); matrix M = new matrix(n, n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { M[i, j] = 4 * rnd.NextDouble() - 1.5; M[j, i] = M[i, j]; } } matrix M2 = M.copy(); M.print("We choose an arbitrary matrix M = "); vector D = new vector(n); matrix V = new matrix(n, n); int sweeps = Jacobi_diagonalization.cyclic_sweep(M, V, D); matrix temp2 = V.T * M2 * V; Console.WriteLine($"Total number of sweeps done is = {sweeps}"); temp2.print("V.T*M*V = "); D.print("Eigenvalues = "); }
/* * Remember: a = v^Tav=d; */ public diagJacobi(matrix x, bool eigVec = false, bool classic = false) { if (classic) { this.classicJacobi(x); } else { a = x.copy(); if (eigVec) { v = new matrix(a.size1, a.size1); v.set_identity(); } l = new vector(a.size1); for (int i = 0; i < a.size1; i++) { l[i] = a[i, i]; } bool changed; sweeps = 0; rotations = 0; do { changed = this.cyclicSweep(); sweeps++; } while(changed); } }//constructor
static void Main() { var rnd = new Random(); var A = new matrix(3, 3); for (int i = 0; i < A.size1; i++) { for (int j = 0; j < A.size2; j++) { A[i, j] = 10 * (rnd.NextDouble() - 0.5); } } var Q = A.copy(); var R = new matrix(Q.size2, Q.size2); WriteLine("\n__________________________________________________________________________________________________________"); WriteLine("Question B:\nMatrix inverse by Gram-Schmidt QR factorization"); WriteLine("Random matrix"); A.print("A = "); qr_gs.qr_gs_decomp(Q, R); WriteLine("Factorized into"); Q.print("Q = "); R.print("R = "); var B = qr_gs.qr_gs_inverse(Q, R); WriteLine("Inverse of A:"); B.print("A^-1=B="); WriteLine("Product should give identity"); (A * B).print("I=AB="); WriteLine("__________________________________________________________________________________________________________\n"); }
public QRdecompositionGS(matrix A) { Q = A.copy(); R = new matrix(Q.size2, Q.size2); GramSchmidt(A); }
public static matrix Givens(matrix A) { int n = A.size1; int m = A.size2; matrix A_t = A.copy(); // The Jacobi matrix G is given as an identity matrix except that it contains elements of a rotation matrix // The elements G_pp, G_qq are replaced with cos(θ) and G_qp and G_pq with -sin(θ) and sin(θ) respectively // G is therefore a rotation of a vector in the p,q plane // We aim to use this transformation to zero elements of A by using the Givens rotation: A->GA=A_t // We must choose θ=Atan2(A[p,q],A[q,q]) to zero the p,qth element in A under a Givens rotation: for (int q = 0; q < m; q = q + 1) { for (int p = q + 1; p < n; p = p + 1) { double θ = Atan2(A_t[p, q], A_t[q, q]); for (int k = q; k < m; k = k + 1) { double xq = A_t[q, k]; double xp = A_t[p, k]; A_t[q, k] = xq * Cos(θ) + xp * Sin(θ); A_t[p, k] = -xq *Sin(θ) + xp * Cos(θ); } // New elements in A, after the rotation A_t[p, q] = θ; } // Adding the θ which zero'ed the p,qth entry in A } // Yields upper triangular matrix R, but with the added θ's which zeroed the corresponding lower triangular entries in A return(A_t); }
public static (matrix, int) values(matrix A, int nvalues = 1) { bool changed; int rotations = 0, n = A.size1; matrix D = A.copy(); // matrix V = new matrix(n,n); // for(int i=0;i<n;i++)V[i,i]=1.0; for (int p = 0; p < nvalues; p++) { do { changed = false; for (int q = p + 1; q < n; q++) { double dpp = D[p, p]; double dqq = D[q, q]; double dpq = D[p, q]; double phi = 0.5 * Math.Atan2(2 * dpq, dqq - dpp); double c = Math.Cos(phi), s = Math.Sin(phi); double dpp1 = c * c * dpp - 2 * s * c * dpq + s * s * dqq; double dqq1 = s * s * dpp + 2 * s * c * dpq + c * c * dqq; if (dpp1 != dpp || dqq1 != dqq) { rotations++; changed = true; D[p, p] = dpp1; D[q, q] = dqq1; D[p, q] = 0.0; D[q, p] = 0.0; for (int i = p + 1; i < q; i++) { double dpi = D[p, i]; double diq = D[i, q]; D[p, i] = c * dpi - s * diq; D[i, q] = c * diq + s * dpi; D[i, p] = D[p, i]; D[q, i] = D[i, q]; } for (int i = q + 1; i < n; i++) { double dpi = D[p, i]; double dqi = D[q, i]; D[p, i] = c * dpi - s * dqi; D[q, i] = c * dqi + s * dpi; D[i, p] = D[p, i]; D[i, q] = D[q, i]; } // for(int i=0;i<n;i++){ // double vip=V[i,p]; // double viq=V[i,q]; // V[i,p]=c*vip-s*viq; // V[i,q]=c*viq+s*vip; // } } } }while(changed); } return(D, rotations); }
public gram_s(matrix A) { matrix a = A.copy(); int rows_A = A.size1; int columns_A = A.size2; matrix q = new matrix(rows_A, columns_A); if (rows_A < columns_A) { Console.Error.WriteLine("Error!!! Matrix A has more columns then rows, try transposing A |\n Error!! \n Error!!!"); }//end if else { matrix R1 = new matrix(columns_A, columns_A); //somthing else... for (int n = 0; n < columns_A; n++) { R1[n, n] = Sqrt(col_ip(a, n, a, n)); a[n] = a[n] / R1[n, n]; //for(int n1=0; n1<rows_A; n1++){ //a[n1,n]=a[n1,n]/R1[n,n]; //}//end for for (int n2 = n + 1; n2 < columns_A; n2++) { R1[n, n2] = col_ip(a, n, a, n2); for (int n3 = 0; n3 < rows_A; n3++) { a[n3, n2] = a[n3, n2] - a[n3, n] * R1[n, n2]; } //end for } //end for } //end for R = R1; Q = a; }//end else // this does not work... I will try somthing else ... //for(int n=0; n<columns_A; n++){ //double rnn= Sqrt(col_ip(a,n,a,n)) ; //R1[n,n]=Sqrt(rnn); // for(int n1=0; n1<rows_A; n1++){ // q[n1,n]=a[n1,n]/rnn; // }// end for // for(int j=n+1; j<columns_A; j++){ // R1[n,j]=col_ip(q,n,a,j); // for(int n2=0; n2< rows_A; n2++){ // a[n2,j]=a[n2,j]-R1[n,j]*q[n2,n]; // }//end for // }//end for //}//end for //R=R1; //Q=q; //}//end else } // end constructor
static void Main() { int n = 5; //size of real symmetric matrix matrix A = new matrix(n, n); var rnd = new Random(1); for (int i = 0; i < n; i++) /* Construction of a random vector */ { for (int j = 0; j < n; j++) { A[i, j] = (rnd.NextDouble() * 10); A[j, i] = A[i, j]; /* We make sure that the matrix is symmetric */ } } A.printfloat("Random symmetric matrix, A:"); matrix V = new matrix(n, n); matrix V2 = new matrix(n, n); vector e = new vector(n); vector e2 = new vector(n); // matrix B=A.copy(); matrix B2 = A.copy(); int rotations = jacobi.classic2(A, e, V); /* We use the jacobi matlib for the implementation of the cyclic sweeps: public static int cyclic(matrix A, vector e, matrix V=null){...} */ WriteLine($"\nNumber of rotations: {rotations}"); // matrix D=(V.T*B*V); // D.printfloat("\nClassic: Eigenvalue-decomposition, V^T*A*V (should be diagonal):"); int sweeps = jacobi.cyclic(B2, e2, V2); WriteLine($"Number of sweeps: {sweeps}"); // matrix D2=(V2.T*B*V2); // D2.printfloat("\nCyclic: Eigenvalue-decomposition, V^T*A*V (should be diagonal):"); // var rnd = new Random(1); // int n = 4; // matrix v_c = new matrix(n,n); // matrix v_classic = new matrix(n,n); // vector e_classic = new vector(n); // var A_c = new matrix(n,n); // for(int i=0;i<n;i++){ // for(int j=i;j<n;j++){ // A_c[i,j]=2*(rnd.NextDouble()-0.5); // A_c[j,i]=A_c[i,j]; // } // } // matrix B=A_c.copy(); // var A_classic = A_c.copy(); // int rotations = classic(A_classic,e_classic,v_classic); // A_classic.printfloat("A classic transformed"); // // e_classic.print("Eigenvalues calculated with classic:"); // // v_classic.print("Eigenvectors calculated with classic:"); // var VTAV=v_classic.T*B*v_classic; // VTAV.printfloat("V^T*A*V:"); }
public static vector high_eig(matrix A, int nvalues = 1) { bool changed; int n = A.size1; matrix D = A.copy(); for (int p = 0; p < nvalues; p++) { do { changed = false; for (int q = p + 1; q < n; q++) { double dpp = D[p, p]; double dqq = D[q, q]; double dpq = D[p, q]; double phi = 0.5 * Math.Atan2(-2 * dpq, -dqq + dpp); double c = Math.Cos(phi), s = Math.Sin(phi); double dpp1 = c * c * dpp - 2 * s * c * dpq + s * s * dqq; double dqq1 = s * s * dpp + 2 * s * c * dpq + c * c * dqq; if (dpp1 != dpp || dqq1 != dqq) { changed = true; D[p, p] = dpp1; D[q, q] = dqq1; D[p, q] = 0.0; D[q, p] = 0.0; for (int i = p + 1; i < q; i++) { double dpi = D[p, i]; double diq = D[i, q]; D[p, i] = c * dpi - s * diq; D[i, q] = c * diq + s * dpi; D[i, p] = D[p, i]; D[q, i] = D[i, q]; } for (int i = q + 1; i < n; i++) { double dpi = D[p, i]; double dqi = D[q, i]; D[p, i] = c * dpi - s * dqi; D[q, i] = c * dqi + s * dpi; D[i, p] = D[p, i]; D[i, q] = D[q, i]; } } } }while(changed); } vector e = new vector(n); for (int i = 0; i < n; i++) { e[i] = D[i, i]; } return(e); }
public static void Main() { for (int n = 5; n < 300; n = n + 50) { matrix A = new matrix(n, n); matrix V = new matrix(n, n); vector e = new vector(n); var rand = new Random(1); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { A[i, j] = 2 * (rand.NextDouble() - 0.5); A[j, i] = A[i, j]; } } Stopwatch rowt = new Stopwatch(); //one EV matrix AAf = A.copy(); rowt.Start(); int count = jacobiB.jacobirow(AAf, e, 1, V); rowt.Stop(); Stopwatch rowh = new Stopwatch(); //full diag matrix Vh = new matrix(n, n); vector eh = new vector(n); matrix AAh = A.copy(); rowh.Start(); int counth = jacobiB.jacobirow(AAh, eh, n, Vh); rowh.Stop(); matrix Vt = new matrix(n, n);//cyclic vector et = new vector(n); matrix AAt = A.copy(); Stopwatch cyct = new Stopwatch(); cyct.Start(); int countt = jacobi.cycsweep(AAt, et, Vt); cyct.Stop(); WriteLine($"{n} {rowt.ElapsedMilliseconds} {count} {rowh.ElapsedMilliseconds} {counth} {cyct.ElapsedMilliseconds} {countt}"); } }
static void Main() { // Testing that the jacobiAlgorithm works: int n = 5; vector e = new vector(n); matrix V = new matrix(n, n); matrix A = generateRandommatrix(n, n); matrix B = A.copy(); int sweeps = jacobi.jacobi_cyclic(A, e, V); WriteLine("---------Problem A1----------"); WriteLine("\nTesting that the Jacobi algorithm works as intended:"); A.print("\nRandom square matrix A:"); WriteLine("\nEigenvalue decomposition of A=V*D*V^T:"); (V.transpose() * B * V).print("\nD = V^T*A*V = "); e.print("\nListed eigenvalues:\t"); WriteLine($"\nNumber of sweeps required to diagonalize A: {sweeps}"); // Particle in a box n = 50; matrix H = Hamiltonian.boxHamilton(n); B = H.copy(); V = new matrix(n, n); e = new vector(n); sweeps = jacobi.jacobi_cyclic(H, e, V); WriteLine("\n---------Problem A2----------"); WriteLine("\nNow solving for a particle in a box."); WriteLine($"\nThe dimensions of the soon to be diagonalized Hamiltonian is {n}x{n}"); WriteLine("\nComparison of the calculated eigenvalues and the exact:\n"); WriteLine("n Calculated Exact:"); for (int k = 0; k < n / 3; k++) { double exact = PI * PI * (k + 1) * (k + 1); double calculated = e[k]; WriteLine($"{k} {calculated:f4}\t {exact:f4}"); } // plotting time StreamWriter solutions = new StreamWriter("SolutionsA.txt"); for (int i = 0; i < n; i++) { solutions.Write($"{i*(1.0/n)}"); for (int k = 0; k < 5; k++) { solutions.Write($" {V[i,k]}"); } solutions.Write("\n"); } solutions.Close(); }
static void Main() { /////////////// QM-problem /////////////// WriteLine($"/////////////// Part A - QM-problem ///////////////"); int N = 100; double s = 1.0 / (N + 1); matrix H = new matrix(N, N); for (int i = 0; i < N - 1; i++) { H[i, i] = -2; H[i, i + 1] = 1; H[i + 1, i] = 1; } H[N - 1, N - 1] = -2; H = -H / s / s; matrix H1 = H.copy(); vector eigenvals = new vector(N); matrix V = new matrix(N, N); int sweeps = jacobi.cyclic(H1, eigenvals, V); // H.print($"Hamilton {H.size1}x{H.size2} matrix"); WriteLine(); WriteLine($"Number of sweeps in jacobi={sweeps}"); WriteLine(); // matrix D=(V.T*H*V); // (D).print("Should be a diagonal matrix V.T*H*V=");WriteLine(); // eigenvals.print("Eigenvalues should equal the diagonal elements above"); WriteLine(); // matrix H2=(V*D*V.T); // (H2).print("Check that V*D*V.T=H"); WriteLine(); WriteLine($"k \t Calculated \t Exact \t Relative deviation"); for (int k = 0; k < N / 3; k++) { double exact = PI * PI * (k + 1) * (k + 1); double calculated = eigenvals[k]; WriteLine($"{k} \t {calculated} \t {exact} \t {(calculated-exact)/exact*100}%"); } for (int k = 0; k < 3; k++) { Error.WriteLine($"{0} {0}"); for (int i = 0; i < N; i++) { Error.WriteLine($"{(i+1.0)/(N+1)} {V[i,k]}"); } Error.WriteLine($"{1} {0}"); Error.WriteLine(); Error.WriteLine(); } }
public static void Main() { // Setup the output file: var outfile = new System.IO.StreamWriter("data.convergence_size.txt"); int mMax = 30; int[] ns = new int[] { 5, 10, 30, 50, 100, 150, 250 }; foreach (int n in ns) { matrix A = matrixHelp.makeRandSymMatrix(n); // Using m = n ensures that all the right eigenvalues are found matrix E_full = new matrix(n, n); vector e_full = new vector(n); lanczos.eigenvalues(A, E_full, e_full); for (int m = 1; (m < n) && (m <= mMax); m++) { matrix A_m = A.copy(); matrix E_m = new matrix(n, m); vector e_m = new vector(m); lanczos.eigenvalues(A_m, E_m, e_m); Func <int, double> e = (i) => { if (i < m) { return(Abs(e_m[(e_m.size - 1) - i] - e_full[e_full.size - 1 - i])); } else { return(Double.NaN); } }; Func <int, double> E_div = (i) => { if (i < m) { double norm1 = (E_m[E_m.size2 - 1 - i] - E_full[E_full.size2 - 1 - i]).norm(); double norm2 = (E_m[E_m.size2 - 1 - i] + E_full[E_full.size2 - 1 - i]).norm(); return((norm1 < norm2)?norm1:norm2); } else { return(Double.NaN); } }; outfile.Write("{0} {1} {2}\n", m, e(0), E_div(0)); } outfile.Write("\n\n"); } outfile.Close(); }