rounding errors in Python floor division

前端 未结 5 1053
挽巷
挽巷 2020-12-04 21:29

I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:

>>> 8.0 / 0.4  # as expected
20.0
>&         


        
5条回答
  •  一个人的身影
    2020-12-04 22:14

    Ok after a little bit of research I have found this issue. What seems to be happening is, that as @khelwood suggested 0.4 evaluates internally to 0.40000000000000002220, which when dividing 8.0 yields something slightly smaller than 20.0. The / operator then rounds to the nearest floating point number, which is 20.0, but the // operator immediately truncates the result, yielding 19.0.

    This should be faster and I suppose its "close to the processor", but I it still isn't what the user wants / is expecting.

提交回复
热议问题