/// <summary>
        /// Permite efectuar a leitura de um polinómio 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 <int> Read(string polynomial)
        {
            var integerDomain   = new IntegerDomain();
            var integerParser   = new IntegerParser <string>();
            var conversion      = new ElementToElementConversion <int>();
            var polInputReader  = new StringReader(polynomial);
            var polSymbolReader = new StringSymbolReader(polInputReader, false);
            var polParser       = new UnivariatePolynomialReader <int, CharSymbolReader <string> >(
                "x",
                integerParser,
                integerDomain);

            var result = default(UnivariatePolynomialNormalForm <int>);

            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.");
            }
        }
示例#2
0
        public void AddPowerTest_Integer()
        {
            var multiplier = new IntegerDomain();

            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[] { 13, 25, 11, 100, 2, 3 };
            var expected = new[] { 26, 75, 44, 100, 40, 39 };

            // 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);
            }
        }
示例#3
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);
        }
示例#4
0
        public void ReplaceTest_Integer()
        {
            // 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>();

            // Estabelece os polinómios.
            var integerPolynomial = TestsHelper.ReadUnivarPolynomial(
                polynomText,
                integerDomain,
                integerParser,
                integerToIntegerConv,
                variableName);
            var integerReplaceValues  = new int[] { 0, 1, 2, 3 };
            var integerExpectedValues = new int[] { 6, 21, 120, 543 };

            for (int i = 0; i < integerReplaceValues.Length; ++i)
            {
                var integerActualValue = integerPolynomial.Replace(integerReplaceValues[i], integerDomain);
                Assert.AreEqual(integerExpectedValues[i], integerActualValue);
            }
        }
示例#5
0
        public override void DomainSizeIsCorrect()
        {
            var boundedDomain = new IntegerDomain(IntegerDomainTest.minimum, IntegerDomainTest.maximum);

            Assert.Equal(
                IntegerDomainTest.maximum - IntegerDomainTest.minimum + 1,
                boundedDomain.DomainSize);

            var upperBoundedDomain = new IntegerDomain(maximum: IntegerDomainTest.maximum);

            Assert.Equal(
                double.PositiveInfinity,
                upperBoundedDomain.DomainSize);

            var lowerBoundedDomain = new IntegerDomain(minimum: IntegerDomainTest.minimum);

            Assert.Equal(
                double.PositiveInfinity,
                lowerBoundedDomain.DomainSize);

            var unbounded = new IntegerDomain();

            Assert.Equal(
                double.PositiveInfinity,
                unbounded.DomainSize);
        }
示例#6
0
        /// <summary>
        /// Constrói uma matriz de teste na qual o valor por defeito é nulo.
        /// </summary>
        /// <remarks>
        ///     - 1 - 2 -
        ///     - 3 - 4 -
        ///     1 2 - - 3
        ///     - - - - -
        ///     3 1 4 5 2
        /// </remarks>
        /// <param name="defaultValue">O valor por defeito.</param>
        /// <returns>A matriz de teste.</returns>
        private SparseDictionaryMathMatrix <Fraction <int> > GetDefaultMatrix(Fraction <int> defaultValue)
        {
            var result        = new SparseDictionaryMathMatrix <Fraction <int> >(5, 5, defaultValue);
            var integerDomain = new IntegerDomain();

            // Primeira linha.
            result[0, 1] = new Fraction <int>(1, 1, integerDomain);
            result[0, 3] = new Fraction <int>(1, 1, integerDomain);

            // Segunda linha.
            result[1, 1] = new Fraction <int>(3, 1, integerDomain);
            result[1, 3] = new Fraction <int>(4, 1, integerDomain);

            // Terceira linha.
            result[2, 0] = new Fraction <int>(1, 1, integerDomain);
            result[2, 1] = new Fraction <int>(2, 1, integerDomain);
            result[2, 4] = new Fraction <int>(3, 1, integerDomain);

            // Quinta linha.
            result[4, 0] = new Fraction <int>(3, 1, integerDomain);
            result[4, 1] = new Fraction <int>(1, 1, integerDomain);
            result[4, 2] = new Fraction <int>(4, 1, integerDomain);
            result[4, 3] = new Fraction <int>(5, 1, integerDomain);
            result[4, 4] = new Fraction <int>(2, 1, integerDomain);

            return(result);
        }
        public void RunTest_IntegerNumbersRhoAlg()
        {
            var integerNumber = new IntegerDomain();
            var integerParser = new IntegerParser <string>();
            var conversion    = new ElementToElementConversion <int>();
            var variableName  = "x";
            var testPols      = new List <UnivariatePolynomialNormalForm <int> >();

            testPols.Add(TestsHelper.ReadUnivarPolynomial("x^2+1", integerNumber, integerParser, conversion, variableName));
            testPols.Add(TestsHelper.ReadUnivarPolynomial("x^2+x+1", integerNumber, integerParser, conversion, variableName));

            var rhoAlgorithm = new PollardRhoAlgorithm <int>(
                testPols,
                new ModularIntegerFieldFactory(),
                integerNumber);
            var factorizationTarget = new DecompositionFactorizationAlgorithm <int, int>(
                rhoAlgorithm,
                1,
                integerNumber,
                integerNumber);
            var value    = 72;
            var expected = new Dictionary <int, int>();

            expected.Add(2, 3);
            expected.Add(3, 2);
            var actual = factorizationTarget.Run(value);

            CollectionAssert.AreEqual(expected, actual);
        }
        public void RunTest_BigIntegerNumbersRhoAlg()
        {
            var bigIntegerNumber = new BigIntegerDomain();
            var integerNumber    = new IntegerDomain();
            var integerParser    = new BigIntegerParser <string>();
            var conversion       = new BigIntegerToIntegerConversion();
            var variableName     = "x";
            var testPols         = new List <UnivariatePolynomialNormalForm <BigInteger> >();

            testPols.Add(TestsHelper.ReadUnivarPolynomial("x^123+1", bigIntegerNumber, integerParser, conversion, variableName));
            testPols.Add(TestsHelper.ReadUnivarPolynomial("x^452+1537*x+1", bigIntegerNumber, integerParser, conversion, variableName));

            var rhoAlgorithm = new PollardRhoAlgorithm <BigInteger>(
                testPols,
                new ModularBigIntFieldFactory(),
                bigIntegerNumber);
            var factorizationTarget = new DecompositionFactorizationAlgorithm <BigInteger, int>(
                rhoAlgorithm,
                1,
                integerNumber,
                bigIntegerNumber);
            var value    = BigInteger.Parse("1000000000001");
            var expected = new Dictionary <BigInteger, int>();

            expected.Add(137, 1);
            expected.Add(73, 1);
            expected.Add(BigInteger.Parse("99990001"), 1);
            var actual = factorizationTarget.Run(value);

            CollectionAssert.AreEquivalent(expected, actual);
        }
示例#9
0
 public override void ToStringShowsMinimumAndMaximum()
 {
     this._integerDomain = new IntegerDomain(IntegerDomainTest.minimum, IntegerDomainTest.maximum);
     Assert.Equal(
         $"integers in [{this._integerDomain.Minimum}, {this._integerDomain.Maximum}]",
         this._integerDomain.ToString());
 }
示例#10
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);
        }
示例#11
0
        public void MutationDistributionMeanAndStandardDeviationAreRoughlyAsExpected()
        {
            // Build up unbounded domain.
            this._integerDomain = new IntegerDomain();

            // Fix value to mutate and the variance percentage corresponding to some expected values.
            int          expectedStandardDeviation = 5;
            int          expectedMean       = 3;
            Allele <int> valueToMutate      = new Allele <int>(expectedMean);
            double       variancePercentage = Math.Pow(expectedStandardDeviation, 2) /
                                              ((double)this._integerDomain.Maximum - this._integerDomain.Minimum);

            // Collect results of a lot of mutations.
            double[] mutations = new double[IntegerDomainTest.triesForRandomTests];
            for (int i = 0; i < IntegerDomainTest.triesForRandomTests; i++)
            {
                mutations[i] =
                    (int)this._integerDomain.MutateGeneValue(valueToMutate, variancePercentage).GetValue();
            }

            // Create distribution.
            var distribution = new EmpiricalDistribution(mutations);

            // Check mean & standard deviation.
            Assert.True(
                Math.Abs(expectedMean - distribution.Mean) < 0.1 * expectedMean);
            Assert.True(
                Math.Abs(expectedStandardDeviation - distribution.StandardDeviation) < 0.1 * expectedStandardDeviation);
        }
        public void RunTest_ListOfLists()
        {
            var costs = new List <List <int> >();

            costs.Add(new List <int>()
            {
                12, 9, 7, 6, 4
            });
            costs.Add(new List <int>()
            {
                12, 11, 8, 7, 5
            });
            costs.Add(new List <int>()
            {
                13, 10, 9, 6, 3
            });
            costs.Add(new List <int>()
            {
                12, 8, 6, 4, 2
            });

            var integerDomain        = new IntegerDomain();
            var numberTdecomposition = new IntegerMinWeightTdecomposition <int>(
                Comparer <int> .Default,
                integerDomain);

            var result          = numberTdecomposition.Run(18, costs);
            var expectedMedians = new List <int>()
            {
                3, 5, 5, 5
            };

            Assert.AreEqual(17, result.Cost);
            CollectionAssert.AreEquivalent(expectedMedians, result.Medians.ToList());
        }
        public void SubsetSumLLLReductionAlgorithmConstructorTest()
        {
            var integerDomain   = new IntegerDomain();
            var decimalField    = new DecimalField();
            var vectorFactory   = new ArrayVectorFactory <decimal>();
            var decimalComparer = Comparer <decimal> .Default;
            var nearest         = new DecimalNearestInteger();

            // Permite calcular o produto escalar de vectores sobre o corpo de decimais.
            var scalarProd = new OrthoVectorScalarProduct <decimal>(
                decimalComparer,
                decimalField);

            // Permite converter um número decimal num inteiro, caso seja possível.
            var integerDecimalConverter = new IntegerDecimalConverter();

            var subsetSumAlg = new SubsetSumLLLReductionAlgorithm <int, decimal>(
                vectorFactory,
                scalarProd,
                nearest,
                Comparer <decimal> .Default,
                integerDecimalConverter,
                decimalField);

            var vector   = new[] { 366, 385, 392, 401, 422, 437 };
            var result   = subsetSumAlg.Run(vector, 1215, 3M / 4);
            var expected = new[] { 392, 401, 422 };

            CollectionAssert.AreEquivalent(expected, result);
        }
        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);
            }
        }
