private static BigDecimal _expTaylor ( final BigDecimal x , final int scale ) { BigDecimal factorial = BigDecimal . ONE ; BigDecimal xPower = x ; BigDecimal sumPrev ; // 1 + x BigDecimal sum = x . add ( BigDecimal . ONE ) ; // Loop until the sums converge // (two successive sums are equal after rounding). int i = 2 ; do { // x^i xPower = xPower . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; // i! factorial = factorial . multiply ( BigDecimal . valueOf ( i ) ) ; // x^i/i! final BigDecimal term = xPower . divide ( factorial , scale , RoundingMode . HALF_EVEN ) ; // sum = sum + x^i/i! sumPrev = sum ; sum = sum . add ( term ) ; ++ i ; Thread . yield ( ) ; } while ( sum . compareTo ( sumPrev ) != 0 ) ; return sum ; }
Compute e^x to a given scale by the Taylor series .