Python frexp()函数示例
Python frexp()是数学库中的内置函数,可帮助我们找到x的尾数和指数作为对(m,e),其中m是浮点数,e是使得x == m * 2的整数** e。如果x的值为0,则此函数返回(0.0,0),否则返回5 <= abs(m)<1。
Python frexp()
内容概述
- 1个Python frexp()
- 2结论
- 3另请参见
frexp()函数是Python中的标准数学库函数之一。它以给定值x的一对(m,e)返回尾数和指数,其中尾数m是浮点数,e指数是整数值。 m是浮点数,e是一个整数,使得x == m * 2 ** e精确。
如果x为零,则返回(0.0,0),否则返回0.5 <= abs(m)<1。这用于以可移植的方式“分离”浮点数的内部表示形式。
句法
math.frexp(x)
x是一个我们可以找到尾数和指数的数字。
返回值
frexp()函数返回x的尾数和指数作为对(m,e),其中m是浮点数,e是整数。但是,如果给定值x不是数字,则此函数返回TypeError。
编程范例
请参阅以下代码。
# app.py # Importing math library import math # Demonstrating working of frexp() # Using different types of value of x # When x is positive number x = 5 print("Pair of mantissa and exponent of ", x, " is: ", math.frexp(x)) # When x is float type number x = 6.4 print("Pair of mantissa and exponent of ", x, " is: ", math.frexp(x)) # When x is a negative number x = -32 print("Pair of mantissa and exponent of ", x, " is: ", math.frexp(x)) # Declaring a list x = [4, 3, 7] # Using frexp() with the 3rd value of the list print("Pair of mantissa and exponent of ", x[2], " is: ", math.frexp(x[2])) # When x is not a number x = '41' print("Pair of mantissa and exponent of ", x, " is: ", math.frexp(x))
输出量
Pair of mantissa and exponent of 5 is: (0.625, 3) Pair of mantissa and exponent of 6.4 is: (0.8, 3) Pair of mantissa and exponent of -32 is: (-0.5, 6) Pair of mantissa and exponent of 7 is: (0.875, 3) Traceback (most recent call last): File "frexp.py", line 27, inprint("Pair of mantissa and exponent of ",x," is: ",math.frexp(x)) TypeError: must be real number, not str
在上面的代码中,我们采用了x的不同类型的值,并使用frexp()方法检查了输出。我们可以看到,在每种情况下,输出都是(m,e)对。
最后,当我们将x的值声明为字符时,将返回TypeError。
将frexp()与Python元组和列表一起使用
请参阅以下代码,其中我们定义了Python列表和元组。
# app.py import math # creating a list lst = [11, 21.11, 21.19, 30] # creating a tuple tpl = (-15.31, -41.31, -11.21, 46.19) # 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]))
输出量
python3 app.py (0.6875, 4) (0.6621875, 5) (-0.64546875, 6) (-0.700625, 4) (0.72171875, 6)
结论
Python frexp()方法是Python数学函数之一,用于将x的尾数和指数作为对(m,e)返回,其中m是浮点值,e是整数值。
也可以看看
Python fmod()
Python阶乘
Python math.fabs()
Python数学copysign()
Python数学函数
Python math.sqrt()
Python math.floor()