public static BigRational ArcTan(BigRational x, int digits, int maxNumberOfIterations)
        {
            iterations = 0;

            // Later needed variable:
            int digitCheck = digits * 100;
            bool subtract = true;
            BigRational result = x;
            int iteration = 0;
            var divisor = new BigInteger(3);

            while (iteration < maxNumberOfIterations)
            {
                var dividend = BigRational.Pow(x, divisor);
                result = (subtract) ? (result - (dividend / divisor)) : (result + (dividend / divisor));

                // Optimation hack:
                // Check only every two calls if end is reached.
                if (!subtract && (result / digitCheck > 100))
                {
                    iterations = iteration;
                    break;
                }
                divisor += 2;
                subtract = !subtract;
                iteration++;
            }

            return result;
        }
 /// <summary>
 /// Возводить текущее число в квадрат
 /// </summary>
 public void t_sqr()
 {
     BigRational i = Imagine;
     Imagine *= Real * _twice;
     Real *= Real;
     Real -= i * i;
 }
        public static BigRational[] RemoveUselessZeros(BigRational[] source)
        {
            int numOfLeadingZero = 0;

            Array.Reverse(source);

            foreach (var i in source)
            {
                if (i == 0 )
                {
                    numOfLeadingZero++;
                }
                else
                {
                    break;
                }
            }

            if (numOfLeadingZero == 0)
            {
                Array.Reverse(source);
                return source;
            }

            BigRational[] arrayBuffer = new BigRational[source.Length - numOfLeadingZero];

            Array.Copy(source, numOfLeadingZero, arrayBuffer, 0, arrayBuffer.Length);
            Array.Reverse(arrayBuffer);
            return arrayBuffer;
        }
Example #4
0
        internal override ParsedSyntax CombineForPlus(PowerSyntax other, BigRational thisValue)
        {
            if(Left.CompareTo(other.Left) == 0 && Right.CompareTo(other.Right) == 0)
                return Times(thisValue + 1);

            return null;
        }
Example #5
0
 public Value(BigRational realPart, BigRational imaginaryPart, NumberType type)
 {
     switch (type) {
         case NumberType.imaginary:
             InitComplexNum(realPart, imaginaryPart);
             break;
     }
 }
Example #6
0
 public Value(BigRational baseVal, BigRational exponent, NumberType type, Restrictions restrictions)
 {
     switch (type) {
         case NumberType.exponent:
             InitExp(baseVal, exponent, restrictions);
             break;
     }
 }
Example #7
0
 public BigNumber(double val)
 {
     if (val == Math.Floor(val)) {
         integerVal = new BigInt((int)val);
         Type = NumberType2.integer;
     } else {
         rationalVal = new BigRational(val);
         Type = NumberType2.rational;
     }
 }
        public static BigRational[] ArraySubtrInts(BigRational[] from, BigRational[] subAmount)
        {
            BigRational[] result = new BigRational[from.Length];

            for (int i = 0; i < from.Length - 1; i++)
            {
                result[i] = from[i] - subAmount[i];
            }

            return result;
        }
Example #9
0
        public void CheckModBigIntegerConsistency(int left, int right)
        {
            var leftInt  = (BigInteger)left;
            var rightInt = (BigInteger)right;
            var expected = new BigRational(leftInt % rightInt);

            var leftRational  = new BigRational(leftInt);
            var rightRational = new BigRational(rightInt);
            var actual        = leftRational % rightRational;

            AssertEqual(expected, actual);
        }
        public void CastToDoubleRoundToInfinity()
        {
            BigRational toRound = BigInteger.Pow(2, 1024) - BigInteger.One;

            Assert.AreEqual(
                double.PositiveInfinity,
                (double)toRound);

            Assert.AreEqual(
                double.NegativeInfinity,
                (double)-toRound);
        }
 public void RoundWithRuleWithDecimals(MidpointRounding decimalMode, RationalRounding rationalMode)
 {
     for (int d = 0; d < 4; d++)
     {
         for (var v = -2.5M; v <= 2.5M; v += 0.0001M)
         {
             Compare(
                 Math.Round(v, d, decimalMode),
                 BigRational.Round(v, d, rationalMode));
         }
     }
 }
        public void Sqrt_Test()
        {
            var r = new BigRational(2, 1);

            Assert.AreEqual(r, BigRational.Sqrt(4));

            r = new BigRational(3, 1);
            Assert.AreEqual(r, BigRational.Sqrt(9));

            r = new BigRational(BigInteger.Parse("2168488286494085478154297235187389205761"), BigInteger.Parse("685736206471705483022831680917430579904"));
            Assert.AreEqual(r, BigRational.Sqrt(10));
        }
 public void RoundWithDecimals()
 {
     for (var v = -2.5M; v <= 2.5M; v += 0.0001M)
     {
         for (int d = 0; d < 4; d++)
         {
             Compare(
                 Math.Round(v, d),
                 BigRational.Round(v, d));
         }
     }
 }
 private static string FormatBigRational(BigRational x, int digits)
 {
     // Let the magic begin:
     BigInteger shiftedBigInteger = x.Numerator * BigInteger.Pow(10, digits);
     string formatString = (shiftedBigInteger / x.Denominator).ToString();
     var sb = new StringBuilder(digits);
     sb.Append(x.GetWholePart().ToString());
     int wholePart = sb.Length;
     sb.Append('.');
     sb.Append(formatString.Substring(1, formatString.Length - wholePart));
     return sb.ToString();
 }
