# Python numpy.frexp() Examples

The following are 30 code examples for showing how to use numpy.frexp(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module , or try the search function .

Example 1
```def test_failing_out_wrap(self):

singleton = np.array([1.0])

class Ok(np.ndarray):
def __array_wrap__(self, obj):
return singleton

def __array_wrap__(self, obj):
raise RuntimeError

ok = np.empty(1).view(Ok)

# double-free (segfault) of "ok" if "bad" raises an exception
for i in range(10):
assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) ```
Example 2
```def robust_outer_product(vec_1, vec_2):
"""
Calculates a 'robust' outer product of two vectors that may or may not
contain very small values.

Parameters
----------
vec_1 : 1D ndarray
vec_2 : 1D ndarray

Returns
-------
outer_prod : 2D ndarray. The outer product of vec_1 and vec_2
"""
mantissa_1, exponents_1 = np.frexp(vec_1)
mantissa_2, exponents_2 = np.frexp(vec_2)
new_mantissas = mantissa_1[None, :] * mantissa_2[:, None]
new_exponents = exponents_1[None, :] + exponents_2[:, None]
return new_mantissas * np.exp2(new_exponents) ```
Example 3
```def testFrexp(self):
t1 = ones((3, 4, 5), chunk_size=2)
t2 = empty((3, 4, 5), dtype=np.float_, chunk_size=2)
op_type = type(t1.op)

o1, o2 = frexp(t1)

self.assertIs(o1.op, o2.op)
self.assertNotEqual(o1.dtype, o2.dtype)

o1, o2 = frexp(t1, t1)

self.assertIs(o1, t1)
self.assertIsNot(o1.inputs[0], t1)
self.assertIsInstance(o1.inputs[0].op, op_type)
self.assertIsNot(o2.inputs[0], t1)

o1, o2 = frexp(t1, t2, where=t1 > 0)

op_type = type(t2.op)
self.assertIs(o1, t2)
self.assertIsNot(o1.inputs[0], t1)
self.assertIsInstance(o1.inputs[0].op, op_type)
self.assertIsNot(o2.inputs[0], t1) ```
Example 4
```def test_failing_out_wrap(self):

singleton = np.array([1.0])

class Ok(np.ndarray):
def __array_wrap__(self, obj):
return singleton

def __array_wrap__(self, obj):
raise RuntimeError

ok = np.empty(1).view(Ok)

# double-free (segfault) of "ok" if "bad" raises an exception
for i in range(10):
assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) ```
Example 5
```def test_failing_out_wrap(self):

singleton = np.array([1.0])

class Ok(np.ndarray):
def __array_wrap__(self, obj):
return singleton

def __array_wrap__(self, obj):
raise RuntimeError

ok = np.empty(1).view(Ok)

# double-free (segfault) of "ok" if "bad" raises an exception
for i in range(10):
assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) ```
Example 6
```def clear_fuss(ar, fuss_binary_bits=7):
"""Clears trailing `fuss_binary_bits` of mantissa of a floating number"""
x = np.asanyarray(ar)
if np.iscomplexobj(x):
return clear_fuss(x.real) + 1j * clear_fuss(x.imag)

significant_binary_bits = np.finfo(x.dtype).nmant
x_mant, x_exp = np.frexp(x)
f = 2.0**(significant_binary_bits - fuss_binary_bits)
x_mant *= f
np.rint(x_mant, out=x_mant)
x_mant /= f

return np.ldexp(x_mant, x_exp)

# XXX: This function should be available through numpy.testing ```
Example 7
```def test_failing_out_wrap(self):

singleton = np.array([1.0])

class Ok(np.ndarray):
def __array_wrap__(self, obj):
return singleton

def __array_wrap__(self, obj):
raise RuntimeError

ok = np.empty(1).view(Ok)

# double-free (segfault) of "ok" if "bad" raises an exception
for i in range(10):
assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) ```
Example 8
```def test_failing_out_wrap(self):

singleton = np.array([1.0])

class Ok(np.ndarray):
def __array_wrap__(self, obj):
return singleton

def __array_wrap__(self, obj):
raise RuntimeError

ok = np.empty(1).view(Ok)

# double-free (segfault) of "ok" if "bad" raises an exception
for i in range(10):
assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) ```
Example 9
```def test_failing_out_wrap(self):

singleton = np.array([1.0])

class Ok(np.ndarray):
def __array_wrap__(self, obj):
return singleton

def __array_wrap__(self, obj):
raise RuntimeError

ok = np.empty(1).view(Ok)

# double-free (segfault) of "ok" if "bad" raises an exception
for i in range(10):
assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) ```
Example 10
```def test_failing_out_wrap(self):

singleton = np.array([1.0])

class Ok(np.ndarray):
def __array_wrap__(self, obj):
return singleton

def __array_wrap__(self, obj):
raise RuntimeError

ok = np.empty(1).view(Ok)

# double-free (segfault) of "ok" if "bad" raises an exception
for i in range(10):
assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) ```
Example 11
```def test_failing_out_wrap(self):

singleton = np.array([1.0])

class Ok(np.ndarray):
def __array_wrap__(self, obj):
return singleton

def __array_wrap__(self, obj):
raise RuntimeError

ok = np.empty(1).view(Ok)

# double-free (segfault) of "ok" if "bad" raises an exception
for i in range(10):
assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) ```
Example 12
```def test_ufunc_two_outputs(self):
mantissa, exponent = np.frexp(2 ** -3)
expected = (ArrayLike(mantissa), ArrayLike(exponent))
_assert_equal_type_and_value(
np.frexp(ArrayLike(2 ** -3)), expected)
_assert_equal_type_and_value(
np.frexp(ArrayLike(np.array(2 ** -3))), expected) ```
Example 13
```def test_doc(self):
# don't bother checking the long list of kwargs, which are likely to
# change
"add(x1, x2, /, out=None, *, where=True"))
assert_(ncu.frexp.__doc__.startswith(
"frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) ```
Example 14
```def execute(cls, ctx, op):
inputs, device_id, xp = as_same_device(
[ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)

with device(device_id):
kw = {'casting': op.casting}

inputs_iter = iter(inputs)
input = next(inputs_iter)
if op.out1 is not None:
out1 = next(inputs_iter)
else:
out1 = None
if op.out2 is not None:
out2 = next(inputs_iter)
else:
out2 = None
if op.where is not None:
where = kw['where'] = next(inputs_iter)
else:
where = None
kw['order'] = op.order

try:
args = [input]
if out1 is not None:
args.append(out1)
if out2 is not None:
args.append(out2)
mantissa, exponent = xp.frexp(*args, **kw)
except TypeError:
if where is None:
raise
mantissa, exponent = xp.frexp(input)
mantissa, exponent = xp.where(where, mantissa, out1), xp.where(where, exponent, out2)

for c, res in zip(op.outputs, (mantissa, exponent)):
ctx[c.key] = res ```
Example 15
```def testFrexpExecution(self):
data1 = np.random.random((5, 9, 4))

arr1 = tensor(data1.copy(), chunk_size=3)

o1, o2 = frexp(arr1)
o = o1 + o2

res = self.executor.execute_tensor(o, concat=True)[0]
expected = sum(np.frexp(data1))
self.assertTrue(np.allclose(res, expected))

arr1 = tensor(data1.copy(), chunk_size=3)
o1 = zeros(data1.shape, chunk_size=3)
o2 = zeros(data1.shape, dtype='i8', chunk_size=3)
frexp(arr1, o1, o2)
o = o1 + o2

res = self.executor.execute_tensor(o, concat=True)[0]
expected = sum(np.frexp(data1))
self.assertTrue(np.allclose(res, expected))

data1 = sps.random(5, 9, density=.1)

arr1 = tensor(data1.copy(), chunk_size=3)

o1, o2 = frexp(arr1)
o = o1 + o2

res = self.executor.execute_tensor(o, concat=True)[0]
expected = sum(np.frexp(data1.toarray()))
np.testing.assert_equal(res.toarray(), expected) ```
Example 16
```def testFrexpOrderExecution(self):
data1 = np.random.random((5, 9))
t = tensor(data1, chunk_size=3)

o1, o2 = frexp(t, order='F')
res1, res2 = self.executor.execute_tileables([o1, o2])
expected1, expected2 = np.frexp(data1, order='F')
np.testing.assert_allclose(res1, expected1)
self.assertTrue(res1.flags['F_CONTIGUOUS'])
self.assertFalse(res1.flags['C_CONTIGUOUS'])
np.testing.assert_allclose(res2, expected2)
self.assertTrue(res2.flags['F_CONTIGUOUS'])
self.assertFalse(res2.flags['C_CONTIGUOUS']) ```
Example 17
```def test_ufunc_override_out(self):
# 2016-01-29: NUMPY_UFUNC_DISABLED
return

class A(object):
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return kwargs

class B(object):
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return kwargs

a = A()
b = B()
res0 = np.multiply(a, b, 'out_arg')
res1 = np.multiply(a, b, out='out_arg')
res2 = np.multiply(2, b, 'out_arg')
res3 = np.multiply(3, b, out='out_arg')
res4 = np.multiply(a, 4, 'out_arg')
res5 = np.multiply(a, 5, out='out_arg')

assert_equal(res0['out'], 'out_arg')
assert_equal(res1['out'], 'out_arg')
assert_equal(res2['out'], 'out_arg')
assert_equal(res3['out'], 'out_arg')
assert_equal(res4['out'], 'out_arg')
assert_equal(res5['out'], 'out_arg')

# ufuncs with multiple output modf and frexp.
res6 = np.modf(a, 'out0', 'out1')
res7 = np.frexp(a, 'out0', 'out1')
assert_equal(res6['out'][0], 'out0')
assert_equal(res6['out'][1], 'out1')
assert_equal(res7['out'][0], 'out0')
assert_equal(res7['out'][1], 'out1') ```
Example 18
```def test_ufunc_two_outputs(self):
mantissa, exponent = np.frexp(2 ** -3)
expected = (ArrayLike(mantissa), ArrayLike(exponent))
_assert_equal_type_and_value(
np.frexp(ArrayLike(2 ** -3)), expected)
_assert_equal_type_and_value(
np.frexp(ArrayLike(np.array(2 ** -3))), expected) ```
Example 19
```def test_doc(self):
# don't bother checking the long list of kwargs, which are likely to
# change
"add(x1, x2, /, out=None, *, where=True"))
assert_(ncu.frexp.__doc__.startswith(
"frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) ```
Example 20
```def test_ufunc_two_outputs(self):
mantissa, exponent = np.frexp(2 ** -3)
expected = (ArrayLike(mantissa), ArrayLike(exponent))
_assert_equal_type_and_value(
np.frexp(ArrayLike(2 ** -3)), expected)
_assert_equal_type_and_value(
np.frexp(ArrayLike(np.array(2 ** -3))), expected) ```
Example 21
```def test_doc(self):
# don't bother checking the long list of kwargs, which are likely to
# change
"add(x1, x2, /, out=None, *, where=True"))
assert_(ncu.frexp.__doc__.startswith(
"frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) ```
Example 22
```def test_ufunc_two_outputs(self):
mantissa, exponent = np.frexp(2 ** -3)
expected = (ArrayLike(mantissa), ArrayLike(exponent))
_assert_equal_type_and_value(
np.frexp(ArrayLike(2 ** -3)), expected)
_assert_equal_type_and_value(
np.frexp(ArrayLike(np.array(2 ** -3))), expected) ```
Example 23
```def test_ufunc_two_outputs(self):
mantissa, exponent = np.frexp(2 ** -3)
expected = (ArrayLike(mantissa), ArrayLike(exponent))
_assert_equal_type_and_value(
np.frexp(ArrayLike(2 ** -3)), expected)
_assert_equal_type_and_value(
np.frexp(ArrayLike(np.array(2 ** -3))), expected) ```
Example 24
```def test_doc(self):
# don't bother checking the long list of kwargs, which are likely to
# change
"add(x1, x2, /, out=None, *, where=True"))
assert_(ncu.frexp.__doc__.startswith(
"frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) ```
Example 25
```def radiance_writer(out_path, image):
with open(out_path, "wb") as f:
f.write(b"-Y %d +X %d\n" %(image.shape[0], image.shape[1]))

brightest = np.maximum(np.maximum(image[...,0], image[...,1]), image[...,2])
mantissa = np.zeros_like(brightest)
exponent = np.zeros_like(brightest)
np.frexp(brightest, mantissa, exponent)
scaled_mantissa = mantissa * 255.0 / brightest
rgbe = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
rgbe[...,0:3] = np.around(image[...,0:3] * scaled_mantissa[...,None])
rgbe[...,3] = np.around(exponent + 128)

rgbe.flatten().tofile(f) ```
Example 26
```def test_frexp(self, dtype):
numpy_a = numpy.array([-300, -20, -10, -1, 0, 1, 10, 20, 300],
dtype=dtype)
numpy_b, numpy_c = numpy.frexp(numpy_a)

cupy_a = cupy.array(numpy_a)
cupy_b, cupy_c = cupy.frexp(cupy_a)

testing.assert_array_equal(cupy_b, numpy_b)
testing.assert_array_equal(cupy_c, numpy_c) ```
Example 27
```def test_ufunc_two_outputs(self):
mantissa, exponent = np.frexp(2 ** -3)
expected = (ArrayLike(mantissa), ArrayLike(exponent))
_assert_equal_type_and_value(
np.frexp(ArrayLike(2 ** -3)), expected)
_assert_equal_type_and_value(
np.frexp(ArrayLike(np.array(2 ** -3))), expected) ```
Example 28
```def test_ufunc_two_outputs(self):
mantissa, exponent = np.frexp(2 ** -3)
expected = (ArrayLike(mantissa), ArrayLike(exponent))
_assert_equal_type_and_value(
np.frexp(ArrayLike(2 ** -3)), expected)
_assert_equal_type_and_value(
np.frexp(ArrayLike(np.array(2 ** -3))), expected) ```
Example 29
```def test_doc(self):
# don't bother checking the long list of kwargs, which are likely to
# change
```def pow_next_log_of_2_no_round(value, bound_shift, shift_max_shift=4):