List of usage examples for java.math MathContext MathContext
public MathContext(String val)
From source file:com.espertech.esper.client.ConfigurationParser.java
private static void handleExpression(Configuration configuration, Element parentElement) { String integerDivision = getOptionalAttribute(parentElement, "integer-division"); if (integerDivision != null) { boolean isIntegerDivision = Boolean.parseBoolean(integerDivision); configuration.getEngineDefaults().getExpression().setIntegerDivision(isIntegerDivision); }//from ww w . j a v a 2s. c o m String divZero = getOptionalAttribute(parentElement, "division-by-zero-is-null"); if (divZero != null) { boolean isDivZero = Boolean.parseBoolean(divZero); configuration.getEngineDefaults().getExpression().setDivisionByZeroReturnsNull(isDivZero); } String udfCache = getOptionalAttribute(parentElement, "udf-cache"); if (udfCache != null) { boolean isUdfCache = Boolean.parseBoolean(udfCache); configuration.getEngineDefaults().getExpression().setUdfCache(isUdfCache); } String selfSubselectPreeval = getOptionalAttribute(parentElement, "self-subselect-preeval"); if (selfSubselectPreeval != null) { boolean isSelfSubselectPreeval = Boolean.parseBoolean(selfSubselectPreeval); configuration.getEngineDefaults().getExpression().setSelfSubselectPreeval(isSelfSubselectPreeval); } String extendedAggregationStr = getOptionalAttribute(parentElement, "extended-agg"); if (extendedAggregationStr != null) { boolean extendedAggregation = Boolean.parseBoolean(extendedAggregationStr); configuration.getEngineDefaults().getExpression().setExtendedAggregation(extendedAggregation); } String duckTypingStr = getOptionalAttribute(parentElement, "ducktyping"); if (duckTypingStr != null) { boolean duckTyping = Boolean.parseBoolean(duckTypingStr); configuration.getEngineDefaults().getExpression().setDuckTyping(duckTyping); } String mathContextStr = getOptionalAttribute(parentElement, "math-context"); if (mathContextStr != null) { try { MathContext mathContext = new MathContext(mathContextStr); configuration.getEngineDefaults().getExpression().setMathContext(mathContext); } catch (IllegalArgumentException ex) { throw new ConfigurationException("Failed to parse '" + mathContextStr + "' as a MathContext"); } } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Pochhammers function./*from ww w .ja v a 2s .c o m*/ * * @param x The main argument. * @param n The non-negative index. * @return (x)_n = x(x+1)(x+2)*...*(x+n-1). */ static public BigDecimal pochhammer(final BigDecimal x, final int n) { /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33 */ if (n < 0) { throw new ProviderException("Unimplemented pochhammer with negative index " + n); } else if (n == 0) { return BigDecimal.ONE; } else { /* internally two safety digits */ BigDecimal xhighpr = scalePrec(x, 2); BigDecimal resul = xhighpr; double xUlpDbl = x.ulp().doubleValue(); double xDbl = x.doubleValue(); /* relative error of the result is the sum of the relative errors of the factors */ double eps = 0.5 * xUlpDbl / Math.abs(xDbl); for (int i = 1; i < n; i++) { eps += 0.5 * xUlpDbl / Math.abs(xDbl + i); resul = resul.multiply(xhighpr.add(new BigDecimal(i))); final MathContext mcloc = new MathContext(4 + err2prec(eps)); resul = resul.round(mcloc); } return resul.round(new MathContext(err2prec(eps))); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Reduce value to the interval [0,2*Pi]. * * @param x the original value//from w ww . j a v a 2 s .co m * @return the value modulo 2*pi in the interval from 0 to 2*pi. */ static public BigDecimal mod2pi(BigDecimal x) { /* write x= 2*pi*k+r with the precision in r defined by the precision of x and not * compromised by the precision of 2*pi, so the ulp of 2*pi*k should match the ulp of x. * First getFloat a guess of k to figure out how many digits of 2*pi are needed. */ int k = (int) (0.5 * x.doubleValue() / Math.PI); /* want to have err(2*pi*k)< err(x)=0.5*x.ulp, so err(pi) = err(x)/(4k) with two safety digits */ double err2pi; if (k != 0) { err2pi = 0.25 * Math.abs(x.ulp().doubleValue() / k); } else { err2pi = 0.5 * Math.abs(x.ulp().doubleValue()); } MathContext mc = new MathContext(2 + err2prec(6.283, err2pi)); BigDecimal twopi = pi(mc).multiply(new BigDecimal(2)); /* Delegate the actual operation to the BigDecimal class, which may return * a negative value of x was negative . */ BigDecimal res = x.remainder(twopi); if (res.compareTo(BigDecimal.ZERO) < 0) { res = res.add(twopi); } /* The actual precision is set by the input value, its absolute value of x.ulp()/2. */ mc = new MathContext(err2prec(res.doubleValue(), x.ulp().doubleValue() / 2.)); return res.round(mc); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Reduce value to the interval [-Pi/2,Pi/2]. * * @param x The original value/*from w ww .j a v a 2 s .c om*/ * @return The value modulo pi, shifted to the interval from -Pi/2 to Pi/2. */ static public BigDecimal modpi(BigDecimal x) { /* write x= pi*k+r with the precision in r defined by the precision of x and not * compromised by the precision of pi, so the ulp of pi*k should match the ulp of x. * First getFloat a guess of k to figure out how many digits of pi are needed. */ int k = (int) (x.doubleValue() / Math.PI); /* want to have err(pi*k)< err(x)=x.ulp/2, so err(pi) = err(x)/(2k) with two safety digits */ double errpi; if (k != 0) { errpi = 0.5 * Math.abs(x.ulp().doubleValue() / k); } else { errpi = 0.5 * Math.abs(x.ulp().doubleValue()); } MathContext mc = new MathContext(2 + err2prec(3.1416, errpi)); BigDecimal onepi = pi(mc); BigDecimal pihalf = onepi.divide(new BigDecimal(2)); /* Delegate the actual operation to the BigDecimal class, which may return * a negative value of x was negative . */ BigDecimal res = x.remainder(onepi); if (res.compareTo(pihalf) > 0) { res = res.subtract(onepi); } else if (res.compareTo(pihalf.negate()) < 0) { res = res.add(onepi); } /* The actual precision is set by the input value, its absolute value of x.ulp()/2. */ mc = new MathContext(err2prec(res.doubleValue(), x.ulp().doubleValue() / 2.)); return res.round(mc); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Riemann zeta function./*ww w. j a v a2s. com*/ * * @param n The positive integer argument. * 32 * @param mc Specification of the accuracy of the result. * @return zeta(n). */ static public BigDecimal zeta(final int n, final MathContext mc) { if (n <= 0) { throw new ProviderException("Unimplemented zeta at negative argument " + n); } 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 = (new Bernoulli()).at(n).abs(); b = b.divide((new Factorial()).at(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. */ MathContext mcpi = new MathContext(mc.getPrecision() + (int) (Math.log10(10.0 * n))); final BigDecimal piton = pi(mcpi).pow(n, mc); return multiplyRound(piton, b); } else if (n == 3) { /* Broadhurst BBP \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067} * 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); } else if (n == 5) { /* Broadhurst BBP \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067} * 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.getPrecision())); BigDecimal S53 = broadhurstBBP(5, 3, a53, new MathContext(2 + mc.getPrecision())); BigDecimal S55 = broadhurstBBP(5, 5, a55, new MathContext(1 + mc.getPrecision())); 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); } else { /* Cohen et al Exp Math 1 (1) (1992) 25 */ Rational betsum = new Rational(); Bernoulli bern = new Bernoulli(); Factorial fact = new Factorial(); for (int npr = 0; npr <= (n + 1) / 2; npr++) { Rational b = bern.at(2 * npr).multiply(bern.at(n + 1 - 2 * npr)); b = b.divide(fact.at(2 * npr)).divide(fact.at(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. */ MathContext mcloc = new MathContext(2 + mc.getPrecision() + (int) (Math.log10((double) (n)))); BigDecimal ftrm = pi(mcloc).multiply(new BigDecimal(2)); ftrm = ftrm.pow(n); ftrm = multiplyRound(ftrm, betsum.BigDecimalValue(mcloc)); BigDecimal exps = new BigDecimal(0); /* the basic accuracy of the accumulated terms before multiplication with 2 */ double eps = Math.pow(10., -mc.getPrecision()); 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.getPrecision() / 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 = pi(new MathContext(3 + err2prec(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, (new BigInteger("" + 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.getPrecision()) / 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 = pi(new MathContext(3 + err2prec(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, (new BigInteger("" + 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); } }
From source file:org.mifos.accounts.loan.business.LoanCalculationIntegrationTest.java
private Results calculatePayments(InternalConfiguration config, AccountBO accountBO, LoanParameters loanParams) {//from w w w . ja va 2 s. co m Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO).getAccountActionDates(); LoanScheduleEntity[] paymentsArray = LoanBOTestUtils.getSortedAccountActionDateEntity(actionDateEntities, loanParams.getNumberOfPayments()); MathContext context = new MathContext(config.getInternalPrecision()); BigDecimal totalPrincipal = new BigDecimal(0, context); BigDecimal totalInterest = new BigDecimal(0, context); BigDecimal totalFees = new BigDecimal(0, context); Money totalPayments = new Money(getCurrency(), "0"); Results calculatedResult = new Results(); List<PaymentDetail> payments = new ArrayList<PaymentDetail>(); for (LoanScheduleEntity loanEntry : paymentsArray) { PaymentDetail payment = new PaymentDetail(); Money calculatedPayment = new Money(getCurrency(), loanEntry.getPrincipal().getAmount().add( loanEntry.getInterest().getAmount().add(loanEntry.getTotalFeesDueWithMiscFee().getAmount()))); payment.setPayment(calculatedPayment); payment.setInterest(loanEntry.getInterest()); payment.setPrincipal(loanEntry.getPrincipal()); payment.setFee(loanEntry.getTotalFeesDueWithMiscFee()); totalPrincipal = totalPrincipal.add(loanEntry.getPrincipal().getAmount()); totalInterest = totalInterest.add(loanEntry.getInterest().getAmount()); totalPayments = totalPayments.add(calculatedPayment); totalFees = totalFees.add(loanEntry.getTotalFeesDueWithMiscFee().getAmount()); payments.add(payment); } calculatedResult.setPayments(payments); calculatedResult.setTotalInterest(new Money(getCurrency(), totalInterest)); calculatedResult.setTotalPayments(totalPayments); calculatedResult.setTotalPrincipal(new Money(getCurrency(), totalPrincipal)); calculatedResult.setTotalFee(new Money(getCurrency(), totalFees)); /* * Set balance after each installment is paid, excluding fees or penalties. For flat-interest loans, balance is * total of all remaining principal and interest. For declining-interest loans, balance is total remaining * principal. */ if (loanParams.loanType.getValue() == InterestType.FLAT.getValue()) { Money balance = new Money(getCurrency(), totalPrincipal.add(totalInterest)); for (PaymentDetail paymentDetail : payments) { balance = balance.subtract(paymentDetail.getPrincipal()).subtract(paymentDetail.getInterest()); paymentDetail.setBalance(balance); } } else if (loanParams.loanType.getValue() == InterestType.DECLINING.getValue()) { Money balance = new Money(getCurrency(), totalPrincipal); for (PaymentDetail paymentDetail : payments) { balance = balance.subtract(paymentDetail.getPrincipal()); paymentDetail.setBalance(balance); } } return calculatedResult; }
From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java
private Validator getPaymentValidator(final DoPaymentDTO payment) { final Validator validator = new Validator("transfer"); Collection<TransactionContext> possibleContexts = new ArrayList<TransactionContext>(); possibleContexts.add(TransactionContext.PAYMENT); if (LoggedUser.isWebService() || LoggedUser.isSystem()) { possibleContexts.add(TransactionContext.AUTOMATIC); } else {//from ww w .j a v a 2 s .c o m possibleContexts.add(TransactionContext.SELF_PAYMENT); } validator.property("context").required().anyOf(possibleContexts); validator.property("to").required().key("payment.recipient"); // as currency is maybe not set on the DTO, we get it from the TT in stead of directly from the DTO final TransferType tt = fetchService.fetch(payment.getTransferType(), Relationships.TRANSACTION_FEES, RelationshipHelper.nested(TransferType.Relationships.FROM, TransferType.Relationships.TO, AccountType.Relationships.CURRENCY, Currency.Relationships.A_RATE_PARAMETERS), RelationshipHelper.nested(TransferType.Relationships.FROM, TransferType.Relationships.TO, AccountType.Relationships.CURRENCY, Currency.Relationships.D_RATE_PARAMETERS)); final Currency currency = tt == null ? null : tt.getCurrency(); if (currency != null && (currency.isEnableARate() || currency.isEnableDRate())) { // if the date is not null at this moment, it is in the past, which is not allowed with rates. if (payment.getDate() != null) { validator.general(new NoPastDateWithRatesValidator()); } } else { validator.property("date").key("payment.manualDate").past(); } validator.property("ticket").add(new TicketValidation()); addAmountValidator(validator, tt); validator.property("transferType").key("transfer.type").required(); validator.property("description").maxLength(1000); validator.general(new SchedulingValidator()); validator.general(new PendingContractValidator()); if (payment.getTransferType() != null && payment.getTo() != null && payment.getAmount() != null) { /* * For user validation, we need to check if the transaction amount is high enough to cover all fees. This depends on all fees, but only in * case of fixed fees it makes sense to increase the transaction amount. The formula for this is: given transactionamount > (sum of fixed * fees )/ (1 minus sum of percentage fees expressed as fractions). This of course only applies for fees with deductAmount; fees which are * not deducted are excluded from this calculation. */ final TransactionFeePreviewDTO preview = transactionFeeService.preview(payment.getFrom(), payment.getTo(), tt, payment.getAmount()); final Property amount = validator.property("amount"); final Collection<? extends TransactionFee> fees = preview.getFees().keySet(); BigDecimal sumOfFixedFees = BigDecimal.ZERO; BigDecimal sumOfPercentageFees = BigDecimal.ZERO; for (final TransactionFee fee : fees) { if (fee.isDeductAmount()) { if (fee.getChargeType() == ChargeType.FIXED) { sumOfFixedFees = sumOfFixedFees.add(preview.getFees().get(fee)); } else { sumOfPercentageFees = sumOfPercentageFees.add(preview.getFees().get(fee)); } } } // Show a warning if there are fixed fees and if the amount is not enough to cover them if (sumOfFixedFees.signum() == 1) { final int scale = LocalSettings.MAX_PRECISION; final MathContext mc = new MathContext(scale); final BigDecimal sumOfPercentages = sumOfPercentageFees.divide(payment.getAmount(), mc); final BigDecimal minimalAmount = sumOfFixedFees.divide((BigDecimal.ONE.subtract(sumOfPercentages)), mc); amount.comparable(minimalAmount, ">", new ValidationError("errors.greaterThan", messageResolver.message("transactionFee.invalidChargeValue", minimalAmount))); } else if (preview.getFinalAmount().signum() == -1) { validator.general(new FinalAmountValidator()); } // Custom fields validator.chained(new DelegatingValidator(new DelegatingValidator.DelegateSource() { @Override public Validator getValidator() { return paymentCustomFieldService.getValueValidator(payment.getTransferType()); } })); } return validator; }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Riemann zeta function./*from w w w .j av a 2 s .co m*/ * * @param n The positive integer argument. * @return zeta(n)-1. */ static public double zeta1(final int n) { /* precomputed static table in double precision */ final double[] zmin1 = { 0., 0., 6.449340668482264364724151666e-01, 2.020569031595942853997381615e-01, 8.232323371113819151600369654e-02, 3.692775514336992633136548646e-02, 1.734306198444913971451792979e-02, 8.349277381922826839797549850e-03, 4.077356197944339378685238509e-03, 2.008392826082214417852769232e-03, 9.945751278180853371459589003e-04, 4.941886041194645587022825265e-04, 2.460865533080482986379980477e-04, 1.227133475784891467518365264e-04, 6.124813505870482925854510514e-05, 3.058823630702049355172851064e-05, 1.528225940865187173257148764e-05, 7.637197637899762273600293563e-06, 3.817293264999839856461644622e-06, 1.908212716553938925656957795e-06, 9.539620338727961131520386834e-07, 4.769329867878064631167196044e-07, 2.384505027277329900036481868e-07, 1.192199259653110730677887189e-07, 5.960818905125947961244020794e-08, 2.980350351465228018606370507e-08, 1.490155482836504123465850663e-08, 7.450711789835429491981004171e-09, 3.725334024788457054819204018e-09, 1.862659723513049006403909945e-09, 9.313274324196681828717647350e-10, 4.656629065033784072989233251e-10, 2.328311833676505492001455976e-10, 1.164155017270051977592973835e-10, 5.820772087902700889243685989e-11, 2.910385044497099686929425228e-11, 1.455192189104198423592963225e-11, 7.275959835057481014520869012e-12, 3.637979547378651190237236356e-12, 1.818989650307065947584832101e-12, 9.094947840263889282533118387e-13, 4.547473783042154026799112029e-13, 2.273736845824652515226821578e-13, 1.136868407680227849349104838e-13, 5.684341987627585609277182968e-14, 2.842170976889301855455073705e-14, 1.421085482803160676983430714e-14, 7.105427395210852712877354480e-15, 3.552713691337113673298469534e-15, 1.776356843579120327473349014e-15, 8.881784210930815903096091386e-16, 4.440892103143813364197770940e-16, 2.220446050798041983999320094e-16, 1.110223025141066133720544570e-16, 5.551115124845481243723736590e-17, 2.775557562136124172581632454e-17, 1.387778780972523276283909491e-17, 6.938893904544153697446085326e-18, 3.469446952165922624744271496e-18, 1.734723476047576572048972970e-18, 8.673617380119933728342055067e-19, 4.336808690020650487497023566e-19, 2.168404344997219785013910168e-19, 1.084202172494241406301271117e-19, 5.421010862456645410918700404e-20, 2.710505431223468831954621312e-20, 1.355252715610116458148523400e-20, 6.776263578045189097995298742e-21, 3.388131789020796818085703100e-21, 1.694065894509799165406492747e-21, 8.470329472546998348246992609e-22, 4.235164736272833347862270483e-22, 2.117582368136194731844209440e-22, 1.058791184068023385226500154e-22, 5.293955920339870323813912303e-23, 2.646977960169852961134116684e-23, 1.323488980084899080309451025e-23, 6.617444900424404067355245332e-24, 3.308722450212171588946956384e-24, 1.654361225106075646229923677e-24, 8.271806125530344403671105617e-25, 4.135903062765160926009382456e-25, 2.067951531382576704395967919e-25, 1.033975765691287099328409559e-25, 5.169878828456431320410133217e-26, 2.584939414228214268127761771e-26, 1.292469707114106670038112612e-26, 6.462348535570531803438002161e-27, 3.231174267785265386134814118e-27, 1.615587133892632521206011406e-27, 8.077935669463162033158738186e-28, 4.038967834731580825622262813e-28, 2.019483917365790349158762647e-28, 1.009741958682895153361925070e-28, 5.048709793414475696084771173e-29, 2.524354896707237824467434194e-29, 1.262177448353618904375399966e-29, 6.310887241768094495682609390e-30, 3.155443620884047239109841220e-30, 1.577721810442023616644432780e-30, 7.888609052210118073520537800e-31 }; if (n <= 0) { throw new ProviderException("Unimplemented zeta at negative argument " + n); } if (n == 1) { throw new ArithmeticException("Pole at zeta(1) "); } if (n < zmin1.length) /* look it up if available */ { return zmin1[n]; } else { /* Result is roughly 2^(-n), desired accuracy 18 digits. If zeta(n) is computed, the equivalent accuracy * in relative units is higher, because zeta is around 1. */ double eps = 1.e-18 * Math.pow(2., (double) (-n)); MathContext mc = new MathContext(err2prec(eps)); return zeta(n, mc).subtract(BigDecimal.ONE).doubleValue(); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Broadhurst ladder sequence./*w w w.j av a 2 s . co m*/ * * @param a The vector of 8 integer arguments * @param mc Specification of the accuracy of the result * @return S_(n, p)(a) * @see \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067} */ static protected BigDecimal broadhurstBBP(final int n, final int p, final int a[], MathContext mc) { /* Explore the actual magnitude of the result first with a quick estimate. */ double x = 0.0; for (int k = 1; k < 10; k++) { x += a[(k - 1) % 8] / Math.pow(2., p * (k + 1) / 2) / Math.pow((double) k, n); } /* Convert the relative precision and estimate of the result into an absolute precision. */ double eps = prec2err(x, mc.getPrecision()); /* Divide this through the number of terms in the sum to account for error accumulation * The divisor 2^(p(k+1)/2) means that on the average each 8th term in k has shrunk by * relative to the 8th predecessor by 1/2^(4p). 1/2^(4pc) = 10^(-precision) with c the 8term * cycles yields c=log_2( 10^precision)/4p = 3.3*precision/4p with k=8c */ int kmax = (int) (6.6 * mc.getPrecision() / p); /* Now eps is the absolute error in each term */ eps /= kmax; BigDecimal res = BigDecimal.ZERO; for (int c = 0;; c++) { Rational r = new Rational(); for (int k = 0; k < 8; k++) { Rational tmp = new Rational(new BigInteger("" + a[k]), (new BigInteger("" + (1 + 8 * c + k))).pow(n)); /* floor( (pk+p)/2) */ int pk1h = p * (2 + 8 * c + k) / 2; tmp = tmp.divide(BigInteger.ONE.shiftLeft(pk1h)); r = r.add(tmp); } if (Math.abs(r.doubleValue()) < eps) { break; } MathContext mcloc = new MathContext(1 + err2prec(r.doubleValue(), eps)); res = res.add(r.BigDecimalValue(mcloc)); } return res.round(mc); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Add and round according to the larger of the two ulps. * * @param x The left summand// w w w . j a v a2 s .co m * @param y The right summand * @return The sum x+y. */ static public BigDecimal addRound(final BigDecimal x, final BigDecimal y) { BigDecimal resul = x.add(y); /* The estimation of the absolute error in the result is |err(y)|+|err(x)| */ double errR = Math.abs(y.ulp().doubleValue() / 2.) + Math.abs(x.ulp().doubleValue() / 2.); MathContext mc = new MathContext(err2prec(resul.doubleValue(), errR)); return resul.round(mc); }