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)); }
/// <summary>Returns a list of BigDecimals one element longer than the list of input splits. /// </summary> /// <remarks> /// Returns a list of BigDecimals one element longer than the list of input splits. /// This represents the boundaries between input splits. /// All splits are open on the top end, except the last one. /// So the list [0, 5, 8, 12, 18] would represent splits capturing the intervals: /// [0, 5) /// [5, 8) /// [8, 12) /// [12, 18] note the closed interval for the last split. /// </remarks> /// <exception cref="Java.Sql.SQLException"/> internal virtual IList <BigDecimal> Split(BigDecimal numSplits, BigDecimal minVal, BigDecimal maxVal) { IList <BigDecimal> splits = new AList <BigDecimal>(); // Use numSplits as a hint. May need an extra task if the size doesn't // divide cleanly. BigDecimal splitSize = TryDivide(maxVal.Subtract(minVal), (numSplits)); if (splitSize.CompareTo(MinIncrement) < 0) { splitSize = MinIncrement; Log.Warn("Set BigDecimal splitSize to MIN_INCREMENT"); } BigDecimal curVal = minVal; while (curVal.CompareTo(maxVal) <= 0) { splits.AddItem(curVal); curVal = curVal.Add(splitSize); } if (splits[splits.Count - 1].CompareTo(maxVal) != 0 || splits.Count == 1) { // We didn't end on the maxVal. Add that to the end of the list. splits.AddItem(maxVal); } return(splits); }
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); }
/* * This method shows use of optional payment details and item list. */ private PayPalPayment getStuffToBuy(string paymentIntent) { //--- include an item list, payment amount details PayPalItem[] items = { new PayPalItem("sample item #1", new Java.Lang.Integer(2), new BigDecimal("87.50"), "USD", "sku-12345678"), new PayPalItem("free sample item #2", new Java.Lang.Integer(1), new BigDecimal("0.00"), "USD", "sku-zero-price"), new PayPalItem("sample item #3 with a longer name", new Java.Lang.Integer(6), new BigDecimal("37.99"), "USD", "sku-33333") }; BigDecimal subtotal = PayPalItem.GetItemTotal(items); BigDecimal shipping = new BigDecimal("7.21"); BigDecimal tax = new BigDecimal("4.67"); PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax); BigDecimal amount = subtotal.Add(shipping).Add(tax); PayPalPayment payment = new PayPalPayment(amount, "USD", "sample item", paymentIntent); payment.Items(items).PaymentDetails(paymentDetails); //--- set other optional fields like invoice_number, custom field, and soft_descriptor payment.Custom("This is text that will be associated with the payment that the app can use."); return(payment); }
public override Number Calculate(BigDecimal bigDecimal1, BigDecimal bigDecimal2) { if (bigDecimal1 == null || bigDecimal2 == null) { return(0); } return(bigDecimal1.Add(bigDecimal2)); }
public void Add(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.Add(leftDecimal, rightDecimal)); }
public void Add(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.Add(bNumber); Assert.AreEqual(c, result.ToString(), "incorrect value"); Assert.AreEqual(cScale, result.Scale, "incorrect scale"); }
public void AddTest3() { var v1 = BigDecimal.MinusOne; var v2 = BigDecimal.MinusOne; var res = BigDecimal.Add(v1, v2); Assert.AreEqual(new BigDecimal(-2), res); }
/// <summary> /// Convert a <c>BigDecimal</c> datetime from the given time scale to /// the universal time scale. All calculations are done using /// <c>BigDecimal</c> to guarantee that the value does not go out of /// range. /// </summary> /// /// <param name="otherTime">The <c>BigDecimal</c> datetime</param> /// <param name="timeScale">The time scale to convert from</param> /// <returns>The datetime converted to the universal time scale</returns> /// @stable ICU 3.2 public static BigDecimal BigDecimalFrom(BigDecimal otherTime, int timeScale) { UniversalTimeScale.TimeScaleData data = GetTimeScaleData(timeScale); BigDecimal units_0 = new BigDecimal(data.units); BigDecimal epochOffset_1 = new BigDecimal(data.epochOffset); return(otherTime.Add(epochOffset_1).Multiply(units_0)); }
public void AddWithContext(string a, int aScale, string b, int bScale, string c, int cScale, int precision, RoundingMode mode) { BigDecimal aNumber = new BigDecimal(BigInteger.Parse(a), aScale); BigDecimal bNumber = new BigDecimal(BigInteger.Parse(b), bScale); MathContext mc = new MathContext(precision, mode); BigDecimal result = aNumber.Add(bNumber, mc); Assert.AreEqual(c, result.ToString(), "incorrect value"); Assert.AreEqual(cScale, result.Scale, "incorrect scale"); }
public void AddTest2() { var v1 = new BigDecimal(0.01m); var v2 = new BigDecimal(0.00001m); var res = BigDecimal.Add(v1, v2); Assert.AreEqual(new BigDecimal(0.01001m), res); }
public void AddTest4() { var v1 = new BigDecimal((BigInteger)ulong.MaxValue); var v2 = BigDecimal.One; var res = BigDecimal.Add(v1, v2); var bigInt = new BigInteger(ulong.MaxValue) + 1; Assert.AreEqual(new BigDecimal(bigInt), res); }
public void Add_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.Add(right); Assert.AreEqual(expected, actual.ToString(), message); }
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>(); }
public Number Add(Number number) { if (numberState == NumberState.None) { if (number.numberState == NumberState.None) { return(new Number(NumberState.None, bigDecimal.Add(number.bigDecimal))); } return(new Number(number.numberState, null)); } return(new Number(numberState, null)); }
// 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); }
/** * * @param lineItems List of {@link com.google.android.gms.wallet.LineItem} used for calculating * the cart total. * @return cart total. */ private static String calculateCartTotal(List <LineItem> lineItems) { BigDecimal cartTotal = BigDecimal.Zero; // Calculate the total price by adding up each of the line items foreach (var lineItem in lineItems) { BigDecimal lineItemTotal = lineItem.TotalPrice == null ? new BigDecimal(lineItem.UnitPrice) .Multiply(new BigDecimal(lineItem.Quantity)) : new BigDecimal(lineItem.TotalPrice); cartTotal = cartTotal.Add(lineItemTotal); } return(cartTotal.SetScale(2, RoundingMode.HalfEven).ToString()); }
public static BigDecimal ToDecimal(string s) { s = s.Replace(" ", string.Empty); char[] c = new char[4]; c[0] = '+'; c[1] = '-'; c[2] = '*'; c[3] = '/'; TotalValue = BigDecimal.Zero; string[] str = s.Split('(', ')'); str = Referesh(str); string cast = ""; for (int i = 0; i < str.Length; i++) { if (IsVaidCaculate(str[i])) { sum = 0; ToChangeDecimal(ref str[i], c); TotalValue = TotalValue.Add(sum); } cast += str[i]; cast = cast.Replace(" ", string.Empty); } //Check case if value = 5 or value = (5 + 2) if (str.Length == 1 && IsDigit(str[0])) { str[0] = str[0].Replace(" ", string.Empty); return(BigDecimal.Parse(str[0])); } cast = cast.Trim().Replace("--", "+"); if (str.Length != 1 || !IsDigitString(str)) { sum = 0; ToChangeDecimal(ref cast, c); TotalValue = sum; } return(TotalValue); }
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 Add(SqlNumber value) { if (State == NumericState.None) { if (value.State == NumericState.None) { if (IsNull || value.IsNull) { return(Null); } return(new SqlNumber(NumericState.None, innerValue.Add(value.innerValue))); } return(new SqlNumber(value.State, null)); } return(new SqlNumber(State, null)); }
public static BigDecimal ToDecimal(this string s) { char[] c = new char[4]; c[0] = '+'; c[1] = '-'; c[2] = '*'; c[3] = '/'; TotalValue = BigDecimal.Zero; string[] str = s.Split('(', ')'); string cast = ""; for (int i = 0; i < str.Length; i++) { if (IsVaidCaculate(str[i])) { sum = 0; ToChangeDecimal(ref str[i], c); TotalValue = TotalValue.Add(sum); } cast += str[i]; cast = cast.Replace(" ", string.Empty); } cast = cast.Trim().Replace("--", "+"); if (!IsDigitString(str)) { sum = 0; ToChangeDecimal(ref cast, c); TotalValue = sum; } return(TotalValue); }
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."); }
private static string ResolveExpression(string s, string express) { s = s.Replace(" ", string.Empty); s = s.Trim().Replace("(-", "(0-"); if (s.Length > 1 && s[0].Equals('π')) { s = s.Trim().Replace("π", $"{Math.PI}"); } if (s.Length > 1 && s[0].Equals('e')) { s = s.Trim().Replace("e", $"{Math.E}"); } s = s.Trim().Replace("+π", $"+{Math.PI}"); s = s.Trim().Replace("(π", $"({Math.PI}"); s = s.Trim().Replace("-π", $"-{Math.PI}"); s = s.Trim().Replace("*π", $"*{Math.PI}"); s = s.Trim().Replace("/π", $"/{Math.PI}"); s = s.Trim().Replace("+e", $"+{Math.E}"); s = s.Trim().Replace("(e", $"({Math.E}"); s = s.Trim().Replace("-e", $"-{Math.E}"); s = s.Trim().Replace("*e", $"*{Math.E}"); s = s.Trim().Replace("/e", $"/{Math.E}"); s = s.Trim().Replace("π", $"*{Math.PI}"); s = s.Trim().Replace("e", $"*{Math.E}"); string output; char[] c = new char[4]; c[0] = '+'; c[1] = '-'; c[2] = '*'; c[3] = '/'; while (s.IndexOf(express) != -1) { string[] str = s.Split('(', ')'); str = Referesh(str); string cast = ""; for (int i = 0; i < str.Length; i++) { if (IsVaidCaculate(str[i])) { sum = 0; ToChangeDecimal(ref str[i], c); TotalValue = TotalValue.Add(sum); } if (IsDigit(str[i]) && IsDigit(str[i])) { cast += "(" + str[i] + ")"; } else { cast += str[i]; } cast = cast.Replace(" ", string.Empty); } //Solve bugs sin(sqrt(2)), but result sinsqrt(2)+1 //cast = sinsqrt(2)+1 //partCuting = sinsqrt(2) //resolveCutting = sin(sqrt(2)) // cast = cast.replace(partCuting, resolveCutting)); if (cast.Contains("sqrt") || cast.Contains("ln")) { int start = cast.IndexOf(express); string partCutting = cast.Substring(start, IndexOfLast(cast, start, c) - start); string resolveCutting = partCutting.Replace(express, express + "("); resolveCutting += ")"; cast = cast.Replace(partCutting, resolveCutting); output = cast.Substring(start, IndexOfLast(cast, start, c) - start); } else { output = cast; } Expression e = new Expression(output); BigDecimal bigDecimal = BigDecimal.Parse(e.calculate().ToString()); s = cast.Replace(output, bigDecimal.ToPlainString()); } return(s); }
public static Number operator +(Number a, Number b) { return(BigDecimal.Add(new BigDecimal.Config(), a.value, b.value)); }
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 static BigDecimal AddRound(BigDecimal x, BigDecimal y) { BigDecimal resul = x.Add(y); /* The estimation of the absolute error in the result is |err(y)|+|err(x)| */ double errR = System.Math.Abs(y.Ulp().ToDouble()/2d) + System.Math.Abs(x.Ulp().ToDouble()/2d); MathContext mc = new MathContext(ErrorToPrecision(resul.ToDouble(), errR)); return resul.Round(mc); }
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; }
public void AddTest() { var res = BigDecimal.Add(BigDecimal.One, BigDecimal.One); Assert.AreEqual(new BigDecimal(2), res); }
public void BuyItems( PayPal.Forms.Abstractions.PayPalItem[] items, Decimal xfshipping, Decimal xftax, PaymentIntent xfintent, Action onCancelled, Action <string> onSuccess, Action <string> onError, PayPal.Forms.Abstractions.ShippingAddress address ) { OnCancelled = onCancelled; OnSuccess = onSuccess; OnError = onError; List <PayPalItem> nativeItems = new List <PayPalItem> (); foreach (var product in items) { nativeItems.Add(new PayPalItem( product.Name, new Java.Lang.Integer((int)product.Quantity), new BigDecimal(RoundNumber((double)product.Price)), product.Currency, product.SKU) ); } BigDecimal subtotal = PayPalItem.GetItemTotal(nativeItems.ToArray()); BigDecimal shipping = new BigDecimal(RoundNumber((double)xfshipping)); BigDecimal tax = new BigDecimal(RoundNumber((double)xftax)); PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax); BigDecimal amount = subtotal.Add(shipping).Add(tax); string paymentIntent; switch (xfintent) { case PaymentIntent.Authorize: paymentIntent = PayPalPayment.PaymentIntentAuthorize; break; case PaymentIntent.Order: paymentIntent = PayPalPayment.PaymentIntentOrder; break; default: case PaymentIntent.Sale: paymentIntent = PayPalPayment.PaymentIntentSale; break; } PayPalPayment payment = new PayPalPayment(amount, nativeItems.FirstOrDefault().Currency, "Multiple items", paymentIntent); payment = payment.Items(nativeItems.ToArray()).PaymentDetails(paymentDetails); if (address != null) { ShippingAddress shippingAddress = new ShippingAddress() .RecipientName(address.RecipientName) .Line1(address.Line1) .Line2(address.Line2) .City(address.City) .State(address.State) .PostalCode(address.PostalCode) .CountryCode(address.CountryCode); payment = payment.InvokeProvidedShippingAddress(shippingAddress); } switch (_xfconfig.ShippingAddressOption) { case Abstractions.Enum.ShippingAddressOption.Both: case Abstractions.Enum.ShippingAddressOption.PayPal: payment = payment.EnablePayPalShippingAddressesRetrieval(true); break; default: payment = payment.EnablePayPalShippingAddressesRetrieval(false); break; } Intent intent = new Intent(Context, typeof(PaymentActivity)); intent.PutExtra(PayPalService.ExtraPaypalConfiguration, config); intent.PutExtra(PaymentActivity.ExtraPayment, payment); (Context as Activity).StartActivityForResult(intent, REQUEST_CODE_PAYMENT); }
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 override Number Calculate(BigDecimal bigDecimal1, BigDecimal bigDecimal2) { if (bigDecimal1 == null || bigDecimal2 == null) { return 0; } return bigDecimal1.Add(bigDecimal2); }
private static BigDecimal AddBigDecimal(BigDecimal value1, BigDecimal value2) { return(value1.Add(value2)); }
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 static BigDecimal Add(BigDecimal x, BigInteger y) { return x.Add(new BigDecimal(y)); }
public static BigDecimal /*!*/ Add(RubyContext /*!*/ context, BigDecimal /*!*/ self, [NotNull] BigInteger /*!*/ other) { BigDecimal.Config config = GetConfig(context); return(BigDecimal.Add(config, self, BigDecimal.Create(config, other))); }
public static BigDecimal /*!*/ Add(RubyContext /*!*/ context, BigDecimal /*!*/ self, [NotNull] BigDecimal /*!*/ other, int n) { return(BigDecimal.Add(GetConfig(context), self, other, n)); }
public static BigDecimal /*!*/ Add(RubyContext /*!*/ context, BigDecimal /*!*/ self, double other, int n) { BigDecimal.Config config = GetConfig(context); return(BigDecimal.Add(config, self, BigDecimal.Create(config, other), n)); }
public void ToDouble() { BigDecimal bigDB = new BigDecimal(-1.234E-112); // Commenting out this part because it causes an endless loop (see HARMONY-319 and HARMONY-329) // Assert.IsTrue( // "the double representation of this BigDecimal is not correct", // bigDB.ToDouble() == -1.234E-112); bigDB = new BigDecimal(5.00E-324); Assert.IsTrue(bigDB.ToDouble() == 5.00E-324, "the double representation of bigDecimal is not correct"); bigDB = new BigDecimal(1.79E308); Assert.IsTrue(bigDB.ToDouble() == 1.79E308 && bigDB.Scale == 0, "the double representation of bigDecimal is not correct"); bigDB = new BigDecimal(-2.33E102); Assert.IsTrue(bigDB.ToDouble() == -2.33E102 && bigDB.Scale == 0, "the double representation of bigDecimal -2.33E102 is not correct"); bigDB = new BigDecimal(Double.MaxValue); bigDB = bigDB.Add(bigDB); Assert.IsTrue(bigDB.ToDouble() == Double.PositiveInfinity, "a + number out of the double range should return infinity"); bigDB = new BigDecimal(-Double.MaxValue); bigDB = bigDB.Add(bigDB); Assert.IsTrue(bigDB.ToDouble() == Double.NegativeInfinity, "a - number out of the double range should return neg infinity"); }