Example #1
0
        public static BigRational FractionToDouble(UnicodeStream stream, UInt64 decPt)
        {
            UInt64[][] fract = stream.Split(decPt, true);

            if (fract.Length != 2)
            {
                throw new Exception();
            }

            if (!IsNumber(fract[0]) | !IsNumber(fract[1]))
            {
                throw new Exception();
            }


            BigRational d = 0;

            for (int i = 0; i < fract[0].Length; i++)
            {
                d = d + (BigRational.Pow(10, i) * ReadDigit(fract[0][fract[0].Length - (i + 1)]));
            }

            for (int i = 1; i <= fract[1].Length; i++)
            {
                d = d + (BigRational.Pow(10, i * -1) * ReadDigit(fract[1][i - 1]));
            }

            return(d);
        }
Example #2
0
    private static BigRational CalculateEulerNumber(object threadIndexObject)
    {
        Stopwatch stopwatch = new Stopwatch();

        stopwatch.Start();
        int         threadIndex = Convert.ToInt32(threadIndexObject);
        BigRational sum         = new BigRational(0.0m);

        for (int k = threadIndex; k < elementsCount; k += threadsCount)
        {
            BigRational numerator   = BigRational.Pow((3 * k), 2) + 1;
            BigRational denominator = Factorial(3 * k);
            sum += BigRational.Divide(numerator, denominator);
        }
        stopwatch.Stop();
        int threadNumber = threadIndex + 1;

        Console.WriteLine("Тhread " + threadNumber + ": ");
        Console.WriteLine("Time elapsed - " + stopwatch.Elapsed);
        if (!isInQuietMode)
        {
            Console.WriteLine("Intermediate sum - " + sum.ToString());
        }
        Console.WriteLine();
        return(sum);
    }
    public static BigRational ComputeP(int k, int n, int p)
    {
        // the P(n) equation
        BigRational pnNumerator   = BigRational.Pow(p, n);
        BigRational pnDenominator = BigRational.Pow(k, (n - k)) * Factorial(k);


        // the P(0) equation

        //---the right side of "+" sign in Denominator
        BigRational pk         = BigRational.Pow(p, k);
        BigRational factorialK = Factorial(k);
        // CHANGED: Don't cast to double here (loses precision)
        BigRational lastPart             = (BigRational.Subtract(1, BigRational.Divide(p, k)));
        BigRational factorialAndLastPart = BigRational.Multiply(factorialK, lastPart);
        BigRational fullRightSide        = BigRational.Divide(pk, factorialAndLastPart);
        //---the left side of "+" sign in Denominator
        BigRational series = Series(k, p);


        BigRational p0Denominator = series + fullRightSide;
        BigRational p0Result      = BigRational.Divide(1, p0Denominator);

        BigRational pNResult = BigRational.Divide((pnNumerator * p0Result), pnDenominator);

        return(pNResult);
    }
Example #4
0
 /// <summary>Exponent</summary>
 public void InitExp(BigRational expBase, BigRational expPower, Restrictions restrictionsToPass)
 {
     this.ExpBase       = new Value(expBase, restrictionsToPass);
     this.ExpPower      = new Value(expPower, restrictionsToPass);
     this.RationalValue = (BigRational.Pow(expBase, (BigInteger)expPower));
     primaryNumType     = NumberType.exponent;
 }
Example #5
0
        public void Pow(int n, int d, int power, int expectedNumerator, int expectedDenominator)
        {
            var rational = new BigRational(n, d);
            var expected = new BigRational(expectedNumerator, expectedDenominator);

            AssertEqual(expected, BigRational.Pow(rational, power));
        }
Example #6
0
        public void TestPow()
        {
            BigRational nineFifths = new BigRational(1, 4, 5);

            BigRational expected = new BigRational(3, 6, 25);
            BigRational result   = BigRational.Pow(nineFifths, 2);

            Assert.AreEqual(expected, result);
        }
