test_polynomial.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import numpy as np
  2. from numpy.testing import (
  3. assert_, assert_equal, assert_array_equal, assert_almost_equal,
  4. assert_array_almost_equal, assert_raises, assert_allclose
  5. )
  6. class TestPolynomial:
  7. def test_poly1d_str_and_repr(self):
  8. p = np.poly1d([1., 2, 3])
  9. assert_equal(repr(p), 'poly1d([1., 2., 3.])')
  10. assert_equal(str(p),
  11. ' 2\n'
  12. '1 x + 2 x + 3')
  13. q = np.poly1d([3., 2, 1])
  14. assert_equal(repr(q), 'poly1d([3., 2., 1.])')
  15. assert_equal(str(q),
  16. ' 2\n'
  17. '3 x + 2 x + 1')
  18. r = np.poly1d([1.89999 + 2j, -3j, -5.12345678, 2 + 1j])
  19. assert_equal(str(r),
  20. ' 3 2\n'
  21. '(1.9 + 2j) x - 3j x - 5.123 x + (2 + 1j)')
  22. assert_equal(str(np.poly1d([-3, -2, -1])),
  23. ' 2\n'
  24. '-3 x - 2 x - 1')
  25. def test_poly1d_resolution(self):
  26. p = np.poly1d([1., 2, 3])
  27. q = np.poly1d([3., 2, 1])
  28. assert_equal(p(0), 3.0)
  29. assert_equal(p(5), 38.0)
  30. assert_equal(q(0), 1.0)
  31. assert_equal(q(5), 86.0)
  32. def test_poly1d_math(self):
  33. # here we use some simple coeffs to make calculations easier
  34. p = np.poly1d([1., 2, 4])
  35. q = np.poly1d([4., 2, 1])
  36. assert_equal(p/q, (np.poly1d([0.25]), np.poly1d([1.5, 3.75])))
  37. assert_equal(p.integ(), np.poly1d([1/3, 1., 4., 0.]))
  38. assert_equal(p.integ(1), np.poly1d([1/3, 1., 4., 0.]))
  39. p = np.poly1d([1., 2, 3])
  40. q = np.poly1d([3., 2, 1])
  41. assert_equal(p * q, np.poly1d([3., 8., 14., 8., 3.]))
  42. assert_equal(p + q, np.poly1d([4., 4., 4.]))
  43. assert_equal(p - q, np.poly1d([-2., 0., 2.]))
  44. assert_equal(p ** 4, np.poly1d([1., 8., 36., 104., 214., 312., 324., 216., 81.]))
  45. assert_equal(p(q), np.poly1d([9., 12., 16., 8., 6.]))
  46. assert_equal(q(p), np.poly1d([3., 12., 32., 40., 34.]))
  47. assert_equal(p.deriv(), np.poly1d([2., 2.]))
  48. assert_equal(p.deriv(2), np.poly1d([2.]))
  49. assert_equal(np.polydiv(np.poly1d([1, 0, -1]), np.poly1d([1, 1])),
  50. (np.poly1d([1., -1.]), np.poly1d([0.])))
  51. def test_poly1d_misc(self):
  52. p = np.poly1d([1., 2, 3])
  53. assert_equal(np.asarray(p), np.array([1., 2., 3.]))
  54. assert_equal(len(p), 2)
  55. assert_equal((p[0], p[1], p[2], p[3]), (3.0, 2.0, 1.0, 0))
  56. def test_poly1d_variable_arg(self):
  57. q = np.poly1d([1., 2, 3], variable='y')
  58. assert_equal(str(q),
  59. ' 2\n'
  60. '1 y + 2 y + 3')
  61. q = np.poly1d([1., 2, 3], variable='lambda')
  62. assert_equal(str(q),
  63. ' 2\n'
  64. '1 lambda + 2 lambda + 3')
  65. def test_poly(self):
  66. assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]),
  67. [1, -3, -2, 6])
  68. # From matlab docs
  69. A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
  70. assert_array_almost_equal(np.poly(A), [1, -6, -72, -27])
  71. # Should produce real output for perfect conjugates
  72. assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j])))
  73. assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j,
  74. 1-2j, 1.+3.5j, 1-3.5j])))
  75. assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j])))
  76. assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j])))
  77. assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j])))
  78. assert_(np.isrealobj(np.poly([1j, -1j])))
  79. assert_(np.isrealobj(np.poly([1, -1])))
  80. assert_(np.iscomplexobj(np.poly([1j, -1.0000001j])))
  81. np.random.seed(42)
  82. a = np.random.randn(100) + 1j*np.random.randn(100)
  83. assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a))))))
  84. def test_roots(self):
  85. assert_array_equal(np.roots([1, 0, 0]), [0, 0])
  86. def test_str_leading_zeros(self):
  87. p = np.poly1d([4, 3, 2, 1])
  88. p[3] = 0
  89. assert_equal(str(p),
  90. " 2\n"
  91. "3 x + 2 x + 1")
  92. p = np.poly1d([1, 2])
  93. p[0] = 0
  94. p[1] = 0
  95. assert_equal(str(p), " \n0")
  96. def test_polyfit(self):
  97. c = np.array([3., 2., 1.])
  98. x = np.linspace(0, 2, 7)
  99. y = np.polyval(c, x)
  100. err = [1, -1, 1, -1, 1, -1, 1]
  101. weights = np.arange(8, 1, -1)**2/7.0
  102. # Check exception when too few points for variance estimate. Note that
  103. # the estimate requires the number of data points to exceed
  104. # degree + 1
  105. assert_raises(ValueError, np.polyfit,
  106. [1], [1], deg=0, cov=True)
  107. # check 1D case
  108. m, cov = np.polyfit(x, y+err, 2, cov=True)
  109. est = [3.8571, 0.2857, 1.619]
  110. assert_almost_equal(est, m, decimal=4)
  111. val0 = [[ 1.4694, -2.9388, 0.8163],
  112. [-2.9388, 6.3673, -2.1224],
  113. [ 0.8163, -2.1224, 1.161 ]]
  114. assert_almost_equal(val0, cov, decimal=4)
  115. m2, cov2 = np.polyfit(x, y+err, 2, w=weights, cov=True)
  116. assert_almost_equal([4.8927, -1.0177, 1.7768], m2, decimal=4)
  117. val = [[ 4.3964, -5.0052, 0.4878],
  118. [-5.0052, 6.8067, -0.9089],
  119. [ 0.4878, -0.9089, 0.3337]]
  120. assert_almost_equal(val, cov2, decimal=4)
  121. m3, cov3 = np.polyfit(x, y+err, 2, w=weights, cov="unscaled")
  122. assert_almost_equal([4.8927, -1.0177, 1.7768], m3, decimal=4)
  123. val = [[ 0.1473, -0.1677, 0.0163],
  124. [-0.1677, 0.228 , -0.0304],
  125. [ 0.0163, -0.0304, 0.0112]]
  126. assert_almost_equal(val, cov3, decimal=4)
  127. # check 2D (n,1) case
  128. y = y[:, np.newaxis]
  129. c = c[:, np.newaxis]
  130. assert_almost_equal(c, np.polyfit(x, y, 2))
  131. # check 2D (n,2) case
  132. yy = np.concatenate((y, y), axis=1)
  133. cc = np.concatenate((c, c), axis=1)
  134. assert_almost_equal(cc, np.polyfit(x, yy, 2))
  135. m, cov = np.polyfit(x, yy + np.array(err)[:, np.newaxis], 2, cov=True)
  136. assert_almost_equal(est, m[:, 0], decimal=4)
  137. assert_almost_equal(est, m[:, 1], decimal=4)
  138. assert_almost_equal(val0, cov[:, :, 0], decimal=4)
  139. assert_almost_equal(val0, cov[:, :, 1], decimal=4)
  140. # check order 1 (deg=0) case, were the analytic results are simple
  141. np.random.seed(123)
  142. y = np.random.normal(size=(4, 10000))
  143. mean, cov = np.polyfit(np.zeros(y.shape[0]), y, deg=0, cov=True)
  144. # Should get sigma_mean = sigma/sqrt(N) = 1./sqrt(4) = 0.5.
  145. assert_allclose(mean.std(), 0.5, atol=0.01)
  146. assert_allclose(np.sqrt(cov.mean()), 0.5, atol=0.01)
  147. # Without scaling, since reduced chi2 is 1, the result should be the same.
  148. mean, cov = np.polyfit(np.zeros(y.shape[0]), y, w=np.ones(y.shape[0]),
  149. deg=0, cov="unscaled")
  150. assert_allclose(mean.std(), 0.5, atol=0.01)
  151. assert_almost_equal(np.sqrt(cov.mean()), 0.5)
  152. # If we estimate our errors wrong, no change with scaling:
  153. w = np.full(y.shape[0], 1./0.5)
  154. mean, cov = np.polyfit(np.zeros(y.shape[0]), y, w=w, deg=0, cov=True)
  155. assert_allclose(mean.std(), 0.5, atol=0.01)
  156. assert_allclose(np.sqrt(cov.mean()), 0.5, atol=0.01)
  157. # But if we do not scale, our estimate for the error in the mean will
  158. # differ.
  159. mean, cov = np.polyfit(np.zeros(y.shape[0]), y, w=w, deg=0, cov="unscaled")
  160. assert_allclose(mean.std(), 0.5, atol=0.01)
  161. assert_almost_equal(np.sqrt(cov.mean()), 0.25)
  162. def test_objects(self):
  163. from decimal import Decimal
  164. p = np.poly1d([Decimal('4.0'), Decimal('3.0'), Decimal('2.0')])
  165. p2 = p * Decimal('1.333333333333333')
  166. assert_(p2[1] == Decimal("3.9999999999999990"))
  167. p2 = p.deriv()
  168. assert_(p2[1] == Decimal('8.0'))
  169. p2 = p.integ()
  170. assert_(p2[3] == Decimal("1.333333333333333333333333333"))
  171. assert_(p2[2] == Decimal('1.5'))
  172. assert_(np.issubdtype(p2.coeffs.dtype, np.object_))
  173. p = np.poly([Decimal(1), Decimal(2)])
  174. assert_equal(np.poly([Decimal(1), Decimal(2)]),
  175. [1, Decimal(-3), Decimal(2)])
  176. def test_complex(self):
  177. p = np.poly1d([3j, 2j, 1j])
  178. p2 = p.integ()
  179. assert_((p2.coeffs == [1j, 1j, 1j, 0]).all())
  180. p2 = p.deriv()
  181. assert_((p2.coeffs == [6j, 2j]).all())
  182. def test_integ_coeffs(self):
  183. p = np.poly1d([3, 2, 1])
  184. p2 = p.integ(3, k=[9, 7, 6])
  185. assert_(
  186. (p2.coeffs == [1/4./5., 1/3./4., 1/2./3., 9/1./2., 7, 6]).all())
  187. def test_zero_dims(self):
  188. try:
  189. np.poly(np.zeros((0, 0)))
  190. except ValueError:
  191. pass
  192. def test_poly_int_overflow(self):
  193. """
  194. Regression test for gh-5096.
  195. """
  196. v = np.arange(1, 21)
  197. assert_almost_equal(np.poly(v), np.poly(np.diag(v)))
  198. def test_zero_poly_dtype(self):
  199. """
  200. Regression test for gh-16354.
  201. """
  202. z = np.array([0, 0, 0])
  203. p = np.poly1d(z.astype(np.int64))
  204. assert_equal(p.coeffs.dtype, np.int64)
  205. p = np.poly1d(z.astype(np.float32))
  206. assert_equal(p.coeffs.dtype, np.float32)
  207. p = np.poly1d(z.astype(np.complex64))
  208. assert_equal(p.coeffs.dtype, np.complex64)
  209. def test_poly_eq(self):
  210. p = np.poly1d([1, 2, 3])
  211. p2 = np.poly1d([1, 2, 4])
  212. assert_equal(p == None, False)
  213. assert_equal(p != None, True)
  214. assert_equal(p == p, True)
  215. assert_equal(p == p2, False)
  216. assert_equal(p != p2, True)
  217. def test_polydiv(self):
  218. b = np.poly1d([2, 6, 6, 1])
  219. a = np.poly1d([-1j, (1+2j), -(2+1j), 1])
  220. q, r = np.polydiv(b, a)
  221. assert_equal(q.coeffs.dtype, np.complex128)
  222. assert_equal(r.coeffs.dtype, np.complex128)
  223. assert_equal(q*a + r, b)
  224. c = [1, 2, 3]
  225. d = np.poly1d([1, 2, 3])
  226. s, t = np.polydiv(c, d)
  227. assert isinstance(s, np.poly1d)
  228. assert isinstance(t, np.poly1d)
  229. u, v = np.polydiv(d, c)
  230. assert isinstance(u, np.poly1d)
  231. assert isinstance(v, np.poly1d)
  232. def test_poly_coeffs_mutable(self):
  233. """ Coefficients should be modifiable """
  234. p = np.poly1d([1, 2, 3])
  235. p.coeffs += 1
  236. assert_equal(p.coeffs, [2, 3, 4])
  237. p.coeffs[2] += 10
  238. assert_equal(p.coeffs, [2, 3, 14])
  239. # this never used to be allowed - let's not add features to deprecated
  240. # APIs
  241. assert_raises(AttributeError, setattr, p, 'coeffs', np.array(1))