Ejemplo n.º 1
0
        /** {@inheritDoc} */
        public RealMatrix power(int p)
        {
            if (p < 0)
            {
                throw new Exception("NotPositiveException");
            }

            if (!isSquare())
            {
                throw new Exception("NonSquareMatrixException");
            }

            if (p == 0)
            {
                return(MatrixUtils.CreateRealIdentityMatrix(getRowDimension()));
            }

            if (p == 1)
            {
                return(copy());
            }

            int power = p - 1;

            /*
             * Only log_2(p) operations is used by doing as follows:
             * 5^214 = 5^128 * 5^64 * 5^16 * 5^4 * 5^2
             *
             * In general, the same approach is used for A^p.
             */


            char[]         binaryRepresentation = Integer.ToBinaryString(power).ToCharArray();
            List <Integer> nonZeroPositions     = new List <Integer>();
            int            maxI = -1;

            for (int i = 0; i < binaryRepresentation.Length; ++i)
            {
                if (binaryRepresentation[i] == '1')
                {
                    int pos = binaryRepresentation.Length - i - 1;
                    nonZeroPositions.Add(pos);

                    // The positions are taken in turn, so maxI is only changed once
                    if (maxI == -1)
                    {
                        maxI = pos;
                    }
                }
            }

            RealMatrix[] results = new RealMatrix[maxI + 1];
            results[0] = copy();

            for (int i = 1; i <= maxI; ++i)
            {
                results[i] = results[i - 1].multiply(results[i - 1]);
            }

            RealMatrix result = copy();

            foreach (Integer i in nonZeroPositions)
            {
                result = result.multiply(results[i]);
            }

            return(result);
        }