Safest way to convert float to integer in python?

后端 未结 10 2556
不思量自难忘°
不思量自难忘° 2020-11-27 13:44

Python\'s math module contain handy functions like floor & ceil. These functions take a floating point number and return the nearest integer be

10条回答
  •  北海茫月
    2020-11-27 14:05

    All integers that can be represented by floating point numbers have an exact representation. So you can safely use int on the result. Inexact representations occur only if you are trying to represent a rational number with a denominator that is not a power of two.

    That this works is not trivial at all! It's a property of the IEEE floating point representation that int∘floor = ⌊⋅⌋ if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.

    To quote from Wikipedia,

    Any integer with absolute value less than or equal to 224 can be exactly represented in the single precision format, and any integer with absolute value less than or equal to 253 can be exactly represented in the double precision format.

提交回复
热议问题