Example #1
0
        public void CombineLinesTest_NullDefaultValuesZeroZero()
        {
            var target        = this.GetDefaultMatrix(null);
            var integerDomain = new IntegerDomain();
            var fractionField = new FractionField <int>(integerDomain);

            // Constrói a linha a ser analisada.
            var matrixColumns = target.GetLength(1);
            var firstLine     = new Fraction <int> [matrixColumns];

            for (int i = 0; i < matrixColumns; ++i)
            {
                if (target[0, i] != null)
                {
                    firstLine[i] = fractionField.AdditiveUnity;
                }
            }

            target.CombineLines(0, 1, fractionField.AdditiveUnity, fractionField.AdditiveUnity, fractionField);
            for (int i = 0; i < matrixColumns; ++i)
            {
                Assert.AreEqual(firstLine[i], target[0, i]);
            }

            this.AssertLinesExcept(0, target);
        }
        /// <summary>
        /// Permite efectuar a leitura de um polinómio com coeficientes fraccionários a partir de texto.
        /// </summary>
        /// <remarks>
        /// Se a leitura não for bem sucedida, é lançada uma excep~ção.
        /// </remarks>
        /// <param name="polynomial">O texto.</param>
        /// <returns>O polinómio.</returns>
        public UnivariatePolynomialNormalForm <Fraction <BigInteger> > Read(string polynomial)
        {
            var integerDomain  = new BigIntegerDomain();
            var fractionField  = new FractionField <BigInteger>(integerDomain);
            var integerParser  = new BigIntegerParser <string>();
            var fractionParser = new FieldDrivenExpressionParser <Fraction <BigInteger> >(
                new SimpleElementFractionParser <BigInteger>(integerParser, integerDomain),
                fractionField);
            var conversion      = new IntegerBigIntFractionConversion(integerDomain, new BigIntegerToIntegerConversion());
            var polInputReader  = new StringReader(polynomial);
            var polSymbolReader = new StringSymbolReader(polInputReader, false);
            var polParser       = new UnivariatePolynomialReader <Fraction <BigInteger>, CharSymbolReader <string> >(
                "x",
                fractionParser,
                fractionField);

            var result = default(UnivariatePolynomialNormalForm <Fraction <BigInteger> >);

            if (polParser.TryParsePolynomial(polSymbolReader, conversion, out result))
            {
                // O polinómio foi lido com sucesso.
                return(result);
            }
            else
            {
                // Não é possível ler o polinómio.
                throw new Exception("Can't read integer polynomial.");
            }
        }
        public void RunTest()
        {
            var polynomialText = "((2*x+1)*(x-4))^2*(x+3)^3";

            // Os objectos responsáveis pelas operações sobre os coeficientes
            var bigIntegerDomain          = new BigIntegerDomain();
            var bigIntegerParser          = new BigIntegerParser <string>();
            var bigIntToIntegerConversion = new BigIntegerToIntegerConversion();
            var bigIntFractionConversion  = new OuterElementFractionConversion <int, BigInteger>(
                bigIntToIntegerConversion,
                bigIntegerDomain);

            var polynomial = TestsHelper.ReadFractionalCoeffsUnivarPol <BigInteger, BigIntegerDomain>(
                polynomialText,
                bigIntegerDomain,
                bigIntegerParser,
                bigIntFractionConversion,
                "x");

            var squareFreeFactorizationAlg = new SquareFreeFractionFactorizationAlg <BigInteger>(
                bigIntegerDomain);
            var result = squareFreeFactorizationAlg.Run(polynomial);

            // O teste passa se a expansão da factorização ser igual ao polinómio original.
            Assert.IsTrue(result.Factors.Count > 0, "At least two factors are expected.");
            var factorsEnum = result.Factors.GetEnumerator();

            if (factorsEnum.MoveNext())
            {
                var polynomialDomain = new UnivarPolynomPseudoDomain <BigInteger>(
                    "x",
                    bigIntegerDomain);
                var productPol = MathFunctions.Power(
                    factorsEnum.Current.Value,
                    factorsEnum.Current.Key,
                    polynomialDomain);
                while (factorsEnum.MoveNext())
                {
                    var temporary = MathFunctions.Power(
                        factorsEnum.Current.Value,
                        factorsEnum.Current.Key,
                        polynomialDomain);
                    productPol = polynomialDomain.Multiply(
                        productPol,
                        temporary);
                }

                var fractionField = new FractionField <BigInteger>(bigIntegerDomain);
                var expectedPol   = new UnivariatePolynomialNormalForm <Fraction <BigInteger> >("x");
                foreach (var term in productPol)
                {
                    expectedPol = expectedPol.Add(
                        result.IndependentCoeff.Multiply(term.Value, bigIntegerDomain),
                        term.Key,
                        fractionField);
                }

                Assert.AreEqual(expectedPol, polynomial);
            }
        }
        public void LdlDecompLinearSystemAlgorithm_RunTest()
        {
            var domain           = new IntegerDomain();
            var fractionField    = new FractionField <int>(domain);
            var decompositionAlg = new TriangDiagSymmMatrixDecomposition <Fraction <int> >(
                fractionField);
            var symmDecompSolver = new SymmetricLdlDecompLinearSystemAlgorithm <Fraction <int> >(
                decompositionAlg);
            var target = new LdlDecompLinearSystemAlgorithm <Fraction <int> >(
                symmDecompSolver,
                fractionField);
            var matrix = this.GetGeneralMatrix(domain);
            var vector = this.GetIndVectorForGenMatrix(domain);
            var actual = target.Run(matrix, vector);

            var lines          = matrix.GetLength(0);
            var columns        = matrix.GetLength(1);
            var nullVector     = new ZeroVector <Fraction <int> >(lines, fractionField);
            var expectedVector = new ArrayMathVector <Fraction <int> >(lines);

            for (var i = 0; i < lines; ++i)
            {
                expectedVector[i] = vector[i, 0];
            }

            actual = target.Run(matrix, vector);
            this.AssertVector(expectedVector, matrix, actual.Vector, fractionField);

            for (var i = 0; i < actual.VectorSpaceBasis.Count; ++i)
            {
                var vec = actual.VectorSpaceBasis[i];
                this.AssertVector(nullVector, matrix, vec, fractionField);
            }
        }
