Here you can find the source of expTaylor(BigDecimal x, int scale)
Parameter | Description |
---|---|
x | the value of x |
scale | the desired scale of the result |
private static BigDecimal expTaylor(BigDecimal x, int scale)
//package com.java2s; //License from project: Apache License import java.math.BigDecimal; public class Main { /**//from w ww . j a v a2 s . c om * Compute e^x to a given scale by the Taylor series. * @param x the value of x * @param scale the desired scale of the result * @return the result value */ private static BigDecimal expTaylor(BigDecimal x, int scale) { BigDecimal factorial = BigDecimal.valueOf(1); BigDecimal xPower = x; BigDecimal sumPrev; // 1 + x BigDecimal sum = x.add(BigDecimal.valueOf(1)); // Loop until the sums converge // (two successive sums are equal after rounding). int i = 2; do { // x^i xPower = xPower.multiply(x).setScale(scale, BigDecimal.ROUND_HALF_EVEN); // i! factorial = factorial.multiply(BigDecimal.valueOf(i)); // x^i/i! BigDecimal term = xPower.divide(factorial, scale, BigDecimal.ROUND_HALF_EVEN); // sum = sum + x^i/i! sumPrev = sum; sum = sum.add(term); ++i; Thread.yield(); } while (sum.compareTo(sumPrev) != 0); return sum; } }