Java BigDecimal expTaylor(BigDecimal x, int scale)

Here you can find the source of expTaylor(BigDecimal x, int scale)

Description

Compute e^x to a given scale by the Taylor series.

License

Apache License

Parameter

Parameter Description
x the value of x
scale the desired scale of the result

Return

the result value

Declaration

private static BigDecimal expTaylor(BigDecimal x, int scale) 

Method Source Code


//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;
    }
}

Related

  1. decimalDigits(BigDecimal d)
  2. deserializeBigDecimalFromString(String decimal)
  3. exp(BigDecimal power)
  4. exp(BigDecimal x, int scale)
  5. exponentialFormatBigDecimal(BigDecimal bd)
  6. extractBigDecimal(String value)
  7. firstNonZero(final BigDecimal... values)
  8. floatValue(BigDecimal val)
  9. fromLongToBigDecimal(long longValue)