Python numpy.longdouble() Examples

The following are 30 code examples of numpy.longdouble(). 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_floating.py    From me-ica with GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_as_int():
    # Integer representation of number
    assert_equal(as_int(2.0), 2)
    assert_equal(as_int(-2.0), -2)
    assert_raises(FloatingError, as_int, 2.1)
    assert_raises(FloatingError, as_int, -2.1)
    assert_equal(as_int(2.1, False), 2)
    assert_equal(as_int(-2.1, False), -2)
    v = np.longdouble(2**64)
    assert_equal(as_int(v), 2**64)
    # Have all long doubles got 63+1 binary bits of precision?  Windows 32-bit
    # longdouble appears to have 52 bit precision, but we avoid that by checking
    # for known precisions that are less than that required
    try:
        nmant = type_info(np.longdouble)['nmant']
    except FloatingError:
        nmant = 63 # Unknown precision, let's hope it's at least 63
    v = np.longdouble(2) ** (nmant + 1) - 1
    assert_equal(as_int(v), 2**(nmant + 1) -1)
    # Check for predictable overflow
    nexp64 = floor_log2(type_info(np.float64)['max'])
    val = np.longdouble(2**nexp64) * 2 # outside float64 range
    assert_raises(OverflowError, as_int, val)
    assert_raises(OverflowError, as_int, -val) 
Example #2
Source File: test_getlimits.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_known_types():
    # Test we are correctly compiling parameters for known types
    for ftype, ma_like in ((np.float16, _float_ma[16]),
                           (np.float32, _float_ma[32]),
                           (np.float64, _float_ma[64])):
        assert_ma_equal(_discovered_machar(ftype), ma_like)
    # Suppress warning for broken discovery of double double on PPC
    with np.errstate(all='ignore'):
        ld_ma = _discovered_machar(np.longdouble)
    bytes = np.dtype(np.longdouble).itemsize
    if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in (12, 16):
        # 80-bit extended precision
        assert_ma_equal(ld_ma, _float_ma[80])
    elif (ld_ma.it, ld_ma.maxexp) == (112, 16384) and bytes == 16:
        # IEE 754 128-bit
        assert_ma_equal(ld_ma, _float_ma[128]) 
Example #3
Source File: test_print.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_float_types(tp):
    """ Check formatting.

        This is only for the str function, and only for simple types.
        The precision of np.float32 and np.longdouble aren't the same as the
        python float precision.

    """
    for x in [0, 1, -1, 1e20]:
        assert_equal(str(tp(x)), str(float(x)),
                     err_msg='Failed str formatting for type %s' % tp)

    if tp(1e16).itemsize > 4:
        assert_equal(str(tp(1e16)), str(float('1e16')),
                     err_msg='Failed str formatting for type %s' % tp)
    else:
        ref = '1e+16'
        assert_equal(str(tp(1e16)), ref,
                     err_msg='Failed str formatting for type %s' % tp) 
Example #4
Source File: test_scalarprint.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_str(self):
        svals = [0.0, -0.0, 1, -1, np.inf, -np.inf, np.nan]
        styps = [np.float16, np.float32, np.float64, np.longdouble]
        wanted = [
             ['0.0',  '0.0',  '0.0',  '0.0' ],
             ['-0.0', '-0.0', '-0.0', '-0.0'],
             ['1.0',  '1.0',  '1.0',  '1.0' ],
             ['-1.0', '-1.0', '-1.0', '-1.0'],
             ['inf',  'inf',  'inf',  'inf' ],
             ['-inf', '-inf', '-inf', '-inf'],
             ['nan',  'nan',  'nan',  'nan']]

        for wants, val in zip(wanted, svals):
            for want, styp in zip(wants, styps):
                msg = 'for str({}({}))'.format(np.dtype(styp).name, repr(val))
                assert_equal(str(styp(val)), want, err_msg=msg) 
Example #5
Source File: test_scalar_ctors.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_floating_overflow(self):
        """ Strings containing an unrepresentable float overflow """
        fhalf = np.half('1e10000')
        assert_equal(fhalf, np.inf)
        fsingle = np.single('1e10000')
        assert_equal(fsingle, np.inf)
        fdouble = np.double('1e10000')
        assert_equal(fdouble, np.inf)
        flongdouble = assert_warns(RuntimeWarning, np.longdouble, '1e10000')
        assert_equal(flongdouble, np.inf)

        fhalf = np.half('-1e10000')
        assert_equal(fhalf, -np.inf)
        fsingle = np.single('-1e10000')
        assert_equal(fsingle, -np.inf)
        fdouble = np.double('-1e10000')
        assert_equal(fdouble, -np.inf)
        flongdouble = assert_warns(RuntimeWarning, np.longdouble, '-1e10000')
        assert_equal(flongdouble, -np.inf) 
