static BigDecimal CalcTerm(int n)
        {
            Console.Write('.');
            BigDecimal neg1 = new BigDecimal(-1);

            neg1 = neg1.Pow(n);
            neg1 = neg1.Multiply(fact(4 * n));

            BigDecimal t1b = new BigDecimal(4);

            t1b = t1b.Pow(n);
            t1b = t1b.Multiply(fact(n));
            t1b = t1b.Pow(4);

            neg1 = neg1.Divide(t1b, acc, RoundingMode.HalfUp);

            BigDecimal t2 = new BigDecimal(21460);

            t2 = t2.Multiply(n);
            t2 = t2.Add(1123);

            BigDecimal t2b = new BigDecimal(882);

            t2b = t2b.Pow(2 * n);

            t2 = t2.Divide(t2b, acc, RoundingMode.HalfUp);

            return(neg1.Multiply(t2));
        }
Beispiel #2
0
        public void DecimalPowerLimitPrecisionTest()
        {
            BigDecimal bd = new BigDecimal(22, 1);

            Assert.AreEqual(new BigDecimal(265599227, 5), BigDecimal.Pow(bd, 10, 5));
            Assert.AreEqual(new BigDecimal(BigInteger.Parse("70542949868640404"), 10), BigDecimal.Pow(bd, 20, 10));
        }
Beispiel #3
0
        public string ToHexString()
        {
            var fullDecimal = Value * BigDecimal.Pow(10, (int)Token.Precision);
            var bytes       = ByteUtils.TrimLeadingZeroes(fullDecimal.GetWholePart().ToByteArray());

            return(ByteUtils.ToHexString(bytes, Prefix.ZeroLowerX));
        }
Beispiel #4
0
        public void DecimalPowerTest1()
        {
            BigDecimal bd = new BigDecimal(21, 1);

            Assert.AreEqual(new BigDecimal(441, 2), BigDecimal.Pow(bd, 2));
            Assert.AreEqual(new BigDecimal(9261, 3), BigDecimal.Pow(bd, 3));
            Assert.AreEqual(new BigDecimal(194481, 4), BigDecimal.Pow(bd, 4));
        }
Beispiel #5
0
        public void DecimalPowerTest2()
        {
            BigDecimal bd = new BigDecimal(212, 2);

            Assert.AreEqual(new BigDecimal(44944, 4), BigDecimal.Pow(bd, 2));
            Assert.AreEqual(new BigDecimal(9528128, 6), BigDecimal.Pow(bd, 3));
            Assert.AreEqual(new BigDecimal(2019963136, 8), BigDecimal.Pow(bd, 4));
        }
Beispiel #6
0
        public void PowersOf2Test()
        {
            BigDecimal bd = new BigDecimal(2);

            Assert.AreEqual(new BigDecimal(8), BigDecimal.Pow(bd, 3));
            Assert.AreEqual(new BigDecimal(16), BigDecimal.Pow(bd, 4));
            Assert.AreEqual(new BigDecimal(256), BigDecimal.Pow(BigDecimal.Pow(bd, 4), 2));
        }
Beispiel #7
0
        public SqlNumber Pow(SqlNumber exp)
        {
            if (State == NumericState.None)
            {
                return(new SqlNumber(innerValue.Pow(exp.innerValue)));
            }

            return(this);
        }
Beispiel #8
0
        public void OperatorDouble4()
        {
            var v = BigDecimal.Pow(10, -300);

            var d  = (double)v;
            var ok = (double)Math.Pow(10, -300);

            Assert.AreEqual(ok, d);
        }
Beispiel #9
0
        public void OperatorDouble5()
        {
            var v = (BigDecimal.Pow(10, 600) + 1) / BigDecimal.Pow(10, 300);

            var d  = (double)v;
            var ok = (double)Math.Pow(10, 300);

            Assert.AreEqual(ok, d);
        }
Beispiel #10
0
        public void OperatorDecimal4()
        {
            var v = BigDecimal.Pow(10, -25);

            var d  = (decimal)v;
            var ok = (decimal)Math.Pow(10, -25);

            Assert.AreEqual(ok, d);
        }
Beispiel #11
0
        public void OperatorDecimal5()
        {
            var v = (BigDecimal.Pow(10, 50) + 1) / BigDecimal.Pow(10, 25);

            var d  = (decimal)v;
            var ok = (decimal)Math.Pow(10, 25);

            Assert.AreEqual(ok, d);
        }