示例#15
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);
        }
示例#16
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);
        }
示例#17
0
        public void PowerTest_BigInteger()
        {
            var multiplier = new BigIntegerDomain();

            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 BigInteger[] { 13, 25, 11, 100, 2, 3 };
            var expected = new BigInteger[] { 169, 15625, 14641, 100, 1048576, 1594323 };

            // 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);
            }
        }
        /// <summary>
        /// Obtém um vector cujas entradas são nulas.
        /// </summary>
        /// <param name="integerDomain">
        /// O objecto responsável pelas operações sobre os números inteiros.
        /// </param>
        /// <returns>O vector.</returns>
        private ArrayMathMatrix <Fraction <int> > GetZeroFilledVector(
            IntegerDomain integerDomain)
        {
            var result = new ArrayMathMatrix <Fraction <int> >(
                6,
                1,
                new Fraction <int>(0, 1, integerDomain));

            return(result);
        }
        /// <summary>
        /// Obtém o vector independente para tetar a matriz geral.
        /// </summary>
        /// <param name="domain">O objecto responsável pelas operações sobre inteiros.</param>
        private ArrayMathMatrix <Fraction <int> > GetIndVectorForGenMatrix(
            IntegerDomain domain)
        {
            var result = new ArrayMathMatrix <Fraction <int> >(2, 1);

            result[0, 0] = new Fraction <int>(2, 1, domain);
            result[1, 0] = new Fraction <int>(5, 1, domain);

            return(result);
        }
示例#20
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);
        }
示例#21
0
        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);
        }
示例#22
0
        public void GreatCommonDivisorTest_IntegerNumber()
        {
            var domain       = new IntegerDomain();
            var firstValues  = new[] { 6, 48, 3251, 100, 3528, 427 };
            var secondValues = new[] { 12, 36, 4525, 75, 4116, 254 };
            var expected     = new[] { 6, 12, 1, 25, 588, 1 };

            for (int i = 0; i < firstValues.Length; ++i)
            {
                var actual = MathFunctions.GreatCommonDivisor(firstValues[i], secondValues[i], domain);
                Assert.AreEqual(expected[i], actual);
            }
        }
示例#23
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);
        }
        /// <summary>
        /// Obtém o vector independente para utilizar com a matriz singular.
        /// </summary>
        /// <param name="domain">O objecto responsável pelas operações sobre os números inteiros.</param>
        /// <returns>O vector.</returns>
        private ArrayMathMatrix <Fraction <int> > GetIndtVectorForSingularMatrix(
            IntegerDomain domain)
        {
            var result = new ArrayMathMatrix <Fraction <int> >(6, 1);

            result[0, 0] = new Fraction <int>(3, 1, domain);
            result[1, 0] = new Fraction <int>(-3, 1, domain);
            result[2, 0] = new Fraction <int>(-8, 1, domain);
            result[3, 0] = new Fraction <int>(-5, 1, domain);
            result[4, 0] = new Fraction <int>(-5, 1, domain);
            result[5, 0] = new Fraction <int>(8, 1, domain);

            return(result);
        }