Example #5
0
        public void GetQuotientAndRemainderTest()
        {
            var dividend = "    x^3-1/3*x^2+ - -x/5-1/2";
            var divisor  = "x^2-x/2+1";

            // Os objectos responsáveis pelas operações sobre os coeficientes.
            var integerDomain = new IntegerDomain();
            var integerParser = new IntegerParser <string>();
            var conversion    = new ElementFractionConversion <int>(integerDomain);
            var fractionField = new FractionField <int>(integerDomain);

            // A leitura dos polinómios.
            var dividendPol = TestsHelper.ReadFractionalCoeffsUnivarPol <int, IntegerDomain>(
                dividend,
                integerDomain,
                integerParser,
                conversion,
                "x");
            var divisorPol = TestsHelper.ReadFractionalCoeffsUnivarPol <int, IntegerDomain>(
                divisor,
                integerDomain,
                integerParser,
                conversion,
                "x");
            var polynomialDomain = new UnivarPolynomEuclideanDomain <Fraction <int> >(
                "x",
                fractionField);
            var result   = polynomialDomain.GetQuotientAndRemainder(dividendPol, divisorPol);
            var expected = divisorPol.Multiply(result.Quotient, fractionField);

            expected = expected.Add(result.Remainder, fractionField);

            Assert.AreEqual(expected, dividendPol);
        }
Example #6
0
        /// <summary>
        /// Permit realizar a leitura de um polinómio com coeficientes fraccionários.
        /// </summary>
        /// <typeparam name="T">O tipo de dados dos componentes das fracções.</typeparam>
        /// <param name="polynomialRepresentation">A representação polinomial.</param>
        /// <param name="domain">O domínio responsável pelas operações sobre os elementos das fracções.</param>
        /// <param name="itemsParser">O leitor de elementos da fracção.</param>
        /// <param name="conversion">A conversão entre cada fracção e o valor inteiro.</param>
        /// <param name="variableName">O nome da variável.</param>
        /// <param name="readNegativeNumbers">Indica se são lidos os números negativos.</param>
        /// <returns>O polinómio lido.</returns>
        public static UnivariatePolynomialNormalForm <Fraction <T> > ReadFractionalCoeffsUnivarPol <T, D>(
            string polynomialRepresentation,
            D domain,
            IParse <T, string, string> itemsParser,
            IConversion <int, Fraction <T> > conversion,
            string variableName,
            bool readNegativeNumbers = false) where D : IEuclidenDomain <T>
        {
            var fractionField  = new FractionField <T>(domain);
            var fractionParser = new FieldDrivenExpressionParser <Fraction <T> >(
                new SimpleElementFractionParser <T>(itemsParser, domain),
                fractionField);
            var polInputReader  = new StringReader(polynomialRepresentation);
            var polSymbolReader = new StringSymbolReader(polInputReader, readNegativeNumbers);
            var polParser       = new UnivariatePolynomialReader <Fraction <T>, CharSymbolReader <string> >(
                "x",
                fractionParser,
                fractionField);

            var result = default(UnivariatePolynomialNormalForm <Fraction <T> >);

            if (polParser.TryParsePolynomial(polSymbolReader, conversion, out result))
            {
                // O polinómio foi lido com sucesso.
                return(result);
            }
            else
            {
                // Não é possível ler o polinómio.
                throw new Exception("Can't read polynomial.");
            }
        }
Example #7
0
        public void CombineLinesTest_NullDefaultValuesAnyAny()
        {
            var target        = this.GetDefaultMatrix(null);
            var integerDomain = new IntegerDomain();
            var fractionField = new FractionField <int>(integerDomain);

            // Constrói a linha a ser analisada.
            var matrixColumns = target.GetLength(1);
            var firstLine     = new Fraction <int> [matrixColumns];
            var firstProduct  = new Fraction <int>(3, 1, integerDomain);
            var secondProduct = new Fraction <int>(2, 1, integerDomain);

            for (int i = 0; i < matrixColumns; ++i)
            {
                var firstValue  = target[0, i];
                var secondValue = target[1, i];
                if (firstValue != null && secondValue != null)
                {
                    firstValue  = fractionField.Multiply(firstProduct, firstValue);
                    secondValue = fractionField.Multiply(secondProduct, secondValue);
                    var value = fractionField.Add(firstValue, secondValue);
                    firstLine[i] = value;
                }
            }

            target.CombineLines(0, 1, firstProduct, secondProduct, fractionField);
            for (int i = 0; i < matrixColumns; ++i)
            {
                Assert.AreEqual(firstLine[i], target[0, i]);
            }

            this.AssertLinesExcept(0, target);
        }
Example #8
0
        public void CombineLinesTest_NullDefaultValuesOneOneException()
        {
            var target        = this.GetDefaultMatrix(null);
            var integerDomain = new IntegerDomain();
            var fractionField = new FractionField <int>(integerDomain);

            target.CombineLines(1, 2, fractionField.MultiplicativeUnity, fractionField.MultiplicativeUnity, fractionField);
        }
