1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include <iostream>
#include <vector>
#include <cmath>
typedef int unit;
void printMatrix ( const std::vector<unit> & matrix, int width, int height );
void eigenvalues ( std::vector<unit> matrix, std::vector<unit> & eValues, std::vector<unit> & found, unit multiplier = 1 );
int main ( )
{
const int size = 2;
std::vector<unit> matrix ( size * size, 0 );
std::vector<unit> eValues ( size, 0 );
std::vector<unit> found ( eValues );
eigenvalues ( matrix, eValues, found );
printMatrix ( matrix, size, size );
printMatrix ( eValues, size, 1 );
printMatrix ( found, size, 1 );
}
void printMatrix ( const std::vector<unit> & matrix, int width, int height )
{
for ( int i = 0; i < height; ++i )
{
for ( int j = 0; j < width; ++j )
std::cout << matrix[j+i*height] << ' ';
std::cout << '\n';
}
std::cout << '\n';
}
void eigenvalues ( std::vector<unit> matrix, std::vector<unit> & eValues, std::vector<unit> & found, unit multiplier )
{
int mSize = matrix.size ( );
if ( mSize > 4 )
{
int width = sqrt ( mSize );
for ( int i = 0; i < width; ++i ) // for every item in the top row
{
std::vector<unit> temp;
int newSize = ( width - 1 ) * ( width - 1 );
for ( int j = width; j < mSize; ++j ) // start at the second row
{
if ( !( j % ( width + i ) ) ) ++j;
else temp.push_back ( matrix[j] );
}
eigenvalues ( temp, eValues, found, matrix[i] );
}
}
else
{
unit A = matrix[0], B = matrix[1], C = matrix[2], D = matrix[3];
unit vOne = -1*B + sqrt ( B*B - 4*A*C ) / 2*A, vTwo = -1*B - sqrt ( B*B - 4*A*C ) / 2*A;
vOne *= multiplier; vTwo *= multiplier;
int fSize = found.size ( );
for ( int i = 0; i < fSize; ++i )
{
if ( !found[i] )
{
found[i] = 1;
eValues[i] = vOne;
found[i+1] = 1;
eValues[i+1] = vTwo;
break;
}
}
}
}
|