Using the numpy.ldexp() in Numpy


To return the x1 * 2**x2, element-wise, use the numpy.ldexp() method in Python Numpy. The 1st parameter X1 is the array of multipliers. The 2nd parameter X2 is the array of twos exponents. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

The out is a location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

The condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Steps

At first, import the required library −

import numpy as np

To return the x1 * 2**x2, element-wise, use the numpy.ldexp() method in Python Numpy.

Check for float −

print("Result? ", np.ldexp(5.6, np.arange(3)))

Check for negative float −

print("Result? ", np.ldexp(-7.5, np.arange(3)))

Check for int −

print("Result? ", np.ldexp(9, np.arange(3)))

Check for negative int −

print("Result? ", np.ldexp(106, np.arange(3)))

Check for nan −

print("Result? ", np.ldexp(np.nan, np.arange(3)))

Check for inf −

print("Result? ", np.ldexp(np.inf, np.arange(3)))

Example

import numpy as np

# To return the x1 * 2**x2, element-wise, use the numpy.ldexp() method in Python Numpy
# The 1st parameter X1 is the array of multipliers.
# The 2nd parameter X2 is the array of twos exponents.
# If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

# Check for float
print("Result? ", np.ldexp(5.6, np.arange(3)))

# Check for negative float
print("Result? ", np.ldexp(-7.5, np.arange(3)))

# Check for int
print("Result? ", np.ldexp(9, np.arange(3)))

# Check for negative int
print("Result? ", np.ldexp(106, np.arange(3)))

# Check for nan
print("Result? ", np.ldexp(np.nan, np.arange(3)))

# Check for inf
print("Result? ", np.ldexp(np.inf, np.arange(3)))

# Checking for log
print("Result? ", np.ldexp(np.log(1), np.arange(3)))

Output

Result? [ 5.6 11.2 22.4]
Result? [ -7.5 -15. -30. ]
Result? [ 9. 18. 36.]
Result? [106. 212. 424.]
Result? [nan nan nan]
Result? [inf inf inf]
Result? [0. 0. 0.]

Updated on: 08-Feb-2022

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements