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)); }
public BigDecimal StarsEnergy(BigInteger mass, BigDecimal massUsedUp, BigDecimal massAtCenter) { BigDecimal eng = BigDecimal.Parse("0"); BigInteger speedOfLightSq = BigInteger.Parse("89875517900000000"); BigDecimal mass2 = BigDecimal.Parse(mass); //.007 eng = massUsedUp.Multiply(massAtCenter); eng = eng.Multiply(mass2); eng = eng.Multiply(BigDecimal.Parse(speedOfLightSq)); setEnergy(eng); return(eng); }
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); }
private static BigDecimal Calculate(string[] a, char c) { BigDecimal value = BigDecimal.Parse(a[0].Trim()); for (int i = 1; i < a.Length; i++) { if (c == '+') { value = value.Add(BigDecimal.Parse(a[i].Trim())); } else if (c == '-') { value = value.Subtract(BigDecimal.Parse(a[i].Trim())); } else if (c == '*') { value = value.Multiply(BigDecimal.Parse(a[i].Trim())); } else { value = value.Divide(BigDecimal.Parse(a[i].Trim()), 5, RoundingMode.HalfEven); } } return(value); }
/// <summary> /// Chuyển số thập phân thành hỗn số. /// </summary> /// <param name="n">Số thập phân nhận từ bên ngoài.</param> /// <returns>Phần thực của hỗn số</returns> private static FractionBigNum ChangeFraction(BigDecimal n) { FractionBigNum frac = new FractionBigNum(); int sign = n.Sign; n = n.Abs(); BigDecimal whole = n.DivideToIntegralValue(BigDecimal.One); BigDecimal decimalPoint = n.Subtract(whole); frac.Numerator = decimalPoint.Multiply(BigDecimal.Ten.Pow(CountDecimal(decimalPoint))).DivideToIntegralValue(BigDecimal.One); frac.Denominator = BigDecimal.Ten.Pow(CountDecimal(decimalPoint)).DivideToIntegralValue(BigDecimal.One); frac.Minimalism(); if (!whole.IsZero) { //If Whole is not zero then we change whole to fraction, add fraction. FractionBigNum frac2 = new FractionBigNum(whole, BigDecimal.One); frac = frac + frac2; } frac.Numerator *= sign; return(frac); }
private static PhysicalQuantity Half(PhysicalQuantity value_ren) { BigDecimal quantity = value_ren.Quantity; BigDecimal newValue = quantity == null ? null : quantity.Multiply(new BigDecimal("0.5")); return(new PhysicalQuantity(newValue, value_ren.Unit)); }
public static BigDecimal ApplyRate(BigDecimal amount, BigDecimal rate, TimeSpan timeSpan) { BigDecimal appliedRate = GetSeconds(timeSpan).Divide(rate, MathContext.Decimal64); BigDecimal factor = BigDecimal.ValueOf(Math.Exp(appliedRate.ToDouble())); return(amount.Multiply(factor, MathContext.Decimal64)); }
private static Money Half(Money value) { BigDecimal quantity = value.Amount; BigDecimal newValue = quantity == null ? null : quantity.Multiply(new BigDecimal("0.5")); return(new Money(newValue, value.Currency)); }
private static BigDecimal FromValues(int lo, int mid, int hi, bool isNegative, byte scale) { BigDecimal d; unchecked { var dlo = new BigDecimal((long)(ulong)lo, MathContext.DECIMAL128); var dmid = new BigDecimal((long)(ulong)mid, MathContext.DECIMAL128); var dhi = new BigDecimal((long)(ulong)hi, MathContext.DECIMAL128); d = dhi.Multiply(Scale32Bit.Val).Add(dmid).Multiply(Scale32Bit.Val).Add(dlo); d = d.MovePointLeft((int)scale); if (scale > 28) { throw new ArgumentOutOfRangeException("scale must be between 0 and 28"); } if (isNegative) { d = d.Negate(MathContext.DECIMAL128); } } return(d); }
public void Multiply(string result, string left, string right) { var resultDecimal = BigDecimal.Parse(result, CultureInfo.InvariantCulture); var leftDecimal = BigDecimal.Parse(left, CultureInfo.InvariantCulture); var rightDecimal = BigDecimal.Parse(right, CultureInfo.InvariantCulture); Assert.Equal(resultDecimal, BigDecimal.Multiply(leftDecimal, rightDecimal)); }
public static BigDecimal FahrenheitToKexle(BigDecimal fahrenheit) { MathContext mcInt = new MathContext(9999, RoundingMode.Ceiling); BigDecimal f2 = fahrenheit.Subtract(27.0, mcInt); BigDecimal s1f2s3 = f2.Multiply(0.6, mcInt); BigDecimal s1f2 = new BigDecimal(2634.0).Divide(s1f2s3, mcInt); return(s1f2.Subtract(4.0, mcInt)); }
public void Multiply_ParametersFromData_Pass() { var left = new BigDecimal(TestContext.DataRow[0].ToString()); var right = new BigDecimal(TestContext.DataRow[1].ToString()); var expected = TestContext.DataRow[2].ToString(); string message = TestContext.DataRow[3].ToString(); var actual = left.Multiply(right); Assert.AreEqual(expected, actual.ToString(), message); }
public Number Multiply(Number number) { if (numberState == NumberState.None) { if (number.numberState == 0) { return(new Number(NumberState.None, bigDecimal.Multiply(number.bigDecimal))); } return(new Number(number.numberState, null)); } return(new Number(numberState, null)); }
/// <summary> /// Phương thức trả về số lượng sau dấu ".". /// </summary> /// <param name="n">Số thập phân.</param> /// <returns>số lượng số nguyên sau dấu ".".</returns> private static int CountDecimal(BigDecimal n) { int count = 0; while (!n.IsZero) { count++; n = n.Multiply(BigDecimal.Ten); n = n.Subtract(n.DivideToIntegralValue(BigDecimal.One)); } return(count); }
// Maximum number of characters to convert. This is to prevent rounding errors // or repeating fractions near the very bottom from getting out of control. Note // that this still gives us a huge number of possible splits. /// <summary> /// Return a BigDecimal representation of string 'str' suitable for use /// in a numerically-sorting order. /// </summary> internal virtual BigDecimal StringToBigDecimal(string str) { BigDecimal result = BigDecimal.Zero; BigDecimal curPlace = OnePlace; // start with 1/65536 to compute the first digit. int len = System.Math.Min(str.Length, MaxChars); for (int i = 0; i < len; i++) { int codePoint = str.CodePointAt(i); result = result.Add(TryDivide(new BigDecimal(codePoint), curPlace)); // advance to the next less significant place. e.g., 1/(65536^2) for the second char. curPlace = curPlace.Multiply(OnePlace); } return(result); }
/// <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())); }
/// <summary>Return the string encoded in a BigDecimal.</summary> /// <remarks> /// Return the string encoded in a BigDecimal. /// Repeatedly multiply the input value by 65536; the integer portion after such a multiplication /// represents a single character in base 65536. Convert that back into a char and create a /// string out of these until we have no data left. /// </remarks> internal virtual string BigDecimalToString(BigDecimal bd) { BigDecimal cur = bd.StripTrailingZeros(); StringBuilder sb = new StringBuilder(); for (int numConverted = 0; numConverted < MaxChars; numConverted++) { cur = cur.Multiply(OnePlace); int curCodePoint = cur; if (0 == curCodePoint) { break; } cur = cur.Subtract(new BigDecimal(curCodePoint)); sb.Append(char.ToChars(curCodePoint)); } return(sb.ToString()); }
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)); }
public SqlNumber Multiply(SqlNumber value) { if (State == NumericState.None) { if (value.State == NumericState.None) { if (IsNull || value.IsNull) { return(Null); } return(new SqlNumber(NumericState.None, innerValue.Multiply(value.innerValue))); } return(new SqlNumber(value.State, null)); } return(new SqlNumber(State, null)); }
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); }
public void run(SellItemsRequest request) { Order order = new Order(); order.setStatus(OrderStatus.CREATED); order.setItems(new List <OrderItem>()); order.setCurrency("EUR"); order.setTotal(new BigDecimal(0.0)); order.setTax(new BigDecimal(0.0)); foreach (SellItemRequest itemRequest in request.getRequests()) { Product product = productCatalog.getByName(itemRequest.getProductName()); if (product == null) { throw new UnknownProductException(); } else { BigDecimal unitaryTax = product.getPrice().Divide(BigDecimal.ValueOf(100)).Multiply(product.getCategory().getTaxPercentage()).SetScale(2, RoundingMode.HalfUp); BigDecimal unitaryTaxedAmount = product.getPrice().Add(unitaryTax).SetScale(2, RoundingMode.HalfUp); BigDecimal taxedAmount = unitaryTaxedAmount.Multiply(BigDecimal.ValueOf(itemRequest.getQuantity())).SetScale(2, RoundingMode.HalfUp); BigDecimal taxAmount = unitaryTax.Multiply(BigDecimal.ValueOf(itemRequest.getQuantity())); OrderItem orderItem = new OrderItem(); orderItem.setProduct(product); orderItem.setQuantity(itemRequest.getQuantity()); orderItem.setTax(taxAmount); orderItem.setTaxedAmount(taxedAmount); order.getItems().Add(orderItem); order.setTotal(order.getTotal().Add(taxedAmount)); order.setTax(order.getTax().Add(taxAmount)); } } orderRepository.save(order); }
public static BigDecimal /*!*/ Multiply(RubyContext /*!*/ context, BigDecimal /*!*/ self, BigDecimal /*!*/ other, int n) { return(BigDecimal.Multiply(GetConfig(context), self, other, n)); }
public static BigDecimal /*!*/ Multiply(RubyContext /*!*/ context, BigDecimal /*!*/ self, double other, int n) { BigDecimal.Config config = GetConfig(context); return(BigDecimal.Multiply(config, self, BigDecimal.Create(config, other), n)); }
public override bool Validate() { if (this.contract == null) { throw new ContractValidateException("No contract!"); } if (this.db_manager == null) { throw new ContractValidateException("No this.db_manager!"); } if (this.contract.Is(ExchangeWithdrawContract.Descriptor)) { ExchangeWithdrawContract contract = null; try { contract = this.contract.Unpack <ExchangeWithdrawContract>(); } catch (InvalidProtocolBufferException e) { throw new ContractValidateException(e.Message); } byte[] owner_address = contract.OwnerAddress.ToByteArray(); if (!Wallet.IsValidAddress(owner_address)) { throw new ContractValidateException("Invalid address"); } if (!this.db_manager.Account.Contains(owner_address)) { throw new ContractValidateException("account[" + owner_address.ToHexString() + "] not exists"); } AccountCapsule account = this.db_manager.Account.Get(owner_address); if (account.Balance < CalcFee()) { throw new ContractValidateException("No enough balance for exchange withdraw fee!"); } ExchangeCapsule exchange = null; try { exchange = this.db_manager.ExchangeFinal.Get(BitConverter.GetBytes(contract.ExchangeId)); } catch (ItemNotFoundException e) { throw new ContractValidateException("Exchange[" + contract.ExchangeId + "] not exists", e); } if (!account.Address.Equals(exchange.CreatorAddress)) { throw new ContractValidateException("account[" + owner_address.ToHexString() + "] is not creator"); } byte[] first_token_id = exchange.FirstTokenId.ToByteArray(); byte[] second_token_id = exchange.SecondTokenId.ToByteArray(); long first_token_balance = exchange.FirstTokenBalance; long second_token_balance = exchange.SecondTokenBalance; byte[] token_id = contract.TokenId.ToByteArray(); long token_quantity = contract.Quant; long other_token_quantity = 0; if (this.db_manager.DynamicProperties.GetAllowSameTokenName() == 1) { if (!token_id.SequenceEqual(COMPARE_CHARICTOR) && !TransactionUtil.IsNumber(token_id)) { throw new ContractValidateException("token id is not a valid number"); } } if (!token_id.SequenceEqual(first_token_id) && !token_id.SequenceEqual(second_token_id)) { throw new ContractValidateException("token is not in exchange"); } if (token_quantity <= 0) { throw new ContractValidateException("withdraw token quant must greater than zero"); } if (first_token_balance == 0 || second_token_balance == 0) { throw new ContractValidateException("Token balance in exchange is equal with 0," + "the exchange has been closed"); } BigDecimal first_balance = new BigDecimal(first_token_balance); BigDecimal second_balance = new BigDecimal(second_token_balance); BigDecimal bigTokenQuant = new BigDecimal(token_quantity); if (token_id.SequenceEqual(first_token_id)) { other_token_quantity = second_balance.Multiply(bigTokenQuant) .DivideToIntegralValue(first_balance).ToInt64(); if (first_token_balance < token_quantity || second_token_balance < other_token_quantity) { throw new ContractValidateException("exchange balance is not enough"); } if (other_token_quantity <= 0) { throw new ContractValidateException("withdraw another token quant must greater than zero"); } double remainder = second_balance.Multiply(bigTokenQuant) .Divide(first_balance, 4, RoundingMode.HalfUp).ToDouble(); remainder -= other_token_quantity; if (remainder / other_token_quantity > 0.0001) { throw new ContractValidateException("Not precise enough"); } } else { other_token_quantity = first_balance.Multiply(bigTokenQuant) .DivideToIntegralValue(second_balance).ToInt64(); if (second_token_balance < token_quantity || first_token_balance < other_token_quantity) { throw new ContractValidateException("exchange balance is not enough"); } if (other_token_quantity <= 0) { throw new ContractValidateException("withdraw another token quant must greater than zero"); } double remainder = first_balance.Multiply(bigTokenQuant) .Divide(second_balance, 4, RoundingMode.HalfUp).ToDouble(); remainder -= other_token_quantity; if (remainder / other_token_quantity > 0.0001) { throw new ContractValidateException("Not precise enough"); } } } else { throw new ContractValidateException( "contract type error,expected type [ExchangeWithdrawContract],real type[" + this.contract.GetType().Name + "]"); } return(true); }
public static BigDecimal /*!*/ Multiply(RubyContext /*!*/ context, BigDecimal /*!*/ self, [NotNull] BigInteger /*!*/ other) { BigDecimal.Config config = GetConfig(context); return(BigDecimal.Multiply(config, self, BigDecimal.Create(config, other))); }
public void Multiply(string a, int aScale, string b, int bScale, string c, int cScale) { BigDecimal aNumber = new BigDecimal(BigInteger.Parse(a), aScale); BigDecimal bNumber = new BigDecimal(BigInteger.Parse(b), bScale); BigDecimal result = aNumber.Multiply(bNumber); Assert.AreEqual(c, result.ToString(), "incorrect value"); Assert.AreEqual(cScale, result.Scale, "incorrect scale"); }
public static Number operator *(Number a, Number b) { return(BigDecimal.Multiply(new BigDecimal.Config(), a.value, b.value)); }
public void MultiplyTest() { var res = BigDecimal.Multiply(new BigDecimal(2), new BigDecimal(4)); Assert.AreEqual(new BigDecimal(8), res); }
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))); }
public void MultiplyBigDecimal() { BigDecimal multi1 = new BigDecimal(value, 5); BigDecimal multi2 = new BigDecimal(2.345D); BigDecimal result = multi1.Multiply(multi2); Assert.IsTrue(result.ToString().StartsWith("289.51154260") && result.Scale == multi1.Scale + multi2.Scale, "123.45908 * 2.345 is not correct: " + result); multi1 = BigDecimal.Parse("34656"); multi2 = BigDecimal.Parse("-2"); result = multi1.Multiply(multi2); Assert.IsTrue(result.ToString().Equals("-69312") && result.Scale == 0, "34656 * 2 is not correct"); multi1 = new BigDecimal(-2.345E-02); multi2 = new BigDecimal(-134E130); result = multi1.Multiply(multi2); Assert.IsTrue(result.ToDouble() == 3.1422999999999997E130 && result.Scale == multi1.Scale + multi2.Scale, "-2.345E-02 * -134E130 is not correct " + result.ToDouble()); multi1 = BigDecimal.Parse("11235"); multi2 = BigDecimal.Parse("0"); result = multi1.Multiply(multi2); Assert.IsTrue(result.ToDouble() == 0 && result.Scale == 0, "11235 * 0 is not correct"); multi1 = BigDecimal.Parse("-0.00234"); multi2 = new BigDecimal(13.4E10); result = multi1.Multiply(multi2); Assert.IsTrue(result.ToDouble() == -313560000 && result.Scale == multi1.Scale + multi2.Scale, "-0.00234 * 13.4E10 is not correct"); }
static void CalcPi(int t) { Console.WriteLine("You have entered " + t + " iterations"); Console.WriteLine("Calculating constant..."); acc = t * 20; BigDecimal c = new BigDecimal(1); c = c.Divide(882, acc, RoundingMode.HalfUp); Console.WriteLine("Calculating summation..."); Console.ForegroundColor = ConsoleColor.Blue; BigDecimal sumTerm = new BigDecimal(0, acc); Parallel.For(0, t, i => { BigDecimal a = CalcTerm(i); lock (l0ck) { sumTerm = sumTerm.Add(a); } }); Console.ForegroundColor = ConsoleColor.White; Console.Write('\n'); c = c.Multiply(sumTerm); BigDecimal pi1 = new BigDecimal(1); pi1 = pi1.Divide(c, acc, RoundingMode.HalfUp); pi1 = pi1.Multiply(4); string pi = pi1.ToString(); Console.WriteLine("Printing reliable digits..."); Console.ForegroundColor = ConsoleColor.Green; Console.Write("π≈"); //Check digits of pi against source int idx = 0; int digits = 1; StreamReader sr = new StreamReader(File.OpenRead("pi.txt")); while (!sr.EndOfStream && (idx < pi.Length)) { char ch = (char)sr.Read(); if (ch == pi[idx]) { Console.Write(pi[idx]); digits++; } idx++; } Console.ForegroundColor = ConsoleColor.White; Console.Write('\n'); Console.WriteLine("Calculated " + digits + " digits of pi."); }
public static BigDecimal MultiplyRound(BigDecimal x, BigDecimal y) { BigDecimal resul = x.Multiply(y); // The estimation of the relative error in the result is the sum of the relative // errors |err(y)/y|+|err(x)/x| var mc = new MathContext(System.Math.Min(x.Precision, y.Precision)); return resul.Round(mc); }
public static BigDecimal MultiplyRound(BigDecimal x, BigInteger n) { BigDecimal resul = x.Multiply(new BigDecimal(n)); // The estimation of the absolute error in the result is |n*err(x)| var mc = new MathContext(n.CompareTo(BigInteger.Zero) != 0 ? x.Precision : 0); return resul.Round(mc); }
public static BigDecimal Zeta(int n, MathContext mc) { if (n <= 0) throw new NotSupportedException("Zeta at negative argument " + n + " not supported"); if (n == 1) throw new ArithmeticException("Pole at zeta(1) "); if (n%2 == 0) { /* Even indices. Abramowitz-Stegun 23.2.16. Start with 2^(n-1)*B(n)/n! */ Rational b = Bernoulli.Default[n].Abs(); b = b.Divide(Factorial.Default[n]); b = b.Multiply(BigInteger.One.ShiftLeft(n - 1)); /* to be multiplied by pi^n. Absolute error in the result of pi^n is n times * error in pi times pi^(n-1). Relative error is n*error(pi)/pi, requested by mc. * Need one more digit in pi if n=10, two digits if n=100 etc, and add one extra digit. */ var mcpi = new MathContext(mc.Precision + (int) (System.Math.Log10(10.0*n))); BigDecimal piton = PiRound(mcpi).Pow(n, mc); return MultiplyRound(piton, b); } if (n == 3) { /* Broadhurst BBP <a href="http://arxiv.org/abs/math/9803067">arXiv:math/9803067</a> * Error propagation: S31 is roughly 0.087, S33 roughly 0.131 */ int[] a31 = {1, -7, -1, 10, -1, -7, 1, 0}; int[] a33 = {1, 1, -1, -2, -1, 1, 1, 0}; BigDecimal S31 = BroadhurstBbp(3, 1, a31, mc); BigDecimal S33 = BroadhurstBbp(3, 3, a33, mc); S31 = S31.Multiply(new BigDecimal(48)); S33 = S33.Multiply(new BigDecimal(32)); return S31.Add(S33).Divide(new BigDecimal(7), mc); } if (n == 5) { /* Broadhurst BBP <a href=http://arxiv.org/abs/math/9803067">arXiv:math/9803067</a> * Error propagation: S51 is roughly -11.15, S53 roughly 22.165, S55 is roughly 0.031 * 9*2048*S51/6265 = -3.28. 7*2038*S53/61651= 5.07. 738*2048*S55/61651= 0.747. * The result is of the order 1.03, so we add 2 digits to S51 and S52 and one digit to S55. */ int[] a51 = {31, -1614, -31, -6212, -31, -1614, 31, 74552}; int[] a53 = {173, 284, -173, -457, -173, 284, 173, -111}; int[] a55 = {1, 0, -1, -1, -1, 0, 1, 1}; BigDecimal S51 = BroadhurstBbp(5, 1, a51, new MathContext(2 + mc.Precision)); BigDecimal S53 = BroadhurstBbp(5, 3, a53, new MathContext(2 + mc.Precision)); BigDecimal S55 = BroadhurstBbp(5, 5, a55, new MathContext(1 + mc.Precision)); S51 = S51.Multiply(new BigDecimal(18432)); S53 = S53.Multiply(new BigDecimal(14336)); S55 = S55.Multiply(new BigDecimal(1511424)); return S51.Add(S53).Subtract(S55).Divide(new BigDecimal(62651), mc); } /* Cohen et al Exp Math 1 (1) (1992) 25 */ var betsum = new Rational(); var bern = new Bernoulli(); var fact = new Factorial(); for (int npr = 0; npr <= (n + 1)/2; npr++) { Rational b = bern[2*npr].Multiply(bern[n + 1 - 2*npr]); b = b.Divide(fact[2*npr]).Divide(fact[n + 1 - 2*npr]); b = b.Multiply(1 - 2*npr); if (npr%2 == 0) betsum = betsum.Add(b); else betsum = betsum.Subtract(b); } betsum = betsum.Divide(n - 1); /* The first term, including the facor (2pi)^n, is essentially most * of the result, near one. The second term below is roughly in the range 0.003 to 0.009. * So the precision here is matching the precisionn requested by mc, and the precision * requested for 2*pi is in absolute terms adjusted. */ var mcloc = new MathContext(2 + mc.Precision + (int) (System.Math.Log10(n))); BigDecimal ftrm = PiRound(mcloc).Multiply(new BigDecimal(2)); ftrm = ftrm.Pow(n); ftrm = MultiplyRound(ftrm, betsum.ToBigDecimal(mcloc)); var exps = new BigDecimal(0); /* the basic accuracy of the accumulated terms before multiplication with 2 */ double eps = System.Math.Pow(10d, -mc.Precision); if (n%4 == 3) { /* since the argument n is at least 7 here, the drop * of the terms is at rather constant pace at least 10^-3, for example * 0.0018, 0.2e-7, 0.29e-11, 0.74e-15 etc for npr=1,2,3.... We want 2 times these terms * fall below eps/10. */ int kmax = mc.Precision/3; eps /= kmax; /* need an error of eps for 2/(exp(2pi)-1) = 0.0037 * The absolute error is 4*exp(2pi)*err(pi)/(exp(2pi)-1)^2=0.0075*err(pi) */ BigDecimal exp2p = PiRound(new MathContext(3 + ErrorToPrecision(3.14, eps/0.0075))); exp2p = Exp(exp2p.Multiply(new BigDecimal(2))); BigDecimal c = exp2p.Subtract(BigDecimal.One); exps = DivideRound(1, c); for (int npr = 2; npr <= kmax; npr++) { /* the error estimate above for npr=1 is the worst case of * the absolute error created by an error in 2pi. So we can * safely re-use the exp2p value computed above without * reassessment of its error. */ c = PowRound(exp2p, npr).Subtract(BigDecimal.One); c = MultiplyRound(c, (BigInteger.ValueOf(npr)).Pow(n)); c = DivideRound(1, c); exps = exps.Add(c); } } else { /* since the argument n is at least 9 here, the drop * of the terms is at rather constant pace at least 10^-3, for example * 0.0096, 0.5e-7, 0.3e-11, 0.6e-15 etc. We want these terms * fall below eps/10. */ int kmax = (1 + mc.Precision)/3; eps /= kmax; /* need an error of eps for 2/(exp(2pi)-1)*(1+4*Pi/8/(1-exp(-2pi)) = 0.0096 * at k=7 or = 0.00766 at k=13 for example. * The absolute error is 0.017*err(pi) at k=9, 0.013*err(pi) at k=13, 0.012 at k=17 */ BigDecimal twop = PiRound(new MathContext(3 + ErrorToPrecision(3.14, eps/0.017))); twop = twop.Multiply(new BigDecimal(2)); BigDecimal exp2p = Exp(twop); BigDecimal c = exp2p.Subtract(BigDecimal.One); exps = DivideRound(1, c); c = BigDecimal.One.Subtract(DivideRound(1, exp2p)); c = DivideRound(twop, c).Multiply(new BigDecimal(2)); c = DivideRound(c, n - 1).Add(BigDecimal.One); exps = MultiplyRound(exps, c); for (int npr = 2; npr <= kmax; npr++) { c = PowRound(exp2p, npr).Subtract(BigDecimal.One); c = MultiplyRound(c, (BigInteger.ValueOf(npr)).Pow(n)); BigDecimal d = DivideRound(1, exp2p.Pow(npr)); d = BigDecimal.One.Subtract(d); d = DivideRound(twop, d).Multiply(new BigDecimal(2*npr)); d = DivideRound(d, n - 1).Add(BigDecimal.One); d = DivideRound(d, c); exps = exps.Add(d); } } exps = exps.Multiply(new BigDecimal(2)); return ftrm.Subtract(exps, mc); }
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"); }
public void MultiplyWithContext(string a, int aScale, string b, int bScale, string c, int cScale, int precision, RoundingMode roundingMode) { BigDecimal aNumber = new BigDecimal(BigInteger.Parse(a), aScale); BigDecimal bNumber = new BigDecimal(BigInteger.Parse(b), bScale); MathContext mc = new MathContext(precision, roundingMode); BigDecimal result = aNumber.Multiply(bNumber, mc); Assert.AreEqual(c, result.ToString(), "incorrect value"); Assert.AreEqual(cScale, result.Scale, "incorrect scale"); }
static void Main(string[] args) { // Parse parameters var pIndex = Array.IndexOf(args, PRECISION_PARAM); var precision = pIndex >= 0 ? int.Parse(args[pIndex + 1]) : -1; var tIndex = Array.IndexOf(args, THREADS_PARAM); var threadsCount = tIndex >= 0 ? int.Parse(args[tIndex + 1]) : -1; var oIndex = Array.IndexOf(args, OUTPUT_FILE_PARAM); var outputFilename = oIndex >= 0 ? args[oIndex + 1] : DEFAULT_FILENAME; var isQuiet = Array.IndexOf(args, QUIET_MODE_PARAM); // Calculate PI BigDecimal sum = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); Parallel.For(0, precision, new ParallelOptions() { MaxDegreeOfParallelism = threadsCount }, i => { var currentThreadId = Thread.CurrentThread.ManagedThreadId; if (isQuiet < 0) { Console.WriteLine("Thread-" + currentThreadId + " started."); } BigDecimal numerator; if (i % 2 == 0) { numerator = MultiplyRange(i + 1, 4 * i) * (1123 + (21460 * i)); } else { numerator = -MultiplyRange(i + 1, 4 * i) * (1123 + (21460 * i)); } BigDecimal denominator = (Factorial(i).Pow(3)).Multiply((new BigDecimal(14112)).Pow(2 * i)); BigDecimal currentAddition = numerator / denominator; sum = sum.Add(currentAddition); if (isQuiet < 0) { Console.WriteLine("Thread-" + currentThreadId + " stopped."); } }); BigDecimal constant = new BigDecimal((double)1 / 3528); BigDecimal opposite = constant.Multiply(sum); BigDecimal pi = new BigDecimal(1 / opposite.ToDouble()); stopwatch.Stop(); if (isQuiet < 0) { Console.WriteLine("Pi is: " + pi); } Console.WriteLine("Threads used in current execution: " + threadsCount); var totalExecutionTime = stopwatch.ElapsedMilliseconds; Console.WriteLine("Total execution time with precision of " + precision + " terms in the series: " + totalExecutionTime + " ms"); // ------------------------------------------------ // Optimized BigDecimal sum2 = 0; var stopwatch2 = new Stopwatch(); stopwatch2.Start(); var factorials = CalculateFactorials(4 * precision); Parallel.For(0, precision, new ParallelOptions() { MaxDegreeOfParallelism = threadsCount }, i => { BigDecimal numerator; if (i % 2 == 0) { numerator = (factorials[4 * i] / factorials[i]) * (1123 + (21460 * i)); } else { numerator = -(factorials[4 * i] / factorials[i]) * (1123 + (21460 * i)); } BigDecimal denominator = (factorials[i].Pow(3)).Multiply((new BigDecimal(14112)).Pow(2 * i)); BigDecimal currentAddition = numerator / denominator; sum2 = sum2.Add(currentAddition); }); BigDecimal constant2 = new BigDecimal((double)1 / 3528); BigDecimal opposite2 = constant2.Multiply(sum2); BigDecimal pi2 = new BigDecimal(1 / opposite2.ToDouble()); stopwatch2.Stop(); Console.WriteLine("Pi: " + pi2); Console.WriteLine("Threads used in current execution: " + threadsCount); var totalExecutionTime2 = stopwatch2.ElapsedMilliseconds; Console.WriteLine("Total execution time with precision of " + precision + " terms in the series: " + totalExecutionTime2 + " ms"); // Write result to file //using (StreamWriter writer = new StreamWriter(outputFilename)) //{ // writer.WriteLine("Pi is: " + pi); // writer.WriteLine("Total execution time with " + threadsCount + " threads and precision " + precision + ": " + totalExecutionTime + " ms"); //} }
public static BigDecimal Pow(BigDecimal x, BigDecimal y) { if (x.CompareTo(BigDecimal.Zero) < 0) throw new ArithmeticException("Cannot power negative " + x); if (x.CompareTo(BigDecimal.Zero) == 0) return BigDecimal.Zero; /* return x^y = exp(y*log(x)) ; */ BigDecimal logx = Log(x); BigDecimal ylogx = y.Multiply(logx); BigDecimal resul = Exp(ylogx); /* The estimation of the relative error in the result is |log(x)*err(y)|+|y*err(x)/x| */ double errR = System.Math.Abs(logx.ToDouble())*y.Ulp().ToDouble()/2d + System.Math.Abs(y.ToDouble()*x.Ulp().ToDouble()/2d/x.ToDouble()); var mcR = new MathContext(ErrorToPrecision(1.0, errR)); return resul.Round(mcR); }