Example #9
0
        public void CombineLinesTest_NullDefaultValuesAnyZeroException()
        {
            var target        = this.GetDefaultMatrix(null);
            var integerDomain = new IntegerDomain();
            var fractionField = new FractionField <int>(integerDomain);

            var firstProduct = new Fraction <int>(2, 1, integerDomain);

            target.CombineLines(1, 2, firstProduct, fractionField.AdditiveUnity, fractionField);
        }
        public void RunTest_IntegerPolynomial()
        {
            var    integerDomain      = new IntegerDomain();
            var    fractionField      = new FractionField <int>(integerDomain);
            var    integerParser      = new IntegerParser <string>();
            var    conversion         = new ElementToElementConversion <int>();
            var    fractionConversion = new ElementFractionConversion <int>(integerDomain);
            string variableName       = "x";
            var    univarPolDomain    = new UnivarPolynomEuclideanDomain <Fraction <int> >(
                variableName,
                fractionField);

            var lagAlg     = new LagrangeAlgorithm <UnivariatePolynomialNormalForm <Fraction <int> > >(univarPolDomain);
            var firstValue = TestsHelper.ReadFractionalCoeffsUnivarPol <int, IntegerDomain>(
                "(x-1/2)*(x+1/3)",
                integerDomain,
                integerParser,
                fractionConversion,
                variableName);

            var secondValue = TestsHelper.ReadFractionalCoeffsUnivarPol <int, IntegerDomain>(
                "(x-1/2)*(x-1)",
                integerDomain,
                integerParser,
                fractionConversion,
                variableName);

            var gcd = TestsHelper.ReadFractionalCoeffsUnivarPol <int, IntegerDomain>(
                "x-1/2",
                integerDomain,
                integerParser,
                fractionConversion,
                variableName);
            var result = lagAlg.Run(firstValue, secondValue);

            var mainGcdCoeff = result.GreatestCommonDivisor.GetLeadingCoefficient(fractionField);
            var monicGcd     = result.GreatestCommonDivisor.Multiply(
                fractionField.MultiplicativeInverse(mainGcdCoeff),
                fractionField);

            Assert.AreEqual(gcd, monicGcd);

            var firstTermExpression  = univarPolDomain.Multiply(result.FirstFactor, result.FirstItem);
            var secondTermExpression = univarPolDomain.Multiply(result.SecondFactor, result.SecondItem);
            var actualExpression     = univarPolDomain.Add(firstTermExpression, secondTermExpression);

            Assert.AreEqual(result.GreatestCommonDivisor, actualExpression);

            actualExpression = univarPolDomain.Multiply(result.GreatestCommonDivisor, result.FirstCofactor);
            Assert.AreEqual(result.FirstItem, actualExpression);

            actualExpression = univarPolDomain.Multiply(result.GreatestCommonDivisor, result.SecondCofactor);
            Assert.AreEqual(result.SecondItem, actualExpression);
        }
Example #11
0
        public void CombineLinesTest_ArbitraryDefaultValuesGeneral()
        {
            var integerDomain = new IntegerDomain();
            var fractionField = new FractionField <int>(integerDomain);
            var defaultValue  = fractionField.AdditiveUnity;

            // Zero e Zero
            var target = this.GetDefaultMatrix(defaultValue);

            this.AssertTarget(target, fractionField.AdditiveUnity, fractionField.AdditiveUnity, fractionField);

            // Zero e Um
            target = this.GetDefaultMatrix(fractionField.AdditiveUnity);
            this.AssertTarget(target, fractionField.AdditiveUnity, fractionField.MultiplicativeUnity, fractionField);

            // Um e Zero
            target = this.GetDefaultMatrix(defaultValue);
            this.AssertTarget(target, fractionField.MultiplicativeUnity, fractionField.AdditiveUnity, fractionField);

            // Um e Um
            target = this.GetDefaultMatrix(defaultValue);
            this.AssertTarget(target, fractionField.MultiplicativeUnity, fractionField.MultiplicativeUnity, fractionField);

            // Arbitrário e Zero
            var product = new Fraction <int>(2, 1, integerDomain);

            target = this.GetDefaultMatrix(defaultValue);
            this.AssertTarget(target, product, fractionField.AdditiveUnity, fractionField);

            // Zero e Arbitrário
            product = new Fraction <int>(2, 1, integerDomain);
            target  = this.GetDefaultMatrix(defaultValue);
            this.AssertTarget(target, fractionField.AdditiveUnity, product, fractionField);

            // Arbitrário e Um
            product = new Fraction <int>(2, 1, integerDomain);
            target  = this.GetDefaultMatrix(defaultValue);
            this.AssertTarget(target, product, fractionField.MultiplicativeUnity, fractionField);

            // Um e arbitrário
            product = new Fraction <int>(2, 1, integerDomain);
            target  = this.GetDefaultMatrix(defaultValue);
            this.AssertTarget(target, fractionField.MultiplicativeUnity, product, fractionField);

            // Arbitrário e arbitrário
            var firstProduct  = new Fraction <int>(2, 1, integerDomain);
            var secondProduct = new Fraction <int>(3, 1, integerDomain);

            target = this.GetDefaultMatrix(defaultValue);
            this.AssertTarget(target, firstProduct, secondProduct, fractionField);
        }
Example #12
0
        public void ReplaceTest_ReplaceByFraction()
        {
            // Representação dos polinómios.
            var polynomText  = "x^5+2*x^4+3*x^3+4*x^2+5*x+6";
            var variableName = "x";

            // Estabelece os domínios.
            var integerDomain = new IntegerDomain();

            // Estabelece os conversores.
            var integerToIntegerConv = new ElementToElementConversion <int>();

            // Estabelece os leitores individuais.
            var integerParser = new IntegerParser <string>();

            var fractionField = new FractionField <int>(integerDomain);

            var integerFractionAddOp = new ElementFractionAddOper <int>(integerDomain);

            // Estabelece os polinómios.
            var integerPolynomial = TestsHelper.ReadUnivarPolynomial(
                polynomText,
                integerDomain,
                integerParser,
                integerToIntegerConv,
                variableName);
            var fractionValues = new Fraction <int>[] {
                new Fraction <int>(0, 1, integerDomain),
                new Fraction <int>(1, 1, integerDomain),
                new Fraction <int>(1, 2, integerDomain),
                new Fraction <int>(1, 3, integerDomain)
            };

            var fractionExpectedValues = new Fraction <int>[] {
                new Fraction <int>(6, 1, integerDomain),
                new Fraction <int>(21, 1, integerDomain),
                new Fraction <int>(321, 32, integerDomain),
                new Fraction <int>(2005, 243, integerDomain)
            };

            for (int i = 0; i < fractionValues.Length; ++i)
            {
                var integerActualValue = integerPolynomial.Replace(
                    fractionValues[i],
                    integerFractionAddOp,
                    fractionField);
                Assert.AreEqual(fractionExpectedValues[i], integerActualValue);
            }
        }
