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

后端 未结 2 1599
春和景丽
春和景丽 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: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

提交回复
热议问题