For a floating point number x, without underflow and overflow, are the results of x+x and x*2 the same?
P粉064448449
P粉064448449 2023-09-07 10:08:44
0
1
552

For example, initially I had this code:

function(x,y){
  let z=x+y;
  .
  .
  .
}

Later I discovered that y must be the same as x. I wanted to reconstruct x y into x * 2, but I needed to ensure that the entire program behaves the same before and after reconstruction. Is x x the same as x*2? I don't know if and * use different calculation mechanisms, leading to rounding to different results.

I tested:

for(let i=0.01;i<100;i++){
  if(i+i!=i*2){
    console.log(i);
    break;
  }
}

Seems to be correct for certain ranges of i, but not sure if it is correct for all floating point numbers.

P粉064448449
P粉064448449

reply all(1)
P粉012875927

JavaScript is an implementation of ECMAScript, and the ECMAScript specification represents the IEEE-754 "double precision" (binary64) format using the IEEE 754 algorithm. Section 5.2.5 states " …When applied to numbers, operators refer to the relevant operations in IEEE 754-2019…”

In IEEE 754 and any reasonable floating-point system, the result of an operation is an exact mathematical result rounded according to the chosen rounding rule (e.g., round to nearest tie, round to even, round to even) toward zero, round up or round down). IEEE 754-2019 4.3 says:

Since x x and 2•x have the same mathematical result, the floating point operations x x code> and 2* x must produce the same calculation result. If the same rounding rules are applied, both will give the same mathematical result, so the calculations must be the same.

The above covers the case where x is a number, including ∞ and -∞. If x is NaN, then x x and 2*x will also produce NaN code>, so the result is again the same. (Note that x x == 2*x will evaluate to false in this case, since NaN is not equal to anything, not even itself. Nonetheless, both operations produce the same Result; program behavior will be the same if 2*x is used instead of x x, and vice versa.)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template