Beispiel #12
0
        public void Binary_functions_should_throw_for_null_argument()
        {
            var x1 = new BigDecimal(1.1);

            ((Action)(() => x1.Add(null))).ShouldThrow <NullReferenceException>();
            ((Action)(() => x1.Sub(null))).ShouldThrow <NullReferenceException>();
            ((Action)(() => x1.Mul(null))).ShouldThrow <NullReferenceException>();
            ((Action)(() => x1.Div(null))).ShouldThrow <NullReferenceException>();
            ((Action)(() => x1.Pow(null))).ShouldThrow <NullReferenceException>();
            ((Action)(() => x1.Dim(null))).ShouldThrow <NullReferenceException>();
        }
Beispiel #13
0
        object IPowerable.Pow(object right)
        {
            if (!(right is RealNumber))
            {
                throw new ArgumentException("Not a real number", nameof(right));
            }
            var v = (RealNumber)right;

            //return new RealNumber(System.Math.Pow(Value,v.Value));
            return(new RealNumber(BigDecimal.Pow(Value, (BigInteger)v.Value)));
        }
Beispiel #14
0
        public BigDecimal calDens(BigDecimal radius)
        {
            BigDecimal vol  = BigDecimal.Parse("0.0");
            BigDecimal num  = BigDecimal.Parse("1.33333333333");
            BigDecimal pi   = BigDecimal.Parse(Math.PI.ToString());
            BigDecimal mass = BigInteger.Parse("1990000000000000000000000000000");
            BigDecimal dens = BigDecimal.Parse("0.0");

            num  = num.Multiply(pi);
            vol  = radius.Pow(3);
            vol  = num.Multiply(vol);
            dens = mass / (vol);

            //while (mass.compareTo(vol.toBigInteger()) < 0)
            while (mass.CompareTo(((BigInteger)vol)) < 0)
            {
                if (type == ("Average_Star"))
                {
                    mass = range(Average_Starmax, Average_Starmin);
                }
                if (type == ("Massive_Star"))
                {
                    mass = range(Massive_Starmax, Massive_Starmin);
                }
                if (type == ("White_Dwarf"))
                {
                    mass = range(White_Dwarfmax, White_Dwarfmin);
                }
                if (type == ("Neutron_Star"))
                {
                    mass = range(Neutron_Starmax, Neutron_Starmin);
                }
                if (type == ("Black_hole"))
                {
                    mass = range(Black_holemax, Black_holemin);
                }
                else
                {
                    break;
                }
            }


            dens    = mass / (vol);
            density = dens;
            //if(density.compareTo(BigDecimal.Parse("1")) < 0 ){
            //   Console.WriteLine("its 0");
            //    System.exit(0);
            //}
            return(dens);
        }
Beispiel #15
0
        public async Task <string> Mint(string receiverAddress, decimal amount)
        {
            var account     = new Account(privateKey, Chain.Ropsten);
            var web3        = new Web3(account, nodeAddress);
            var mintHandler = web3.Eth.GetContractTransactionHandler <MintFunction>();
            var mint        = new MintFunction()
            {
                To          = receiverAddress,
                TokenAmount = (new BigDecimal(amount) * BigDecimal.Pow(10, 18)).Mantissa
            };
            var receipt = await mintHandler.SendRequestAndWaitForReceiptAsync(contractAddress, mint);

            return(receipt.TransactionHash);
        }
Beispiel #16
0
        public static byte[] ByteArrayAmount(BigDecimal value, int precision)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value), "amount is null");
            }
            if (precision < 0)
            {
                throw new ArgumentNullException(nameof(precision), "precision is invalid");
            }
            var bigDecimal = value * BigDecimal.Pow(10, precision);
            var bigInt     = bigDecimal.GetWholePart();

            return(ByteUtils.TrimLeadingZeroes(bigInt.ToByteArray()));
        }
Beispiel #17
0
        public BigDecimal volume(BigInteger diameter)
        {
            BigDecimal vol  = BigDecimal.Parse("0");
            BigDecimal radi = BigDecimal.Parse(diameter);
            BigDecimal two  = BigDecimal.Parse("2.0");
            BigDecimal FOT  = BigDecimal.Parse("1.33333333333");
            BigDecimal PI   = BigDecimal.Parse(Math.PI.ToString());


            radi = radi.Divide(two);
            vol  = FOT * (PI);
            vol  = vol * (radi.Pow(3));

            setVolume(vol);
            return(vol);
        }