Example #7
0
        List <object> CalculateOperations(List <object> toCalculate, params Operation[] operations)
        {
            List <object> toC = new List <object>(toCalculate);

            for (int i = 0; i < toC.Count; i++)
            {
                object rawValue = toC[i];
                if (rawValue is Operation value)
                {
                    if (!operations.Contains(value))
                    {
                        continue;
                    }

                    BigRational v1 = (BigRational)toC[i - 1];
                    BigRational v2 = (BigRational)toC[i + 1];
                    toC.RemoveAt(i + 1); // Before minus one so that the list isn't changed before removing this value.
                    toC.RemoveAt(i - 1);
                    i--;                 // To fix iteration

                    switch (value)
                    {
                    case Operation.Multiply:
                        toC[i] = v1 * v2;
                        break;

                    case Operation.Divide:
                        toC[i] = v1 / v2;
                        break;

                    case Operation.Add:
                        toC[i] = v1 + v2;
                        break;

                    case Operation.Substract:
                        toC[i] = v1 - v2;
                        break;

                    case Operation.Exponent:
                        if (v2.GetFractionPart() != BigRational.Zero)
                        {
                            throw new CalculationException("Decimal number exponents are not supported yet.");
                        }
                        toC[i] = BigRational.Pow(v1, v2.GetWholePart());
                        break;

                    case Operation.Unspecified:
                        throw new CalculationException("Unspecified operations should be replaced before calling CalculateOperations!");

                    default:
                        throw new CalculationException("Invalid operation type!");
                    }
                }
            }
            return(toC);
        }
Example #8
0
    public static BigRational HackFix_ToApproxBigRational(this double d)
    {
        if (double.IsNaN(d) || double.IsInfinity(d))
        {
            throw new ArgumentException();
        }
        var scalePower = (int)Math.Ceiling(Math.Log(d, 2)) + 53;
        var whole      = (BigInteger)(long)Math.Round(d * Math.Pow(2, scalePower));

        return(whole / BigRational.Pow(2, scalePower));
    }
Example #9
0
        public static BigRational InterpretAsMantissa(UInt64[] codepoints)
        {
            if (!IsNumber(codepoints))
            {
                throw new Exception();
            }

            BigRational d = 0;

            for (int i = 1; i <= codepoints.Length; i++)
            {
                d = d + (BigRational.Pow(10, i * -1) * ReadDigit(codepoints[i - 1]));
            }

            return(d);
        }
    // CHANGED: Removed n as parameter (n just the index of summation here)
    public static BigRational Series(int k, int p)
    {
        BigRational series = new BigRational(0.0);
        var         fin    = k - 1;

        // CHANGED: Should be <= fin (i.e. <= k-1, or < k) because it's inclusive counting
        for (int i = 0; i <= fin; i++)
        {
            var power = BigRational.Pow(p, i);
            // CHANGED: was Factorial(n), should be factorial of n value in this part of the sequence being summed.
            var factorialN = Factorial(i);
            var sum        = BigRational.Divide(power, factorialN);
            series += sum;
        }
        return(series);
    }
