I was viewing some code and found some parts use num/2, while others use num * 0.5. That inspired me a question : within the range of MIN_VALUE and MAX_VALUE, are num/2 and num*0.5 interchangeable?
I was not only interested in the case that num divided by 2, consider:
0.5 = 1/2
4 = 1/0.25
0.125 = 1/8
which y=1/x and both x any y can be perfectly represented with float numbers. My question is, for other cases that x , y can be perfectly represented with float numbers without rounding, and Float.MIN_VALUE<=x,y,z,z*y<=Float.MAX_VALUE, is z * y == z/x always true?
I tested some case, which is true:
document.write(123.456*4 == 123.456/0.25);
document.write("<br/>");
document.write(24.68/16 == 24.68*0.0625);
document.write("<br/>");
document.write(98.765/2 == 98.765*0.5);
I also tried to verify some cases by for-loop:
for(let i=0;i<10000;i++){
const r=Math.random()*10000;
if(r*0.5!=r/2){
document.write(r+"<br/>");
break;
}
}
for(let i=0;i<10000;i++){
const r=Math.random()*10000;
if(r*4!=r/0.25){
document.write(r+"<br/>");
break;
}
}
for(let i=0;i<10000;i++){
const r=Math.random()*10000;
if(r*0.125!=r/8){
document.write(r+"<br/>");
break;
}
}
tested it several times and no counter examples printed. But I don’t know if it is true for all other cases.
Note : y doesn’t includes numbers like 0.1 and 0.2 because 0.1 and 0.2 are not perfectly representable by float numbers, while 0.5 and 0.25 can be. Also y is not something like 1.25 because x=1/1.25=0.8, which 0.8 is also not representable perfectly with float numbers.
2
Answers
Floating point math is broken, therefore generally
(x * 1/y) != (x / y)
:JavaScript is an implementation of ECMAScript, and ECMAScript specifies that the IEEE 754 floating-point standard is used. IEEE 754 defines general operations to produce a result as if the real-number arithmetic result were computed with infinite precision and then rounded according to the applicable rounding rule. Therefore, if the mathematical expressions
z
•y
andz
/x
are equal, which they must be ify
= 1/x
with no rounding error, then the floating-point computationsz*y
andz/x
produce the same result.Specifically, IEEE 754-2019 4.3 says:
ECMAScript 2020 Language Specification does not make a general statement of conformity to IEEE 754 but specifies individually that operations conform. For example, 6.1.6.1.4 discusses multiplication and says: