getlimits.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. """Machine limits for Float32 and Float64 and (long double) if available...
  2. """
  3. __all__ = ['finfo', 'iinfo']
  4. import warnings
  5. from ._machar import MachAr
  6. from .overrides import set_module
  7. from . import numeric
  8. from . import numerictypes as ntypes
  9. from .numeric import array, inf, NaN
  10. from .umath import log10, exp2, nextafter, isnan
  11. def _fr0(a):
  12. """fix rank-0 --> rank-1"""
  13. if a.ndim == 0:
  14. a = a.copy()
  15. a.shape = (1,)
  16. return a
  17. def _fr1(a):
  18. """fix rank > 0 --> rank-0"""
  19. if a.size == 1:
  20. a = a.copy()
  21. a.shape = ()
  22. return a
  23. class MachArLike:
  24. """ Object to simulate MachAr instance """
  25. def __init__(self, ftype, *, eps, epsneg, huge, tiny,
  26. ibeta, smallest_subnormal=None, **kwargs):
  27. self.params = _MACHAR_PARAMS[ftype]
  28. self.ftype = ftype
  29. self.title = self.params['title']
  30. # Parameter types same as for discovered MachAr object.
  31. if not smallest_subnormal:
  32. self._smallest_subnormal = nextafter(
  33. self.ftype(0), self.ftype(1), dtype=self.ftype)
  34. else:
  35. self._smallest_subnormal = smallest_subnormal
  36. self.epsilon = self.eps = self._float_to_float(eps)
  37. self.epsneg = self._float_to_float(epsneg)
  38. self.xmax = self.huge = self._float_to_float(huge)
  39. self.xmin = self._float_to_float(tiny)
  40. self.smallest_normal = self.tiny = self._float_to_float(tiny)
  41. self.ibeta = self.params['itype'](ibeta)
  42. self.__dict__.update(kwargs)
  43. self.precision = int(-log10(self.eps))
  44. self.resolution = self._float_to_float(
  45. self._float_conv(10) ** (-self.precision))
  46. self._str_eps = self._float_to_str(self.eps)
  47. self._str_epsneg = self._float_to_str(self.epsneg)
  48. self._str_xmin = self._float_to_str(self.xmin)
  49. self._str_xmax = self._float_to_str(self.xmax)
  50. self._str_resolution = self._float_to_str(self.resolution)
  51. self._str_smallest_normal = self._float_to_str(self.xmin)
  52. @property
  53. def smallest_subnormal(self):
  54. """Return the value for the smallest subnormal.
  55. Returns
  56. -------
  57. smallest_subnormal : float
  58. value for the smallest subnormal.
  59. Warns
  60. -----
  61. UserWarning
  62. If the calculated value for the smallest subnormal is zero.
  63. """
  64. # Check that the calculated value is not zero, in case it raises a
  65. # warning.
  66. value = self._smallest_subnormal
  67. if self.ftype(0) == value:
  68. warnings.warn(
  69. 'The value of the smallest subnormal for {} type '
  70. 'is zero.'.format(self.ftype), UserWarning, stacklevel=2)
  71. return self._float_to_float(value)
  72. @property
  73. def _str_smallest_subnormal(self):
  74. """Return the string representation of the smallest subnormal."""
  75. return self._float_to_str(self.smallest_subnormal)
  76. def _float_to_float(self, value):
  77. """Converts float to float.
  78. Parameters
  79. ----------
  80. value : float
  81. value to be converted.
  82. """
  83. return _fr1(self._float_conv(value))
  84. def _float_conv(self, value):
  85. """Converts float to conv.
  86. Parameters
  87. ----------
  88. value : float
  89. value to be converted.
  90. """
  91. return array([value], self.ftype)
  92. def _float_to_str(self, value):
  93. """Converts float to str.
  94. Parameters
  95. ----------
  96. value : float
  97. value to be converted.
  98. """
  99. return self.params['fmt'] % array(_fr0(value)[0], self.ftype)
  100. _convert_to_float = {
  101. ntypes.csingle: ntypes.single,
  102. ntypes.complex_: ntypes.float_,
  103. ntypes.clongfloat: ntypes.longfloat
  104. }
  105. # Parameters for creating MachAr / MachAr-like objects
  106. _title_fmt = 'numpy {} precision floating point number'
  107. _MACHAR_PARAMS = {
  108. ntypes.double: dict(
  109. itype = ntypes.int64,
  110. fmt = '%24.16e',
  111. title = _title_fmt.format('double')),
  112. ntypes.single: dict(
  113. itype = ntypes.int32,
  114. fmt = '%15.7e',
  115. title = _title_fmt.format('single')),
  116. ntypes.longdouble: dict(
  117. itype = ntypes.longlong,
  118. fmt = '%s',
  119. title = _title_fmt.format('long double')),
  120. ntypes.half: dict(
  121. itype = ntypes.int16,
  122. fmt = '%12.5e',
  123. title = _title_fmt.format('half'))}
  124. # Key to identify the floating point type. Key is result of
  125. # ftype('-0.1').newbyteorder('<').tobytes()
  126. # See:
  127. # https://perl5.git.perl.org/perl.git/blob/3118d7d684b56cbeb702af874f4326683c45f045:/Configure
  128. _KNOWN_TYPES = {}
  129. def _register_type(machar, bytepat):
  130. _KNOWN_TYPES[bytepat] = machar
  131. _float_ma = {}
  132. def _register_known_types():
  133. # Known parameters for float16
  134. # See docstring of MachAr class for description of parameters.
  135. f16 = ntypes.float16
  136. float16_ma = MachArLike(f16,
  137. machep=-10,
  138. negep=-11,
  139. minexp=-14,
  140. maxexp=16,
  141. it=10,
  142. iexp=5,
  143. ibeta=2,
  144. irnd=5,
  145. ngrd=0,
  146. eps=exp2(f16(-10)),
  147. epsneg=exp2(f16(-11)),
  148. huge=f16(65504),
  149. tiny=f16(2 ** -14))
  150. _register_type(float16_ma, b'f\xae')
  151. _float_ma[16] = float16_ma
  152. # Known parameters for float32
  153. f32 = ntypes.float32
  154. float32_ma = MachArLike(f32,
  155. machep=-23,
  156. negep=-24,
  157. minexp=-126,
  158. maxexp=128,
  159. it=23,
  160. iexp=8,
  161. ibeta=2,
  162. irnd=5,
  163. ngrd=0,
  164. eps=exp2(f32(-23)),
  165. epsneg=exp2(f32(-24)),
  166. huge=f32((1 - 2 ** -24) * 2**128),
  167. tiny=exp2(f32(-126)))
  168. _register_type(float32_ma, b'\xcd\xcc\xcc\xbd')
  169. _float_ma[32] = float32_ma
  170. # Known parameters for float64
  171. f64 = ntypes.float64
  172. epsneg_f64 = 2.0 ** -53.0
  173. tiny_f64 = 2.0 ** -1022.0
  174. float64_ma = MachArLike(f64,
  175. machep=-52,
  176. negep=-53,
  177. minexp=-1022,
  178. maxexp=1024,
  179. it=52,
  180. iexp=11,
  181. ibeta=2,
  182. irnd=5,
  183. ngrd=0,
  184. eps=2.0 ** -52.0,
  185. epsneg=epsneg_f64,
  186. huge=(1.0 - epsneg_f64) / tiny_f64 * f64(4),
  187. tiny=tiny_f64)
  188. _register_type(float64_ma, b'\x9a\x99\x99\x99\x99\x99\xb9\xbf')
  189. _float_ma[64] = float64_ma
  190. # Known parameters for IEEE 754 128-bit binary float
  191. ld = ntypes.longdouble
  192. epsneg_f128 = exp2(ld(-113))
  193. tiny_f128 = exp2(ld(-16382))
  194. # Ignore runtime error when this is not f128
  195. with numeric.errstate(all='ignore'):
  196. huge_f128 = (ld(1) - epsneg_f128) / tiny_f128 * ld(4)
  197. float128_ma = MachArLike(ld,
  198. machep=-112,
  199. negep=-113,
  200. minexp=-16382,
  201. maxexp=16384,
  202. it=112,
  203. iexp=15,
  204. ibeta=2,
  205. irnd=5,
  206. ngrd=0,
  207. eps=exp2(ld(-112)),
  208. epsneg=epsneg_f128,
  209. huge=huge_f128,
  210. tiny=tiny_f128)
  211. # IEEE 754 128-bit binary float
  212. _register_type(float128_ma,
  213. b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
  214. _register_type(float128_ma,
  215. b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
  216. _float_ma[128] = float128_ma
  217. # Known parameters for float80 (Intel 80-bit extended precision)
  218. epsneg_f80 = exp2(ld(-64))
  219. tiny_f80 = exp2(ld(-16382))
  220. # Ignore runtime error when this is not f80
  221. with numeric.errstate(all='ignore'):
  222. huge_f80 = (ld(1) - epsneg_f80) / tiny_f80 * ld(4)
  223. float80_ma = MachArLike(ld,
  224. machep=-63,
  225. negep=-64,
  226. minexp=-16382,
  227. maxexp=16384,
  228. it=63,
  229. iexp=15,
  230. ibeta=2,
  231. irnd=5,
  232. ngrd=0,
  233. eps=exp2(ld(-63)),
  234. epsneg=epsneg_f80,
  235. huge=huge_f80,
  236. tiny=tiny_f80)
  237. # float80, first 10 bytes containing actual storage
  238. _register_type(float80_ma, b'\xcd\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xfb\xbf')
  239. _float_ma[80] = float80_ma
  240. # Guessed / known parameters for double double; see:
  241. # https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format#Double-double_arithmetic
  242. # These numbers have the same exponent range as float64, but extended number of
  243. # digits in the significand.
  244. huge_dd = nextafter(ld(inf), ld(0), dtype=ld)
  245. # As the smallest_normal in double double is so hard to calculate we set
  246. # it to NaN.
  247. smallest_normal_dd = NaN
  248. # Leave the same value for the smallest subnormal as double
  249. smallest_subnormal_dd = ld(nextafter(0., 1.))
  250. float_dd_ma = MachArLike(ld,
  251. machep=-105,
  252. negep=-106,
  253. minexp=-1022,
  254. maxexp=1024,
  255. it=105,
  256. iexp=11,
  257. ibeta=2,
  258. irnd=5,
  259. ngrd=0,
  260. eps=exp2(ld(-105)),
  261. epsneg=exp2(ld(-106)),
  262. huge=huge_dd,
  263. tiny=smallest_normal_dd,
  264. smallest_subnormal=smallest_subnormal_dd)
  265. # double double; low, high order (e.g. PPC 64)
  266. _register_type(float_dd_ma,
  267. b'\x9a\x99\x99\x99\x99\x99Y<\x9a\x99\x99\x99\x99\x99\xb9\xbf')
  268. # double double; high, low order (e.g. PPC 64 le)
  269. _register_type(float_dd_ma,
  270. b'\x9a\x99\x99\x99\x99\x99\xb9\xbf\x9a\x99\x99\x99\x99\x99Y<')
  271. _float_ma['dd'] = float_dd_ma
  272. def _get_machar(ftype):
  273. """ Get MachAr instance or MachAr-like instance
  274. Get parameters for floating point type, by first trying signatures of
  275. various known floating point types, then, if none match, attempting to
  276. identify parameters by analysis.
  277. Parameters
  278. ----------
  279. ftype : class
  280. Numpy floating point type class (e.g. ``np.float64``)
  281. Returns
  282. -------
  283. ma_like : instance of :class:`MachAr` or :class:`MachArLike`
  284. Object giving floating point parameters for `ftype`.
  285. Warns
  286. -----
  287. UserWarning
  288. If the binary signature of the float type is not in the dictionary of
  289. known float types.
  290. """
  291. params = _MACHAR_PARAMS.get(ftype)
  292. if params is None:
  293. raise ValueError(repr(ftype))
  294. # Detect known / suspected types
  295. key = ftype('-0.1').newbyteorder('<').tobytes()
  296. ma_like = None
  297. if ftype == ntypes.longdouble:
  298. # Could be 80 bit == 10 byte extended precision, where last bytes can
  299. # be random garbage.
  300. # Comparing first 10 bytes to pattern first to avoid branching on the
  301. # random garbage.
  302. ma_like = _KNOWN_TYPES.get(key[:10])
  303. if ma_like is None:
  304. ma_like = _KNOWN_TYPES.get(key)
  305. if ma_like is not None:
  306. return ma_like
  307. # Fall back to parameter discovery
  308. warnings.warn(
  309. f'Signature {key} for {ftype} does not match any known type: '
  310. 'falling back to type probe function.\n'
  311. 'This warnings indicates broken support for the dtype!',
  312. UserWarning, stacklevel=2)
  313. return _discovered_machar(ftype)
  314. def _discovered_machar(ftype):
  315. """ Create MachAr instance with found information on float types
  316. """
  317. params = _MACHAR_PARAMS[ftype]
  318. return MachAr(lambda v: array([v], ftype),
  319. lambda v:_fr0(v.astype(params['itype']))[0],
  320. lambda v:array(_fr0(v)[0], ftype),
  321. lambda v: params['fmt'] % array(_fr0(v)[0], ftype),
  322. params['title'])
  323. @set_module('numpy')
  324. class finfo:
  325. """
  326. finfo(dtype)
  327. Machine limits for floating point types.
  328. Attributes
  329. ----------
  330. bits : int
  331. The number of bits occupied by the type.
  332. dtype : dtype
  333. Returns the dtype for which `finfo` returns information. For complex
  334. input, the returned dtype is the associated ``float*`` dtype for its
  335. real and complex components.
  336. eps : float
  337. The difference between 1.0 and the next smallest representable float
  338. larger than 1.0. For example, for 64-bit binary floats in the IEEE-754
  339. standard, ``eps = 2**-52``, approximately 2.22e-16.
  340. epsneg : float
  341. The difference between 1.0 and the next smallest representable float
  342. less than 1.0. For example, for 64-bit binary floats in the IEEE-754
  343. standard, ``epsneg = 2**-53``, approximately 1.11e-16.
  344. iexp : int
  345. The number of bits in the exponent portion of the floating point
  346. representation.
  347. machar : MachAr
  348. The object which calculated these parameters and holds more
  349. detailed information.
  350. .. deprecated:: 1.22
  351. machep : int
  352. The exponent that yields `eps`.
  353. max : floating point number of the appropriate type
  354. The largest representable number.
  355. maxexp : int
  356. The smallest positive power of the base (2) that causes overflow.
  357. min : floating point number of the appropriate type
  358. The smallest representable number, typically ``-max``.
  359. minexp : int
  360. The most negative power of the base (2) consistent with there
  361. being no leading 0's in the mantissa.
  362. negep : int
  363. The exponent that yields `epsneg`.
  364. nexp : int
  365. The number of bits in the exponent including its sign and bias.
  366. nmant : int
  367. The number of bits in the mantissa.
  368. precision : int
  369. The approximate number of decimal digits to which this kind of
  370. float is precise.
  371. resolution : floating point number of the appropriate type
  372. The approximate decimal resolution of this type, i.e.,
  373. ``10**-precision``.
  374. tiny : float
  375. An alias for `smallest_normal`, kept for backwards compatibility.
  376. smallest_normal : float
  377. The smallest positive floating point number with 1 as leading bit in
  378. the mantissa following IEEE-754 (see Notes).
  379. smallest_subnormal : float
  380. The smallest positive floating point number with 0 as leading bit in
  381. the mantissa following IEEE-754.
  382. Parameters
  383. ----------
  384. dtype : float, dtype, or instance
  385. Kind of floating point or complex floating point
  386. data-type about which to get information.
  387. See Also
  388. --------
  389. MachAr : The implementation of the tests that produce this information.
  390. iinfo : The equivalent for integer data types.
  391. spacing : The distance between a value and the nearest adjacent number
  392. nextafter : The next floating point value after x1 towards x2
  393. Notes
  394. -----
  395. For developers of NumPy: do not instantiate this at the module level.
  396. The initial calculation of these parameters is expensive and negatively
  397. impacts import times. These objects are cached, so calling ``finfo()``
  398. repeatedly inside your functions is not a problem.
  399. Note that ``smallest_normal`` is not actually the smallest positive
  400. representable value in a NumPy floating point type. As in the IEEE-754
  401. standard [1]_, NumPy floating point types make use of subnormal numbers to
  402. fill the gap between 0 and ``smallest_normal``. However, subnormal numbers
  403. may have significantly reduced precision [2]_.
  404. This function can also be used for complex data types as well. If used,
  405. the output will be the same as the corresponding real float type
  406. (e.g. numpy.finfo(numpy.csingle) is the same as numpy.finfo(numpy.single)).
  407. However, the output is true for the real and imaginary components.
  408. References
  409. ----------
  410. .. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008,
  411. pp.1-70, 2008, http://www.doi.org/10.1109/IEEESTD.2008.4610935
  412. .. [2] Wikipedia, "Denormal Numbers",
  413. https://en.wikipedia.org/wiki/Denormal_number
  414. Examples
  415. --------
  416. >>> np.finfo(np.float64).dtype
  417. dtype('float64')
  418. >>> np.finfo(np.complex64).dtype
  419. dtype('float32')
  420. """
  421. _finfo_cache = {}
  422. def __new__(cls, dtype):
  423. try:
  424. dtype = numeric.dtype(dtype)
  425. except TypeError:
  426. # In case a float instance was given
  427. dtype = numeric.dtype(type(dtype))
  428. obj = cls._finfo_cache.get(dtype, None)
  429. if obj is not None:
  430. return obj
  431. dtypes = [dtype]
  432. newdtype = numeric.obj2sctype(dtype)
  433. if newdtype is not dtype:
  434. dtypes.append(newdtype)
  435. dtype = newdtype
  436. if not issubclass(dtype, numeric.inexact):
  437. raise ValueError("data type %r not inexact" % (dtype))
  438. obj = cls._finfo_cache.get(dtype, None)
  439. if obj is not None:
  440. return obj
  441. if not issubclass(dtype, numeric.floating):
  442. newdtype = _convert_to_float[dtype]
  443. if newdtype is not dtype:
  444. dtypes.append(newdtype)
  445. dtype = newdtype
  446. obj = cls._finfo_cache.get(dtype, None)
  447. if obj is not None:
  448. return obj
  449. obj = object.__new__(cls)._init(dtype)
  450. for dt in dtypes:
  451. cls._finfo_cache[dt] = obj
  452. return obj
  453. def _init(self, dtype):
  454. self.dtype = numeric.dtype(dtype)
  455. machar = _get_machar(dtype)
  456. for word in ['precision', 'iexp',
  457. 'maxexp', 'minexp', 'negep',
  458. 'machep']:
  459. setattr(self, word, getattr(machar, word))
  460. for word in ['resolution', 'epsneg', 'smallest_subnormal']:
  461. setattr(self, word, getattr(machar, word).flat[0])
  462. self.bits = self.dtype.itemsize * 8
  463. self.max = machar.huge.flat[0]
  464. self.min = -self.max
  465. self.eps = machar.eps.flat[0]
  466. self.nexp = machar.iexp
  467. self.nmant = machar.it
  468. self._machar = machar
  469. self._str_tiny = machar._str_xmin.strip()
  470. self._str_max = machar._str_xmax.strip()
  471. self._str_epsneg = machar._str_epsneg.strip()
  472. self._str_eps = machar._str_eps.strip()
  473. self._str_resolution = machar._str_resolution.strip()
  474. self._str_smallest_normal = machar._str_smallest_normal.strip()
  475. self._str_smallest_subnormal = machar._str_smallest_subnormal.strip()
  476. return self
  477. def __str__(self):
  478. fmt = (
  479. 'Machine parameters for %(dtype)s\n'
  480. '---------------------------------------------------------------\n'
  481. 'precision = %(precision)3s resolution = %(_str_resolution)s\n'
  482. 'machep = %(machep)6s eps = %(_str_eps)s\n'
  483. 'negep = %(negep)6s epsneg = %(_str_epsneg)s\n'
  484. 'minexp = %(minexp)6s tiny = %(_str_tiny)s\n'
  485. 'maxexp = %(maxexp)6s max = %(_str_max)s\n'
  486. 'nexp = %(nexp)6s min = -max\n'
  487. 'smallest_normal = %(_str_smallest_normal)s '
  488. 'smallest_subnormal = %(_str_smallest_subnormal)s\n'
  489. '---------------------------------------------------------------\n'
  490. )
  491. return fmt % self.__dict__
  492. def __repr__(self):
  493. c = self.__class__.__name__
  494. d = self.__dict__.copy()
  495. d['klass'] = c
  496. return (("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s,"
  497. " max=%(_str_max)s, dtype=%(dtype)s)") % d)
  498. @property
  499. def smallest_normal(self):
  500. """Return the value for the smallest normal.
  501. Returns
  502. -------
  503. smallest_normal : float
  504. Value for the smallest normal.
  505. Warns
  506. -----
  507. UserWarning
  508. If the calculated value for the smallest normal is requested for
  509. double-double.
  510. """
  511. # This check is necessary because the value for smallest_normal is
  512. # platform dependent for longdouble types.
  513. if isnan(self._machar.smallest_normal.flat[0]):
  514. warnings.warn(
  515. 'The value of smallest normal is undefined for double double',
  516. UserWarning, stacklevel=2)
  517. return self._machar.smallest_normal.flat[0]
  518. @property
  519. def tiny(self):
  520. """Return the value for tiny, alias of smallest_normal.
  521. Returns
  522. -------
  523. tiny : float
  524. Value for the smallest normal, alias of smallest_normal.
  525. Warns
  526. -----
  527. UserWarning
  528. If the calculated value for the smallest normal is requested for
  529. double-double.
  530. """
  531. return self.smallest_normal
  532. @property
  533. def machar(self):
  534. """The object which calculated these parameters and holds more
  535. detailed information.
  536. .. deprecated:: 1.22
  537. """
  538. # Deprecated 2021-10-27, NumPy 1.22
  539. warnings.warn(
  540. "`finfo.machar` is deprecated (NumPy 1.22)",
  541. DeprecationWarning, stacklevel=2,
  542. )
  543. return self._machar
  544. @set_module('numpy')
  545. class iinfo:
  546. """
  547. iinfo(type)
  548. Machine limits for integer types.
  549. Attributes
  550. ----------
  551. bits : int
  552. The number of bits occupied by the type.
  553. dtype : dtype
  554. Returns the dtype for which `iinfo` returns information.
  555. min : int
  556. The smallest integer expressible by the type.
  557. max : int
  558. The largest integer expressible by the type.
  559. Parameters
  560. ----------
  561. int_type : integer type, dtype, or instance
  562. The kind of integer data type to get information about.
  563. See Also
  564. --------
  565. finfo : The equivalent for floating point data types.
  566. Examples
  567. --------
  568. With types:
  569. >>> ii16 = np.iinfo(np.int16)
  570. >>> ii16.min
  571. -32768
  572. >>> ii16.max
  573. 32767
  574. >>> ii32 = np.iinfo(np.int32)
  575. >>> ii32.min
  576. -2147483648
  577. >>> ii32.max
  578. 2147483647
  579. With instances:
  580. >>> ii32 = np.iinfo(np.int32(10))
  581. >>> ii32.min
  582. -2147483648
  583. >>> ii32.max
  584. 2147483647
  585. """
  586. _min_vals = {}
  587. _max_vals = {}
  588. def __init__(self, int_type):
  589. try:
  590. self.dtype = numeric.dtype(int_type)
  591. except TypeError:
  592. self.dtype = numeric.dtype(type(int_type))
  593. self.kind = self.dtype.kind
  594. self.bits = self.dtype.itemsize * 8
  595. self.key = "%s%d" % (self.kind, self.bits)
  596. if self.kind not in 'iu':
  597. raise ValueError("Invalid integer data type %r." % (self.kind,))
  598. @property
  599. def min(self):
  600. """Minimum value of given dtype."""
  601. if self.kind == 'u':
  602. return 0
  603. else:
  604. try:
  605. val = iinfo._min_vals[self.key]
  606. except KeyError:
  607. val = int(-(1 << (self.bits-1)))
  608. iinfo._min_vals[self.key] = val
  609. return val
  610. @property
  611. def max(self):
  612. """Maximum value of given dtype."""
  613. try:
  614. val = iinfo._max_vals[self.key]
  615. except KeyError:
  616. if self.kind == 'u':
  617. val = int((1 << self.bits) - 1)
  618. else:
  619. val = int((1 << (self.bits-1)) - 1)
  620. iinfo._max_vals[self.key] = val
  621. return val
  622. def __str__(self):
  623. """String representation."""
  624. fmt = (
  625. 'Machine parameters for %(dtype)s\n'
  626. '---------------------------------------------------------------\n'
  627. 'min = %(min)s\n'
  628. 'max = %(max)s\n'
  629. '---------------------------------------------------------------\n'
  630. )
  631. return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
  632. def __repr__(self):
  633. return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
  634. self.min, self.max, self.dtype)