首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Math.log

Math.log()?函数返回一个数的自然对数,即:

?x>0,Math.log(x)=ln(x)=the uniqueysuch thatey=x\forall x > 0, \mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{the unique} \; y \; \text{such that} \; e^y = x

JavaScript Math.log()函数等同于数学中的ln(x)

语法

代码语言:javascript
复制
Math.log(x)

参数

x一个数字.

返回值

给定数字e的自然对数(基数)。如果数字是负数,则返回NaN

描述

如果指定的?number?为负数,则返回值为?NaN

由于?log?是?Math?的静态方法,所以应该像这样使用:Math.log(),而不是作为你创建的?Math?对象的方法。

如果您需要2或10的自然对数,请使用常量Math.LN2Math.LN10。如果您需要以2或10为底数的对数,请使用Math.log2()Math.log10()。如果您需要以其他基数为底的对数,请使用Math.log(x)/ Math.log(otherBase),如下例所示; 你可能要预先计算1 / Math.log(otherBase)。

示例

使用Math.log()

代码语言:javascript
复制
Math.log(-1); // NaN, out of range
Math.log(0);  // -Infinity
Math.log(1);  // 0
Math.log(10); // 2.302585092994046

基于不同的底数使用Math.log

下面的函数返回以?x?为底?y?的对数(即logxy):

代码语言:javascript
复制
function getBaseLog(x, y) {
  return Math.log(y) / Math.log(x);
}

如果你运行?getBaseLog(10, 1000),则会返回2.9999999999999996,非常接近实际答案:3,原因是浮点数精度问题。

规范

Specification

Status

Comment

ECMAScript 1st Edition (ECMA-262)

Standard

Initial definition. Implemented in JavaScript 1.0.

ECMAScript 5.1 (ECMA-262)The definition of 'Math.log' in that specification.

Standard

?

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Math.log' in that specification.

Standard

?

ECMAScript Latest Draft (ECMA-262)The definition of 'Math.log' in that specification.

Draft

?

浏览器兼容性

Feature

Chrome

Firefox

Edge

Internet Explorer

Opera

Safari

Basic Support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com