JavaScript 数学函数 (atan2) 的最后一位是否符合规范?

Are browser differences in the last digit of a JavaScript Math function (atan2) within spec?

我在 Math#atan2 的输出的最后一位数字中看到 Firefox 和 Safari 之间的差异。

我的代码:

Math.atan2(-0.49999999999999994, 0.8660254037844387)

Safari (12.1.1) 给出 -0.5235987755982988 但 Firefox (Mac/67.0) 给出 -0.5235987755982987.

这当然是一个微小的差异。但是,似乎所有实现都应该在所有输入中产生相同的输出。例如,这样的差异可能会导致 if 语句根据浏览器遵循不同的路径。

我看到的是否违反了任何版本的 ECMAScript 规范?

一定是一些浮动的 pt 东西。我建议添加一些阈值检查,而不是在条件上使用 equals。

ECMAScript 2015 规范是这样说的:

The behaviour of the functions acos, acosh, asin, asinh, atan, atanh, atan2, cbrt, cos, cosh, exp, expm1, hypot, log,log1p, log2, log10, pow, random, sin, sinh, sqrt, tan, and tanh is not precisely specified here except to require specific results for certain argument values that represent boundary cases of interest. For other argument values, these functions are intended to compute approximations to the results of familiar mathematical functions, but some latitude is allowed in the choice of approximation algorithms.The general intent is that an implementer should be able to use the same mathematical library for ECMAScript on a given hardware platform that is available to C programmers on that platform.

Although the choice of algorithms is left to the implementation, it is recommended (but not specified by this standard) that implementations use the approximation algorithms for IEEE 754-2008 arithmetic contained in fdlibm, the freely distributable mathematical library from Sun Microsystems (http://www.netlib.org/fdlibm).

5.1 规范有类似的语言。

所以我认为可以肯定地说此行为不违反规范。

像这样的浮点差异会发生在不同的 CPUs/FPUs 和跨任何语言或平台的不同数学库上。如果您依赖于完全正确的精度水平,您就会遇到麻烦。您应该始终将浮点值视为 "fuzzy"。

ECMA spec不指定精度:

The Math.atan2() function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0,0) to the point (x,y), for Math.atan2(y,x).