Beispiel #18
0
        /// <summary>
        /// Convert a decimal defaultDecimalStringToByteArray to a byte array. </summary>
        /// <param name="amountString"> it is a decimal string. e.g. "42.42" </param>
        /// <param name="precisionLevel"> the precision level, means 10 power 18 precision. </param>
        public static byte[] DecimalStringToByteArray(string amountString, int precisionLevel)
        {
            if (string.IsNullOrWhiteSpace(amountString))
            {
                throw new ArgumentException("amount string is blank.", nameof(amountString));
            }
            if (precisionLevel < 0)
            {
                throw new ArgumentException("precision level is less than 0", nameof(precisionLevel));
            }
            BigDecimal amountDecimal    = BigDecimal.Parse(amountString);
            BigDecimal precisionDecimal = BigDecimal.Pow(10, precisionLevel);
            BigDecimal realAmount       = BigDecimal.Multiply(amountDecimal, precisionDecimal);

            return(TrimLeadingZeroes(realAmount.GetWholePart().ToByteArray()));
        }
Beispiel #19
0
        private BigDecimal luminosityOfAStar(BigInteger dia, int surtemp)
        {
            BigDecimal radi = BigDecimal.Parse("0.0");
            BigDecimal surfaceAreaOfTheStar = BigDecimal.Parse("0.0");
            BigInteger two = BigDecimal.Parse("2");

            dia  = dia.Divide(two);
            radi = BigDecimal.Parse(dia);
            radi = radi.Pow(2);
            surfaceAreaOfTheStar = radi * (BigDecimal.Parse((4 * Math.PI).ToString()));
            BigDecimal luminosity = surfaceAreaOfTheStar * (BigDecimal.Parse(".0000000567"));

            luminosity = luminosity * (BigDecimal.Parse(surtemp.ToString()).Pow(4));

            setStarluminosity(luminosity);
            return(luminosity);
        }
Beispiel #20
0
        public Number Pow(int exp)
        {
            if (State == NumberState.NegativeInfinity)
            {
                return(NegativeInfinity);
            }
            if (State == NumberState.PositiveInfinity)
            {
                return(PositiveInfinity);
            }
            if (State == NumberState.NotANumber)
            {
                return(NaN);
            }

            return(new Number(State, bigDecimal.Pow(exp)));
        }
Beispiel #21
0
        private static BigDecimal SqrtNewtonRaphson(BigDecimal c, BigDecimal xn, BigDecimal precision)
        {
            BigDecimal fx  = xn.Pow(2).Add(c.Negate());
            BigDecimal fpx = xn.Multiply(new BigDecimal(2));
            BigDecimal xn1 = fx.Divide(fpx, 2 * SqrtDig.ToInt32(), RoundingMode.HalfDown);

            xn1 = xn.Add(xn1.Negate());
            //----
            BigDecimal currentSquare    = xn1.Pow(2);
            BigDecimal currentPrecision = currentSquare.Subtract(c);

            currentPrecision = currentPrecision.Abs();
            if (currentPrecision.CompareTo(precision) <= -1)
            {
                return(xn1);
            }

            return(SqrtNewtonRaphson(c, xn1, precision));
        }
Beispiel #22
0
        public BigDecimal gPull(BigInteger mass, BigInteger planetMass)
        {
            BigDecimal mass2 = BigDecimal.Parse(mass);

            Console.WriteLine("" + mass);
            BigDecimal planetMass2 = BigDecimal.Parse(planetMass);

            Console.WriteLine("" + mass);
            BigDecimal distance = BigDecimal.Parse("0");

            BigInteger gp = BigInteger.Parse("0");
            BigDecimal G  = BigDecimal.Parse("0.0000000000667");

            distance = BigDecimal.Parse("149000000000");
            gp       = G.Multiply(mass2);
            gp       = gp.Multiply(planetMass2);
            gp       = gp.Divide(distance.Pow(2));
            setgp(gp);
            return(gp);
        }
Beispiel #23
0
        /// <summary>
        /// Convert <seealso cref="BigInteger"/> value to <seealso cref="BigDecimal"/> value. </summary>
        /// <param name="bgInt"> <seealso cref="BigInteger"/> value </param>
        /// <param name="precision">  the precision value for VET and VeThor it is 18, means 10 power 18 </param>
        /// <param name="scale"> the remain digits number of fractional part. </param>
        /// <returns> <seealso cref="BigDecimal"/> value. </returns>
        public static BigDecimal BigIntToBigDecimal(BigInteger bgInt, int precision, int scale)
        {
            if (bgInt == null || precision < 0 || scale < 0)
            {
                return(null);
            }

            var integer2 = new System.Numerics.BigInteger(bgInt.ToByteArray());

            if (scale < precision)
            {
                integer2 /= (int)Math.Pow(10, scale);
                precision = precision - scale;
            }
            var dec = new BigDecimal(integer2);
            var precisionDecimal = BigDecimal.Pow(10, precision);
            var value            = BigDecimal.Divide(dec, precisionDecimal);

            return(value);
        }