Example #15
0
        static string InternalToString(BigRational r, int precision)
        {
            var fraction = r.GetFractionPart();

            // Case where the rational number is a whole number
            // Niko: Incorrect check? F**k it... This works...
            if (fraction.Numerator == 0 && fraction.Denominator == 1)
            {
                return(r.GetWholePart().ToString());
            }

            BigInteger adjustedNumerator = fraction.Numerator * BigInteger.Pow(10, precision);
            // Abs fixes decimals having minuses in front of them
            BigInteger decimalPlaces = BigInteger.Abs(adjustedNumerator / fraction.Denominator);

            // Case where precision wasn't large enough.
            if (decimalPlaces == 0)
            {
                return(null);
            }

            // Give it the capacity for around what we should need for
            // the whole part and total precision
            // (this is kinda sloppy, but does the trick)
            var sb = new StringBuilder(precision + r.ToString().Length);

            bool noMoreTrailingZeros = false;

            for (int i = precision; i > 0; i--)
            {
                if (!noMoreTrailingZeros)
                {
                    if ((decimalPlaces % 10) == 0)
                    {
                        decimalPlaces /= 10;
                        continue;
                    }

                    noMoreTrailingZeros = true;
                }

                // Add the right most decimal to the string
                sb.Insert(0, decimalPlaces % 10);
                decimalPlaces /= 10;
            }

            // Insert the whole part and decimal
            sb.Insert(0, ",");
            sb.Insert(0, r.GetWholePart());

            return(sb.ToString());
        }
Example #16
0
        public bool Intersects(Line2BR other, out Point2BR?intersection, out bool parallel)
        {
            if (this.direction.IsZero)
            {
                parallel = false;
                bool flag;
                if (flag = other.Contains(this.origin))
                {
                    intersection = new Point2BR?(this.origin);
                }
                else
                {
                    intersection = new Point2BR?();
                }
                return(flag);
            }
            if (other.Direction.IsZero)
            {
                parallel = false;
                bool flag;
                if (flag = this.Contains(other.origin))
                {
                    intersection = new Point2BR?(other.origin);
                }
                else
                {
                    intersection = new Point2BR?();
                }
                return(flag);
            }
            BigRational bigRational1 = this.direction.X * other.direction.Y - this.direction.Y * other.direction.X;

            if (bigRational1.IsZero)
            {
                parallel = true;
                bool flag;
                if (flag = other.Contains(this.origin))
                {
                    intersection = new Point2BR?(this.origin);
                }
                else
                {
                    intersection = new Point2BR?();
                }
                return(flag);
            }
            parallel = false;
            BigRational bigRational2 = Vector2BR.CrossProduct(other.Origin - this.origin, other.Direction) / bigRational1;

            intersection = new Point2BR?(this.origin + bigRational2 * this.direction);
            return(true);
        }
        public override byte[] Split(byte[] secretClear, int shareCount, int threshold)
        {
            // var primeArr = ComputeRandomePrime();
            // var prime = new BigInteger(primeArr);
            var primeMinusOne = _prime - 1;
            var number        = new BigInteger(secretClear);

            var coef = new BigInteger[threshold];

            coef[0] = number;

            // TODO: rewrite this to use cryptographically-secure RNG
            var rng = new Random();
            var pmo = new BigRational(primeMinusOne);

            for (int c = 1; c < threshold; ++c)
            {
                coef[c] = BigRational.Multiply(pmo, new BigRational(rng.NextDouble())).GetWholePart();
            }

            var shares = new Tuple <int, BigInteger> [shareCount];

            for (var x = 1; x <= shareCount; ++x)
            {
                System.Console.WriteLine("X: " + x);
                var accum = coef[0];
                for (int exp = 1; exp < threshold; ++exp)
                {
                    // accum = (accum + (coef[exp] * (Math.pow(x, exp) % prime) % prime)) % prime;
                    var a = new BigInteger(Math.Pow(x, exp)) % _prime; // (Math.pow(x, exp) % prime)
                    var b = (coef[exp] * a) % _prime;                  // (coef[exp] * a % prime)
                    var c = (accum + b) % _prime;                      // (accum + b) % prime;

                    accum = c;
                }

                shares[x - 1] = Tuple.Create(x, accum);
            }

            Shares = shares.Select(x => {
                var index = BitConverter.GetBytes(x.Item1);
                var biarr = x.Item2.ToByteArray();
                var bytes = new byte[INT_ARR_LEN + biarr.Length];
                Array.Copy(index, 0, bytes, 0, INT_ARR_LEN);
                Array.Copy(biarr, 0, bytes, INT_ARR_LEN, biarr.Length);
                return(bytes);
            });

            // The original secret value is fully encoded in the distributed shares so there
            // is no need to return any version of the original secreted in encrypted form
            return(new byte[0]);
        }
