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.