Python| frexp()函数
frexp()
函数是Python中的标准数学库函数之一。
它返回尾数和指数作为给定值 x 的对 (m, e),其中尾数m是浮点数, e指数是整数值。 m是一个浮点数, e是一个整数,使得x == m * 2**e精确。
如果 x 为零,则返回 (0.0, 0),否则返回 0.5 <= abs(m) < 1。这用于以可移植的方式“分离”浮点数的内部表示。
Syntax: math.frexp( x )
Parameters: Any valid number (positive or negative).
Returns: Returns mantissa and exponent as a pair (m, e) value of a given number x.
Exception: If x is not a number, function will return TypeError.
代码#1:
# Python3 code demonstrate frexp() function
# importing math library
import math
# calculating mantissa and
# exponent of given integer
print(math.frexp(3))
print(math.frexp(15.7))
print(math.frexp(-15))
输出:
(0.75, 2)
(0.98125, 4)
(-0.9375, 4)
代码#2:
# Python3 code demonstrate frexp() function
# importing math library
import math
# creating a list
lst = [15, 13.76, 17.5, 21]
# creating a tuple
tpl = (-15.85, -41.24, -11.2, 54)
# calculating mantissa and exponent
# of 1st, 3rd elements in list
print(math.frexp(lst[0]))
print(math.frexp(lst[2]))
# calculating mantissa and exponent
# of 2nd, 3rd and 4th elements in tuple
print(math.frexp(tpl[1]))
print(math.frexp(tpl[2]))
print(math.frexp(tpl[3]))
输出:
(0.9375, 4)
(0.546875, 5)
(-0.644375, 6)
(-0.7, 4)
(0.84375, 6)
代码 #3:如果 x 参数不是数字, frexp()
函数将返回TypeError 。
# Python3 code demonstrates when error occurs
import math
print(math.frexp('25'))
输出:
TypeError: a float is required