Example #18
0
        public static void Inverse()
        {
            rational *= -1;
            calculation.Set(rational);

            calculationString = calculationString.RemovePrefix("-");
            if (rational < 0)
            {
                calculationString = calculationString.Insert(0, "-");
            }

            UpdateText();
        }
Example #19
0
 public BigNumber(double val)
 {
     if (val == Math.Floor(val))
     {
         integerVal = new BigInt((int)val);
         Type       = NumberType2.integer;
     }
     else
     {
         rationalVal = new BigRational(val);
         Type        = NumberType2.rational;
     }
 }
Example #20
0
        public void TestConvertFromWholeNumberDecimal()
        {
            decimal seven = 7.0m;

            BigRational expectedValue = new BigRational(7, new Fraction(0, 1));

            BigRational result1 = new BigRational(seven);
            BigRational result2 = (BigRational)seven;


            Assert.AreEqual(expectedValue, result1);
            Assert.AreEqual(expectedValue, result2);
        }
Example #21
0
        public bool ContainsProjection(Point2BR point)
        {
            Vector2BR   delta       = this.GetDelta();
            BigRational bigRational = Vector2BR.DotProduct(point - this.point2BR_0, delta);

            if (bigRational.IsNegative)
            {
                return(false);
            }
            BigRational lengthSquared = delta.GetLengthSquared();

            return(!(bigRational.Square() > lengthSquared));
        }
Example #22
0
        public static BigRational[,] As2DArray(BigRational[][] Array2D, int leftSize, int rightSize)
        {
            var newArray = new BigRational[leftSize, rightSize];

            for (int i = 0; i < Array2D.Length; i++)
            {
                for (int j = 0; j < Array2D[i].Length; j++)
                {
                    newArray[i, j] = Array2D[i][j];
                }
            }
            return(newArray);
        }
        public void Constructor_AllowsValidVectors(int value1, int value2)
        {
            var values = new BigRational[]
            {
                value1,
                value2,
            };

            var vector = new ImmutableVector2D(values);

            Assert.Equal(value1, vector.UnderlyingVector[0]);
            Assert.Equal(value2, vector.UnderlyingVector[1]);
        }
Example #24
0
        public void TestConstruction()
        {
            BigRational result1   = new BigRational(BigInteger.Zero, new Fraction(182, 26));
            BigRational result1_2 = new BigRational(new Fraction(182, 26));
            BigRational result2   = new BigRational(BigInteger.Zero, new Fraction(-7, 5));

            BigRational expected1 = new BigRational(7);
            BigRational expected2 = new BigRational(-1, 2, 5);

            Assert.AreEqual(expected1, result1);
            Assert.AreEqual(expected1, result1_2);
            Assert.AreEqual(expected2, result2);
        }
        public void TestToDecimalOutOfRange()
        {
            decimal     dummy;
            BigRational rational = BigInteger.Pow(10, 30);

            Assert.Throws <OverflowException>(
                () => dummy = (decimal)rational);

            BigRational negative = -rational;

            Assert.Throws <OverflowException>(
                () => dummy = (decimal)negative);
        }
