Java examples for java.lang:Math Calculation
Calculates the natural logarithm of a number
/*/*from w ww . jav 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 { /** * Calculates the natural logarithm of a number * @param x the number * @return the natural logarithm of x */ public static double log(double x) { long l = Double.doubleToLongBits(x); long exp = ((0x7ff0000000000000L & l) >> 52) - 1023; double man = (0x000fffffffffffffL & l) / (double) 0x10000000000000L + 1.0; double lnm = 0.0; double a = (man - 1) / (man + 1); for (int n = 1; n < 8; n += 2) { lnm += pow(a, n) / n; } return 2 * lnm + exp * 0.69314718055994530941723212145818; } /** * Calculates the logarithm of a number, in a given base * @param x the number * @param base the base * @return the logarithm of the number, in the given base */ public static double log(double x, double base) { return log(x) / log(base); } /** * Calculates a^b * @param a a * @param b b * @return a^b */ public static double pow(double a, double b) { if (b == 0) { return 1; } boolean gt1 = (Math.sqrt((a - 1) * (a - 1)) <= 1) ? false : true; int oc = -1, iter = 30; double p = a, x, x2, sumX, sumY; if ((b - Math.floor(b)) == 0) { for (int i = 1; i < b; i++) p *= a; return p; } x = (gt1) ? (a / (a - 1)) : (a - 1); sumX = (gt1) ? (1 / x) : x; for (int i = 2; i < iter; i++) { p = x; for (int j = 1; j < i; j++) p *= x; double xTemp = (gt1) ? (1 / (i * p)) : (p / i); sumX = (gt1) ? (sumX + xTemp) : (sumX + (xTemp * oc)); oc *= -1; } x2 = b * sumX; sumY = 1 + x2; for (int i = 2; i <= iter; i++) { p = x2; for (int j = 1; j < i; j++) p *= x2; int yTemp = 2; for (int j = i; j > 2; j--) yTemp *= j; sumY += p / yTemp; } return sumY; } }