Example #13
0
        public void GetRootPowerSumsTest_IntegerFraction()
        {
            // Representação dos polinómios.
            var polynomText  = "(x-3)*(x-2)^2*(x+1)^3";
            var variableName = "x";

            // Estabelece os domínios.
            var integerDomain = new IntegerDomain();

            // Estabelece o corpo responsável pelas operações sobre as fracções.
            var fractionField = new FractionField <int>(integerDomain);

            // Estabelece os conversores.
            var integerToFractionConversion = new ElementFractionConversion <int>(integerDomain);

            // Estabelece os leitores individuais.
            var integerParser = new IntegerParser <string>();

            // Estabelece o leitor de fracções.
            var fractionParser = new ElementFractionParser <int>(integerParser, integerDomain);

            // Estabelece os polinómios.
            var integerPolynomial = TestsHelper.ReadUnivarPolynomial(
                polynomText,
                fractionField,
                fractionParser,
                integerToFractionConversion,
                variableName);
            var integerFractionExpectedVector = new ArrayVector <Fraction <int> >(6);

            integerFractionExpectedVector[0] = new Fraction <int>(4, 1, integerDomain);
            integerFractionExpectedVector[1] = new Fraction <int>(20, 1, integerDomain);
            integerFractionExpectedVector[2] = new Fraction <int>(40, 1, integerDomain);
            integerFractionExpectedVector[3] = new Fraction <int>(116, 1, integerDomain);
            integerFractionExpectedVector[4] = new Fraction <int>(304, 1, integerDomain);
            integerFractionExpectedVector[5] = new Fraction <int>(860, 1, integerDomain);
            var integerFractionActualVector = integerPolynomial.GetRootPowerSums(
                fractionField,
                new SparseDictionaryMathVectorFactory <Fraction <int> >());

            Assert.AreEqual(
                integerFractionExpectedVector.Length,
                integerFractionActualVector.Length,
                "Vector lengths aren't equal.");
            for (int i = 0; i < integerFractionActualVector.Length; ++i)
            {
                Assert.AreEqual(integerFractionExpectedVector[i], integerFractionActualVector[i]);
            }
        }
Example #14
0
        public void ReplaceTest_ReplaceByMatrixWithMatrixAlgebra()
        {
            // Representação dos polinómios.
            var polynomText  = "x^2 + 2*x + 1";
            var variableName = "x";

            var integerDomain        = new IntegerDomain();
            var integerToIntegerConv = new ElementToElementConversion <int>();
            var integerParser        = new IntegerParser <string>();
            var fractionField        = new FractionField <int>(integerDomain);
            var fractionFieldParser  = new FieldDrivenExpressionParser <Fraction <int> >(
                new SimpleElementFractionParser <int>(integerParser, integerDomain),
                fractionField);

            var polynomial = TestsHelper.ReadUnivarPolynomial <Fraction <int> >(
                polynomText,
                fractionField,
                fractionFieldParser,
                new ElementFractionConversion <int>(integerDomain),
                variableName);

            // Leitura da matriz.
            var matrix = TestsHelper.ReadMatrix <Fraction <int> >(
                2,
                2,
                "[[1/2+1/3,1/2-1/3],[1/5+1/4,1/5-1/4]]",
                (i, j) => new ArrayMathMatrix <Fraction <int> >(i, j),
                fractionFieldParser);

            var matrixAlgebra = new GeneralMatrixAlgebra <Fraction <int> >(
                2,
                new ArrayMathMatrixFactory <Fraction <int> >(),
                fractionField);
            var actual   = polynomial.Replace(matrix, matrixAlgebra);
            var expected = TestsHelper.ReadMatrix <Fraction <int> >(
                2,
                2,
                "[[1237/360,167/360],[501/400,391/400]]",
                (i, j) => new ArrayMathMatrix <Fraction <int> >(i, j),
                fractionFieldParser);

            for (int i = 0; i < 2; ++i)
            {
                for (int j = 0; j < 2; ++j)
                {
                    Assert.AreEqual(expected[i, j], actual[i, j]);
                }
            }
        }