Beispiel #24
0
 public static BigDecimal PowRound(BigDecimal x, int n)
 {
     /** Special cases: x^1=x and x^0 = 1
         */
     if (n == 1)
         return x;
     if (n == 0)
         return BigDecimal.One;
     /* The relative error in the result is n times the relative error in the input.
                 * The estimation is slightly optimistic due to the integer rounding of the logarithm.
                 * Since the standard BigDecimal.pow can only handle positive n, we split the algorithm.
                 */
     var mc = new MathContext(x.Precision - (int) System.Math.Log10(System.Math.Abs(n)));
     if (n > 0)
         return x.Pow(n, mc);
     return BigDecimal.One.Divide(x.Pow(-n), mc);
 }
Beispiel #25
0
        static void BigDecimalLog()
        {
            Console.WindowWidth = 122;
            BigDecimal.SetPrecision(116);

            Console.WriteLine("Constants:");
            Console.WriteLine($"π = {BigDecimal.PI}");
            Console.WriteLine($"e = {BigDecimal.E}");
            Console.WriteLine($"φ = {BigDecimal.GoldenRatio}");

            BigDecimal.SetPrecision(88);
            BigDecimal x = BigDecimal.Exp(BigDecimal.E);

            Console.WriteLine($"\nFunctions:");
            Console.WriteLine($"x              = {x}");

            Console.WriteLine($"Function name  |                                           Value                                           | Average time");
            Console.WriteLine($"Ln(x)          | {BigDecimal.Ln(x).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.Ln(x)).TotalMilliseconds,10:0.000}ms");
            Console.WriteLine($"Ln(Ln(x))      | {BigDecimal.Ln(BigDecimal.Ln(x)).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.Ln(BigDecimal.Ln(x))).TotalMilliseconds,10:0.000}ms");
            Console.WriteLine($"Exp(x)         | {BigDecimal.Exp(x).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.Exp(x)).TotalMilliseconds,10:0.000}ms");
            Console.WriteLine($"Pow(x, x)      | {BigDecimal.Pow(x, x).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.Pow(x, x)).TotalMilliseconds,10:0.000}ms");

            x = BigDecimal.PI / 4;
            Console.WriteLine($"\nx              = {x}");

            Console.WriteLine($"Function name  |                                           Value                                           | Average time");
            Console.WriteLine($"Sin(x)         | {BigDecimal.Sin(x).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.Sin(x)).TotalMilliseconds,10:0.000}ms");
            Console.WriteLine($"Cos(x)         | {BigDecimal.Cos(x).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.Cos(x)).TotalMilliseconds,10:0.000}ms");
            Console.WriteLine($"Tg(x)          | {BigDecimal.Tg(x).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.Tg(x)).TotalMilliseconds,10:0.000}ms");
            Console.WriteLine($"Ctg(x)         | {BigDecimal.Ctg(x).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.Ctg(x)).TotalMilliseconds,10:0.000}ms");
            Console.WriteLine($"Arcsin(sin(x)) | {BigDecimal.ArcSin(BigDecimal.Sin(x)).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.ArcSin(BigDecimal.Sin(x))).TotalMilliseconds,10:0.000}ms");
            Console.WriteLine($"Arccos(cos(x)) | {BigDecimal.ArcCos(BigDecimal.Cos(x)).ToString().PadRight(2, '.').PadRight(90, '0').Remove(89),89} | {MeasureTime(() => BigDecimal.ArcCos(BigDecimal.Cos(x))).TotalMilliseconds,10:0.000}ms");

            decimal[] Decimals = new decimal[7]
            {
                decimal.MinusOne,
                decimal.Zero,
                decimal.One,
                decimal.MinValue,
                decimal.MaxValue,
                new decimal(1, 0, 0, true, 28),
                new decimal(1, 0, 0, false, 28)
            };

            BigDecimal.SetPrecision(32);
            Console.WriteLine($"\n{"Convertation:",-15}| {typeof(decimal),-32} |  {typeof(BigDecimal),-32} |  {typeof(decimal),-32}");
            foreach (decimal d in Decimals)
            {
                Console.WriteLine(BigDecimalConvertLog(d));
            }

            double[] Doubles = new double[5]
            {
                -1d, 0d, 1d,
                // double.MinValue,  // No support for scientific notation yet
                // double.MaxValue,  // Too long values
                -double.Epsilon,
                double.Epsilon
            };

            Console.WriteLine($"\n{"Convertation:",-15}| {typeof(double),-32} |  {typeof(BigDecimal),-32} |  {typeof(double),-32}");
            foreach (double d in Doubles)
            {
                Console.WriteLine(BigDecimalConvertLog(d));
            }
        }
Beispiel #26
0
        protected override void UpdateMinerTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (m_isGetMiningParameters)
            {
                return;
            }
            try
            {
                m_isGetMiningParameters = true;
                var miningParameters = GetMiningParameters();
                if (miningParameters == null)
                {
                    OnGetMiningParameterStatus(this, false);
                    return;
                }

                CurrentChallenge = miningParameters.ChallengeByte32;

                if (m_lastParameters == null || miningParameters.Challenge.Value != m_lastParameters.Challenge.Value)
                {
                    Program.Print(string.Format("[INFO] New challenge detected {0}...", miningParameters.ChallengeByte32String));
                    OnNewChallenge(this, miningParameters.ChallengeByte32, MinerAddress);

                    if (m_challengeReceiveDateTime == DateTime.MinValue)
                    {
                        m_challengeReceiveDateTime = DateTime.Now;
                    }
                }

                if (m_lastParameters == null || miningParameters.MiningTarget.Value != m_lastParameters.MiningTarget.Value)
                {
                    Program.Print(string.Format("[INFO] New target detected {0}...", miningParameters.MiningTargetByte32String));
                    OnNewTarget(this, miningParameters.MiningTarget);
                }

                if (m_lastParameters == null || miningParameters.MiningDifficulty.Value != m_lastParameters.MiningDifficulty.Value)
                {
                    Program.Print(string.Format("[INFO] New difficulity detected ({0})...", miningParameters.MiningDifficulty.Value));
                    OnNewDifficulty?.Invoke(this, miningParameters.MiningDifficulty);
                    Difficulty = miningParameters.MiningDifficulty;

                    // Actual difficulty should have decimals
                    var calculatedDifficulty           = BigDecimal.Exp(BigInteger.Log(MaxTarget.Value) - BigInteger.Log(miningParameters.MiningTarget.Value));
                    var calculatedDifficultyBigInteger = BigInteger.Parse(calculatedDifficulty.ToString().Split(",.".ToCharArray())[0]);

                    try // Perform rounding
                    {
                        if (uint.Parse(calculatedDifficulty.ToString().Split(",.".ToCharArray())[1].First().ToString()) >= 5)
                        {
                            calculatedDifficultyBigInteger++;
                        }
                    }
                    catch { }

                    if (Difficulty.Value != calculatedDifficultyBigInteger)
                    {
                        Difficulty = new HexBigInteger(calculatedDifficultyBigInteger);
                        var expValue         = BigInteger.Log10(calculatedDifficultyBigInteger);
                        var calculatedTarget = BigInteger.Parse(
                            (BigDecimal.Parse(MaxTarget.Value.ToString()) * BigDecimal.Pow(10, expValue) / (calculatedDifficulty * BigDecimal.Pow(10, expValue))).
                            ToString().Split(",.".ToCharArray())[0]);
                        var calculatedTargetHex = new HexBigInteger(calculatedTarget);

                        Program.Print(string.Format("[INFO] Update target 0x{0}...", calculatedTarget.ToString("x64")));
                        OnNewTarget(this, calculatedTargetHex);
                        CurrentTarget = calculatedTargetHex;
                    }
                }

                IsPause          = miningParameters.IsPause;
                m_lastParameters = miningParameters;

                OnStopSolvingCurrentChallenge(this, stopSolving: miningParameters.IsPause);
                OnGetMiningParameterStatus(this, true);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally { m_isGetMiningParameters = false; }
        }