Example #26
0
        public void TestXmlDeserialise(int n, int d)
        {
            var expected   = new BigRational(n, d);
            var serializer = new XmlSerializer(typeof(BigRational));
            var text       = $"<BigRational>{expected.Numerator}/{expected.Denominator}</BigRational>";

            using (var textReader = new StringReader(text))
                using (var reader = XmlReader.Create(textReader))
                {
                    var actual = (BigRational)serializer.Deserialize(reader);
                    Assert.AreEqual(expected, actual);
                }
        }
        public void Determinant_FindsDeterminant()
        {
            var values = new BigRational[2, 2]
            {
                { 2, 5 },
                { 1, 4 }
            };
            var matrix = new ImmutableMatrix2x2(values);

            var determinant = matrix.Determinant();

            Assert.Equal(3, determinant);
        }
 public void RoundWithDecimals2()
 {
     for (int d = -4; d <= 4; d++)
     {
         var scale = TenPow(d);
         for (var v = -2.5M; v <= 2.5M; v += 0.0001M)
         {
             Compare(
                 Math.Round(v * scale) / scale,
                 BigRational.Round(v, d));
         }
     }
 }
 public void RoundWithRuleWithDecimals2(MidpointRounding decimalMode, RationalRounding rationalMode)
 {
     for (int d = -4; d <= 4; d++)
     {
         var scale = TenPow(d);
         for (var v = -2.5M; v <= 2.5M; v += 0.0001M)
         {
             Compare(
                 Math.Round(v * scale, decimalMode) / scale,
                 BigRational.Round(v, d, rationalMode));
         }
     }
 }
    public static string ToDecimalString(this BigRational r, int precision)
    {
        var fraction = r.GetFractionPart();

        // Case where the rational number is a whole number
        if (fraction.Numerator == 0 && fraction.Denominator == 1)
        {
            return(r.GetWholePart() + ".0");
        }

        var adjustedNumerator = (fraction.Numerator
                                 * BigInteger.Pow(10, precision));
        var decimalPlaces = adjustedNumerator / fraction.Denominator;

        // Case where precision wasn't large enough.
        if (decimalPlaces == 0)
        {
            return("0.0");
        }

        // Give it the capacity for around what we should need for
        // the whole part and total precision
        // (this is kinda sloppy, but does the trick)
        var sb = new StringBuilder(precision + r.ToString().Length);

        bool noMoreTrailingZeros = false;

        for (int i = precision; i > 0; i--)
        {
            if (!noMoreTrailingZeros)
            {
                if ((decimalPlaces % 10) == 0)
                {
                    decimalPlaces = decimalPlaces / 10;
                    continue;
                }

                noMoreTrailingZeros = true;
            }

            // Add the right most decimal to the string
            sb.Insert(0, decimalPlaces % 10);
            decimalPlaces = decimalPlaces / 10;
        }

        // Insert the whole part and decimal
        sb.Insert(0, ".");
        sb.Insert(0, r.GetWholePart());

        return(sb.ToString());
    }
Example #31
0
        public void ConvertMatrixToUseTAndSGeneratorMatrices_ConvertsCorrectly()
        {
            var matrixValues = new BigRational[2, 2] {
                { 437, 202 }, { 543, 251 }
            };
            var matrix = new ImmutableMatrix2x2(matrixValues);
            var expectedIdentifierList = new[]
            {
                GeneratorMatrixIdentifier.X,
                GeneratorMatrixIdentifier.SInverse,
                // -1
                GeneratorMatrixIdentifier.TInverse,
                // S Switch
                GeneratorMatrixIdentifier.SInverse,
                // 4
                GeneratorMatrixIdentifier.T,
                GeneratorMatrixIdentifier.T,
                GeneratorMatrixIdentifier.T,
                GeneratorMatrixIdentifier.T,
                // S Switch
                GeneratorMatrixIdentifier.SInverse,
                // -8
                GeneratorMatrixIdentifier.TInverse,
                GeneratorMatrixIdentifier.TInverse,
                GeneratorMatrixIdentifier.TInverse,
                GeneratorMatrixIdentifier.TInverse,
                GeneratorMatrixIdentifier.TInverse,
                GeneratorMatrixIdentifier.TInverse,
                GeneratorMatrixIdentifier.TInverse,
                GeneratorMatrixIdentifier.TInverse,
                // S Switch
                GeneratorMatrixIdentifier.SInverse,
                // 6
                GeneratorMatrixIdentifier.T,
                GeneratorMatrixIdentifier.T,
                GeneratorMatrixIdentifier.T,
                GeneratorMatrixIdentifier.T,
                GeneratorMatrixIdentifier.T,
                GeneratorMatrixIdentifier.T,
                // S Switch
                GeneratorMatrixIdentifier.SInverse,
                // -2
                GeneratorMatrixIdentifier.TInverse,
                GeneratorMatrixIdentifier.TInverse,
                // S Switch
                GeneratorMatrixIdentifier.SInverse
            };
            var matrixIdentifierList = MathematicalHelper.ConvertMatrixToUseTAndSGeneratorMatrices(matrix);

            Assert.Equal(expectedIdentifierList, matrixIdentifierList);
        }