Example #15
0
        public void AddPowerTest_BigIntegerFraction()
        {
            var domain     = new BigIntegerDomain();
            var multiplier = new FractionField <BigInteger>(domain);

            var intPowers    = new int[] { 2, 3, 4, 1, 20, 13 };
            var longPowers   = new long[] { 2, 3, 4, 1, 20, 13 };
            var bigIntPowers = new BigInteger[] { 2, 3, 4, 1, 20, 13 };

            var values = new[] {
                new Fraction <BigInteger>(13, 17, domain),
                new Fraction <BigInteger>(25, 23, domain),
                new Fraction <BigInteger>(11, 15, domain),
                new Fraction <BigInteger>(100, 99, domain),
                new Fraction <BigInteger>(1, 2, domain),
                new Fraction <BigInteger>(3, 5, domain)
            };

            var expected = new[] {
                new Fraction <BigInteger>(26, 17, domain),
                new Fraction <BigInteger>(75, 23, domain),
                new Fraction <BigInteger>(44, 15, domain),
                new Fraction <BigInteger>(100, 99, domain),
                new Fraction <BigInteger>(10, 1, domain),
                new Fraction <BigInteger>(39, 5, domain)
            };

            // Potências inteiras.
            for (int i = 0; i < intPowers.Length; ++i)
            {
                var actual = MathFunctions.AddPower(values[i], intPowers[i], multiplier);
                Assert.AreEqual(expected[i], actual);
            }

            // Potências longas
            for (int i = 0; i < intPowers.Length; ++i)
            {
                var actual = MathFunctions.AddPower(values[i], longPowers[i], multiplier);
                Assert.AreEqual(expected[i], actual);
            }

            // Potências com inteiros grandes.
            for (int i = 0; i < intPowers.Length; ++i)
            {
                var actual = MathFunctions.AddPower(values[i], bigIntPowers[i], multiplier);
                Assert.AreEqual(expected[i], actual);
            }
        }
        public void RunTest()
        {
            var inputMatrix  = "[[1,2,1],[2,-1,-1],[1,-1,3]]";
            var inputVector  = "[[1,2,3]]";
            var expectedText = "[[21/19,-6/19,10/19]]";

            var integerDomain       = new BigIntegerDomain();
            var integerParser       = new BigIntegerParser <string>();
            var fractionField       = new FractionField <BigInteger>(integerDomain);
            var fractionFieldParser = new FieldDrivenExpressionParser <Fraction <BigInteger> >(
                new SimpleElementFractionParser <BigInteger>(integerParser, integerDomain),
                fractionField);
            var matrixFactory = new ArrayMathMatrixFactory <Fraction <BigInteger> >();

            // Leitura da matriz que representa o sistema de equações.
            var coeffsMatrix = TestsHelper.ReadMatrix <Fraction <BigInteger> >(
                3,
                3,
                inputMatrix,
                (i, j) => new ArrayMathMatrix <Fraction <BigInteger> >(i, j),
                fractionFieldParser);

            // Leitura do vector de termos independente.
            var vectorMatrix = TestsHelper.ReadMatrix <Fraction <BigInteger> >(
                3,
                1,
                inputVector,
                (i, j) => new ArrayMathMatrix <Fraction <BigInteger> >(i, j),
                fractionFieldParser);

            var expectedMatrix = TestsHelper.ReadMatrix <Fraction <BigInteger> >(
                3,
                1,
                expectedText,
                (i, j) => new ArrayMathMatrix <Fraction <BigInteger> >(i, j),
                fractionFieldParser);

            var systemSolver = new SequentialLanczosAlgorithm <Fraction <BigInteger>, FractionField <BigInteger> >(
                matrixFactory,
                fractionField);
            var squareMatrix = (coeffsMatrix as ArrayMathMatrix <Fraction <BigInteger> >).AsSquare();
            var actual       = systemSolver.Run(squareMatrix, vectorMatrix);

            for (int i = 0; i < 3; ++i)
            {
                Assert.AreEqual(expectedMatrix[i, 0], actual[i, 0]);
            }
        }
Example #17
0
        public void CombineLinesTest_ZeroDefaultValuesZeroZero()
        {
            var integerDomain = new IntegerDomain();
            var fractionField = new FractionField <int>(integerDomain);
            var target        = this.GetDefaultMatrix(fractionField.AdditiveUnity);

            var numberOfProcessedLines = target.GetLength(0) - 1;

            for (int i = 0; i < numberOfProcessedLines; ++i)
            {
                target.CombineLines(i, i + 1, fractionField.AdditiveUnity, fractionField.AdditiveUnity, fractionField);
            }

            // Resta apenas a última linha.
            Assert.AreEqual(1, target.GetLines().Count());
        }
        public void RunTest()
        {
            var coefficientsMatrixText = "[[1,0,0],[0,0,0],[0,3,3],[2,0,1]]";
            var independentVectorText  = "[[1,3,3]]";
            var expectedText           = "[[1,0,1,0]]";

            var integerDomain       = new IntegerDomain();
            var integerParser       = new IntegerParser <string>();
            var fractionField       = new FractionField <int>(integerDomain);
            var fractionFieldParser = new FieldDrivenExpressionParser <Fraction <int> >(
                new SimpleElementFractionParser <int>(integerParser, integerDomain),
                fractionField);
            var matrixFactory = new ArrayMatrixFactory <Fraction <int> >();

            // Leitura da matriz que representa o sistema de equações.
            var coeffsMatrix = TestsHelper.ReadMatrix <Fraction <int> >(
                3,
                4,
                coefficientsMatrixText,
                matrixFactory,
                fractionFieldParser);

            // Leitura do vector de termos independente.
            var vectorMatrix = TestsHelper.ReadMatrix <Fraction <int> >(
                3,
                1,
                independentVectorText,
                new ArrayMatrixFactory <Fraction <int> >(),
                fractionFieldParser);

            var expectedMatrixVector = TestsHelper.ReadMatrix <Fraction <int> >(
                4,
                1,
                expectedText,
                matrixFactory,
                fractionFieldParser);

            var algorithm = new DenseCondensationLinSysAlgorithm <Fraction <int> >(fractionField);
            var actual    = algorithm.Run(coeffsMatrix, vectorMatrix);

            Assert.AreEqual(expectedMatrixVector.GetLength(0), actual.Vector.Length);
            for (int i = 0; i < actual.Vector.Length; ++i)
            {
                Assert.AreEqual(expectedMatrixVector[i, 0], actual.Vector[i]);
            }
        }
        public void SymmetricLdlDecompLinearSystemAlgorithm_RunTest()
        {
            var domain           = new IntegerDomain();
            var fractionField    = new FractionField <int>(domain);
            var decompositionAlg = new TriangDiagSymmMatrixDecomposition <Fraction <int> >(
                fractionField);
            var target = new SymmetricLdlDecompLinearSystemAlgorithm <Fraction <int> >(
                decompositionAlg);
            var matrix = this.GetSingularMatrix(domain);
            var vector = this.GetZeroFilledVector(domain);
            var actual = target.Run(matrix, vector);

            // Teste à característica da matriz
            Assert.AreEqual(2, actual.VectorSpaceBasis.Count);

            // Teste ao vector independente
            var size       = matrix.GetLength(0);
            var nullVector = new ZeroVector <Fraction <int> >(size, fractionField);

            this.AssertVector(nullVector, matrix, actual.Vector, fractionField);

            // Teste aos vectores da base
            for (var i = 0; i < actual.VectorSpaceBasis.Count; ++i)
            {
                var vec = actual.VectorSpaceBasis[i];
                this.AssertVector(nullVector, matrix, vec, fractionField);
            }

            // Teste à matriz com vector independente
            vector = this.GetIndtVectorForSingularMatrix(domain);
            var expectedVector = new ArrayMathVector <Fraction <int> >(size);

            for (var i = 0; i < size; ++i)
            {
                expectedVector[i] = vector[i, 0];
            }

            actual = target.Run(matrix, vector);
            this.AssertVector(expectedVector, matrix, actual.Vector, fractionField);

            for (var i = 0; i < actual.VectorSpaceBasis.Count; ++i)
            {
                var vec = actual.VectorSpaceBasis[i];
                this.AssertVector(nullVector, matrix, vec, fractionField);
            }
        }
