Introduction Python ldexp() Method with Examples

Python Ldexp() method is a library method of math module, it is used to calculate expression x*(2i), where x is a mantissa and i is an exponent. It accepts two numbers (x is either float or integer, i is an integer) and returns the result of the expression x*(2i)).

Python Ldexp()

Syntax

    math.ldexp(x, i)

Parameter(s):

  • x is any valid Python number (positive or negative).
  • i is any valid Python number (positive or negative).

Return value:

The ldexp() function returns a single value that is x*(2**i) in floating-point . If the value of x or i is not a number, then this function returns a TypeError.

Examples of Python ldexp() method

Example 1

# import math library
import math
 
print (math.ldexp(15,2))
print (math.ldexp(-2.3,6))
print (math.ldexp(3.5,-5))
print (math.ldexp(9,-75))
print (math.ldexp(-2.3,2))
print (math.ldexp(3.5,9))

Output

60.0
-147.2
0.109375
2.3822801641527197e-22
-9.2
1792.0

Note that in output all the numbers (whether they are negative or positive) return value of x * (2**i) by using math.ldexp() function.

Example 2


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

Output


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 <module>
    print(math.ldexp(x,i))
TypeError: must be real number, not str

In this example, we have three types of input example.

In the first type of example, we have taken input from the user, and then we have printed the value of ldexp(x, i) where x=10 and i=3. In the second case, we have taken a list and a tuple, and then we have taken the value of x from both list and tuple respectively and given value of i, then we have printed value of ldexp().

At last, we have taken the value of x a character, which is not a number, so the function returned a TypeError.

Thanks for reading !

#python #programming

Introduction Python ldexp() Method with Examples
1 Likes17.15 GEEK