Why am I getting a different result from std::fmod and std::remainder

后端 未结 2 1578
春和景丽
春和景丽 2020-12-19 17:29

In the below example app I calculate the floating point remainder from dividing 953 by 0.1, using std::fmod

What I was expectin

相关标签:
2条回答
  • 2020-12-19 18:08

    Welcome to floating point math. Here's what happens: One tenth cannot be represented exactly in binary, just as one third cannot be represented exactly in decimal. As a result, the division produces a result slightly below 9530. The floor operation produces the integer 9529 instead of 9530. And then this leaves 0.1 left over.

    0 讨论(0)
  • 2020-12-19 18:25

    Because they are different functions.

    std::remainder(x, y) calculates IEEE remainder which is x - (round(x/y)*y) where round is rounding half to even (so in particular round(1.0/2.0) == 0)

    std::fmod(x, y) calculates x - trunc(x/y)*y. When you divide 953 by 0.1 you may get a number slightly smaller than 9530, so truncation gives 9529. So as the result you get 953.0 - 952.9 = 0.1

    0 讨论(0)
提交回复
热议问题