Skip to main content
 首页 » 编程设计

python之为什么 math.modf 返回 float

2025年05月04日15Renyi-Fan

来自 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.

在this related question ,它指出返回 float 对于 ceil 和 floor 没有真正意义,因此在 Python 3 中,它们被更改为返回整数。 modf 的整数结果也没有作为整数返回有什么原因吗?在 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) 

在 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) 

请您参考如下方法:

大多数 math 模块函数都是 C 语言标准定义的同名函数的精简包装器。 frexp() 和 modf() 就是其中两个,它们返回的内容与同名 C 函数返回的内容相同。

因此,部分原因在于易于跨语言操作。

但另一部分是实用性:

>>> from math import modf 
>>> modf(1e100) 
(0.0, 1e+100) 

您真的想要将 10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104 返回为“整数部分”吗?

C 不可能这样做,因为它没有无界整数。 Python 根本不想想要 这样做;-) 请注意,足够大的所有 浮点值都是精确的整数——尽管它们可能需要数百位小数来表示.