Example #32
0
        protected override string AddConstrain(SimplexTable inputTable, out SimplexTable outputTable, out bool success)
        {
            outputTable = new SimplexTable(inputTable);
            success     = true;

            ReevaluateBasisAndDeltas(outputTable);
            var bFracts   = FormBFractVector(outputTable);
            int selectedI = FindIndexOfMin(bFracts);

            int nwI = outputTable.NumOfConstrains;

            outputTable.NumOfConstrains += 1;

            var result = $"Let's use {outputTable.cLables[curBasis[selectedI]].Value} row to form new constrain.<br>";

            var bFract = outputTable.bVector[selectedI].value.Fract();

            for (int j = 0; j < outputTable.NumOfVariables; j++)
            {
                BigRational tarA = outputTable.aMatrix[selectedI][j].value;

                if (!outputTable.cLables[j].IsSelected)
                {
                    if (tarA.Sign >= 0)
                    {
                        outputTable.aMatrix[nwI][j].value = -tarA;
                    }
                    else
                    {
                        outputTable.aMatrix[nwI][j].value = -((bFract / (BigRational.One - bFract)) * (-tarA));
                    }
                }
                else
                {
                    if (tarA.Fract() <= bFract)
                    {
                        outputTable.aMatrix[nwI][j].value = -tarA.Fract();
                    }
                    else
                    {
                        outputTable.aMatrix[nwI][j].value = -((bFract / (BigRational.One - bFract)) * (BigRational.One - tarA));
                    }
                }
            }

            outputTable.bVector[nwI].value = -bFract;
            outputTable.NumOfVariables    += 1;
            outputTable.aMatrix[nwI][outputTable.NumOfVariables - 1].value = BigRational.One;

            return(result);
        }
Example #33
0
        public void BigRational_Constructor_TwoBigInteger_SimplifiesFraction()
        {
            var value1 = new BigRational((BigInteger)20, (BigInteger)10);

            Assert.Equal("2/1", value1.ToString("B", null));

            var value2 = new BigRational((BigInteger)10, (BigInteger)10);

            Assert.Equal("1/1", value2.ToString("B", null));

            var value3 = new BigRational((BigInteger)4, (BigInteger)6);

            Assert.Equal("2/3", value3.ToString("B", null));
        }
Example #34
0
        public void BigRational_Divide_DividesBigRationals()
        {
            Assert.Equal("0/1", (BigRational.Create(0).Divide(BigRational.Create(2))).ToString("B", null));
            Assert.Equal("0/1", (BigRational.Create(0).Divide(BigRational.Create(-2))).ToString("B", null));
            Assert.Equal("2/3", (BigRational.Create(2).Divide(BigRational.Create(3))).ToString("B", null));
            Assert.Equal("3/2", (BigRational.Create(3).Divide(BigRational.Create(2))).ToString("B", null));
            Assert.Equal("-3/2", (BigRational.Create(3).Divide(BigRational.Create(-2))).ToString("B", null));
            Assert.Equal("-1/1", (BigRational.Create(-3).Divide(BigRational.Create(3))).ToString("B", null));
            Assert.Equal("1/1", (BigRational.Create(-3).Divide(BigRational.Create(-3))).ToString("B", null));

            Assert.Equal($"1/1", (BigRational.Create(VeryBigNumber).Divide(BigRational.Create(VeryBigNumber))).ToString("B", null));
            Assert.Equal($"{VeryBigNumber}/1", (BigRational.Create($"{DoubleVeryBig}").Divide(BigRational.Create(2))).ToString("B", null));
            Assert.Equal($"-2/1", (BigRational.Create($"{DoubleVeryBig}").Divide(BigRational.Create($"-{VeryBigNumber}"))).ToString("B", null));
        }
Example #35
0
        public void TestConvertFromDecimalPointFloat()
        {
            float negativeOneAndOneHalf = -3f / 2f;
            float oneThird = 1f / 3f;

            BigRational expectedValue1 = new BigRational(-1, new Fraction(1, 2));
            BigRational result1        = (BigRational)negativeOneAndOneHalf;

            BigRational expectedValue2 = new BigRational(0, new Fraction(1, 3));
            BigRational result2        = (BigRational)oneThird;

            Assert.AreEqual(expectedValue1, result1);
            Assert.AreEqual(expectedValue2, result2);
        }
Example #36
0
        public static string ToString(this BigRational r, bool allowRational, ushort precisionLimit)
        {
            string output = InternalToString(r, precisionLimit + (allowRational ? 1 : 0));

            if (!allowRational)
            {
                return(output);
            }
            if (string.IsNullOrEmpty(output) || (output.Length > precisionLimit && !r.Denominator.IsOne))
            {
                return(r.ToString());
            }
            return(output);
        }
Example #37
0
 public BigRational GetVendorValue()
 {
     if (cachedVendorValue < 0)
     {
         int v = StatisticsTracker.moneyMagnitude.value;
         v -= (v % 3);
         v /= 3;
         v  = Math.Max(v - 1, 0);
         UpgradeValueWrapper vendorSellEffectiveness;
         upgrades.TryGetValue(UpgradeType.VENDOR_SELL_VALUE, out vendorSellEffectiveness);
         cachedVendorValue = (((UpgradeFloatValue)vendorSellEffectiveness).value + (0.05f * v)) * (1 + SkillList.VendorEffectiveness.getMultiplier()) + currentGuildmaster.vendorSellMultiplier();
     }
     return(cachedVendorValue);
 }
        public void Constructor_Throws_IfWrongSizeMatrixSupplied(int sizeX, int sizeY)
        {
            var values = new BigRational[sizeX, sizeY];

            for (int i = 0; i < sizeX; i++)
            {
                for (int j = 0; j < sizeY; j++)
                {
                    values[i, j] = 0;
                }
            }

            Assert.Throws <ArgumentException>(() => new ImmutableMatrix2x2(values));
        }
    public void SqrtAsRational()
    {
        var expected = new BigRational[]
        {
            new(1, 1),
            new(3, 2),
            new(7, 5),
            new(17, 12),
            new(41, 29),
        };
        var actual = BigRational.SqrtAsRationals(new BigInteger(2)).Take(5);

        Assert.True(expected.SequenceEqual(actual));
    }
Example #40
0
 public BigNumber(double val, NumberType2 type)
 {
     Type = type;
     switch (type) {
         case NumberType2.integer:
             integerVal = new BigInt((int)val);
             break;
         case NumberType2.rational:
             rationalVal = new BigRational(val);
             break;
         case NumberType2.irrational:
             irrationalVal = new BigIrrational(val);
             break;
     }
 }
Example #41
0
        public CalculationOptions(int width, int height, uint iter)
        {
            this.width = xMax = width;
            this.height = yMax = height;
            this.xSkip = 1;
            this.ySkip = 1;
            this.iteration_count = iter;
            this.orbit_length = iter;
            this.skip_primary_bulbs = 0U;

            this.minRe = new BigRational(-5, 2);    // -2.5 to
            this.maxRe = new BigRational(3, 2);     //  1.5
            this.minIm = new BigRational(-3, 2);    // -1.5 to
            this.maxIm = new BigRational(3, 2);     //  1.5
        }