示例#25
0
        public void RandomGenerationCreatesLegalGenes()
        {
            this._integerDomain = new IntegerDomain(IntegerDomainTest.minimum, IntegerDomainTest.maximum);

            // For a lot of tries:
            for (int i = 0; i < IntegerDomainTest.triesForRandomTests; i++)
            {
                // Check that the generated gene is legal.
                IAllele generated = this._integerDomain.GenerateRandomGeneValue();
                Assert.True(
                    this._integerDomain.ContainsGeneValue(generated),
                    $"Generated value {generated} is not a legal gene of {this._integerDomain}.");
            }
        }
示例#26
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]);
                }
            }
        }
示例#27
0
        /// <summary>
        /// Obtém uma matriz singular a ser utilizada nos testes.
        /// </summary>
        /// <param name="integerDomain">O objecto responsável pelas operações sobre os números inteiros.</param>
        /// <returns>A matriz.</returns>
        private ArraySquareMathMatrix <Fraction <int> > GetSingularMatrix(
            IntegerDomain integerDomain)
        {
            var result = new ArraySquareMathMatrix <Fraction <int> >(6);

            result[0, 0] = new Fraction <int>(3, 1, integerDomain);
            result[0, 1] = new Fraction <int>(3, 1, integerDomain);
            result[0, 2] = new Fraction <int>(0, 1, integerDomain);
            result[0, 3] = new Fraction <int>(3, 1, integerDomain);
            result[0, 4] = new Fraction <int>(-4, 1, integerDomain);
            result[0, 5] = new Fraction <int>(2, 1, integerDomain);

            result[1, 0] = new Fraction <int>(3, 1, integerDomain);
            result[1, 1] = new Fraction <int>(7, 1, integerDomain);
            result[1, 2] = new Fraction <int>(4, 1, integerDomain);
            result[1, 3] = new Fraction <int>(7, 1, integerDomain);
            result[1, 4] = new Fraction <int>(-6, 1, integerDomain);
            result[1, 5] = new Fraction <int>(2, 1, integerDomain);

            result[2, 0] = new Fraction <int>(0, 1, integerDomain);
            result[2, 1] = new Fraction <int>(4, 1, integerDomain);
            result[2, 2] = new Fraction <int>(5, 1, integerDomain);
            result[2, 3] = new Fraction <int>(5, 1, integerDomain);
            result[2, 4] = new Fraction <int>(-1, 1, integerDomain);
            result[2, 5] = new Fraction <int>(-1, 1, integerDomain);

            result[3, 0] = new Fraction <int>(3, 1, integerDomain);
            result[3, 1] = new Fraction <int>(7, 1, integerDomain);
            result[3, 2] = new Fraction <int>(5, 1, integerDomain);
            result[3, 3] = new Fraction <int>(8, 1, integerDomain);
            result[3, 4] = new Fraction <int>(-5, 1, integerDomain);
            result[3, 5] = new Fraction <int>(1, 1, integerDomain);

            result[4, 0] = new Fraction <int>(-4, 1, integerDomain);
            result[4, 1] = new Fraction <int>(-6, 1, integerDomain);
            result[4, 2] = new Fraction <int>(-1, 1, integerDomain);
            result[4, 3] = new Fraction <int>(-5, 1, integerDomain);
            result[4, 4] = new Fraction <int>(8, 1, integerDomain);
            result[4, 5] = new Fraction <int>(-5, 1, integerDomain);

            result[5, 0] = new Fraction <int>(2, 1, integerDomain);
            result[5, 1] = new Fraction <int>(2, 1, integerDomain);
            result[5, 2] = new Fraction <int>(-1, 1, integerDomain);
            result[5, 3] = new Fraction <int>(1, 1, integerDomain);
            result[5, 4] = new Fraction <int>(-5, 1, integerDomain);
            result[5, 5] = new Fraction <int>(5, 1, integerDomain);

            return(result);
        }
示例#28
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]);
            }
        }
示例#29
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);
            }
        }
        /// <summary>
        /// Obtém uma matriz para testar o sistema de equações geral.
        /// </summary>
        /// <param name="integerDomain">
        /// O objecto responsável pelas operações sobre inteiros.
        /// </param>
        /// <returns>A matriz de teste.</returns>
        private ArrayMathMatrix <Fraction <int> > GetGeneralMatrix(
            IntegerDomain integerDomain)
        {
            var result = new ArrayMathMatrix <Fraction <int> >(2, 3);

            result[0, 0] = new Fraction <int>(1, 1, integerDomain);
            result[0, 1] = new Fraction <int>(0, 1, integerDomain);
            result[0, 2] = new Fraction <int>(1, 1, integerDomain);

            result[1, 0] = new Fraction <int>(2, 1, integerDomain);
            result[1, 1] = new Fraction <int>(1, 1, integerDomain);
            result[1, 2] = new Fraction <int>(1, 1, integerDomain);

            return(result);
        }