Home » Python

math.ldexp() method with example in Python

Python math.ldexp() method: Here, we are going to learn about the math.ldexp() method with example in Python.
Submitted by IncludeHelp, on April 18, 2019

Python math.ldexp() method

math.ldexp() method is a library method of math module, it is used to calculate expression x*(2**i), 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*(2**i)).

Note: There is a method in math module math.frexp() that is used to get the pair of mantissa and exponent in a tuple. The math.ldexp() method is an inverse of math.frexp() method. In other words, w can understand that math.frexp() method returns mantissa and exponent of a number and math.ldexp() method reforms/creates the number again using x – mantissa and i – exponent.

Syntax of math.ldexp() method:

    math.ldexp(x, i)

Parameter(s): x, i – the numbers to be calculated the expression "x*(2**i)".

Return value: float – it returns a float value that is the result of expression "x*(2**i)".

Example:

    Input:
    x = 2
    i = 3

    # function call
    print(math.ldexp(x,i))

    Output:
    16.0 # (x*(2**i) = (2*(2**3)) = 16

Python code to demonstrate example of math.ldexp() method

# python code to demonstrate example of 
# math.ldexp() method

# importing math module
import math

# number
x = 2
i = 3
# math.ldexp() method
print(math.ldexp(x,i))

x = 0
i = 0
# math.ldexp() method
print(math.ldexp(x,i))

x = 0.625
i = 4
# math.ldexp() method
print(math.ldexp(x,i))

x = -0.639625
i = 4
# math.ldexp() method
print(math.ldexp(x,i))

Output

16.0
0.0
10.0
-10.234

Python code to differentiate the math.frexp() and math.ldexp() methods

Here, we have a number a and finding it's mantissa and exponent as a pair (x, i), and again making the same number by using math.ldexp() method that calculates the expression (x*(2**i))

# python code to demonstrate example of 
# math.ldexp() method

# importing math module
import math

a = 10
frexp_result = math.frexp(a)
print("frexp() result: ", frexp_result)

# extracing its values
x = frexp_result[0]
i = frexp_result[1]
print("Extracted part from frexp_result...")
print("x = ", x)
print("i = ", i)

# now using method ldexp()
ldexp_result = math.ldexp(x,i)
print("ldexp() result: ", ldexp_result)

Output

frexp() result:  (0.625, 4)
Extracted part from frexp_result...
x =  0.625
i =  4
ldexp() result:  10.0


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.