Example #42
0
 static ExprList MergeArgs(
     CoreBuilder b,
     IEnumerable<Expr> args,
     Func<Expr, ExprList?> getArgs,
     BigRational aggregateSeed,
     Func<BigRational, BigRational, BigRational> aggregate,
     Func<IEnumerable<Expr>, IEnumerable<Expr>> group) {
     var mergedArgs = args
         .SelectMany(x => getArgs(x) ?? x.Yield());
     var @const = mergedArgs
         .Select(x => x.AsConst())
         .Where(x => x != null)
         .Select(x => x.Value)
         .Aggregate(aggregateSeed, aggregate);
     var other = group(mergedArgs.Where(x => !x.IsConst()));
     return (@const == aggregateSeed && other.Any() ? other : Const(@const).Yield().Concat(other)).ToExprList();
 }
        public static DivideResult PolyLongDivision(BigRational[] dividend, BigRational[] divisor)
        {
            DivideResult divideResult = new DivideResult();

            BigRational[] bufferDividend = dividend;

            int divisorMaxPower = divisor.Length - 1;

            BigRational divisorMaxCoeff = divisor.Last();

            BigRational[] result = new BigRational[dividend.Length];

            while (true)
            {
                long dividentMaxPower = bufferDividend.Length - 1;

                long resultXPower = dividentMaxPower - divisorMaxPower;

                if (resultXPower < 0)
                {
                    divideResult.Quotient = RemoveUselessZeros(result);
                    divideResult.Remainder = RemoveUselessZeros(bufferDividend);
                    return divideResult;
                }

                BigRational dividentCoeff = bufferDividend.Last();

                BigRational resultCoeff = dividentCoeff/divisorMaxCoeff;

                result[resultXPower] = resultCoeff;

                BigRational[] buffSubtract = new BigRational[bufferDividend.Length].Select(h => new BigRational(0,1)).ToArray();

                Array.Copy(divisor, 0, buffSubtract, resultXPower, divisor.Length);

                Parallel.For(0, buffSubtract.Length, i => buffSubtract[i] *= resultCoeff);

                bufferDividend = ArraySubtrInts(bufferDividend, buffSubtract);

                bufferDividend = RemoveUselessZeros(bufferDividend);

            }
        }
        public static StringBuilder BigRationalToStringBuilder(BigRational[] bigRationals)
        {
            StringBuilder resultSb = new StringBuilder();

            for (int i = 0; i < bigRationals.Length; i++)
            {

                if (bigRationals[i].Equals(0)) { continue; }

                resultSb.Insert(0, bigRationals[i]);

                switch (i)
                {
                    case 0:
                        break;
                    case 1:
                        resultSb.Insert(bigRationals[i].ToString().Length, "x ");
                        break;
                    default:
                        resultSb.Insert(bigRationals[i].ToString().Length, "x^" + i + " ");
                        break;
                }

                if (bigRationals[i].Sign.Equals(1))
                {
                    resultSb.Insert(0, "+");
                }

            }

            if (resultSb[0].Equals('+'))
            {
                resultSb.Remove(0, 1);
            }

            return resultSb;
        }
Example #45
0
 public static bool CanShrink(BigRational d)
 {
     return (d.Denominator == 1);
 }
Example #46
0
 public Value(BigRational doubleVal, Restrictions restrictions)
 {
     InitDouble(doubleVal, restrictions);
 }
Example #47
0
 public static object Shrink(BigRational d)
 {
     if (CanShrink(d))
     {
         return Shrink(d.Numerator);
     }
     else {
         return d;
     }
 }
Example #48
0
 public override double[] GetDoubleFirstInserts(BigInteger[] args)
 {
     BigRational absciss_start = _2df_get_br_abciss_start(), absciss_interval = _2df_get_br_abciss_interval_length();
     BigRational[] be_Result = new BigRational[4];
         be_Result[0] =  absciss_start+ (absciss_interval * new BigRational(args[0], BigInteger.One));
         be_Result[1] = absciss_start + (absciss_interval * new BigRational(args[1], BigInteger.One));
     BigRational ordinate_start=_2df_get_br_ordinate_start(),ordinate_interval=_2df_get_br_ordinate_interval_length();
     be_Result[2]=ordinate_start+(ordinate_interval * new BigRational(args[2], BigInteger.One));
     be_Result[3] = ordinate_start + (ordinate_interval * new BigRational(args[3], BigInteger.One));
     double[] Result=new double[4];
     Result[0] = ((double)be_Result[0].Numerator) / ((double)be_Result[0].Denominator);
     Result[1] = ((double)be_Result[1].Numerator) / ((double)be_Result[1].Denominator);
     Result[2] = ((double)be_Result[2].Numerator) / ((double)be_Result[2].Denominator);
     Result[3] = ((double)be_Result[3].Numerator) / ((double)be_Result[3].Denominator);
     return Result;
 }
Example #49
0
 public Value(BigRational doubleVal, Factors factors, Restrictions restrictions)
 {
     InitDouble(doubleVal, restrictions);
     this.factors = factors;
 }
Example #50
0
 public KoeffMultInfo(BigRational _Koeff, ExprList _Mult)
 {
     Koeff = _Koeff;
     Mult = _Mult;
 }