Example #20
0
        public void RunTest_ParallelTrianguDiagSummMatrixDecomp()
        {
            var domain        = new IntegerDomain();
            var fractionField = new FractionField <int>(domain);
            var target        = new ParallelTriangDiagSymmMatrixDecomp <Fraction <int> >(fractionField);

            // Matrix normal
            var matrix = this.GetDefaulMatrix(domain);

            Assert.IsTrue(matrix.IsSymmetric(fractionField));
            this.TestDecomposition(target, matrix);

            // Matriz singular
            matrix = this.GetSingularMatrix(domain);
            Assert.IsTrue(matrix.IsSymmetric(fractionField));
            this.TestDecomposition(target, matrix);
        }
        public void Run_TriangDiagSymmDecompNoInverse()
        {
            // Definição dos domínios e fábricas.
            var integerDomain = new IntegerDomain();
            var fractionField = new FractionField <int>(integerDomain);

            // Definição dos algoritmos.
            var target       = new TriangDiagSymmDecompInverseAlg <Fraction <int> >();
            var triangDecomp = new ParallelTriangDiagSymmMatrixDecomp <Fraction <int> >(fractionField);

            var arraySquareMatrixFactory = new ArraySquareMatrixFactory <Fraction <int> >();
            var arrayMatrixFactory       = new ArrayMathMatrixFactory <Fraction <int> >();

            // A matriz
            var matrix = this.GetSingularMatrix(integerDomain);

            // Cálculos
            var triangDiagDecomp = triangDecomp.Run(
                matrix);
            var inverseMatrix = target.Run(
                triangDiagDecomp,
                arraySquareMatrixFactory,
                fractionField);

            // Verificação dos valores.
            var expected = ArrayMathMatrix <Fraction <int> > .GetIdentity(3, fractionField);

            var matrixMultiplication = new MatrixMultiplicationOperation <Fraction <int> >(
                arrayMatrixFactory,
                fractionField,
                fractionField);
            var actual = matrixMultiplication.Multiply(inverseMatrix, matrix);

            for (int i = 0; i < 3; ++i)
            {
                for (int j = 0; j < 3; ++j)
                {
                    Assert.AreEqual(expected[i, j], actual[i, j]);
                }
            }
        }
Example #22
0
        public void PowerTest_BigIntegerFraction()
        {
            var domain     = new BigIntegerDomain();
            var multiplier = new FractionField <BigInteger>(domain);

            var intPowers    = new int[] { 2, 3, 4, 1, 20, 13 };
            var longPowers   = new long[] { 2, 3, 4, 1, 20, 13 };
            var bigIntPowers = new BigInteger[] { 2, 3, 4, 1, 20, 13 };

            var values = new[] {
                new Fraction <BigInteger>(13, 17, domain),
                new Fraction <BigInteger>(25, 23, domain),
                new Fraction <BigInteger>(11, 15, domain),
                new Fraction <BigInteger>(100, 99, domain),
                new Fraction <BigInteger>(1, 2, domain),
                new Fraction <BigInteger>(3, 5, domain)
            };

            var expected = new[] {
                new Fraction <BigInteger>(169, 289, domain),
                new Fraction <BigInteger>(15625, 12167, domain),
                new Fraction <BigInteger>(14641, 50625, domain),
                new Fraction <BigInteger>(100, 99, domain),
                new Fraction <BigInteger>(1, 1048576, domain),
                new Fraction <BigInteger>(1594323, 1220703125, domain)
            };

            // Potências inteiras.
            for (int i = 0; i < intPowers.Length; ++i)
            {
                var actual = MathFunctions.Power(values[i], intPowers[i], multiplier);
                Assert.AreEqual(expected[i], actual);
            }

            // Potências longas
            for (int i = 0; i < intPowers.Length; ++i)
            {
                var actual = MathFunctions.Power(values[i], longPowers[i], multiplier);
                Assert.AreEqual(expected[i], actual);
            }

            // Potências com inteiros grandes.
            for (int i = 0; i < intPowers.Length; ++i)
            {
                var actual = MathFunctions.Power(values[i], bigIntPowers[i], multiplier);
                Assert.AreEqual(expected[i], actual);
            }

            // Potências genéricas.
            var integerNumber    = new IntegerDomain();
            var longNumber       = new LongDomain();
            var bigIntegerNumber = new BigIntegerDomain();

            // Potências inteiras.
            for (int i = 0; i < intPowers.Length; ++i)
            {
                var actual = MathFunctions.Power(values[i], intPowers[i], multiplier, integerNumber);
                Assert.AreEqual(expected[i], actual);
            }

            // Potências longas
            for (int i = 0; i < intPowers.Length; ++i)
            {
                var actual = MathFunctions.Power(values[i], longPowers[i], multiplier, longNumber);
                Assert.AreEqual(expected[i], actual);
            }

            // Potências com inteiros grandes.
            for (int i = 0; i < intPowers.Length; ++i)
            {
                var actual = MathFunctions.Power(values[i], bigIntPowers[i], multiplier, bigIntegerNumber);
                Assert.AreEqual(expected[i], actual);
            }
        }
