The Python ldexp math function is used to return x * (2**i). Python ldexp function also called the inverse of the frexp method. In this section, we discuss how to use ldexp function in Python with example.
The syntax of the ldexp Function in Python Programming Language is
math.ldexp(x, i);
- X: Please specify the X value here.
- i: Please specify the i value here.
For example, if x = 2 and i = 3 then, Math.ldexp(2, 3) = 16. It is because, the formula behind this Python ldexp method is x * (2**i)
Output = 2 * (2**3) => 2 * (8)
so, the output is 16
NOTE: If the X value or i value argument is not a number, ldexp function return TypeError.
Python ldexp Function Example
The math ldexp function returns x * (2**i). In this example, we are going to find the ldexp value of different data types and display the output.
import math Tup = (1.50, 2.26, -3.05, -4.95 , 5.85) # Tuple Declaration Lis = [-1.98, 2.65, -9.29, -4.15 , 9.97] # List Declaration print('LDEXP() Function on Positive Number = %.2f' %math.ldexp(2, 3)) print('LDEXP() Function on Negative Number = %.2f' %math.ldexp(-3, 2)) print('LDEXP() Function on Positive Decimal = %.2f' %math.ldexp(4.5, 2)) print('LDEXP() Function on Negative Decimal = %.2f' %math.ldexp(-6.5, 3)) print('LDEXP() Function on Tuple Item = %.2f' %math.ldexp(Tup[2], 3)) print('LDEXP() Function on Tuple Item = %.2f' %math.ldexp(Tup[4], 3)) print('LDEXP() Function on List Item = %.2f' %math.ldexp(Lis[2], 4)) print('LDEXP() Function on List Item = %.2f' %math.ldexp(Lis[4], 4)) print('LDEXP() Function on Multiple Number = %.2f' %math.ldexp(1 + 2 - 9, 2)) print('LDEXP() Function on String Value = ', math.ldexp('2.95', 2))
- Within the first two statements, We passed both the Positive integer and negative integer as the ldexp Function arguments. From the above screenshot, the ldexp Function is returning output.
- Within the next two statements, we passed both the Positive and negative decimal values as the Python ldexp math Function arguments.
- Next four statements, We used the Tuple and List items as first arguments and Positive and negative decimal values as the second argument for this math method. If you observe the above, the ldexp function is working perfectly on them.
- Next, we assigned multiple values as the Python first arguments. And the ldexp Function worked without any issue.
- Last, We tried ldexp method on the String value, and it returns TypeError.