test_polynomial.py 9.9 KB

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