Beispiel #27
0
    public void TestTruncateOnAllArithmeticOperations()
    {
        var savePrecision = BigDecimal.Precision;

        BigDecimal mod1 = BigDecimal.Parse("3141592653589793238462643383279502");
        BigDecimal mod2 = BigDecimal.Parse("27182818284590452");
        BigDecimal neg1 = BigDecimal.Parse("-3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647");
        BigDecimal lrg1 = BigDecimal.Parse("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647");
        BigDecimal lrg2 = BigDecimal.Parse("2.718281828459045235360287471352662497757247093699959574966967");

        var expected1  = "5.859874482";
        var expected2  = "0.4233108251";
        var expected3  = "8.5397342226";
        var expected4  = "0.8652559794";
        var expected5  = "9.869604401";
        var expected6  = "148.4131591";
        var expected7  = "8003077319547306";
        var expected8  = "-3.1415926535";
        var expected9  = "3";
        var expected10 = "4";
        var expected11 = "3.1415926535";

        var actual1  = "";
        var actual2  = "";
        var actual3  = "";
        var actual4  = "";
        var actual5  = "";
        var actual6  = "";
        var actual7  = "";
        var actual8  = "";
        var actual9  = "";
        var actual10 = "";
        var actual11 = "";

        try
        {
            BigDecimal.Precision      = 10;
            BigDecimal.AlwaysTruncate = true;

            TestContext.WriteLine($"E = {BigDecimal.E}");
            TestContext.WriteLine($"{new BigDecimal(lrg1.Mantissa, lrg1.Exponent)}");
            TestContext.WriteLine($"{new BigDecimal(lrg2.Mantissa, lrg2.Exponent)}");

            BigDecimal result1  = BigDecimal.Add(lrg1, lrg2);
            BigDecimal result2  = BigDecimal.Subtract(lrg1, lrg2);
            BigDecimal result3  = BigDecimal.Multiply(lrg1, lrg2);
            BigDecimal result4  = BigDecimal.Divide(lrg2, lrg1);
            BigDecimal result5  = BigDecimal.Pow(lrg1, 2);
            BigDecimal result6  = BigDecimal.Exp(new BigInteger(5));
            BigDecimal result7  = BigDecimal.Mod(mod1, mod2);
            BigDecimal result8  = BigDecimal.Negate(lrg1);
            BigDecimal result9  = BigDecimal.Floor(lrg1);
            BigDecimal result10 = BigDecimal.Ceiling(lrg1);
            BigDecimal result11 = BigDecimal.Abs(lrg1);

            actual1  = result1.ToString();
            actual2  = result2.ToString();
            actual3  = result3.ToString();
            actual4  = result4.ToString();
            actual5  = result5.ToString();
            actual6  = result6.ToString();
            actual7  = result7.ToString();
            actual8  = result8.ToString();
            actual9  = result9.ToString();
            actual10 = result10.ToString();
            actual11 = result11.ToString();
        }
        finally
        {
            BigDecimal.Precision      = savePrecision;
            BigDecimal.AlwaysTruncate = false;
        }

        Assert.AreEqual(expected1, actual1, $"Test Truncate On All Arithmetic Operations  - #1: ");
        Assert.AreEqual(expected2, actual2, $"Test Truncate On All Arithmetic Operations  - #2: ");
        Assert.AreEqual(expected3, actual3, $"Test Truncate On All Arithmetic Operations  - #3: ");
        Assert.AreEqual(expected4, actual4, $"Test Truncate On All Arithmetic Operations  - #4: ");
        Assert.AreEqual(expected5, actual5, $"Test Truncate On All Arithmetic Operations  - #5: ");
        StringAssert.StartsWith(expected6, actual6, $"Test Truncate On All Arithmetic Operations  - #6: ");
        Assert.AreEqual(expected7, actual7, $"Test Truncate On All Arithmetic Operations  - #7: ");
        Assert.AreEqual(expected8, actual8, $"Test Truncate On All Arithmetic Operations  - #8: ");
        Assert.AreEqual(expected9, actual9, $"Test Truncate On All Arithmetic Operations  - #9: ");
        Assert.AreEqual(expected10, actual10, $"Test Truncate On All Arithmetic Operations - #10: ");
        Assert.AreEqual(expected11, actual11, $"Test Truncate On All Arithmetic Operations - #11: ");

        Assert.AreEqual(5000, BigDecimal.Precision, "Restore Precision to 5000");
    }
Beispiel #28
0
        public void PowTest2()
        {
            var res = BigDecimal.Pow(2.5, 5);

            Assert.AreEqual(new BigDecimal(97.65625m), res, "BigDecimal.Pow() does not work.");
        }
Beispiel #29
0
        public static BigDecimal Hypot(int n, BigDecimal x)
        {
            /* compute n^2+x^2 in infinite precision
                */
            BigDecimal z = (new BigDecimal(n)).Pow(2).Add(x.Pow(2));

            /* Truncate to the precision set by x. Absolute error = in z (square of the result) is |2*x*xerr|,
                * where the error is 1/2 of the ulp. Two intermediate protection digits.
                * zerr is a signed value, but used only in conjunction with err2prec(), so this feature does not harm.
                */
            double zerr = x.ToDouble()*x.Ulp().ToDouble();
            var mc = new MathContext(2 + ErrorToPrecision(z.ToDouble(), zerr));

            /* Pull square root */
            z = Sqrt(z.Round(mc));

            /* Final rounding. Absolute error in the square root is x*xerr/z, where zerr holds 2*x*xerr.
                */
            mc = new MathContext(ErrorToPrecision(z.ToDouble(), 0.5*zerr/z.ToDouble()));
            return z.Round(mc);
        }
