Compute e^x to a given scale by the Taylor series. - Java java.lang

Java examples for java.lang:Math Operation

Description

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

Demo Code

/*/*from w w  w  .ja  v  a2  s .  com*/
 Anders H?fft, note: This class was downloaded as a quick, and temprory, way of getting a BigDecimal ln() method. 
 The code belongs to Cyclos. See comment below:

 This file is part of Cyclos (www.cyclos.org).
 A project of the Social Trade Organisation (www.socialtrade.org).
 Cyclos is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.
 Cyclos is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.
 You should have received a copy of the GNU General Public License
 along with Cyclos; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
//package com.java2s;
import java.math.BigDecimal;

public class Main {
    public static void main(String[] argv) throws Exception {
        BigDecimal x = new BigDecimal("1234");
        int scale = 2;
        System.out.println(expTaylor(x, scale));
    }

    /**
     * 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
     * @author Ronald Mak: "Java Number Cruncher, the java programmer's guide to numerical computing" Prentice Hall PTR, 2003. pages 330 & 331
     */
    private static BigDecimal expTaylor(final BigDecimal x, final 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!
            final 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 Tutorials