multiplication of double with integer precision

后端 未结 5 889
难免孤独
难免孤独 2021-01-22 20:35

I have a double of 3.4. However, when I multiply it with 100, it gives 339 instead of 340. It seems to be caused by the precision of double. How could I get around this?

5条回答
  •  时光说笑
    2021-01-22 21:13

    First what is going on:

    1. 3.4 can't be represented exactly as binary fraction. So the implementation chooses closest binary fraction that is representable. I am not sure whether it always rounds towards zero or not, but in your case the represented number is indeed smaller.
    2. The conversion to integer truncates, that is uses the closest integer with smaller absolute value.
    3. Since both conversions are biased in the same direction, you can always get a rounding error.

    Now you need to know what you want, but probably you want to use symmetrical rounding, i.e. find the closest integer be it smaller or larger. This can be implemented as

    #include 
    int round(double x) { std::floor(x + 0.5); } // floor is provided, round not
    

    or

    int round(double x) { return x < 0 ? x - 0.5 : x + 0.5; }
    

    I am not completely sure it's indeed rounding towards zero, so please verify the later if you use it.

提交回复
热议问题