Beispiel #30
0
        public static BigDecimal Hypot(BigDecimal x, BigDecimal y)
        {
            /* compute x^2+y^2
                */
            BigDecimal z = x.Pow(2).Add(y.Pow(2));

            /* truncate to the precision set by x and y. Absolute error = 2*x*xerr+2*y*yerr,
                * where the two errors are 1/2 of the ulp's.  Two intermediate protectio digits.
                */
            BigDecimal zerr = x.Abs().Multiply(x.Ulp()).Add(y.Abs().Multiply(y.Ulp()));
            var mc = new MathContext(2 + ErrorToPrecision(z, zerr));

            /* Pull square root */
            z = Sqrt(z.Round(mc));

            /* Final rounding. Absolute error in the square root is (y*yerr+x*xerr)/z, where zerr holds 2*(x*xerr+y*yerr).
                */
            mc = new MathContext(ErrorToPrecision(z.ToDouble(), 0.5*zerr.ToDouble()/z.ToDouble()));
            return z.Round(mc);
        }
Beispiel #31
0
        public static BigDecimal Sqrt(BigDecimal x, MathContext mc)
        {
            if (x.CompareTo(BigDecimal.Zero) < 0)
                throw new ArithmeticException("negative argument " + x + " of square root");

            if (x.Abs().Subtract(new BigDecimal(System.Math.Pow(10d, -mc.Precision))).CompareTo(BigDecimal.Zero) < 0)
                return ScalePrecision(BigDecimal.Zero, mc);

            /* start the computation from a double precision estimate */
            var s = new BigDecimal(System.Math.Sqrt(x.ToDouble()), mc);
            BigDecimal half = BigDecimal.ValueOf(2);

            /* increase the local accuracy by 2 digits */
            var locmc = new MathContext(mc.Precision + 2, mc.RoundingMode);

            /* relative accuracy requested is 10^(-precision)
                */
            double eps = System.Math.Pow(10.0, -mc.Precision);
            while (true) {
                /* s = s -(s/2-x/2s); test correction s-x/s for being
                        * smaller than the precision requested. The relative correction is 1-x/s^2,
                        * (actually half of this, which we use for a little bit of additional protection).
                        */
                if (System.Math.Abs(BigDecimal.One.Subtract(x.Divide(s.Pow(2, locmc), locmc)).ToDouble()) < eps)
                    break;
                s = s.Add(x.Divide(s, locmc)).Divide(half, locmc);
            }

            return s;
        }
Beispiel #32
0
        public static BigDecimal Root(int n, BigDecimal x)
        {
            if (x.CompareTo(BigDecimal.Zero) < 0)
                throw new ArithmeticException("negative argument " + x + " of root");
            if (n <= 0)
                throw new ArithmeticException("negative power " + n + " of root");

            if (n == 1)
                return x;

            /* start the computation from a double precision estimate */
            var s = new BigDecimal(System.Math.Pow(x.ToDouble(), 1.0/n));

            /* this creates nth with nominal precision of 1 digit
                */
            var nth = new BigDecimal(n);

            /* Specify an internal accuracy within the loop which is
                * slightly larger than what is demanded by 'eps' below.
                */
            BigDecimal xhighpr = ScalePrecision(x, 2);
            var mc = new MathContext(2 + x.Precision);

            /* Relative accuracy of the result is eps.
                */
            double eps = x.Ulp().ToDouble()/(2*n*x.ToDouble());
            for (;;) {
                /* s = s -(s/n-x/n/s^(n-1)) = s-(s-x/s^(n-1))/n; test correction s/n-x/s for being
                        * smaller than the precision requested. The relative correction is (1-x/s^n)/n,
                        */
                BigDecimal c = xhighpr.Divide(s.Pow(n - 1), mc);
                c = s.Subtract(c);
                var locmc = new MathContext(c.Precision);
                c = c.Divide(nth, locmc);
                s = s.Subtract(c);
                if (System.Math.Abs(c.ToDouble()/s.ToDouble()) < eps)
                    break;
            }
            return s.Round(new MathContext(ErrorToPrecision(eps)));
        }