Example #11
0
        public static NumericValue Power(FractionValue x, FractionValue exponent)
        {
            NumericValue result;

            // Wikipedia has good info on exponentiation with fractional powers.
            // http://en.wikipedia.org/wiki/Exponentiation#Principal_n-th_root
            if (exponent.Denominator == 1)
            {
                result = new FractionValue(BigRational.Pow(x.value, exponent.Numerator));
            }
            else if (x.Sign < 0 && exponent.Sign > 0 && !exponent.Denominator.IsEven)
            {
                // We can do a better job on odd roots of negative fractions than
                // DoubleValue can.  It ends up deferring to Complex.Pow, which
                // returns non-principal roots.  This will return -2 as the cube root
                // of -8, whereas Complex.Pow would return (1, 1.73205080756888).
                BigRational radicand  = BigRational.Pow(x.value, exponent.Numerator);
                double      rootPower = 1 / (double)exponent.Denominator;
                double      value     = radicand.Sign * Math.Pow(Math.Abs((double)radicand), rootPower);
                result = new DoubleValue(value);
            }
            else if (x.Sign > 0 && exponent.Sign > 0)
            {
                // Take the power of the numerator and denominator separately.
                // Then if we end up with two integers, we can make a fraction.
                double exponentDouble          = exponent.ToDouble();
                double resultNumeratorDouble   = Math.Pow((double)x.Numerator, exponentDouble);
                double resultDenominatorDouble = Math.Pow((double)x.Denominator, exponentDouble);
                if (Utility.IsInteger(resultNumeratorDouble, out BigInteger resultNumerator) &&
                    Utility.IsInteger(resultDenominatorDouble, out BigInteger resultDenominator))
                {
                    result = new FractionValue(resultNumerator, resultDenominator);
                }
                else
                {
                    result = new DoubleValue(resultNumeratorDouble / resultDenominatorDouble);
                }
            }
            else
            {
                result = DoubleValue.Power(new DoubleValue(x.ToDouble()), new DoubleValue(exponent.ToDouble()));
            }

            return(result);
        }
Example #12
0
        public static object Pow(object a1, object a2)
        {
            if (a1 is Complex || a2 is Complex)
            {
                return(Complex.Pow(AsComplex(a1), AsComplex(a2)));
            }
            else if (a1 is Double || a1 is decimal || a2 is double || a2 is decimal || a2 is BigRational)
            {
                var d1 = AsDouble(a1);
                var d2 = AsDouble(a2);

                if (d1 < 0)
                {
                    return(Complex.Pow(new Complex(d1, 0), d2));
                }
                else
                {
                    return(Math.Pow(d1, d2));
                }
            }
            else if (a1 is BigRational)
            {
                var d1 = AsBigRational(a1);
                var d2 = AsBigInteger(a2);
                return(Number.Shrink(BigRational.Pow(d1, d2)));
            }
            else
            {
                var d1 = AsBigInteger(a1);
                var d2 = (int)AsBigInteger(a2);
                if (d2 < 0)
                {
                    return(Number.Shrink(BigRational.Pow(d1, d2)));
                }
                else
                {
                    return(Number.Shrink(BigInteger.Pow(d1, d2)));
                }
            }
        }
Example #13
0
        public static BigRational IntegralSinX2Row(int a)
        {
            BigRational sum = 0;
            BigRational previous;
            BigRational factorial = 1;

            var minus = 1;
            var n     = 0;

            do
            {
                var member = minus
                             * BigRational.Pow(a, 4 * n + 3)
                             / (factorial * (4 * n + 3));
                n++;
                minus     *= -1;
                factorial *= (2 * n + 1) * (2 * n);
                previous   = sum;
                sum       += member;
            } while (BigRational.Abs(sum - previous) > Error);

            return(sum);
        }
Example #14
0
        // https://en.wikipedia.org/wiki/Chudnovsky_algorithm
        private static BigRational CalculateValue(BigRational maxK)
        {
            var K = BigRational.FromDecimal(6m);
            var M = BigRational.FromDecimal(1m);
            var L = BigRational.FromDecimal(13591409m);
            var X = BigRational.FromDecimal(1m);
            var S = BigRational.FromDecimal(13591409m);

            var sixteen    = BigRational.FromInt(16);
            var L_constant = BigRational.FromInt(545140134);
            var X_constant = BigRational.FromDecimal(-262537412640768000M);
            var twelve     = BigRational.FromInt(12);

            for (var k = BigRational.One; k < (maxK + BigRational.One); k += BigRational.One)
            {
                M  = M * (BigRational.Pow(K, 3) - (K * sixteen)) / BigRational.Pow(k, 3);
                L += L_constant;
                X *= X_constant;
                S += M * L / X;
                K += twelve;
            }

            return(BigRational.FromDecimal(426880m) * GetSquareRoot(BigRational.FromDecimal(10005m)) / S);
        }
