Return mantissa and exponent as a pair of a given value in Numpy


To return mantissa and exponent as a pair of a given value, use the numpy.frexp() method in Python Numpy. 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 willbe 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 mantissa and exponent as a pair of a given value, use the numpy.frexp() method in Python Numpy.

Check for float −

print("Result? ", np.frexp(6.9))
print("
Result? ", np.frexp(-4.8))

Check for int and inf −

print("
Result? ", np.frexp(40)) print("
Result? ", np.frexp(-np.inf))

Check for nan and inf −

print("
Result? ", np.frexp(np.nan)) print("
Result? ", np.frexp(np.inf))

Check for log −

print("
Result? ", np.frexp(np.log(1))) print("
Result? ", np.frexp(np.log(2)))

Example

import numpy as np

# To return mantissa and exponent as a pair of a given value, use the numpy.frexp() method in Python Numpy
print("Returning the mantissa and exponent...
") # Check for float print("Result? ", np.frexp(6.9)) print("
Result? ", np.frexp(-4.8)) # Check for int and inf print("
Result? ", np.frexp(40)) print("
Result? ", np.frexp(-np.inf)) # Check for nan and inf print("
Result? ", np.frexp(np.nan)) print("
Result? ", np.frexp(np.inf)) # Check for log print("
Result? ", np.frexp(np.log(1))) print("
Result? ", np.frexp(np.log(2)))

Output

Returning the mantissa and exponent...

Result? (0.8625, 3)

Result? (-0.6, 3)

Result? (0.625, 6)

Result? (-inf, 0)

Result? (nan, 0)

Result? (inf, 0)

Result? (0.0, 0)

Result? (0.6931471805599453, 0)

Updated on: 08-Feb-2022

234 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements