Java examples for java.lang:Math Trigonometric Function
Approximates the atan2 function.
/*/*from w w w .j av a 2s . co m*/ * Created on 02-May-2006 at 17:31:01. * * Copyright (c) 2010 Robert Virkus / Enough Software * * This file is part of J2ME Polish. * * J2ME Polish 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. * * J2ME Polish 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 J2ME Polish; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Commercial licenses are also available, please * refer to the accompanying LICENSE.txt or visit * http://www.j2mepolish.org for details. */ //package com.java2s; public class Main { /** * Approximates the atan2 function. Results are in the [0,2*PI) range. * * @param x * @param y * @return the calculated value */ public static double atan2(double x, double y) { // Origin - return zero if (y == 0.0 && x == 0.0) { return 0.0; } else if (x > 0.0) { if (y > 0.0) { // Point is in first quadrant return atan(y / x); } else { // Point is in fourth quadrant return 2 * Math.PI - atan(-y / x); } } else if (x < 0.0) { if (y < 0.0) { // Point is in third quadrant return Math.PI + atan(y / x); } else { // Point is in second quadrant return Math.PI - atan(-y / x); } } else if (y < 0.0) { // Special cases for when the point is directly on the Y axis. return 2 * Math.PI - Math.PI / 2.; } else { return Math.PI / 2.; } } /** * Approximates the atan function. Uses a polynomial approximation that should * be accurate enough for most practical purposes. * * @param x * @return the calculated value */ public static double atan(double x) { double SQRT3 = 1.732050807568877294; boolean signChange = false; boolean Invert = false; int sp = 0; double x2, a; // check up the sign change if (x < 0.) { x = -x; signChange = true; } // check up the invertation if (x > 1.) { x = 1 / x; Invert = true; } // process shrinking the domain until x<PI/12 while (x > Math.PI / 12) { sp++; a = x + SQRT3; a = 1 / a; x = x * SQRT3; x = x - 1; x = x * a; } // calculation core x2 = x * x; a = x2 + 1.4087812; a = 0.55913709 / a; a = a + 0.60310579; a = a - (x2 * 0.05160454); a = a * x; // process until sp=0 while (sp > 0) { a = a + Math.PI / 6; sp--; } // inversation took place if (Invert) a = Math.PI / 2 - a; // sign change took place if (signChange) a = -a; // return a; } }