2.9999999999999999 >> .5?

后端 未结 10 1830
逝去的感伤
逝去的感伤 2021-02-07 15:32

I heard that you could right-shift a number by .5 instead of using Math.floor(). I decided to check its limits to make sure that it was a suitable replacement, so I checked the

10条回答
  •  盖世英雄少女心
    2021-02-07 16:34

    Try this javascript out: alert(parseFloat("2.9999999999999997779553950749686919152736663818359374999999"));

    Then try this: alert(parseFloat("2.9999999999999997779553950749686919152736663818359375"));

    What you are seeing is simple floating point inaccuracy. For more information about that, see this for example: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems.

    The basic issue is that the closest that a floating point value can get to representing the second number is greater than or equal to 3, whereas the closes that the a float can get to the first number is strictly less than three.

    As for why right shifting by 0.5 does anything sane at all, it seems that 0.5 is just itself getting converted to an int (0) beforehand. Then the original float (2.999...) is getting converted to an int by truncation, as usual.

提交回复
热议问题