Python ldexp()函数示例| Python数学库

Python ldexp()函数与python frexp()函数相反。 Idexp()是一个内置的数学函数,用于计算浮点数中x *(2 ** i)的值。要使用此功能,我们首先必须导入数学库。

Python ldexp()

Python ldexp()函数是Python中的标准数学库函数之一,该函数返回x *(2 ** i)。

句法

ldexp()函数采用两个参数:

x->任何有效数字都可以是正数或负数。

i->任何有效数字都可以是正数或负数。

返回值

ldexp()函数返回一个浮点数为x *(2 ** i)的单个值。如果x或i的值不是数字,则此函数返回TypeError。

编程实例

请参阅以下代码。

# app.py

# Importing math library
import math

# First Type example: Take input from user
x = int(input("Enter value of x: "))
i = int(input("Enter value of i: "))
# Printing the value
print("Output of first type example", math.ldexp(x, i))

# Second Type Example : Using list and tuple value

# Declaring a list
l1 = [42, 12, 34, 6]
# Decalring a tuple
t1 = (24, 14, 34, 5)

# Printing values
print("Output of second type example", math.ldexp(l1[3], 3))  # i=3 x=6
print("Output of third type example", math.ldexp(t1[1], 4))  # i=4 x=14

# Third type example : When x is not a number
x = 'X'
i = 10
print(math.ldexp(x, i))

输出量

Enter value of x: 10
Enter value of i: 3
Output of first type example 80.0
Output of second type example 48.0
Output of third type example 224.0
Traceback (most recent call last):
  File "ldexp.py", line 25, in 
	print(math.ldexp(x,i))
TypeError: must be real number, not str

在此示例中,我们有三种输入示例。

在第一种类型的示例中,我们从用户那里获取了输入,然后打印了ldexp(x,i)的值,其中x = 10,i = 3。在第二种情况下,我们获取了一个列表和一个元组,然后分别从列表和元组中获取了x的值,并给定了i的值,然后得到了ldexp()的打印值。

最后,我们将x的值当作一个字符,而不是数字,因此该函数返回TypeError。

让我们看另一个示例,其中我们使用一个Python列表和元组。

# app.py

import math

# string value taken
print(math.ldexp('6', 36))
print(math.ldexp(36, '6'))

输出量

python3 app.py
Traceback (most recent call last):
  File "app.py", line 4, in 
    print(math.ldexp('6', 36))
TypeError: must be real number, not str

也可以看看

Python isnan()

Python isinf()

Python isfinite()

Python fsum()

Python fmod()

Python acos()

资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Ankit Lathiya所有,未经许可,不得转载
你可能还喜欢