Does casting double to float always return same value?

后端 未结 6 1986
余生分开走
余生分开走 2020-12-17 09:10

Does casting double to float always produce same result, or can there be some \"rounding differences\"?

For example, is x in

6条回答
  •  佛祖请我去吃肉
    2020-12-17 10:00

    In some cases, the closest float representation to a numeric quantity may differ from the value obtained by rounding the closest double representation to a float. Two such quantities are 12,344,321.4999999991 and 12,345,678.50000000093. The integers above and below both those quantities are precisely representable as float, but the nearest double to each of them has a fractional part of precisely 0.5. Because converting such double values (between 2^23 and 2^24, with a fraction of precisely 0.5) to float will round to the nearest even integer; the compiler will in each case end up rounding away from the value which would have been closer to the original number.

    Note that in practice, the compiler seems to parse numbers as double, and then convert to float, so even though 12344321.4999999991f should round to 12344321f, it instead rounds to 12344322f. Likewise 12345678.50000000093f should rounds to 12345679f but rounds to 12345678f, so even in cases where conversion to double and then float loses precision, such conversion loss cannot be avoided by specifying numbers directly as float.

    Incidentally, the values 12344321.4999999992f and 12345678.50000000094f are rounded correctly.

提交回复
热议问题