test_half.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. import platform
  2. import pytest
  3. import numpy as np
  4. from numpy import uint16, float16, float32, float64
  5. from numpy.testing import assert_, assert_equal, _OLD_PROMOTION, IS_WASM
  6. def assert_raises_fpe(strmatch, callable, *args, **kwargs):
  7. try:
  8. callable(*args, **kwargs)
  9. except FloatingPointError as exc:
  10. assert_(str(exc).find(strmatch) >= 0,
  11. "Did not raise floating point %s error" % strmatch)
  12. else:
  13. assert_(False,
  14. "Did not raise floating point %s error" % strmatch)
  15. class TestHalf:
  16. def setup_method(self):
  17. # An array of all possible float16 values
  18. self.all_f16 = np.arange(0x10000, dtype=uint16)
  19. self.all_f16.dtype = float16
  20. self.all_f32 = np.array(self.all_f16, dtype=float32)
  21. self.all_f64 = np.array(self.all_f16, dtype=float64)
  22. # An array of all non-NaN float16 values, in sorted order
  23. self.nonan_f16 = np.concatenate(
  24. (np.arange(0xfc00, 0x7fff, -1, dtype=uint16),
  25. np.arange(0x0000, 0x7c01, 1, dtype=uint16)))
  26. self.nonan_f16.dtype = float16
  27. self.nonan_f32 = np.array(self.nonan_f16, dtype=float32)
  28. self.nonan_f64 = np.array(self.nonan_f16, dtype=float64)
  29. # An array of all finite float16 values, in sorted order
  30. self.finite_f16 = self.nonan_f16[1:-1]
  31. self.finite_f32 = self.nonan_f32[1:-1]
  32. self.finite_f64 = self.nonan_f64[1:-1]
  33. def test_half_conversions(self):
  34. """Checks that all 16-bit values survive conversion
  35. to/from 32-bit and 64-bit float"""
  36. # Because the underlying routines preserve the NaN bits, every
  37. # value is preserved when converting to/from other floats.
  38. # Convert from float32 back to float16
  39. b = np.array(self.all_f32, dtype=float16)
  40. assert_equal(self.all_f16.view(dtype=uint16),
  41. b.view(dtype=uint16))
  42. # Convert from float64 back to float16
  43. b = np.array(self.all_f64, dtype=float16)
  44. assert_equal(self.all_f16.view(dtype=uint16),
  45. b.view(dtype=uint16))
  46. # Convert float16 to longdouble and back
  47. # This doesn't necessarily preserve the extra NaN bits,
  48. # so exclude NaNs.
  49. a_ld = np.array(self.nonan_f16, dtype=np.longdouble)
  50. b = np.array(a_ld, dtype=float16)
  51. assert_equal(self.nonan_f16.view(dtype=uint16),
  52. b.view(dtype=uint16))
  53. # Check the range for which all integers can be represented
  54. i_int = np.arange(-2048, 2049)
  55. i_f16 = np.array(i_int, dtype=float16)
  56. j = np.array(i_f16, dtype=int)
  57. assert_equal(i_int, j)
  58. @pytest.mark.parametrize("string_dt", ["S", "U"])
  59. def test_half_conversion_to_string(self, string_dt):
  60. # Currently uses S/U32 (which is sufficient for float32)
  61. expected_dt = np.dtype(f"{string_dt}32")
  62. assert np.promote_types(np.float16, string_dt) == expected_dt
  63. assert np.promote_types(string_dt, np.float16) == expected_dt
  64. arr = np.ones(3, dtype=np.float16).astype(string_dt)
  65. assert arr.dtype == expected_dt
  66. @pytest.mark.parametrize("string_dt", ["S", "U"])
  67. def test_half_conversion_from_string(self, string_dt):
  68. string = np.array("3.1416", dtype=string_dt)
  69. assert string.astype(np.float16) == np.array(3.1416, dtype=np.float16)
  70. @pytest.mark.parametrize("offset", [None, "up", "down"])
  71. @pytest.mark.parametrize("shift", [None, "up", "down"])
  72. @pytest.mark.parametrize("float_t", [np.float32, np.float64])
  73. @np._no_nep50_warning()
  74. def test_half_conversion_rounding(self, float_t, shift, offset):
  75. # Assumes that round to even is used during casting.
  76. max_pattern = np.float16(np.finfo(np.float16).max).view(np.uint16)
  77. # Test all (positive) finite numbers, denormals are most interesting
  78. # however:
  79. f16s_patterns = np.arange(0, max_pattern+1, dtype=np.uint16)
  80. f16s_float = f16s_patterns.view(np.float16).astype(float_t)
  81. # Shift the values by half a bit up or a down (or do not shift),
  82. if shift == "up":
  83. f16s_float = 0.5 * (f16s_float[:-1] + f16s_float[1:])[1:]
  84. elif shift == "down":
  85. f16s_float = 0.5 * (f16s_float[:-1] + f16s_float[1:])[:-1]
  86. else:
  87. f16s_float = f16s_float[1:-1]
  88. # Increase the float by a minimal value:
  89. if offset == "up":
  90. f16s_float = np.nextafter(f16s_float, float_t(np.inf))
  91. elif offset == "down":
  92. f16s_float = np.nextafter(f16s_float, float_t(-np.inf))
  93. # Convert back to float16 and its bit pattern:
  94. res_patterns = f16s_float.astype(np.float16).view(np.uint16)
  95. # The above calculations tries the original values, or the exact
  96. # mid points between the float16 values. It then further offsets them
  97. # by as little as possible. If no offset occurs, "round to even"
  98. # logic will be necessary, an arbitrarily small offset should cause
  99. # normal up/down rounding always.
  100. # Calculate the expected pattern:
  101. cmp_patterns = f16s_patterns[1:-1].copy()
  102. if shift == "down" and offset != "up":
  103. shift_pattern = -1
  104. elif shift == "up" and offset != "down":
  105. shift_pattern = 1
  106. else:
  107. # There cannot be a shift, either shift is None, so all rounding
  108. # will go back to original, or shift is reduced by offset too much.
  109. shift_pattern = 0
  110. # If rounding occurs, is it normal rounding or round to even?
  111. if offset is None:
  112. # Round to even occurs, modify only non-even, cast to allow + (-1)
  113. cmp_patterns[0::2].view(np.int16)[...] += shift_pattern
  114. else:
  115. cmp_patterns.view(np.int16)[...] += shift_pattern
  116. assert_equal(res_patterns, cmp_patterns)
  117. @pytest.mark.parametrize(["float_t", "uint_t", "bits"],
  118. [(np.float32, np.uint32, 23),
  119. (np.float64, np.uint64, 52)])
  120. def test_half_conversion_denormal_round_even(self, float_t, uint_t, bits):
  121. # Test specifically that all bits are considered when deciding
  122. # whether round to even should occur (i.e. no bits are lost at the
  123. # end. Compare also gh-12721. The most bits can get lost for the
  124. # smallest denormal:
  125. smallest_value = np.uint16(1).view(np.float16).astype(float_t)
  126. assert smallest_value == 2**-24
  127. # Will be rounded to zero based on round to even rule:
  128. rounded_to_zero = smallest_value / float_t(2)
  129. assert rounded_to_zero.astype(np.float16) == 0
  130. # The significand will be all 0 for the float_t, test that we do not
  131. # lose the lower ones of these:
  132. for i in range(bits):
  133. # slightly increasing the value should make it round up:
  134. larger_pattern = rounded_to_zero.view(uint_t) | uint_t(1 << i)
  135. larger_value = larger_pattern.view(float_t)
  136. assert larger_value.astype(np.float16) == smallest_value
  137. def test_nans_infs(self):
  138. with np.errstate(all='ignore'):
  139. # Check some of the ufuncs
  140. assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32))
  141. assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32))
  142. assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32))
  143. assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32))
  144. assert_equal(np.spacing(float16(65504)), np.inf)
  145. # Check comparisons of all values with NaN
  146. nan = float16(np.nan)
  147. assert_(not (self.all_f16 == nan).any())
  148. assert_(not (nan == self.all_f16).any())
  149. assert_((self.all_f16 != nan).all())
  150. assert_((nan != self.all_f16).all())
  151. assert_(not (self.all_f16 < nan).any())
  152. assert_(not (nan < self.all_f16).any())
  153. assert_(not (self.all_f16 <= nan).any())
  154. assert_(not (nan <= self.all_f16).any())
  155. assert_(not (self.all_f16 > nan).any())
  156. assert_(not (nan > self.all_f16).any())
  157. assert_(not (self.all_f16 >= nan).any())
  158. assert_(not (nan >= self.all_f16).any())
  159. def test_half_values(self):
  160. """Confirms a small number of known half values"""
  161. a = np.array([1.0, -1.0,
  162. 2.0, -2.0,
  163. 0.0999755859375, 0.333251953125, # 1/10, 1/3
  164. 65504, -65504, # Maximum magnitude
  165. 2.0**(-14), -2.0**(-14), # Minimum normal
  166. 2.0**(-24), -2.0**(-24), # Minimum subnormal
  167. 0, -1/1e1000, # Signed zeros
  168. np.inf, -np.inf])
  169. b = np.array([0x3c00, 0xbc00,
  170. 0x4000, 0xc000,
  171. 0x2e66, 0x3555,
  172. 0x7bff, 0xfbff,
  173. 0x0400, 0x8400,
  174. 0x0001, 0x8001,
  175. 0x0000, 0x8000,
  176. 0x7c00, 0xfc00], dtype=uint16)
  177. b.dtype = float16
  178. assert_equal(a, b)
  179. def test_half_rounding(self):
  180. """Checks that rounding when converting to half is correct"""
  181. a = np.array([2.0**-25 + 2.0**-35, # Rounds to minimum subnormal
  182. 2.0**-25, # Underflows to zero (nearest even mode)
  183. 2.0**-26, # Underflows to zero
  184. 1.0+2.0**-11 + 2.0**-16, # rounds to 1.0+2**(-10)
  185. 1.0+2.0**-11, # rounds to 1.0 (nearest even mode)
  186. 1.0+2.0**-12, # rounds to 1.0
  187. 65519, # rounds to 65504
  188. 65520], # rounds to inf
  189. dtype=float64)
  190. rounded = [2.0**-24,
  191. 0.0,
  192. 0.0,
  193. 1.0+2.0**(-10),
  194. 1.0,
  195. 1.0,
  196. 65504,
  197. np.inf]
  198. # Check float64->float16 rounding
  199. with np.errstate(over="ignore"):
  200. b = np.array(a, dtype=float16)
  201. assert_equal(b, rounded)
  202. # Check float32->float16 rounding
  203. a = np.array(a, dtype=float32)
  204. with np.errstate(over="ignore"):
  205. b = np.array(a, dtype=float16)
  206. assert_equal(b, rounded)
  207. def test_half_correctness(self):
  208. """Take every finite float16, and check the casting functions with
  209. a manual conversion."""
  210. # Create an array of all finite float16s
  211. a_bits = self.finite_f16.view(dtype=uint16)
  212. # Convert to 64-bit float manually
  213. a_sgn = (-1.0)**((a_bits & 0x8000) >> 15)
  214. a_exp = np.array((a_bits & 0x7c00) >> 10, dtype=np.int32) - 15
  215. a_man = (a_bits & 0x03ff) * 2.0**(-10)
  216. # Implicit bit of normalized floats
  217. a_man[a_exp != -15] += 1
  218. # Denormalized exponent is -14
  219. a_exp[a_exp == -15] = -14
  220. a_manual = a_sgn * a_man * 2.0**a_exp
  221. a32_fail = np.nonzero(self.finite_f32 != a_manual)[0]
  222. if len(a32_fail) != 0:
  223. bad_index = a32_fail[0]
  224. assert_equal(self.finite_f32, a_manual,
  225. "First non-equal is half value %x -> %g != %g" %
  226. (self.finite_f16[bad_index],
  227. self.finite_f32[bad_index],
  228. a_manual[bad_index]))
  229. a64_fail = np.nonzero(self.finite_f64 != a_manual)[0]
  230. if len(a64_fail) != 0:
  231. bad_index = a64_fail[0]
  232. assert_equal(self.finite_f64, a_manual,
  233. "First non-equal is half value %x -> %g != %g" %
  234. (self.finite_f16[bad_index],
  235. self.finite_f64[bad_index],
  236. a_manual[bad_index]))
  237. def test_half_ordering(self):
  238. """Make sure comparisons are working right"""
  239. # All non-NaN float16 values in reverse order
  240. a = self.nonan_f16[::-1].copy()
  241. # 32-bit float copy
  242. b = np.array(a, dtype=float32)
  243. # Should sort the same
  244. a.sort()
  245. b.sort()
  246. assert_equal(a, b)
  247. # Comparisons should work
  248. assert_((a[:-1] <= a[1:]).all())
  249. assert_(not (a[:-1] > a[1:]).any())
  250. assert_((a[1:] >= a[:-1]).all())
  251. assert_(not (a[1:] < a[:-1]).any())
  252. # All != except for +/-0
  253. assert_equal(np.nonzero(a[:-1] < a[1:])[0].size, a.size-2)
  254. assert_equal(np.nonzero(a[1:] > a[:-1])[0].size, a.size-2)
  255. def test_half_funcs(self):
  256. """Test the various ArrFuncs"""
  257. # fill
  258. assert_equal(np.arange(10, dtype=float16),
  259. np.arange(10, dtype=float32))
  260. # fillwithscalar
  261. a = np.zeros((5,), dtype=float16)
  262. a.fill(1)
  263. assert_equal(a, np.ones((5,), dtype=float16))
  264. # nonzero and copyswap
  265. a = np.array([0, 0, -1, -1/1e20, 0, 2.0**-24, 7.629e-6], dtype=float16)
  266. assert_equal(a.nonzero()[0],
  267. [2, 5, 6])
  268. a = a.byteswap().newbyteorder()
  269. assert_equal(a.nonzero()[0],
  270. [2, 5, 6])
  271. # dot
  272. a = np.arange(0, 10, 0.5, dtype=float16)
  273. b = np.ones((20,), dtype=float16)
  274. assert_equal(np.dot(a, b),
  275. 95)
  276. # argmax
  277. a = np.array([0, -np.inf, -2, 0.5, 12.55, 7.3, 2.1, 12.4], dtype=float16)
  278. assert_equal(a.argmax(),
  279. 4)
  280. a = np.array([0, -np.inf, -2, np.inf, 12.55, np.nan, 2.1, 12.4], dtype=float16)
  281. assert_equal(a.argmax(),
  282. 5)
  283. # getitem
  284. a = np.arange(10, dtype=float16)
  285. for i in range(10):
  286. assert_equal(a.item(i), i)
  287. def test_spacing_nextafter(self):
  288. """Test np.spacing and np.nextafter"""
  289. # All non-negative finite #'s
  290. a = np.arange(0x7c00, dtype=uint16)
  291. hinf = np.array((np.inf,), dtype=float16)
  292. hnan = np.array((np.nan,), dtype=float16)
  293. a_f16 = a.view(dtype=float16)
  294. assert_equal(np.spacing(a_f16[:-1]), a_f16[1:]-a_f16[:-1])
  295. assert_equal(np.nextafter(a_f16[:-1], hinf), a_f16[1:])
  296. assert_equal(np.nextafter(a_f16[0], -hinf), -a_f16[1])
  297. assert_equal(np.nextafter(a_f16[1:], -hinf), a_f16[:-1])
  298. assert_equal(np.nextafter(hinf, a_f16), a_f16[-1])
  299. assert_equal(np.nextafter(-hinf, a_f16), -a_f16[-1])
  300. assert_equal(np.nextafter(hinf, hinf), hinf)
  301. assert_equal(np.nextafter(hinf, -hinf), a_f16[-1])
  302. assert_equal(np.nextafter(-hinf, hinf), -a_f16[-1])
  303. assert_equal(np.nextafter(-hinf, -hinf), -hinf)
  304. assert_equal(np.nextafter(a_f16, hnan), hnan[0])
  305. assert_equal(np.nextafter(hnan, a_f16), hnan[0])
  306. assert_equal(np.nextafter(hnan, hnan), hnan)
  307. assert_equal(np.nextafter(hinf, hnan), hnan)
  308. assert_equal(np.nextafter(hnan, hinf), hnan)
  309. # switch to negatives
  310. a |= 0x8000
  311. assert_equal(np.spacing(a_f16[0]), np.spacing(a_f16[1]))
  312. assert_equal(np.spacing(a_f16[1:]), a_f16[:-1]-a_f16[1:])
  313. assert_equal(np.nextafter(a_f16[0], hinf), -a_f16[1])
  314. assert_equal(np.nextafter(a_f16[1:], hinf), a_f16[:-1])
  315. assert_equal(np.nextafter(a_f16[:-1], -hinf), a_f16[1:])
  316. assert_equal(np.nextafter(hinf, a_f16), -a_f16[-1])
  317. assert_equal(np.nextafter(-hinf, a_f16), a_f16[-1])
  318. assert_equal(np.nextafter(a_f16, hnan), hnan[0])
  319. assert_equal(np.nextafter(hnan, a_f16), hnan[0])
  320. def test_half_ufuncs(self):
  321. """Test the various ufuncs"""
  322. a = np.array([0, 1, 2, 4, 2], dtype=float16)
  323. b = np.array([-2, 5, 1, 4, 3], dtype=float16)
  324. c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16)
  325. assert_equal(np.add(a, b), [-2, 6, 3, 8, 5])
  326. assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1])
  327. assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6])
  328. assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625])
  329. assert_equal(np.equal(a, b), [False, False, False, True, False])
  330. assert_equal(np.not_equal(a, b), [True, True, True, False, True])
  331. assert_equal(np.less(a, b), [False, True, False, False, True])
  332. assert_equal(np.less_equal(a, b), [False, True, False, True, True])
  333. assert_equal(np.greater(a, b), [True, False, True, False, False])
  334. assert_equal(np.greater_equal(a, b), [True, False, True, True, False])
  335. assert_equal(np.logical_and(a, b), [False, True, True, True, True])
  336. assert_equal(np.logical_or(a, b), [True, True, True, True, True])
  337. assert_equal(np.logical_xor(a, b), [True, False, False, False, False])
  338. assert_equal(np.logical_not(a), [True, False, False, False, False])
  339. assert_equal(np.isnan(c), [False, False, False, True, False])
  340. assert_equal(np.isinf(c), [False, False, True, False, False])
  341. assert_equal(np.isfinite(c), [True, True, False, False, True])
  342. assert_equal(np.signbit(b), [True, False, False, False, False])
  343. assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3])
  344. assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3])
  345. x = np.maximum(b, c)
  346. assert_(np.isnan(x[3]))
  347. x[3] = 0
  348. assert_equal(x, [0, 5, 1, 0, 6])
  349. assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2])
  350. x = np.minimum(b, c)
  351. assert_(np.isnan(x[3]))
  352. x[3] = 0
  353. assert_equal(x, [-2, -1, -np.inf, 0, 3])
  354. assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3])
  355. assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6])
  356. assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2])
  357. assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3])
  358. assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0])
  359. assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2])
  360. assert_equal(np.divmod(a, b), ([0, 0, 2, 1, 0], [0, 1, 0, 0, 2]))
  361. assert_equal(np.square(b), [4, 25, 1, 16, 9])
  362. assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125])
  363. assert_equal(np.ones_like(b), [1, 1, 1, 1, 1])
  364. assert_equal(np.conjugate(b), b)
  365. assert_equal(np.absolute(b), [2, 5, 1, 4, 3])
  366. assert_equal(np.negative(b), [2, -5, -1, -4, -3])
  367. assert_equal(np.positive(b), b)
  368. assert_equal(np.sign(b), [-1, 1, 1, 1, 1])
  369. assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b))
  370. assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2]))
  371. assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
  372. @np._no_nep50_warning()
  373. def test_half_coercion(self, weak_promotion):
  374. """Test that half gets coerced properly with the other types"""
  375. a16 = np.array((1,), dtype=float16)
  376. a32 = np.array((1,), dtype=float32)
  377. b16 = float16(1)
  378. b32 = float32(1)
  379. assert np.power(a16, 2).dtype == float16
  380. assert np.power(a16, 2.0).dtype == float16
  381. assert np.power(a16, b16).dtype == float16
  382. expected_dt = float32 if weak_promotion else float16
  383. assert np.power(a16, b32).dtype == expected_dt
  384. assert np.power(a16, a16).dtype == float16
  385. assert np.power(a16, a32).dtype == float32
  386. expected_dt = float16 if weak_promotion else float64
  387. assert np.power(b16, 2).dtype == expected_dt
  388. assert np.power(b16, 2.0).dtype == expected_dt
  389. assert np.power(b16, b16).dtype, float16
  390. assert np.power(b16, b32).dtype, float32
  391. assert np.power(b16, a16).dtype, float16
  392. assert np.power(b16, a32).dtype, float32
  393. assert np.power(a32, a16).dtype == float32
  394. assert np.power(a32, b16).dtype == float32
  395. expected_dt = float32 if weak_promotion else float16
  396. assert np.power(b32, a16).dtype == expected_dt
  397. assert np.power(b32, b16).dtype == float32
  398. @pytest.mark.skipif(platform.machine() == "armv5tel",
  399. reason="See gh-413.")
  400. @pytest.mark.skipif(IS_WASM,
  401. reason="fp exceptions don't work in wasm.")
  402. def test_half_fpe(self):
  403. with np.errstate(all='raise'):
  404. sx16 = np.array((1e-4,), dtype=float16)
  405. bx16 = np.array((1e4,), dtype=float16)
  406. sy16 = float16(1e-4)
  407. by16 = float16(1e4)
  408. # Underflow errors
  409. assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sx16)
  410. assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sy16)
  411. assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sx16)
  412. assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sy16)
  413. assert_raises_fpe('underflow', lambda a, b:a/b, sx16, bx16)
  414. assert_raises_fpe('underflow', lambda a, b:a/b, sx16, by16)
  415. assert_raises_fpe('underflow', lambda a, b:a/b, sy16, bx16)
  416. assert_raises_fpe('underflow', lambda a, b:a/b, sy16, by16)
  417. assert_raises_fpe('underflow', lambda a, b:a/b,
  418. float16(2.**-14), float16(2**11))
  419. assert_raises_fpe('underflow', lambda a, b:a/b,
  420. float16(-2.**-14), float16(2**11))
  421. assert_raises_fpe('underflow', lambda a, b:a/b,
  422. float16(2.**-14+2**-24), float16(2))
  423. assert_raises_fpe('underflow', lambda a, b:a/b,
  424. float16(-2.**-14-2**-24), float16(2))
  425. assert_raises_fpe('underflow', lambda a, b:a/b,
  426. float16(2.**-14+2**-23), float16(4))
  427. # Overflow errors
  428. assert_raises_fpe('overflow', lambda a, b:a*b, bx16, bx16)
  429. assert_raises_fpe('overflow', lambda a, b:a*b, bx16, by16)
  430. assert_raises_fpe('overflow', lambda a, b:a*b, by16, bx16)
  431. assert_raises_fpe('overflow', lambda a, b:a*b, by16, by16)
  432. assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sx16)
  433. assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sy16)
  434. assert_raises_fpe('overflow', lambda a, b:a/b, by16, sx16)
  435. assert_raises_fpe('overflow', lambda a, b:a/b, by16, sy16)
  436. assert_raises_fpe('overflow', lambda a, b:a+b,
  437. float16(65504), float16(17))
  438. assert_raises_fpe('overflow', lambda a, b:a-b,
  439. float16(-65504), float16(17))
  440. assert_raises_fpe('overflow', np.nextafter, float16(65504), float16(np.inf))
  441. assert_raises_fpe('overflow', np.nextafter, float16(-65504), float16(-np.inf))
  442. assert_raises_fpe('overflow', np.spacing, float16(65504))
  443. # Invalid value errors
  444. assert_raises_fpe('invalid', np.divide, float16(np.inf), float16(np.inf))
  445. assert_raises_fpe('invalid', np.spacing, float16(np.inf))
  446. assert_raises_fpe('invalid', np.spacing, float16(np.nan))
  447. # These should not raise
  448. float16(65472)+float16(32)
  449. float16(2**-13)/float16(2)
  450. float16(2**-14)/float16(2**10)
  451. np.spacing(float16(-65504))
  452. np.nextafter(float16(65504), float16(-np.inf))
  453. np.nextafter(float16(-65504), float16(np.inf))
  454. np.nextafter(float16(np.inf), float16(0))
  455. np.nextafter(float16(-np.inf), float16(0))
  456. np.nextafter(float16(0), float16(np.nan))
  457. np.nextafter(float16(np.nan), float16(0))
  458. float16(2**-14)/float16(2**10)
  459. float16(-2**-14)/float16(2**10)
  460. float16(2**-14+2**-23)/float16(2)
  461. float16(-2**-14-2**-23)/float16(2)
  462. def test_half_array_interface(self):
  463. """Test that half is compatible with __array_interface__"""
  464. class Dummy:
  465. pass
  466. a = np.ones((1,), dtype=float16)
  467. b = Dummy()
  468. b.__array_interface__ = a.__array_interface__
  469. c = np.array(b)
  470. assert_(c.dtype == float16)
  471. assert_equal(a, c)