Example #23
0
        public void Statistcs_ListGeneralizeMeanBlockAlgorithmTest()
        {
            var target = new ListGeneralizedMeanAlgorithm <int, double>(
                i => i,
                d => d,
                (d, i) => d / i,
                new DoubleField());
            var blockNumber = 2500;

            var integerSequence = new List <int>();

            for (var i = 1; i < 5500; ++i)
            {
                integerSequence.Add(i);
                var expected = (i + 1) / 2.0;
                var actual   = target.Run <double>(
                    integerSequence,
                    blockNumber,
                    (j, k) => j / (double)k,
                    (d1, d2) => d1 * d2);
                Assert.IsTrue(Math.Abs(expected - actual) < 0.001);
            }

            var n = 1000500;

            for (var i = 5500; i <= n; ++i)
            {
                integerSequence.Add(i);
            }

            var outerExpected = (n + 1) / 2.0;
            var outerActual   = target.Run <double>(
                integerSequence,
                blockNumber,
                (j, k) => j / (double)k,
                (d1, d2) => d1 * d2);

            Assert.AreEqual(outerExpected, outerActual);

            var integerDomain = new BigIntegerDomain();
            var fractionField = new FractionField <BigInteger>(integerDomain);
            var fracTarget    = new ListGeneralizedMeanAlgorithm <int, Fraction <BigInteger> >(
                i => new Fraction <BigInteger>(i, 1, integerDomain),
                d => d,
                (d, i) => d.Divide(i, integerDomain),
                fractionField);

            var fractionExpected = new Fraction <BigInteger>(n + 1, 2, integerDomain);
            var fractionActual   = fracTarget.Run <Fraction <BigInteger> >(
                integerSequence,
                blockNumber,
                (j, k) => new Fraction <BigInteger>(j, k, integerDomain),
                (d1, d2) => d1.Multiply(d2, integerDomain));

            Assert.AreEqual(fractionExpected, fractionActual);

            // Teste com alteração da função directa
            fracTarget.DirectFunction = i => new Fraction <BigInteger>(new BigInteger(i) * i, 1, integerDomain);
            fractionExpected          = new Fraction <BigInteger>(
                (new BigInteger(n) + BigInteger.One) * (2 * new BigInteger(n) + 1), 6, integerDomain);
            fractionActual = fracTarget.Run <Fraction <BigInteger> >(
                integerSequence,
                blockNumber,
                (j, k) => new Fraction <BigInteger>(j, k, integerDomain),
                (d1, d2) => d1.Multiply(d2, integerDomain));

            // Teste com transformação
            var transformedTarget = new ListGeneralizedMeanAlgorithm <BigInteger, Fraction <BigInteger> >(
                i => new Fraction <BigInteger>(i, 1, integerDomain),
                d => d,
                (d, i) => d.Divide(i, integerDomain),
                fractionField);
            var transformedSeq = new TransformList <int, BigInteger>(
                integerSequence,
                i => new BigInteger(i) * i);
            var transformedExpected = new Fraction <BigInteger>(
                (new BigInteger(n) + BigInteger.One) * (2 * new BigInteger(n) + 1), 6, integerDomain);
            var transformedActual = transformedTarget.Run <Fraction <BigInteger> >(
                transformedSeq,
                blockNumber,
                (j, k) => new Fraction <BigInteger>(j, k, integerDomain),
                (d1, d2) => d1.Multiply(d2, integerDomain));

            Assert.AreEqual(transformedExpected, transformedActual);
        }
Example #24
0
        public void GetPolynomialDerivativeTest_IntegerFraction()
        {
            var polynomialText           = "1/2*x^5+3/4*x^4-2/7*x^3+5/3*x^2+1/5*x+9";
            var polynomialDerivativeText = "5/2*x^4+3*x^3-6/7*x^2+10/3*x+1/5";
            var variableName             = "x";

            var integerDomain    = new IntegerDomain();
            var longDomain       = new LongDomain();
            var bigIntegerDomain = new BigIntegerDomain();

            var integerParser    = new IntegerParser <string>();
            var longParser       = new LongParser <string>();
            var bigIntegerParser = new BigIntegerParser <string>();

            var longConversion       = new LongToIntegerConversion();
            var bigIntegerConversion = new BigIntegerToIntegerConversion();

            var integerFractionConversion    = new ElementFractionConversion <int>(integerDomain);
            var longfractionConversion       = new OuterElementFractionConversion <int, long>(longConversion, longDomain);
            var bigIntegerfractionConversion = new OuterElementFractionConversion <int, BigInteger>(bigIntegerConversion, bigIntegerDomain);

            var integerFractionField    = new FractionField <int>(integerDomain);
            var longFractionField       = new FractionField <long>(longDomain);
            var bigIntegerFractionField = new FractionField <BigInteger>(bigIntegerDomain);

            // Coeficientes inteiros
            var integerPolynomial = TestsHelper.ReadFractionalCoeffsUnivarPol <int, IntegerDomain>(
                polynomialText,
                integerDomain,
                integerParser,
                integerFractionConversion,
                variableName);

            var integerPolynomialDerivative = TestsHelper.ReadFractionalCoeffsUnivarPol <int, IntegerDomain>(
                polynomialDerivativeText,
                integerDomain,
                integerParser,
                integerFractionConversion,
                variableName);
            var integerActualPolDerivative = integerPolynomial.GetPolynomialDerivative(integerFractionField);

            Assert.AreEqual(integerPolynomialDerivative, integerActualPolDerivative);

            // Coeficientes longos
            var longPolynomial = TestsHelper.ReadFractionalCoeffsUnivarPol <long, LongDomain>(
                polynomialText,
                longDomain,
                longParser,
                longfractionConversion,
                variableName);

            var longPolynomialDerivative = TestsHelper.ReadFractionalCoeffsUnivarPol <long, LongDomain>(
                polynomialDerivativeText,
                longDomain,
                longParser,
                longfractionConversion,
                variableName);
            var longActualPolDerivative = longPolynomial.GetPolynomialDerivative(longFractionField);

            Assert.AreEqual(longPolynomialDerivative, longActualPolDerivative);

            var bigIntegerPolynomial = TestsHelper.ReadFractionalCoeffsUnivarPol <BigInteger, BigIntegerDomain>(
                polynomialText,
                bigIntegerDomain,
                bigIntegerParser,
                bigIntegerfractionConversion,
                variableName);

            var bigIntegerPolynomialDerivative = TestsHelper.ReadFractionalCoeffsUnivarPol <BigInteger, BigIntegerDomain>(
                polynomialDerivativeText,
                bigIntegerDomain,
                bigIntegerParser,
                bigIntegerfractionConversion,
                variableName);
            var bigIntegerActualPolDerivative = bigIntegerPolynomial.GetPolynomialDerivative(bigIntegerFractionField);

            Assert.AreEqual(bigIntegerPolynomialDerivative, bigIntegerActualPolDerivative);
        }
