diff options
Diffstat (limited to 'numpy/lib')
-rw-r--r-- | numpy/lib/__init__.py | 4 | ||||
-rw-r--r-- | numpy/lib/getlimits.py | 288 | ||||
-rw-r--r-- | numpy/lib/machar.py | 317 | ||||
-rw-r--r-- | numpy/lib/polynomial.py | 3 | ||||
-rw-r--r-- | numpy/lib/tests/test_getlimits.py | 59 | ||||
-rw-r--r-- | numpy/lib/tests/test_machar.py | 31 | ||||
-rw-r--r-- | numpy/lib/type_check.py | 4 |
7 files changed, 3 insertions, 703 deletions
diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py index 07f6d5c27..5af08b23f 100644 --- a/numpy/lib/__init__.py +++ b/numpy/lib/__init__.py @@ -11,8 +11,6 @@ from ufunclike import * import scimath as emath from polynomial import * -from machar import * -from getlimits import * #import convertcode from utils import * from arraysetops import * @@ -30,8 +28,6 @@ __all__ += stride_tricks.__all__ __all__ += twodim_base.__all__ __all__ += ufunclike.__all__ __all__ += polynomial.__all__ -__all__ += machar.__all__ -__all__ += getlimits.__all__ __all__ += utils.__all__ __all__ += arraysetops.__all__ __all__ += io.__all__ diff --git a/numpy/lib/getlimits.py b/numpy/lib/getlimits.py deleted file mode 100644 index ccb0e2b3d..000000000 --- a/numpy/lib/getlimits.py +++ /dev/null @@ -1,288 +0,0 @@ -""" Machine limits for Float32 and Float64 and (long double) if available... -""" - -__all__ = ['finfo','iinfo'] - -from machar import MachAr -import numpy.core.numeric as numeric -import numpy.core.numerictypes as ntypes -from numpy.core.numeric import array -import numpy as np - -def _frz(a): - """fix rank-0 --> rank-1""" - if a.ndim == 0: a.shape = (1,) - return a - -_convert_to_float = { - ntypes.csingle: ntypes.single, - ntypes.complex_: ntypes.float_, - ntypes.clongfloat: ntypes.longfloat - } - -class finfo(object): - """ - finfo(dtype) - - Machine limits for floating point types. - - Attributes - ---------- - eps : floating point number of the appropriate type - The smallest representable number such that ``1.0 + eps != 1.0``. - epsneg : floating point number of the appropriate type - The smallest representable number such that ``1.0 - epsneg != 1.0``. - iexp : int - The number of bits in the exponent portion of the floating point - representation. - machar : MachAr - The object which calculated these parameters and holds more detailed - information. - machep : int - The exponent that yields ``eps``. - max : floating point number of the appropriate type - The largest representable number. - maxexp : int - The smallest positive power of the base (2) that causes overflow. - min : floating point number of the appropriate type - The smallest representable number, typically ``-max``. - minexp : int - The most negative power of the base (2) consistent with there being - no leading 0s in the mantissa. - negep : int - The exponent that yields ``epsneg``. - nexp : int - The number of bits in the exponent including its sign and bias. - nmant : int - The number of bits in the mantissa. - precision : int - The approximate number of decimal digits to which this kind of float - is precise. - resolution : floating point number of the appropriate type - The approximate decimal resolution of this type, i.e. - ``10**-precision``. - tiny : floating point number of the appropriate type - The smallest-magnitude usable number. - - Parameters - ---------- - dtype : floating point type, dtype, or instance - The kind of floating point data type to get information about. - - See Also - -------- - numpy.lib.machar.MachAr : - The implementation of the tests that produce this information. - iinfo : - The equivalent for integer data types. - - Notes - ----- - For developers of numpy: do not instantiate this at the module level. The - initial calculation of these parameters is expensive and negatively impacts - import times. These objects are cached, so calling ``finfo()`` repeatedly - inside your functions is not a problem. - - """ - - _finfo_cache = {} - - def __new__(cls, dtype): - try: - dtype = np.dtype(dtype) - except TypeError: - # In case a float instance was given - dtype = np.dtype(type(dtype)) - - obj = cls._finfo_cache.get(dtype,None) - if obj is not None: - return obj - dtypes = [dtype] - newdtype = numeric.obj2sctype(dtype) - if newdtype is not dtype: - dtypes.append(newdtype) - dtype = newdtype - if not issubclass(dtype, numeric.inexact): - raise ValueError, "data type %r not inexact" % (dtype) - obj = cls._finfo_cache.get(dtype,None) - if obj is not None: - return obj - if not issubclass(dtype, numeric.floating): - newdtype = _convert_to_float[dtype] - if newdtype is not dtype: - dtypes.append(newdtype) - dtype = newdtype - obj = cls._finfo_cache.get(dtype,None) - if obj is not None: - return obj - obj = object.__new__(cls)._init(dtype) - for dt in dtypes: - cls._finfo_cache[dt] = obj - return obj - - def _init(self, dtype): - self.dtype = np.dtype(dtype) - if dtype is ntypes.double: - itype = ntypes.int64 - fmt = '%24.16e' - precname = 'double' - elif dtype is ntypes.single: - itype = ntypes.int32 - fmt = '%15.7e' - precname = 'single' - elif dtype is ntypes.longdouble: - itype = ntypes.longlong - fmt = '%s' - precname = 'long double' - else: - raise ValueError, repr(dtype) - - machar = MachAr(lambda v:array([v], dtype), - lambda v:_frz(v.astype(itype))[0], - lambda v:array(_frz(v)[0], dtype), - lambda v: fmt % array(_frz(v)[0], dtype), - 'numpy %s precision floating point number' % precname) - - for word in ['precision', 'iexp', - 'maxexp','minexp','negep', - 'machep']: - setattr(self,word,getattr(machar, word)) - for word in ['tiny','resolution','epsneg']: - setattr(self,word,getattr(machar, word).squeeze()) - self.max = machar.huge.flat[0] - self.min = -self.max - self.eps = machar.eps.flat[0] - self.nexp = machar.iexp - self.nmant = machar.it - self.machar = machar - self._str_tiny = machar._str_xmin.strip() - self._str_max = machar._str_xmax.strip() - self._str_epsneg = machar._str_epsneg.strip() - self._str_eps = machar._str_eps.strip() - self._str_resolution = machar._str_resolution.strip() - return self - - def __str__(self): - return '''\ -Machine parameters for %(dtype)s ---------------------------------------------------------------------- -precision=%(precision)3s resolution= %(_str_resolution)s -machep=%(machep)6s eps= %(_str_eps)s -negep =%(negep)6s epsneg= %(_str_epsneg)s -minexp=%(minexp)6s tiny= %(_str_tiny)s -maxexp=%(maxexp)6s max= %(_str_max)s -nexp =%(nexp)6s min= -max ---------------------------------------------------------------------- -''' % self.__dict__ - - -class iinfo: - """ - iinfo(type) - - Machine limits for integer types. - - Attributes - ---------- - min : int - The smallest integer expressible by the type. - max : int - The largest integer expressible by the type. - - Parameters - ---------- - type : integer type, dtype, or instance - The kind of integer data type to get information about. - - See Also - -------- - finfo : The equivalent for floating point data types. - - Examples - -------- - With types: - - >>> ii16 = np.iinfo(np.int16) - >>> ii16.min - -32768 - >>> ii16.max - 32767 - >>> ii32 = np.iinfo(np.int32) - >>> ii32.min - -2147483648 - >>> ii32.max - 2147483647 - - With instances: - - >>> ii32 = np.iinfo(np.int32(10)) - >>> ii32.min - -2147483648 - >>> ii32.max - 2147483647 - - """ - - _min_vals = {} - _max_vals = {} - - def __init__(self, int_type): - try: - self.dtype = np.dtype(int_type) - except TypeError: - self.dtype = np.dtype(type(int_type)) - self.kind = self.dtype.kind - self.bits = self.dtype.itemsize * 8 - self.key = "%s%d" % (self.kind, self.bits) - if not self.kind in 'iu': - raise ValueError("Invalid integer data type.") - - def min(self): - """Minimum value of given dtype.""" - if self.kind == 'u': - return 0 - else: - try: - val = iinfo._min_vals[self.key] - except KeyError: - val = int(-(1L << (self.bits-1))) - iinfo._min_vals[self.key] = val - return val - - min = property(min) - - def max(self): - """Maximum value of given dtype.""" - try: - val = iinfo._max_vals[self.key] - except KeyError: - if self.kind == 'u': - val = int((1L << self.bits) - 1) - else: - val = int((1L << (self.bits-1)) - 1) - iinfo._max_vals[self.key] = val - return val - - max = property(max) - - def __str__(self): - """String representation.""" - return '''\ -Machine parameters for %(dtype)s ---------------------------------------------------------------------- -min = %(min)s -max = %(max)s ---------------------------------------------------------------------- -''' % {'dtype': self.dtype, 'min': self.min, 'max': self.max} - - -if __name__ == '__main__': - f = finfo(ntypes.single) - print 'single epsilon:',f.eps - print 'single tiny:',f.tiny - f = finfo(ntypes.float) - print 'float epsilon:',f.eps - print 'float tiny:',f.tiny - f = finfo(ntypes.longfloat) - print 'longfloat epsilon:',f.eps - print 'longfloat tiny:',f.tiny diff --git a/numpy/lib/machar.py b/numpy/lib/machar.py deleted file mode 100644 index facade612..000000000 --- a/numpy/lib/machar.py +++ /dev/null @@ -1,317 +0,0 @@ -""" -Machine arithmetics - determine the parameters of the -floating-point arithmetic system -""" -# Author: Pearu Peterson, September 2003 - - -__all__ = ['MachAr'] - -from numpy.core.fromnumeric import any -from numpy.core.numeric import seterr - -# Need to speed this up...especially for longfloat - -class MachAr(object): - """ - Diagnosing machine parameters. - - Attributes - ---------- - ibeta : int - Radix in which numbers are represented. - it : int - Number of base-`ibeta` digits in the floating point mantissa M. - machep : int - Exponent of the smallest (most negative) power of `ibeta` that, - added to 1.0, gives something different from 1.0 - eps : float - Floating-point number ``beta**machep`` (floating point precision) - negep : int - Exponent of the smallest power of `ibeta` that, substracted - from 1.0, gives something different from 1.0. - epsneg : float - Floating-point number ``beta**negep``. - iexp : int - Number of bits in the exponent (including its sign and bias). - minexp : int - Smallest (most negative) power of `ibeta` consistent with there - being no leading zeros in the mantissa. - xmin : float - Floating point number ``beta**minexp`` (the smallest [in - magnitude] usable floating value). - maxexp : int - Smallest (positive) power of `ibeta` that causes overflow. - xmax : float - ``(1-epsneg) * beta**maxexp`` (the largest [in magnitude] - usable floating value). - irnd : int - In ``range(6)``, information on what kind of rounding is done - in addition, and on how underflow is handled. - ngrd : int - Number of 'guard digits' used when truncating the product - of two mantissas to fit the representation. - - epsilon : float - Same as `eps`. - tiny : float - Same as `xmin`. - huge : float - Same as `xmax`. - precision : float - ``- int(-log10(eps))`` - resolution : float - `` - 10**(-precision)`` - - References - ---------- - .. [1] Press, Teukolsky, Vetterling and Flannery, - "Numerical Recipes in C++," 2nd ed, - Cambridge University Press, 2002, p. 31. - - """ - def __init__(self, float_conv=float,int_conv=int, - float_to_float=float, - float_to_str = lambda v:'%24.16e' % v, - title = 'Python floating point number'): - """ - float_conv - convert integer to float (array) - int_conv - convert float (array) to integer - float_to_float - convert float array to float - float_to_str - convert array float to str - title - description of used floating point numbers - """ - # We ignore all errors here because we are purposely triggering - # underflow to detect the properties of the runninng arch. - saverrstate = seterr(under='ignore') - try: - self._do_init(float_conv, int_conv, float_to_float, float_to_str, title) - finally: - seterr(**saverrstate) - - def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title): - max_iterN = 10000 - msg = "Did not converge after %d tries with %s" - one = float_conv(1) - two = one + one - zero = one - one - - # Do we really need to do this? Aren't they 2 and 2.0? - # Determine ibeta and beta - a = one - for _ in xrange(max_iterN): - a = a + a - temp = a + one - temp1 = temp - a - if any(temp1 - one != zero): - break - else: - raise RuntimeError, msg % (_, one.dtype) - b = one - for _ in xrange(max_iterN): - b = b + b - temp = a + b - itemp = int_conv(temp-a) - if any(itemp != 0): - break - else: - raise RuntimeError, msg % (_, one.dtype) - ibeta = itemp - beta = float_conv(ibeta) - - # Determine it and irnd - it = -1 - b = one - for _ in xrange(max_iterN): - it = it + 1 - b = b * beta - temp = b + one - temp1 = temp - b - if any(temp1 - one != zero): - break - else: - raise RuntimeError, msg % (_, one.dtype) - - betah = beta / two - a = one - for _ in xrange(max_iterN): - a = a + a - temp = a + one - temp1 = temp - a - if any(temp1 - one != zero): - break - else: - raise RuntimeError, msg % (_, one.dtype) - temp = a + betah - irnd = 0 - if any(temp-a != zero): - irnd = 1 - tempa = a + beta - temp = tempa + betah - if irnd==0 and any(temp-tempa != zero): - irnd = 2 - - # Determine negep and epsneg - negep = it + 3 - betain = one / beta - a = one - for i in range(negep): - a = a * betain - b = a - for _ in xrange(max_iterN): - temp = one - a - if any(temp-one != zero): - break - a = a * beta - negep = negep - 1 - # Prevent infinite loop on PPC with gcc 4.0: - if negep < 0: - raise RuntimeError, "could not determine machine tolerance " \ - "for 'negep', locals() -> %s" % (locals()) - else: - raise RuntimeError, msg % (_, one.dtype) - negep = -negep - epsneg = a - - # Determine machep and eps - machep = - it - 3 - a = b - - for _ in xrange(max_iterN): - temp = one + a - if any(temp-one != zero): - break - a = a * beta - machep = machep + 1 - else: - raise RuntimeError, msg % (_, one.dtype) - eps = a - - # Determine ngrd - ngrd = 0 - temp = one + eps - if irnd==0 and any(temp*one - one != zero): - ngrd = 1 - - # Determine iexp - i = 0 - k = 1 - z = betain - t = one + eps - nxres = 0 - for _ in xrange(max_iterN): - y = z - z = y*y - a = z*one # Check here for underflow - temp = z*t - if any(a+a == zero) or any(abs(z)>=y): - break - temp1 = temp * betain - if any(temp1*beta == z): - break - i = i + 1 - k = k + k - else: - raise RuntimeError, msg % (_, one.dtype) - if ibeta != 10: - iexp = i + 1 - mx = k + k - else: - iexp = 2 - iz = ibeta - while k >= iz: - iz = iz * ibeta - iexp = iexp + 1 - mx = iz + iz - 1 - - # Determine minexp and xmin - for _ in xrange(max_iterN): - xmin = y - y = y * betain - a = y * one - temp = y * t - if any(a+a != zero) and any(abs(y) < xmin): - k = k + 1 - temp1 = temp * betain - if any(temp1*beta == y) and any(temp != y): - nxres = 3 - xmin = y - break - else: - break - else: - raise RuntimeError, msg % (_, one.dtype) - minexp = -k - - # Determine maxexp, xmax - if mx <= k + k - 3 and ibeta != 10: - mx = mx + mx - iexp = iexp + 1 - maxexp = mx + minexp - irnd = irnd + nxres - if irnd >= 2: - maxexp = maxexp - 2 - i = maxexp + minexp - if ibeta == 2 and not i: - maxexp = maxexp - 1 - if i > 20: - maxexp = maxexp - 1 - if any(a != y): - maxexp = maxexp - 2 - xmax = one - epsneg - if any(xmax*one != xmax): - xmax = one - beta*epsneg - xmax = xmax / (xmin*beta*beta*beta) - i = maxexp + minexp + 3 - for j in range(i): - if ibeta==2: - xmax = xmax + xmax - else: - xmax = xmax * beta - - self.ibeta = ibeta - self.it = it - self.negep = negep - self.epsneg = float_to_float(epsneg) - self._str_epsneg = float_to_str(epsneg) - self.machep = machep - self.eps = float_to_float(eps) - self._str_eps = float_to_str(eps) - self.ngrd = ngrd - self.iexp = iexp - self.minexp = minexp - self.xmin = float_to_float(xmin) - self._str_xmin = float_to_str(xmin) - self.maxexp = maxexp - self.xmax = float_to_float(xmax) - self._str_xmax = float_to_str(xmax) - self.irnd = irnd - - self.title = title - # Commonly used parameters - self.epsilon = self.eps - self.tiny = self.xmin - self.huge = self.xmax - - import math - self.precision = int(-math.log10(float_to_float(self.eps))) - ten = two + two + two + two + two - resolution = ten ** (-self.precision) - self.resolution = float_to_float(resolution) - self._str_resolution = float_to_str(resolution) - - def __str__(self): - return '''\ -Machine parameters for %(title)s ---------------------------------------------------------------------- -ibeta=%(ibeta)s it=%(it)s iexp=%(iexp)s ngrd=%(ngrd)s irnd=%(irnd)s -machep=%(machep)s eps=%(_str_eps)s (beta**machep == epsilon) -negep =%(negep)s epsneg=%(_str_epsneg)s (beta**epsneg) -minexp=%(minexp)s xmin=%(_str_xmin)s (beta**minexp == tiny) -maxexp=%(maxexp)s xmax=%(_str_xmax)s ((1-epsneg)*beta**maxexp == huge) ---------------------------------------------------------------------- -''' % self.__dict__ - - -if __name__ == '__main__': - print MachAr() diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index 6a2b5f18a..a97c07e87 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -10,8 +10,7 @@ import re import warnings import numpy.core.numeric as NX -from numpy.core import isscalar, abs -from numpy.lib.getlimits import finfo +from numpy.core import isscalar, abs, finfo from numpy.lib.twodim_base import diag, vander from numpy.lib.shape_base import hstack, atleast_1d from numpy.lib.function_base import trim_zeros, sort_complex diff --git a/numpy/lib/tests/test_getlimits.py b/numpy/lib/tests/test_getlimits.py deleted file mode 100644 index 325e5a444..000000000 --- a/numpy/lib/tests/test_getlimits.py +++ /dev/null @@ -1,59 +0,0 @@ -""" Test functions for limits module. -""" - -from numpy.testing import * -import numpy.lib -reload(numpy.lib) -from numpy.lib.getlimits import finfo, iinfo -from numpy import single,double,longdouble -import numpy as np - -################################################## - -class TestPythonFloat(TestCase): - def test_singleton(self): - ftype = finfo(float) - ftype2 = finfo(float) - assert_equal(id(ftype),id(ftype2)) - -class TestSingle(TestCase): - def test_singleton(self): - ftype = finfo(single) - ftype2 = finfo(single) - assert_equal(id(ftype),id(ftype2)) - -class TestDouble(TestCase): - def test_singleton(self): - ftype = finfo(double) - ftype2 = finfo(double) - assert_equal(id(ftype),id(ftype2)) - -class TestLongdouble(TestCase): - def test_singleton(self,level=2): - ftype = finfo(longdouble) - ftype2 = finfo(longdouble) - assert_equal(id(ftype),id(ftype2)) - -class TestIinfo(TestCase): - def test_basic(self): - dts = zip(['i1', 'i2', 'i4', 'i8', - 'u1', 'u2', 'u4', 'u8'], - [np.int8, np.int16, np.int32, np.int64, - np.uint8, np.uint16, np.uint32, np.uint64]) - for dt1, dt2 in dts: - assert_equal(iinfo(dt1).min, iinfo(dt2).min) - assert_equal(iinfo(dt1).max, iinfo(dt2).max) - self.assertRaises(ValueError, iinfo, 'f4') - - def test_unsigned_max(self): - types = np.sctypes['uint'] - for T in types: - assert_equal(iinfo(T).max, T(-1)) - - -def test_instances(): - iinfo(10) - finfo(3.0) - -if __name__ == "__main__": - run_module_suite() diff --git a/numpy/lib/tests/test_machar.py b/numpy/lib/tests/test_machar.py deleted file mode 100644 index 64abf7236..000000000 --- a/numpy/lib/tests/test_machar.py +++ /dev/null @@ -1,31 +0,0 @@ -from numpy.testing import * - -from numpy.lib.machar import MachAr -import numpy.core.numerictypes as ntypes -from numpy import seterr, array - -class TestMachAr(TestCase): - def _run_machar_highprec(self): - # Instanciate MachAr instance with high enough precision to cause - # underflow - try: - hiprec = ntypes.float96 - machar = MachAr(lambda v:array([v], hiprec)) - except AttributeError: - "Skipping test: no nyptes.float96 available on this platform." - - def test_underlow(self): - """Regression testing for #759: instanciating MachAr for dtype = - np.float96 raises spurious warning.""" - serrstate = seterr(all='raise') - try: - try: - self._run_machar_highprec() - except FloatingPointError, e: - self.fail("Caught %s exception, should not have been raised." % e) - finally: - seterr(**serrstate) - - -if __name__ == "__main__": - run_module_suite() diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py index 69f4f2193..5dfe6330b 100644 --- a/numpy/lib/type_check.py +++ b/numpy/lib/type_check.py @@ -275,7 +275,7 @@ def isrealobj(x): #----------------------------------------------------------------------------- def _getmaxmin(t): - import getlimits + from numpy.core import getlimits f = getlimits.finfo(t) return f.max, f.min @@ -400,7 +400,7 @@ def real_if_close(a,tol=100): if not issubclass(a.dtype.type, _nx.complexfloating): return a if tol > 1: - import getlimits + from numpy.core import getlimits f = getlimits.finfo(a.dtype.type) tol = f.eps * tol if _nx.allclose(a.imag, 0, atol=tol): |