0

According to this post, floating point numbers in JavaScript are not deterministic.

I wonder, is the following code deterministic?

z = Math.floor(x/y)

If not, how can I do deterministic integer division in JavaScript?

Edit: I would like to know if I can rely on the resulting value being the same across different JavaScript implementations (given they follow the standards).

Simon Farshid
  • 2,636
  • 1
  • 22
  • 31
  • 2
    "implementation dependent" and "nondeterministic" are not exactly the same concept. The latter tends to refer to functions which depend on random numbers, which isn't really the issue here. – John Coleman Feb 22 '19 at 21:30
  • To clarify: In my question I am asking for an implementation independent method of dividing whole numbers in javascript – Simon Farshid Feb 22 '19 at 21:37
  • Your question is perfectly clear, just not what I expected given its title. – John Coleman Feb 22 '19 at 21:47

2 Answers2

1

It should be deterministic.

According to the specification

20.2.2.16 Math.floor ( x )

Returns the greatest (closest to +∞) Number value that is not greater than x and is equal to a mathematical integer. If x is already an integer, the result is x.

  • If x is NaN, the result is NaN.
  • If x is +0, the result is +0.
  • If x is −0, the result is −0.
  • If x is +∞, the result is +∞.
  • If x is −∞, the result is −∞.
  • If x is greater than 0 but less than 1, the result is +0.

NOTE The value of Math.floor(x) is the same as the value of -Math.ceil(-x).

The non-determinism of some Math functions has to do with possible rounding issues when the underlying engine uses higher-precision numbers. That shouldn't be a factor here.

Update :

Division is also deterministic. Here the JS specification depends on the IEEE 754 specification. But that specification is deterministic. (Sorry no link, as the actual specification is paywalled.)

The non-determinisim is in the less common JS functions.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
  • If I understand correctly, x / y may result in a different value depending on the architecture. Could these rounding errors "leak" through the Math.floor function? – Simon Farshid Feb 22 '19 at 21:41
  • Updated. I've never actually read the IEEE 754 specification, but I've been told that its division algorithm is deterministic as well. – Scott Sauyet Feb 22 '19 at 21:50
-1

Yes. Math.floor always returns a lowest integer value.

Whereas this is not deterministic: z = 3/1.5; //z !== 2

This, by the function's design, is: z = Math.floor(3/1.5); //z === 2

See the MDN docs for more details.

Byron Jones
  • 702
  • 5
  • 11