Example #25
0
        public void Statistcs_EnumGeneralizeMeanAlgorithmTest()
        {
            var integerNumb = new IntegerDomain();
            var target      = new EnumGeneralizedMeanAlgorithm <int, double, int>(
                i => i,
                d => d,
                (d, i) => d / i,
                new DoubleField(),
                integerNumb);

            var integerSequence = new IntegerSequence();

            for (var i = 1; i < 5000; ++i)
            {
                integerSequence.Add(i);
                var expected = (i + 1) / 2.0;
                var actual   = target.Run(integerSequence);
                Assert.AreEqual(expected, actual);
            }

            integerSequence = new IntegerSequence();
            var n = 1000000;

            integerSequence.Add(1, n);
            var outerExpected = (n + 1) / 2.0;
            var outerActual   = target.Run(integerSequence);

            Assert.AreEqual(outerExpected, outerActual);

            var bigIntegerDomain = new BigIntegerDomain();
            var fractionField    = new FractionField <BigInteger>(bigIntegerDomain);
            var fractionTarget   = new EnumGeneralizedMeanAlgorithm <int, Fraction <BigInteger>, int>(
                i => new Fraction <BigInteger>(i, 1, bigIntegerDomain),
                d => d,
                (d, i) => d.Divide(i, bigIntegerDomain),
                fractionField,
                integerNumb);
            var fractionExpected = new Fraction <BigInteger>(n + 1, 2, bigIntegerDomain);
            var fractionActual   = fractionTarget.Run(integerSequence);

            Assert.AreEqual(fractionExpected, fractionActual);

            // Teste com alteração da função directa
            fractionTarget.DirectFunction = i => new Fraction <BigInteger>(new BigInteger(i) * i, 1, bigIntegerDomain);
            fractionExpected = new Fraction <BigInteger>(
                (new BigInteger(n) + BigInteger.One) * (2 * new BigInteger(n) + 1), 6, bigIntegerDomain);
            fractionActual = fractionTarget.Run(integerSequence);
            Assert.AreEqual(fractionExpected, fractionActual);

            // Teste com transformação
            var transformedTarget = new EnumGeneralizedMeanAlgorithm <BigInteger, Fraction <BigInteger>, int>(
                i => new Fraction <BigInteger>(i, 1, bigIntegerDomain),
                d => d,
                (d, i) => d.Divide(i, bigIntegerDomain),
                fractionField,
                integerNumb);
            var transformedSeq = new TransformEnumerable <int, BigInteger>(
                integerSequence,
                i => new BigInteger(i) * i);
            var transformedExpected = new Fraction <BigInteger>(
                (new BigInteger(n) + BigInteger.One) * (2 * new BigInteger(n) + 1), 6, bigIntegerDomain);
            var transformedActual = transformedTarget.Run(transformedSeq);

            Assert.AreEqual(transformedExpected, transformedActual);
        }
Example #26
0
        public void GetRootPowerSumsTest()
        {
            // Representação dos polinómios.
            var polynomText  = "(x-3)*(x-2)^2*(x+1)^3";
            var variableName = "x";

            // Estabelece os domínios.
            var integerDomain = new IntegerDomain();

            // Estabelece o corpo responsável pelas operações sobre as fracções.
            var fractionField = new FractionField <int>(integerDomain);

            // Estabelece os conversores.
            var integerToFractionConversion = new ElementFractionConversion <int>(integerDomain);

            // Estabelece os leitores individuais.
            var integerParser = new IntegerParser <string>();

            // Estabelece o leitor de fracções.
            var fractionParser = new ElementFractionParser <int>(integerParser, integerDomain);

            // Estabelece os polinómios.
            var integerPolynomial = TestsHelper.ReadUnivarPolynomial(
                polynomText,
                fractionField,
                fractionParser,
                integerToFractionConversion,
                variableName);

            var number     = 10;
            var roots      = new int[] { 3, 2, 2, -1, -1, -1 };
            var powerRoots = new int[] { 3, 2, 2, -1, -1, -1 };
            var integerFractionExpectedVector = new ArrayVector <Fraction <int> >(number);

            // Primeiro cálculo
            var sum = powerRoots[0];

            for (int i = 1; i < powerRoots.Length; ++i)
            {
                sum += powerRoots[i];
            }

            integerFractionExpectedVector[0] = new Fraction <int>(sum, 1, integerDomain);
            for (int i = 1; i < number; ++i)
            {
                for (int j = 0; j < roots.Length; ++j)
                {
                    powerRoots[j] *= roots[j];
                }

                sum = powerRoots[0];
                for (int j = 1; j < powerRoots.Length; ++j)
                {
                    sum += powerRoots[j];
                }

                integerFractionExpectedVector[i] = new Fraction <int>(sum, 1, integerDomain);
            }

            var integerFractionActualVector = integerPolynomial.GetRootPowerSums(
                number,
                fractionField,
                new SparseDictionaryMathVectorFactory <Fraction <int> >());

            Assert.AreEqual(
                integerFractionExpectedVector.Length,
                integerFractionActualVector.Length,
                "Vector lengths aren't equal.");
            for (int i = 0; i < integerFractionActualVector.Length; ++i)
            {
                Assert.AreEqual(integerFractionExpectedVector[i], integerFractionActualVector[i]);
            }
        }