Latest Code Tutorials

Python ldexp() Function Example | Python Math Library


Python ldexp() function is the inverse of the python frexp() function. The Idexp() is an inbuilt math function that is used to calculate the value of x*(2**i) in floating numbers. To use this function, we first have to import the math library.

Python ldexp()

Python ldexp() function is one of the Standard math library functions in Python that returns x * (2**i).


The ldexp() function takes two arguments:

x -> any valid number can be positive or negative.

i -> any valid number can be 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.

Programming examples

See the following code.


# 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 "", line 25, in <module>
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.

Let’s see another example in which we take a Python list and tuple.


import math

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


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

See also

Python isnan()

Python isinf()

Python isfinite()

Python fsum()

Python fmod()

Python acos()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.