ldexp() function in Python


In this article, we are going see how to use ldexp() function. This is one of the methods from the math library.

The function ldexp(first, second) take two valid number either positive or negative and returns the result of first * (2 ** second). Let's see some examples.

Example

 Live Demo

# importing the math library
import math

# using the function ldexp
print(math.ldexp(1, 4))
print(math.ldexp(5, -4))
print(math.ldexp(-3, -1))

If you run the above code, then you will get the following result.

Output

16.0
0.3125
-1.5

We will get error if we pass arguments other than numbers to the ldexp function. Let's see an example.

Example

 Live Demo

# importing the math library
import math

# using the function ldexp
print(math.ldexp(1, '4'))

If you run the above code, then you will get the following result.

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
3
4 # using the function ldexp
----> 5 print(math.ldexp(1, '4'))

TypeError: Expected an int as second argument to ldexp.

Conclusion

If you have any queries in the article, mention them in the comment section.

Updated on: 13-Nov-2020

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements