Math.log1p() - JavaScript 编辑

The Math.log1p() function returns the natural logarithm (base e) of 1 + a number, that is

x>-1,Math.log1p(x)=ln(1+x)\forall x > -1, \mathtt{\operatorname{Math.log1p}(x)} = \ln(1 + x)

Syntax

Math.log1p(x)

Parameters

x
A number.

Return value

The natural logarithm (base e) of 1 plus the given number. If the number is less than -1, NaN is returned.

Description

For very small values of x, adding 1 can reduce or eliminate precision.  The double floats used in JS give you about 15 digits of precision.  1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.  

When you calculate log(1 + x), you should get an answer very close to x, if x is small (that's why these are called 'natural' logarithms).  If you calculate Math.log(1 + 1.1111111111e-15) you should get an answer close to 1.1111111111e-15.  Instead, you will end up taking the logarithm of 1.00000000000000111022 (the roundoff is in binary so sometimes it gets ugly), so you get the answer 1.11022...e-15, with only  3 correct digits.  If, instead, you calculate Math.log1p(1.1111111111e-15) you will get a much more accurate answer 1.1111111110999995e-15 with 15 correct digits of precision (actually 16 in this case).

If the value of x is less than -1, the return value is always NaN.

Because log1p() is a static method of Math, you always use it as Math.log1p(), rather than as a method of a Math object you created (Math is not a constructor).

Polyfill

This can be emulated with the following function:

Math.log1p = Math.log1p || function(x) {
  x = Number(x);
  if (x < -1 || x !== x)
    return NaN;
  if (x === 0 || x === Infinity)
    return x;

  var nearX = (x + 1) - 1;

  return nearX === 0 ? x : x * (Math.log(x + 1) / nearX);
};

Examples

Using Math.log1p()

Math.log1p(1);  // 0.6931471805599453
Math.log1p(0);  // 0
Math.log1p(-1); // -Infinity
Math.log1p(-2); // NaN

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'Math.log1p' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:59 次

字数:6025

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文