Python math.ldexp() 方法用于计算数字 “x” 乘以 2i 的值,其中 “x” 是有效数字(也称为尾数),“i” 是指数。
例如,如果您有一个有效数字 “x = 0.75” 和一个指数 “i = 3”,则 math.ldexp(0.75, 3) 将返回 0.75 × 23 = 6.0。
注意:要使用此功能,您需要导入 math 模块。
语法
以下是 Python math.ldexp() 方法的基本语法 -
math.ldexp(x, i)
参数
此方法接受以下参数 -
- x − 它是有效数,介于 0.5(含)和 1.0(不含)之间的实数。
- i -它是指数,表示 2 的幂的整数。
返回值
该方法返回一个浮点数,它是 x × 2exp 的结果。
示例 1
在下面的示例中,我们通过将数字提高到正指数来计算数字的 ldexp -
import math
result = math.ldexp(0.75, 3)
print("The result obtained is:",result)
输出
获得的输出如下 -
The result obtained is: 6.0
示例 2
在这里,我们通过将数字提高到负指数来计算数字的 ldexp -
import math
result = math.ldexp(1.5, -2)
print("The result obtained is:",result)
输出
以下是上述代码的输出 -
The result obtained is: 0.375
示例 3
现在,我们使用 “0” 作为有效数字来计算数字的 ldexp -
import math
result = math.ldexp(0, 5)
print("The result is:",result)
输出
我们得到的输出如下所示 -
The result obtained is: 0.0
示例 4
在此示例中,我们使用变量 “significand” 和 “exponent” 分别存储值 “1.25” 和 “-3”。然后我们计算 ldexp −
import math
significand = 1.25
exponent = -3
result = math.ldexp(significand, exponent)
print("The result obtained is:",result)
输出
生成的结果如下所示 -
The result obtained is: 0.15625