Example #6
Source File: test_ufunc.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_sum(self):
        for dt in (np.int, np.float16, np.float32, np.float64, np.longdouble):
            for v in (0, 1, 2, 7, 8, 9, 15, 16, 19, 127,
                      128, 1024, 1235):
                tgt = dt(v * (v + 1) / 2)
                d = np.arange(1, v + 1, dtype=dt)
                assert_almost_equal(np.sum(d), tgt)
                assert_almost_equal(np.sum(d[::-1]), tgt)

            d = np.ones(500, dtype=dt)
            assert_almost_equal(np.sum(d[::2]), 250.)
            assert_almost_equal(np.sum(d[1::2]), 250.)
            assert_almost_equal(np.sum(d[::3]), 167.)
            assert_almost_equal(np.sum(d[1::3]), 167.)
            assert_almost_equal(np.sum(d[::-2]), 250.)
            assert_almost_equal(np.sum(d[-1::-2]), 250.)
            assert_almost_equal(np.sum(d[::-3]), 167.)
            assert_almost_equal(np.sum(d[-1::-3]), 167.)
            # sum with first reduction entry != 0
            d = np.ones((1,), dtype=dt)
            d += d
            assert_almost_equal(d, 2.) 
Example #7
Source File: casting.py    From me-ica with GNU Lesser General Public License v2.1 6 votes vote down vote up
def best_float():
    """ Floating point type with best precision

    This is nearly always np.longdouble, except on Windows, where np.longdouble
    is Intel80 storage, but with float64 precision for calculations.  In that
    case we return float64 on the basis it's the fastest and smallest at the
    highest precision.

    Returns
    -------
    best_type : numpy type
        floating point type with highest precision
    """
    if (type_info(np.longdouble)['nmant'] > type_info(np.float64)['nmant'] and
        machine() != 'sparc64'): # sparc has crazy-slow float128
        return np.longdouble
    return np.float64 
Example #8
Source File: test_print.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_scalar_format():
    """Test the str.format method with NumPy scalar types"""
    tests = [('{0}', True, np.bool_),
            ('{0}', False, np.bool_),
            ('{0:d}', 130, np.uint8),
            ('{0:d}', 50000, np.uint16),
            ('{0:d}', 3000000000, np.uint32),
            ('{0:d}', 15000000000000000000, np.uint64),
            ('{0:d}', -120, np.int8),
            ('{0:d}', -30000, np.int16),
            ('{0:d}', -2000000000, np.int32),
            ('{0:d}', -7000000000000000000, np.int64),
            ('{0:g}', 1.5, np.float16),
            ('{0:g}', 1.5, np.float32),
            ('{0:g}', 1.5, np.float64),
            ('{0:g}', 1.5, np.longdouble)]
    # Python 2.6 doesn't implement complex.__format__
    if sys.version_info[:2] > (2, 6):
        tests += [('{0:g}', 1.5+0.5j, np.complex64),
                ('{0:g}', 1.5+0.5j, np.complex128),
                ('{0:g}', 1.5+0.5j, np.clongdouble)]

    for (fmat, val, valtype) in tests:
        try:
            assert_equal(fmat.format(val), fmat.format(valtype(val)),
                    "failed with val %s, type %s" % (val, valtype))
        except ValueError as e:
            assert_(False,
               "format raised exception (fmt='%s', val=%s, type=%s, exc='%s')" %
                            (fmat, repr(val), repr(valtype), str(e)))


# Locale tests: scalar types formatting should be independent of the locale 
Example #9
Source File: test_print.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_complex_types():
    """Check formatting of complex types.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.complex64, np.cdouble, np.clongdouble]:
        yield check_complex_type, t 
Example #10
Source File: test_print.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_locale_longdouble():
    assert_equal(str(np.longdouble(1.2)), str(float(1.2))) 
Example #11
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_fromstring_foreign_sep(self):
        a = np.array([1, 2, 3, 4])
        b = np.fromstring("1,2,3,4,", dtype=np.longdouble, sep=",")
        assert_array_equal(a, b) 
Example #12
Source File: test_print.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_nan_inf_float():
    """ Check formatting of nan & inf.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.float32, np.double, np.longdouble]:
        yield check_nan_inf_float, t 
