java对数

先看看Java源码里的对数函数(在Java.lang.Math里)

方法1:log()

  作用:返回以自然常数e为底数的对数值

说明:

e ≈ 2.71828 18284 59045 23536 02874 71352 66249 77572 47093 69995 95749 66967 62772 40766 30353 54759 45713 82178 52516 64274

 public static double log(double a) {
return StrictMath.log(a); // default impl. delegates to StrictMath
} /**
* Returns the base 10 logarithm of a value.返回10为底的对数
*
***Special cases特别注意:
*
* 1.If the argument is NaN or less than zero, then the result is NaN.非数或小于0返回NAN
* 2.If the argument is positive infinity, then the result is positive infinity. 正无穷,返回正无穷
* 3.If the argument is positive zero or negative zero, then the result is negative infinity. 参数是正负0,返回负无穷
* 4. If the argument is equal to 10 ^n for integer n, then the result is n.
*
*/

方法2:log10()

作用:返回以10为底数的对数值

 public static double log10(double a) {
return StrictMath.log10(a); // default impl. delegates to StrictMath
} /** Returns the correctly rounded positive square root of a
* value.
* Special cases:
* If the argument is NaN or less than zero, then the result is NaN.
* If the argument is positive infinity, then the result is positive infinity.
* If the argument is positive zero or negative zero, then the
* result is the same as the argument.
* Otherwise, the result is the value closest to
* the true mathematical square root of the argument value.
* @return the positive square root of .
*If the argument is NaN or less than zero, the result is NaN.
*/
*翻译:
*特殊情况: *如果参数是NA或小于零,则结果是楠。 *如果参数是正无穷大,则结果是正无穷大。 *如果参数为正零或负零点,则 *结果与论点相同。 *否则,结果是最接近的值。 *参数值的真正数学平方根。 *@返回正平方根。 *如果参数是NA或小于零,则结果是楠。 */

如果不能理解特别注意的几条,看图:

Java对数-LMLPHP

那么问题来了,怎样实现求任意底数的对数?

(注意:底数>0,底数不等于1)

先来看看换底公式:

log(a) b=log (c) b÷log (c) a ,即:

Java对数-LMLPHP

有了换底公式,我们就可以将任意其他底数换成jvm支持的底数e或10:

 public class Logarithm {
public int log(double value, int base){
return (int)(Math.log(value)/Math.log(base));//换成了底数e
}
}
05-04 12:28