Beispiel #33
0
        public BigInteger ToBigInteger()
        {
            var fullDecimal = Value * (BigDecimal.Pow(10, (int)Token.Precision));

            return(fullDecimal.GetWholePart());
        }
 public void PowWithContext(string a, int aScale, int exp, string c, int cScale, int precision, RoundingMode roundingMode)
 {
     BigDecimal aNumber = new BigDecimal(BigInteger.Parse(a), aScale);
     MathContext mc = new MathContext(precision, roundingMode);
     BigDecimal result = aNumber.Pow(exp, mc);
     Assert.AreEqual(c, result.ToString(), "incorrect value");
     Assert.AreEqual(cScale, result.Scale, "incorrect scale");
 }
 public void Pow(string a, int aScale, int exp, string c, int cScale)
 {
     BigDecimal aNumber = new BigDecimal(BigInteger.Parse(a), aScale);
     BigDecimal result = aNumber.Pow(exp);
     Assert.AreEqual(c, result.ToString(), "incorrect value");
     Assert.AreEqual(cScale, result.Scale, "incorrect scale");
 }
Beispiel #36
0
        public void PowTest()
        {
            var res = BigDecimal.Pow(2, 5);

            Assert.AreEqual(new BigDecimal(32), res, "BigDecimal.Pow() does not work.");
        }
Beispiel #37
0
        public static BigDecimal PowRound(BigDecimal x, Rational q)
        {
            /** Special cases: x^1=x and x^0 = 1
                */
            if (q.CompareTo(BigInteger.One) == 0)
                return x;
            if (q.Sign == 0)
                return BigDecimal.One;
            if (q.IsInteger) {
                /* We are sure that the denominator is positive here, because normalize() has been
                        * called during constrution etc.
                        */
                return PowRound(x, q.Numerator);
            }
            /* Refuse to operate on the general negative basis. The integer q have already been handled above.
                        */
            if (x.CompareTo(BigDecimal.Zero) < 0)
                throw new ArithmeticException("Cannot power negative " + x);
            if (q.IsIntegerFraction) {
                /* Newton method with first estimate in double precision.
                                * The disadvantage of this first line here is that the result must fit in the
                                * standard range of double precision numbers exponents.
                                */
                double estim = System.Math.Pow(x.ToDouble(), q.ToDouble());
                var res = new BigDecimal(estim);

                /* The error in x^q is q*x^(q-1)*Delta(x).
                                * The relative error is q*Delta(x)/x, q times the relative error of x.
                                */
                var reserr = new BigDecimal(0.5*q.Abs().ToDouble()
                                            *x.Ulp().Divide(x.Abs(), MathContext.Decimal64).ToDouble());

                /* The main point in branching the cases above is that this conversion
                                * will succeed for numerator and denominator of q.
                                */
                int qa = q.Numerator.ToInt32();
                int qb = q.Denominator.ToInt32();

                /* Newton iterations. */
                BigDecimal xpowa = PowRound(x, qa);
                for (;;) {
                    /* numerator and denominator of the Newton term.  The major
                                        * disadvantage of this implementation is that the updates of the powers
                                        * of the new estimate are done in full precision calling BigDecimal.pow(),
                                        * which becomes slow if the denominator of q is large.
                                        */
                    BigDecimal nu = res.Pow(qb).Subtract(xpowa);
                    BigDecimal de = MultiplyRound(res.Pow(qb - 1), q.Denominator);

                    /* estimated correction */
                    BigDecimal eps = nu.Divide(de, MathContext.Decimal64);

                    BigDecimal err = res.Multiply(reserr, MathContext.Decimal64);
                    int precDiv = 2 + ErrorToPrecision(eps, err);
                    if (precDiv <= 0) {
                        /* The case when the precision is already reached and any precision
                                                * will do. */
                        eps = nu.Divide(de, MathContext.Decimal32);
                    } else {
                        eps = nu.Divide(de, new MathContext(precDiv));
                    }

                    res = SubtractRound(res, eps);
                    /* reached final precision if the relative error fell below reserr,
                                        * |eps/res| < reserr
                                        */
                    if (eps.Divide(res, MathContext.Decimal64).Abs().CompareTo(reserr) < 0) {
                        /* delete the bits of extra precision kept in this
                                                * working copy.
                                                */
                        return res.Round(new MathContext(ErrorToPrecision(reserr.ToDouble())));
                    }
                }
            }
            /* The error in x^q is q*x^(q-1)*Delta(x) + Delta(q)*x^q*log(x).
                                * The relative error is q/x*Delta(x) + Delta(q)*log(x). Convert q to a floating point
                                * number such that its relative error becomes negligible: Delta(q)/q << Delta(x)/x/log(x) .
                                */
            int precq = 3 + ErrorToPrecision((x.Ulp().Divide(x, MathContext.Decimal64)).ToDouble()
                                             /System.Math.Log(x.ToDouble()));

            /* Perform the actual calculation as exponentiation of two floating point numbers.
                                */
            return Pow(x, q.ToBigDecimal(new MathContext(precq)));
        }