1

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)
Community
  • 1
  • 1
endolith
  • 25,479
  • 34
  • 128
  • 192
  • Most places where you'd want to use this you probably want a float. (Although in 3.x, now that int/int returns float it probably doesn't matter as much.) What's your use case? – abarnert Oct 12 '13 at 00:02

1 Answers1

8

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.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132
  • 1
    +1. I wish we were still returning floats from `math.floor` and `math.ceil`, too. – Mark Dickinson Oct 12 '13 at 08:42
  • @MarkDickinson, ack! I didn't realize that (just started with Py3). How did that happen?! I see Guido didn't change floating `%` either (e.g., `-1 % 1e20` is still `1e20`). Should I blame you? LOL ;-) – Tim Peters Oct 12 '13 at 17:28
  • Doesn't it make more sense for `int(floor(100000000000000000000000))` to produce `100000000000000000000000` than to produce `99999999999999991611392`? – endolith Oct 23 '13 at 13:37
  • @endolith, I agree that's nicer for general use :-) – Tim Peters Oct 24 '13 at 17:55