Java examples for java.lang:Math Trigonometric Function
Compute the arctangent of x to a given scale by the Taylor series, |x| < 1
/*// ww w.j a v a 2s. co m 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(arctanTaylor(x, scale)); } /** * Compute the arctangent of x to a given scale by the Taylor series, |x| < 1 * @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 arctanTaylor(final BigDecimal x, final int scale) { final int sp1 = scale + 1; int i = 3; boolean addFlag = false; BigDecimal power = x; BigDecimal sum = x; BigDecimal term; // Convergence tolerance = 5*(10^-(scale+1)) final BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft( sp1); // Loop until the approximations converge // (two successive approximations are within the tolerance). do { // x^i power = power.multiply(x).multiply(x) .setScale(sp1, BigDecimal.ROUND_HALF_EVEN); // (x^i)/i term = power.divide(BigDecimal.valueOf(i), sp1, BigDecimal.ROUND_HALF_EVEN); // sum = sum +- (x^i)/i sum = addFlag ? sum.add(term) : sum.subtract(term); i += 2; addFlag = !addFlag; Thread.yield(); } while (term.compareTo(tolerance) > 0); return sum; } }