Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't?

前端 未结 4 1477
心在旅途
心在旅途 2020-11-30 18:38

I know that most decimals don\'t have an exact floating point representation (Is floating point math broken?).

But I don\'t see why 4*0.1 is printed nic

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 19:16

    Here's a simplified conclusion from other answers.

    If you check a float on Python's command line or print it, it goes through function repr which creates its string representation.

    Starting with version 3.2, Python's str and repr use a complex rounding scheme, which prefers nice-looking decimals if possible, but uses more digits where necessary to guarantee bijective (one-to-one) mapping between floats and their string representations.

    This scheme guarantees that value of repr(float(s)) looks nice for simple decimals, even if they can't be represented precisely as floats (eg. when s = "0.1").

    At the same time it guarantees that float(repr(x)) == x holds for every float x

提交回复
热议问题