Example #51
0
 protected void _2df_safe_set_scale(int _Width, int _Height, int n_left, int n_top, int width, int height)
 {
     if (_2df_imagine_width == null)
     {
         _2df_imagine_width = new BigInteger(width);
         _2df_imagine_height = new BigInteger(height);
         _2df_imagine_left = BigInteger.Zero;
         _2df_imagine_top = BigInteger.Zero;
         return;
     }
     if (_Width == width && _Height == height && n_left == 0 && n_top == 0) return;
     _2df_push_fractal_state();
     if(_Width<width||_Height<height)
     {
         _2df_set_scale(_Width, _Height, n_left, n_top, width, height);
         return;
     }
     BigRational width_dif = new BigRational(_Width, width);
     BigRational height_dif = new BigRational(_Height, height);
     BigRational safe_dif = width_dif > height_dif ? height_dif : width_dif;
     BigRational im_left = new BigRational(_2df_imagine_left + (BigInteger)n_left) * safe_dif;
     BigRational im_top = new BigRational(_2df_imagine_top + (BigInteger)n_top) * safe_dif;
     BigRational im_width = new BigRational(_2df_imagine_width) * safe_dif;
     BigRational im_height = new BigRational(_2df_imagine_height) * safe_dif;
     _2df_imagine_left = im_left.Numerator / im_left.Denominator;
     _2df_imagine_top = im_top.Numerator / im_top.Denominator;
     _2df_imagine_width = im_width.Numerator / im_width.Denominator;
     _2df_imagine_height = im_height.Numerator / im_height.Denominator;
 }
            //Let's format any BigRational (e.g. Pi) to a string with specified significant figures
            public static string Format(BigRational pi, int numberOfDigits)
            {
                var numeratorShiftedToEnoughDigits =
                               (pi.Numerator * BigInteger.Pow(new BigInteger(10), numberOfDigits));
                var test = pi.Numerator%pi.Denominator;
                var bigInteger = numeratorShiftedToEnoughDigits / pi.Denominator;
                string piToBeFormatted = bigInteger.ToString();
                int len = piToBeFormatted.Length-numberOfDigits;

                var builder = new StringBuilder();
                builder.Append(piToBeFormatted.Substring(0,len));
                builder.Append(".");
                builder.Append(piToBeFormatted.Substring(len, numberOfDigits - len));
                return builder.ToString();
            }
Example #53
0
 internal override ParsedSyntax CombineForPlus(ParsedSyntax other, BigRational otherValue)
     => other.CombineForPlus(this, otherValue);
 public BigRational Calculate(BigRational x, int maxNumberOfIterations, int precision)
 {
     bool doASubtract = true;
     var runningTotal = x;
     int count = 0;
     var divisor = 3;
     while (count < maxNumberOfIterations)
     {
         var current = BigRational.Pow(x, divisor);
         current = current/BigRational.FromInt(divisor);
         if (doASubtract)
         {
             runningTotal = runningTotal - current;
         }
         else
         {
             runningTotal = runningTotal + current;
         }
         doASubtract = !doASubtract;
         count++;
         divisor = divisor + 2;
         if (!WeHaveEnoughPrecision(current, precision)) continue;
         Iterations = count;
         break;
     }
     return runningTotal;
 }
 private static bool WeHaveEnoughPrecision(BigRational current, int precision)
 {
     var fractionPart = (current.Numerator%current.Denominator);
     var thing = BigRational.FromBigInt(fractionPart)/BigRational.FromBigInt(current.Denominator);
     return thing.ToString().Length > precision + 2; //extra 2 digits to ensure enough precision
 }
Example #56
0
 internal void Add(BigRational re, BigRational im)
 {
     if (currentindex == points.LongLength) // Have to expand array
     {
         long newsize = points.LongLength == 0 ? 1 : points.LongLength * 2;
         BigComplex[] newarr = new BigComplex[newsize];
         Array.Copy(points, newarr, currentindex);
         points = newarr;
     }
     points[currentindex++] = new BigComplex(re, im);
 }
 public BigComplex()
 {
     Real = Imagine = BigRational.Zero;
 }
 public BigComplex(BigRational r, BigRational i)
 {
     Real = r;
     Imagine = i;
 }
 public BigComplex(double Re, double Im)
 {
     Real = BigRational.ConvertToBigRational(Re);
     Imagine = BigRational.ConvertToBigRational(Im);
 }
 public BigComplex(long value)
 {
     Real = new BigRational(value, 1);
     Imagine = BigRational.Zero;
 }