Python numpy.frexp() Examples

The following are 30 code examples of numpy.frexp(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: test_decomp.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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 #2
Source File: test_umath.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

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

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

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

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example #3
Source File: test_umath.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

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

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

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

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example #4
Source File: test_umath.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

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

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

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

        # 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
Source File: test_umath.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

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

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

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

        # 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
Source File: test_umath.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

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

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

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

        # double-free (segfault) of "ok" if "bad" raises an exception
        for i in range(10):
            assert_raises(RuntimeError, ncu.frexp, 1, ok, bad) 
Example #7
Source File: test_umath.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

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

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

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

        # 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
Source File: test_arithmetic.py    From mars with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: test_umath.py    From pySINDy with MIT License 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

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

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

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

        # 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
Source File: test_umath.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_failing_out_wrap(self):

        singleton = np.array([1.0])

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

        class Bad(np.ndarray):
            def __array_wrap__(self, obj):
                raise RuntimeError

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

        # 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
Source File: choice_calcs.py    From pylogit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #12
Source File: test_umath.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def test_doc(self):
        # don't bother checking the long list of kwargs, which are likely to
        # change
        assert_(ncu.add.__doc__.startswith(
            "add(x1, x2, /, out=None, *, where=True"))
        assert_(ncu.frexp.__doc__.startswith(
            "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) 
Example #13
Source File: test_umath.py    From keras-lambda with MIT License 5 votes vote down vote up
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 #14
Source File: test_mixins.py    From coffeegrindsize with MIT License 5 votes vote down vote up
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 #15
Source File: k210_layer.py    From Maix-EMC with Apache License 2.0 5 votes vote down vote up
def pow_next_log_of_2_no_round(value, bound_shift, shift_max_shift=4):
    mul, shift = np.frexp(np.abs(value))    # value = mul(0~1)*(1 << shift)
    ret = bound_shift - 1 - shift           # shift to full bound_shift
    mul = np.sign(value) * mul * np.power(2, bound_shift - 1)   # scale mul
    # value = mul>>ret
    return ret, mul 
Example #16
Source File: test_mixins.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
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 #17
Source File: test_mixins.py    From recruit with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: test_mixins.py    From pySINDy with MIT License 5 votes vote down vote up
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
Source File: test_umath.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_doc(self):
        # don't bother checking the long list of kwargs, which are likely to
        # change
        assert_(ncu.add.__doc__.startswith(
            "add(x1, x2, /, out=None, *, where=True"))
        assert_(ncu.frexp.__doc__.startswith(
            "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) 
Example #20
Source File: test_umath.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def test_doc(self):
        # don't bother checking the long list of kwargs, which are likely to
        # change
        assert_(ncu.add.__doc__.startswith(
            "add(x1, x2, /, out=None, *, where=True"))
        assert_(ncu.frexp.__doc__.startswith(
            "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) 
Example #21
Source File: _financial.py    From numpy-financial with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _roots(p):
    """Modified version of NumPy's roots function.

    NumPy's roots uses the companion matrix method, which divides by
    p[0]. This can causes overflows/underflows. Instead form a
    modified companion matrix that is scaled by 2^c * p[0], where the
    exponent c is chosen to balance the magnitudes of the
    coefficients. Since scaling the matrix just scales the
    eigenvalues, we can remove the scaling at the end.

    Scaling by a power of 2 is chosen to avoid rounding errors.

    """
    _, e = np.frexp(p)
    # Balance the most extreme exponents e_max and e_min by solving
    # the equation
    #
    # |c + e_max| = |c + e_min|.
    #
    # Round the exponent to an integer to avoid rounding errors.
    c = int(-0.5 * (np.max(e) + np.min(e)))
    p = np.ldexp(p, c)

    A = np.diag(np.full(p.size - 2, p[0]), k=-1)
    A[0,:] = -p[1:]
    eigenvalues = np.linalg.eigvals(A)
    return eigenvalues / p[0] 
Example #22
Source File: utils.py    From DeepHDR with MIT License 5 votes vote down vote up
def radiance_writer(out_path, image):
    with open(out_path, "wb") as f:
        f.write(b"#?RADIANCE\n# Made with Python & Numpy\nFORMAT=32-bit_rle_rgbe\n\n")
        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 #23
Source File: test_umath.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_out_subok(self):
        for b in (True, False):
            aout = np.array(0.5)

            r = np.add(aout, 2, out=aout)
            assert_(r is aout)
            assert_array_equal(r, aout)

            r = np.add(aout, 2, out=aout, subok=b)
            assert_(r is aout)
            assert_array_equal(r, aout)

            r = np.add(aout, 2, aout, subok=False)
            assert_(r is aout)
            assert_array_equal(r, aout)

            d = np.ones(5)
            o1 = np.zeros(5)
            o2 = np.zeros(5, dtype=np.int32)
            r1, r2 = np.frexp(d, o1, o2, subok=b)
            assert_(r1 is o1)
            assert_array_equal(r1, o1)
            assert_(r2 is o2)
            assert_array_equal(r2, o2)

            r1, r2 = np.frexp(d, out=o1, subok=b)
            assert_(r1 is o1)
            assert_array_equal(r1, o1) 
Example #24
Source File: test_umath.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_doc(self):
        # don't bother checking the long list of kwargs, which are likely to
        # change
        assert_(ncu.add.__doc__.startswith(
            "add(x1, x2, /, out=None, *, where=True"))
        assert_(ncu.frexp.__doc__.startswith(
            "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) 
Example #25
Source File: test_quantity_ufuncs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_frexp_scalar(self):
        q = np.frexp(3. * u.m / (6. * u.m))
        assert q == (np.array(0.5), np.array(0.0)) 
Example #26
Source File: test_umath.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_ufunc_override_out(self):
        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 #27
Source File: test_quantity_ufuncs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_frexp_array(self):
        q = np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.m))
        assert all((_q0, _q1) == np.frexp(_d) for _q0, _q1, _d
                   in zip(q[0], q[1], [1. / 3., 1. / 2., 1.])) 
Example #28
Source File: test_mixins.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
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
Source File: test_mixins.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
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 #30
Source File: test_floating.py    From cupy with MIT License 5 votes vote down vote up
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)