Example #15
0
        public static BigRational GetRelicValue(ItemStack examinedStack)
        {
            BigRational val = examinedStack.item.getBaseValue() * 2000 * BigRational.Pow(1.1f, examinedStack.enchants.Count + examinedStack.antiquity);

            if (examinedStack.relicData != null)
            {
                RelicInfo ri = examinedStack.relicData.OrderByDescending(o => o.notoriety).First();
                if (ri != null)
                {
                    UpgradeValueWrapper wrap;
                    Main.instance.player.upgrades.TryGetValue(UpgradeType.QUEST_SCALAR, out wrap);
                    BigRational b = examinedStack.item.getBaseValue() * BigRational.Pow(1.5f, ri.notoriety) * 1000;
                    b   *= ((UpgradeFloatValue)wrap).value;
                    val += b;
                }
                if (examinedStack.relicData.Any(x => x.relicName == "Lost"))
                {
                    val /= 10000;
                }
                val *= Main.instance.GetRelicSellMultiplier();
            }
            val = BigRational.Truncate(val, 6, false);
            return(val);
        }
Example #16
0
 public void PowError()
 {
     Assert.Throws <ArgumentException>(
         () => BigRational.Pow(0, 0));
 }
Example #17
0
        public BigRational getCost(int n)
        {
            UnityEngine.Profiling.Profiler.BeginSample("Recalc");
            if (ranks == lastranks && n == lastN)
            {
                return(lastTotal);
            }
            lastN = n;
            if (ranks != lastranks)
            {
                lastranks    = ranks;
                powLastranks = Math.Pow(costMultiplier, ranks);
            }
            UnityEngine.Profiling.Profiler.EndSample();
            UnityEngine.Profiling.Profiler.BeginSample("Return");
            BigRational b  = baseCost;
            BigRational dd = new BigRational(costMultiplier);

            dd -= 1;
            //+0.51?
            lastTotal = b * ((powLastranks * ((n == 1 ? pow1 : (n == 10 ? pow10 : (n == 50 ? pow50 : BigRational.Pow(costMultiplier, n)))) - 1) / (dd)));
            UnityEngine.Profiling.Profiler.EndSample();
            return(lastTotal);
        }
Example #18
0
        public override (object, int) Decode(byte[] data, int position, bool packed)
        {
            (BigInteger nominator, int newPosition) = Int256.DecodeInt(data, position, packed);
            BigRational rational = BigRational.FromBigInt(nominator) * BigRational.Reciprocal(BigRational.Pow(BigRational.FromInt(10), Precision));

            return(rational, newPosition);
        }
Example #19
0
 public void Pow(BigRational rational, int power, BigRational expected)
 {
     Assert.AreEqual(expected, BigRational.Pow(rational, power));
 }
Example #20
0
        public virtual BigRational GetScaledCost(int n)
        {
            UnityEngine.Profiling.Profiler.BeginSample("Recalc");
            if (level == lastLevel && n == lastN)
            {
                return(lastTotal);
            }
            lastN = n;
            if (level != lastLevel)
            {
                lastLevel    = level;
                powLastLevel = Math.Pow(productType.amount, level);
            }
            UnityEngine.Profiling.Profiler.EndSample();
            UnityEngine.Profiling.Profiler.BeginSample("Return");
            BigRational b  = (cost * halvesAndDoubles);
            BigRational dd = new BigRational(productType.amount);

            dd -= 1;
            //+0.51?
            lastTotal = b * ((powLastLevel * ((n == 1 ? pow1 : (n == 10 ? pow10 : (n == 50 ? pow50 : BigRational.Pow(productType.amount, n)))) - 1) / (dd)));
            UnityEngine.Profiling.Profiler.EndSample();
            return(lastTotal);
        }
Example #21
0
        public void Test_ufixed(AbiEncodingStyle encodingStyle)
        {
            AbiUFixed type = AbiType.UFixed;

            BigRational  data      = BigRational.FromBigInt(-123456789) * BigRational.Reciprocal(BigRational.Pow(BigRational.FromInt(10), type.Precision));
            AbiSignature signature = new AbiSignature("abc", type);

            byte[]   encoded   = _abiEncoder.Encode(encodingStyle, signature, data);
            object[] arguments = _abiEncoder.Decode(encodingStyle, signature, encoded);
            Assert.AreEqual(arguments[0], data);
        }
Example #22
0
        public static ManagedBigRational ReadNumberAt(ref int i, string s)
        {
            bool negative = false;

            if (s[i] == '-')
            {
                negative = true;
                i++;
            }

            Stage  stg      = Stage.integer;
            string integer  = "";
            string fraction = "";
            char   expsign  = '+';
            string exponent = "";

            for (int x = i; x < s.Length; x++, i++)
            {
                if (s[x] == '.')
                {
                    if (String.IsNullOrEmpty(integer))
                    {
                        throw new Exception();
                    }
                    if (stg != Stage.integer)
                    {
                        throw new Exception();
                    }
                    stg = Stage.fraction;
                }
                else if (s[x] == 'e' || s[x] == 'E')
                {
                    if (String.IsNullOrEmpty(integer))
                    {
                        throw new Exception();
                    }
                    if (stg == Stage.exponent)
                    {
                        throw new Exception();
                    }
                    if (x == s.Length - 1)
                    {
                        throw new Exception();
                    }
                    if (stg == Stage.fraction && String.IsNullOrEmpty(fraction))
                    {
                        throw new Exception();
                    }
                    x++;
                    i++;
                    if (s[x] == '+' ^ s[x] == '-')
                    {
                        expsign = s[x];
                    }
                    stg = Stage.exponent;
                }
                else if ('0' <= s[x] && s[x] <= '9')
                {
                    if (stg == Stage.integer)
                    {
                        integer += s[x];
                    }
                    else if (stg == Stage.fraction)
                    {
                        fraction += s[x];
                    }
                    else if (stg == Stage.exponent)
                    {
                        exponent += s[x];
                    }
                }
                else
                {
                    if (String.IsNullOrEmpty(integer))
                    {
                        throw new Exception();
                    }
                    if (stg == Stage.exponent && String.IsNullOrEmpty(exponent))
                    {
                        throw new Exception();
                    }
                    break;
                }
            }

            BigRational d = UnicodeCore.InterpretAsInteger(new UnicodeStream(integer)) + UnicodeCore.InterpretAsMantissa(new UnicodeStream(fraction));

            if (!String.IsNullOrEmpty(exponent))
            {
                d = BigRational.Pow(d, Convert.ToInt32(exponent));
                if (expsign == '-')
                {
                    d = 1 / d;
                }
            }

            if (negative)
            {
                d *= -1;
            }
            return(d);
        }
Example #23
0
    public void RaisedToTest()
    {
        Polynomial.FromBigEndianCoefficients(1).RaisedTo(10000000).AssertEquals(Polynomial.FromBigEndianCoefficients(1));
        Polynomial.FromBigEndianCoefficients(1, 0).RaisedTo(10000000).AssertSimilar(new XTerm(10000000).KeyVal(BigRational.One));
        Polynomial.FromBigEndianCoefficients(2, 0).RaisedTo(50).AssertSimilar(new XTerm(50).KeyVal(BigRational.Pow(2, 50)));
        Polynomial.FromBigEndianCoefficients(1, 1).RaisedTo(5).AssertSimilar(Polynomial.FromBigEndianCoefficients(1, 5, 10, 10, 5, 1));

        Polynomial.FromBigEndianCoefficientsOverVar2Of2(1, 0).RaisedTo(10000000).AssertSimilar(new XYTerm(0, 10000000).KeyVal(BigRational.One));
    }
Example #24
0
 static Calculating()
 {
     Error = 1 / BigRational.Pow(10, 6);
 }