Example #13
Source File: test_half.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_half_conversions(self):
        """Checks that all 16-bit values survive conversion
           to/from 32-bit and 64-bit float"""
        # Because the underlying routines preserve the NaN bits, every
        # value is preserved when converting to/from other floats.

        # Convert from float32 back to float16
        b = np.array(self.all_f32, dtype=float16)
        assert_equal(self.all_f16.view(dtype=uint16),
                     b.view(dtype=uint16))

        # Convert from float64 back to float16
        b = np.array(self.all_f64, dtype=float16)
        assert_equal(self.all_f16.view(dtype=uint16),
                     b.view(dtype=uint16))

        # Convert float16 to longdouble and back
        # This doesn't necessarily preserve the extra NaN bits,
        # so exclude NaNs.
        a_ld = np.array(self.nonan_f16, dtype=np.longdouble)
        b = np.array(a_ld, dtype=float16)
        assert_equal(self.nonan_f16.view(dtype=uint16),
                     b.view(dtype=uint16))

        # Check the range for which all integers can be represented
        i_int = np.arange(-2048, 2049)
        i_f16 = np.array(i_int, dtype=float16)
        j = np.array(i_f16, dtype=np.int)
        assert_equal(i_int, j) 
Example #14
Source File: test_numerictypes.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_longdouble(self):
        assert_(np.sctypeDict['f8'] is not np.longdouble)
        assert_(np.sctypeDict['c16'] is not np.clongdouble) 
Example #15
Source File: test_umath.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_spacingl():
    return _test_spacing(np.longdouble) 
Example #16
Source File: test_umath.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _check_ldexp(self, tp):
        assert_almost_equal(ncu.ldexp(np.array(2., np.float32),
                                      np.array(3, tp)), 16.)
        assert_almost_equal(ncu.ldexp(np.array(2., np.float64),
                                      np.array(3, tp)), 16.)
        assert_almost_equal(ncu.ldexp(np.array(2., np.longdouble),
                                      np.array(3, tp)), 16.) 
Example #17
Source File: test_longdouble.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_scalar_extraction():
    """Confirm that extracting a value doesn't convert to python float"""
    o = 1 + np.finfo(np.longdouble).eps
    a = np.array([o, o, o])
    assert_equal(a[1], o)


# Conversions string -> long double 
Example #18
Source File: test_longdouble.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_unicode():
    np.longdouble(sixu("1.2")) 
Example #19
Source File: test_getlimits.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_singleton(self):
        ftype = finfo(longdouble)
        ftype2 = finfo(longdouble)
        assert_equal(id(ftype), id(ftype2)) 
Example #20
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_fromstring_foreign_value(self):
        b = np.fromstring("1,234", dtype=np.longdouble, sep=" ")
        assert_array_equal(b[0], 1) 
Example #21
Source File: test_scalarmath.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_int_from_infinite_longdouble(self):
        # gh-627
        x = np.longdouble(np.inf)
        assert_raises(OverflowError, int, x)
        with suppress_warnings() as sup:
            sup.record(np.ComplexWarning)
            x = np.clongdouble(np.inf)
            assert_raises(OverflowError, int, x)
            assert_equal(len(sup.log), 1) 
Example #22
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_fromstring_best_effort(self):
        assert_equal(np.fromstring("1,234", dtype=np.longdouble, sep=" "),
                     np.array([1.])) 
Example #23
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_repr_roundtrip_foreign(self):
        o = 1.5
        assert_equal(o, np.longdouble(repr(o))) 
Example #24
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_array_repr():
    o = 1 + LD_INFO.eps
    a = np.array([o])
    b = np.array([1], dtype=np.longdouble)
    if not np.all(a != b):
        raise ValueError("precision loss creating arrays")
    assert_(repr(a) != repr(b))

#
# Locale tests: scalar types formatting should be independent of the locale
# 
Example #25
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_tofile_roundtrip(self):
        with temppath() as path:
            self.tgt.tofile(path, sep=" ")
            res = np.fromfile(path, dtype=np.longdouble, sep=" ")
        assert_equal(res, self.tgt)


# Conversions long double -> string 
Example #26
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_loadtxt(self):
        with temppath() as path:
            with open(path, 'wt') as f:
                f.write(self.out)
            res = np.loadtxt(path, dtype=np.longdouble)
        assert_equal(res, self.tgt) 
Example #27
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_fromfile(self):
        with temppath() as path:
            with open(path, 'wt') as f:
                f.write(self.out)
            res = np.fromfile(path, dtype=np.longdouble, sep="\n")
        assert_equal(res, self.tgt) 
Example #28
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_fromstring():
    o = 1 + LD_INFO.eps
    s = (" " + repr(o))*5
    a = np.array([o]*5)
    assert_equal(np.fromstring(s, sep=" ", dtype=np.longdouble), a,
                 err_msg="reading '%s'" % s) 
Example #29
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_bogus_string():
    assert_raises(ValueError, np.longdouble, "spam")
    assert_raises(ValueError, np.longdouble, "1.0 flub") 
Example #30
Source File: test_longdouble.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_repr_roundtrip_bytes():
    o = 1 + LD_INFO.eps
    assert_equal(np.longdouble(repr(o).encode("ascii")), o)