Reputation: 26833
from http://docs.python.org/2/library/math.html:
math.frexp(x)
Return the mantissa and exponent of x as the pair (m, e). m is a float and e is an integer such that x == m * 2**e exactly. If x is zero, returns (0.0, 0), otherwise 0.5 <= abs(m) < 1. This is used to “pick apart” the internal representation of a float in a portable way.
math.modf(x)
Return the fractional and integer parts of x. Both results carry the sign of x and are floats.
In this related question, it's pointed out that returning floats doesn't really make sense for ceil and floor, so in Python 3, they were changed to return integers. Is there some reason why the integer result of modf
isn't returned as an integer, too? In Python 2.7:
In [2]: math.floor(5.5)
Out[2]: 5.0
In [3]: math.modf(5.5)
Out[3]: (0.5, 5.0)
In [4]: math.frexp(5.5)
Out[4]: (0.6875, 3)
In Python 3:
In [2]: math.floor(5.5)
Out[2]: 5
In [3]: math.modf(5.5)
Out[3]: (0.5, 5.0)
In [4]: math.frexp(5.5)
Out[4]: (0.6875, 3)
Upvotes: 1
Views: 1806
Reputation: 70735
Most of the math
module functions are thin wrappers around functions of the same name defined by the C language standard. frexp()
and modf()
are two such, and return the same things the C functions of the same names return.
So part of this is ease of inter-language operation.
But another part is practicality:
>>> from math import modf
>>> modf(1e100)
(0.0, 1e+100)
Would you really want to get 10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104 back as "the integer part"?
C can't possibly do so, because it doesn't have unbounded integers. Python simply doesn't want to do so ;-) Note that all floating-point values of sufficient magnitude are exact integers - although they may require hundreds of decimal digits to express.
Upvotes: 8