polynomial.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  1. """
  2. Functions to operate on polynomials.
  3. """
  4. __all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd',
  5. 'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d',
  6. 'polyfit', 'RankWarning']
  7. import functools
  8. import re
  9. import warnings
  10. import numpy.core.numeric as NX
  11. from numpy.core import (isscalar, abs, finfo, atleast_1d, hstack, dot, array,
  12. ones)
  13. from numpy.core import overrides
  14. from numpy.core.overrides import set_module
  15. from numpy.lib.twodim_base import diag, vander
  16. from numpy.lib.function_base import trim_zeros
  17. from numpy.lib.type_check import iscomplex, real, imag, mintypecode
  18. from numpy.linalg import eigvals, lstsq, inv
  19. array_function_dispatch = functools.partial(
  20. overrides.array_function_dispatch, module='numpy')
  21. @set_module('numpy')
  22. class RankWarning(UserWarning):
  23. """
  24. Issued by `polyfit` when the Vandermonde matrix is rank deficient.
  25. For more information, a way to suppress the warning, and an example of
  26. `RankWarning` being issued, see `polyfit`.
  27. """
  28. pass
  29. def _poly_dispatcher(seq_of_zeros):
  30. return seq_of_zeros
  31. @array_function_dispatch(_poly_dispatcher)
  32. def poly(seq_of_zeros):
  33. """
  34. Find the coefficients of a polynomial with the given sequence of roots.
  35. .. note::
  36. This forms part of the old polynomial API. Since version 1.4, the
  37. new polynomial API defined in `numpy.polynomial` is preferred.
  38. A summary of the differences can be found in the
  39. :doc:`transition guide </reference/routines.polynomials>`.
  40. Returns the coefficients of the polynomial whose leading coefficient
  41. is one for the given sequence of zeros (multiple roots must be included
  42. in the sequence as many times as their multiplicity; see Examples).
  43. A square matrix (or array, which will be treated as a matrix) can also
  44. be given, in which case the coefficients of the characteristic polynomial
  45. of the matrix are returned.
  46. Parameters
  47. ----------
  48. seq_of_zeros : array_like, shape (N,) or (N, N)
  49. A sequence of polynomial roots, or a square array or matrix object.
  50. Returns
  51. -------
  52. c : ndarray
  53. 1D array of polynomial coefficients from highest to lowest degree:
  54. ``c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]``
  55. where c[0] always equals 1.
  56. Raises
  57. ------
  58. ValueError
  59. If input is the wrong shape (the input must be a 1-D or square
  60. 2-D array).
  61. See Also
  62. --------
  63. polyval : Compute polynomial values.
  64. roots : Return the roots of a polynomial.
  65. polyfit : Least squares polynomial fit.
  66. poly1d : A one-dimensional polynomial class.
  67. Notes
  68. -----
  69. Specifying the roots of a polynomial still leaves one degree of
  70. freedom, typically represented by an undetermined leading
  71. coefficient. [1]_ In the case of this function, that coefficient -
  72. the first one in the returned array - is always taken as one. (If
  73. for some reason you have one other point, the only automatic way
  74. presently to leverage that information is to use ``polyfit``.)
  75. The characteristic polynomial, :math:`p_a(t)`, of an `n`-by-`n`
  76. matrix **A** is given by
  77. :math:`p_a(t) = \\mathrm{det}(t\\, \\mathbf{I} - \\mathbf{A})`,
  78. where **I** is the `n`-by-`n` identity matrix. [2]_
  79. References
  80. ----------
  81. .. [1] M. Sullivan and M. Sullivan, III, "Algebra and Trignometry,
  82. Enhanced With Graphing Utilities," Prentice-Hall, pg. 318, 1996.
  83. .. [2] G. Strang, "Linear Algebra and Its Applications, 2nd Edition,"
  84. Academic Press, pg. 182, 1980.
  85. Examples
  86. --------
  87. Given a sequence of a polynomial's zeros:
  88. >>> np.poly((0, 0, 0)) # Multiple root example
  89. array([1., 0., 0., 0.])
  90. The line above represents z**3 + 0*z**2 + 0*z + 0.
  91. >>> np.poly((-1./2, 0, 1./2))
  92. array([ 1. , 0. , -0.25, 0. ])
  93. The line above represents z**3 - z/4
  94. >>> np.poly((np.random.random(1)[0], 0, np.random.random(1)[0]))
  95. array([ 1. , -0.77086955, 0.08618131, 0. ]) # random
  96. Given a square array object:
  97. >>> P = np.array([[0, 1./3], [-1./2, 0]])
  98. >>> np.poly(P)
  99. array([1. , 0. , 0.16666667])
  100. Note how in all cases the leading coefficient is always 1.
  101. """
  102. seq_of_zeros = atleast_1d(seq_of_zeros)
  103. sh = seq_of_zeros.shape
  104. if len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0:
  105. seq_of_zeros = eigvals(seq_of_zeros)
  106. elif len(sh) == 1:
  107. dt = seq_of_zeros.dtype
  108. # Let object arrays slip through, e.g. for arbitrary precision
  109. if dt != object:
  110. seq_of_zeros = seq_of_zeros.astype(mintypecode(dt.char))
  111. else:
  112. raise ValueError("input must be 1d or non-empty square 2d array.")
  113. if len(seq_of_zeros) == 0:
  114. return 1.0
  115. dt = seq_of_zeros.dtype
  116. a = ones((1,), dtype=dt)
  117. for k in range(len(seq_of_zeros)):
  118. a = NX.convolve(a, array([1, -seq_of_zeros[k]], dtype=dt),
  119. mode='full')
  120. if issubclass(a.dtype.type, NX.complexfloating):
  121. # if complex roots are all complex conjugates, the roots are real.
  122. roots = NX.asarray(seq_of_zeros, complex)
  123. if NX.all(NX.sort(roots) == NX.sort(roots.conjugate())):
  124. a = a.real.copy()
  125. return a
  126. def _roots_dispatcher(p):
  127. return p
  128. @array_function_dispatch(_roots_dispatcher)
  129. def roots(p):
  130. """
  131. Return the roots of a polynomial with coefficients given in p.
  132. .. note::
  133. This forms part of the old polynomial API. Since version 1.4, the
  134. new polynomial API defined in `numpy.polynomial` is preferred.
  135. A summary of the differences can be found in the
  136. :doc:`transition guide </reference/routines.polynomials>`.
  137. The values in the rank-1 array `p` are coefficients of a polynomial.
  138. If the length of `p` is n+1 then the polynomial is described by::
  139. p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
  140. Parameters
  141. ----------
  142. p : array_like
  143. Rank-1 array of polynomial coefficients.
  144. Returns
  145. -------
  146. out : ndarray
  147. An array containing the roots of the polynomial.
  148. Raises
  149. ------
  150. ValueError
  151. When `p` cannot be converted to a rank-1 array.
  152. See also
  153. --------
  154. poly : Find the coefficients of a polynomial with a given sequence
  155. of roots.
  156. polyval : Compute polynomial values.
  157. polyfit : Least squares polynomial fit.
  158. poly1d : A one-dimensional polynomial class.
  159. Notes
  160. -----
  161. The algorithm relies on computing the eigenvalues of the
  162. companion matrix [1]_.
  163. References
  164. ----------
  165. .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK:
  166. Cambridge University Press, 1999, pp. 146-7.
  167. Examples
  168. --------
  169. >>> coeff = [3.2, 2, 1]
  170. >>> np.roots(coeff)
  171. array([-0.3125+0.46351241j, -0.3125-0.46351241j])
  172. """
  173. # If input is scalar, this makes it an array
  174. p = atleast_1d(p)
  175. if p.ndim != 1:
  176. raise ValueError("Input must be a rank-1 array.")
  177. # find non-zero array entries
  178. non_zero = NX.nonzero(NX.ravel(p))[0]
  179. # Return an empty array if polynomial is all zeros
  180. if len(non_zero) == 0:
  181. return NX.array([])
  182. # find the number of trailing zeros -- this is the number of roots at 0.
  183. trailing_zeros = len(p) - non_zero[-1] - 1
  184. # strip leading and trailing zeros
  185. p = p[int(non_zero[0]):int(non_zero[-1])+1]
  186. # casting: if incoming array isn't floating point, make it floating point.
  187. if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)):
  188. p = p.astype(float)
  189. N = len(p)
  190. if N > 1:
  191. # build companion matrix and find its eigenvalues (the roots)
  192. A = diag(NX.ones((N-2,), p.dtype), -1)
  193. A[0,:] = -p[1:] / p[0]
  194. roots = eigvals(A)
  195. else:
  196. roots = NX.array([])
  197. # tack any zeros onto the back of the array
  198. roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype)))
  199. return roots
  200. def _polyint_dispatcher(p, m=None, k=None):
  201. return (p,)
  202. @array_function_dispatch(_polyint_dispatcher)
  203. def polyint(p, m=1, k=None):
  204. """
  205. Return an antiderivative (indefinite integral) of a polynomial.
  206. .. note::
  207. This forms part of the old polynomial API. Since version 1.4, the
  208. new polynomial API defined in `numpy.polynomial` is preferred.
  209. A summary of the differences can be found in the
  210. :doc:`transition guide </reference/routines.polynomials>`.
  211. The returned order `m` antiderivative `P` of polynomial `p` satisfies
  212. :math:`\\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1`
  213. integration constants `k`. The constants determine the low-order
  214. polynomial part
  215. .. math:: \\frac{k_{m-1}}{0!} x^0 + \\ldots + \\frac{k_0}{(m-1)!}x^{m-1}
  216. of `P` so that :math:`P^{(j)}(0) = k_{m-j-1}`.
  217. Parameters
  218. ----------
  219. p : array_like or poly1d
  220. Polynomial to integrate.
  221. A sequence is interpreted as polynomial coefficients, see `poly1d`.
  222. m : int, optional
  223. Order of the antiderivative. (Default: 1)
  224. k : list of `m` scalars or scalar, optional
  225. Integration constants. They are given in the order of integration:
  226. those corresponding to highest-order terms come first.
  227. If ``None`` (default), all constants are assumed to be zero.
  228. If `m = 1`, a single scalar can be given instead of a list.
  229. See Also
  230. --------
  231. polyder : derivative of a polynomial
  232. poly1d.integ : equivalent method
  233. Examples
  234. --------
  235. The defining property of the antiderivative:
  236. >>> p = np.poly1d([1,1,1])
  237. >>> P = np.polyint(p)
  238. >>> P
  239. poly1d([ 0.33333333, 0.5 , 1. , 0. ]) # may vary
  240. >>> np.polyder(P) == p
  241. True
  242. The integration constants default to zero, but can be specified:
  243. >>> P = np.polyint(p, 3)
  244. >>> P(0)
  245. 0.0
  246. >>> np.polyder(P)(0)
  247. 0.0
  248. >>> np.polyder(P, 2)(0)
  249. 0.0
  250. >>> P = np.polyint(p, 3, k=[6,5,3])
  251. >>> P
  252. poly1d([ 0.01666667, 0.04166667, 0.16666667, 3. , 5. , 3. ]) # may vary
  253. Note that 3 = 6 / 2!, and that the constants are given in the order of
  254. integrations. Constant of the highest-order polynomial term comes first:
  255. >>> np.polyder(P, 2)(0)
  256. 6.0
  257. >>> np.polyder(P, 1)(0)
  258. 5.0
  259. >>> P(0)
  260. 3.0
  261. """
  262. m = int(m)
  263. if m < 0:
  264. raise ValueError("Order of integral must be positive (see polyder)")
  265. if k is None:
  266. k = NX.zeros(m, float)
  267. k = atleast_1d(k)
  268. if len(k) == 1 and m > 1:
  269. k = k[0]*NX.ones(m, float)
  270. if len(k) < m:
  271. raise ValueError(
  272. "k must be a scalar or a rank-1 array of length 1 or >m.")
  273. truepoly = isinstance(p, poly1d)
  274. p = NX.asarray(p)
  275. if m == 0:
  276. if truepoly:
  277. return poly1d(p)
  278. return p
  279. else:
  280. # Note: this must work also with object and integer arrays
  281. y = NX.concatenate((p.__truediv__(NX.arange(len(p), 0, -1)), [k[0]]))
  282. val = polyint(y, m - 1, k=k[1:])
  283. if truepoly:
  284. return poly1d(val)
  285. return val
  286. def _polyder_dispatcher(p, m=None):
  287. return (p,)
  288. @array_function_dispatch(_polyder_dispatcher)
  289. def polyder(p, m=1):
  290. """
  291. Return the derivative of the specified order of a polynomial.
  292. .. note::
  293. This forms part of the old polynomial API. Since version 1.4, the
  294. new polynomial API defined in `numpy.polynomial` is preferred.
  295. A summary of the differences can be found in the
  296. :doc:`transition guide </reference/routines.polynomials>`.
  297. Parameters
  298. ----------
  299. p : poly1d or sequence
  300. Polynomial to differentiate.
  301. A sequence is interpreted as polynomial coefficients, see `poly1d`.
  302. m : int, optional
  303. Order of differentiation (default: 1)
  304. Returns
  305. -------
  306. der : poly1d
  307. A new polynomial representing the derivative.
  308. See Also
  309. --------
  310. polyint : Anti-derivative of a polynomial.
  311. poly1d : Class for one-dimensional polynomials.
  312. Examples
  313. --------
  314. The derivative of the polynomial :math:`x^3 + x^2 + x^1 + 1` is:
  315. >>> p = np.poly1d([1,1,1,1])
  316. >>> p2 = np.polyder(p)
  317. >>> p2
  318. poly1d([3, 2, 1])
  319. which evaluates to:
  320. >>> p2(2.)
  321. 17.0
  322. We can verify this, approximating the derivative with
  323. ``(f(x + h) - f(x))/h``:
  324. >>> (p(2. + 0.001) - p(2.)) / 0.001
  325. 17.007000999997857
  326. The fourth-order derivative of a 3rd-order polynomial is zero:
  327. >>> np.polyder(p, 2)
  328. poly1d([6, 2])
  329. >>> np.polyder(p, 3)
  330. poly1d([6])
  331. >>> np.polyder(p, 4)
  332. poly1d([0])
  333. """
  334. m = int(m)
  335. if m < 0:
  336. raise ValueError("Order of derivative must be positive (see polyint)")
  337. truepoly = isinstance(p, poly1d)
  338. p = NX.asarray(p)
  339. n = len(p) - 1
  340. y = p[:-1] * NX.arange(n, 0, -1)
  341. if m == 0:
  342. val = p
  343. else:
  344. val = polyder(y, m - 1)
  345. if truepoly:
  346. val = poly1d(val)
  347. return val
  348. def _polyfit_dispatcher(x, y, deg, rcond=None, full=None, w=None, cov=None):
  349. return (x, y, w)
  350. @array_function_dispatch(_polyfit_dispatcher)
  351. def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
  352. """
  353. Least squares polynomial fit.
  354. .. note::
  355. This forms part of the old polynomial API. Since version 1.4, the
  356. new polynomial API defined in `numpy.polynomial` is preferred.
  357. A summary of the differences can be found in the
  358. :doc:`transition guide </reference/routines.polynomials>`.
  359. Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg`
  360. to points `(x, y)`. Returns a vector of coefficients `p` that minimises
  361. the squared error in the order `deg`, `deg-1`, ... `0`.
  362. The `Polynomial.fit <numpy.polynomial.polynomial.Polynomial.fit>` class
  363. method is recommended for new code as it is more stable numerically. See
  364. the documentation of the method for more information.
  365. Parameters
  366. ----------
  367. x : array_like, shape (M,)
  368. x-coordinates of the M sample points ``(x[i], y[i])``.
  369. y : array_like, shape (M,) or (M, K)
  370. y-coordinates of the sample points. Several data sets of sample
  371. points sharing the same x-coordinates can be fitted at once by
  372. passing in a 2D-array that contains one dataset per column.
  373. deg : int
  374. Degree of the fitting polynomial
  375. rcond : float, optional
  376. Relative condition number of the fit. Singular values smaller than
  377. this relative to the largest singular value will be ignored. The
  378. default value is len(x)*eps, where eps is the relative precision of
  379. the float type, about 2e-16 in most cases.
  380. full : bool, optional
  381. Switch determining nature of return value. When it is False (the
  382. default) just the coefficients are returned, when True diagnostic
  383. information from the singular value decomposition is also returned.
  384. w : array_like, shape (M,), optional
  385. Weights to apply to the y-coordinates of the sample points. For
  386. gaussian uncertainties, use 1/sigma (not 1/sigma**2).
  387. cov : bool or str, optional
  388. If given and not `False`, return not just the estimate but also its
  389. covariance matrix. By default, the covariance are scaled by
  390. chi2/dof, where dof = M - (deg + 1), i.e., the weights are presumed
  391. to be unreliable except in a relative sense and everything is scaled
  392. such that the reduced chi2 is unity. This scaling is omitted if
  393. ``cov='unscaled'``, as is relevant for the case that the weights are
  394. 1/sigma**2, with sigma known to be a reliable estimate of the
  395. uncertainty.
  396. Returns
  397. -------
  398. p : ndarray, shape (deg + 1,) or (deg + 1, K)
  399. Polynomial coefficients, highest power first. If `y` was 2-D, the
  400. coefficients for `k`-th data set are in ``p[:,k]``.
  401. residuals, rank, singular_values, rcond
  402. Present only if `full` = True. Residuals is sum of squared residuals
  403. of the least-squares fit, the effective rank of the scaled Vandermonde
  404. coefficient matrix, its singular values, and the specified value of
  405. `rcond`. For more details, see `linalg.lstsq`.
  406. V : ndarray, shape (M,M) or (M,M,K)
  407. Present only if `full` = False and `cov`=True. The covariance
  408. matrix of the polynomial coefficient estimates. The diagonal of
  409. this matrix are the variance estimates for each coefficient. If y
  410. is a 2-D array, then the covariance matrix for the `k`-th data set
  411. are in ``V[:,:,k]``
  412. Warns
  413. -----
  414. RankWarning
  415. The rank of the coefficient matrix in the least-squares fit is
  416. deficient. The warning is only raised if `full` = False.
  417. The warnings can be turned off by
  418. >>> import warnings
  419. >>> warnings.simplefilter('ignore', np.RankWarning)
  420. See Also
  421. --------
  422. polyval : Compute polynomial values.
  423. linalg.lstsq : Computes a least-squares fit.
  424. scipy.interpolate.UnivariateSpline : Computes spline fits.
  425. Notes
  426. -----
  427. The solution minimizes the squared error
  428. .. math ::
  429. E = \\sum_{j=0}^k |p(x_j) - y_j|^2
  430. in the equations::
  431. x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]
  432. x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]
  433. ...
  434. x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]
  435. The coefficient matrix of the coefficients `p` is a Vandermonde matrix.
  436. `polyfit` issues a `RankWarning` when the least-squares fit is badly
  437. conditioned. This implies that the best fit is not well-defined due
  438. to numerical error. The results may be improved by lowering the polynomial
  439. degree or by replacing `x` by `x` - `x`.mean(). The `rcond` parameter
  440. can also be set to a value smaller than its default, but the resulting
  441. fit may be spurious: including contributions from the small singular
  442. values can add numerical noise to the result.
  443. Note that fitting polynomial coefficients is inherently badly conditioned
  444. when the degree of the polynomial is large or the interval of sample points
  445. is badly centered. The quality of the fit should always be checked in these
  446. cases. When polynomial fits are not satisfactory, splines may be a good
  447. alternative.
  448. References
  449. ----------
  450. .. [1] Wikipedia, "Curve fitting",
  451. https://en.wikipedia.org/wiki/Curve_fitting
  452. .. [2] Wikipedia, "Polynomial interpolation",
  453. https://en.wikipedia.org/wiki/Polynomial_interpolation
  454. Examples
  455. --------
  456. >>> import warnings
  457. >>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
  458. >>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
  459. >>> z = np.polyfit(x, y, 3)
  460. >>> z
  461. array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) # may vary
  462. It is convenient to use `poly1d` objects for dealing with polynomials:
  463. >>> p = np.poly1d(z)
  464. >>> p(0.5)
  465. 0.6143849206349179 # may vary
  466. >>> p(3.5)
  467. -0.34732142857143039 # may vary
  468. >>> p(10)
  469. 22.579365079365115 # may vary
  470. High-order polynomials may oscillate wildly:
  471. >>> with warnings.catch_warnings():
  472. ... warnings.simplefilter('ignore', np.RankWarning)
  473. ... p30 = np.poly1d(np.polyfit(x, y, 30))
  474. ...
  475. >>> p30(4)
  476. -0.80000000000000204 # may vary
  477. >>> p30(5)
  478. -0.99999999999999445 # may vary
  479. >>> p30(4.5)
  480. -0.10547061179440398 # may vary
  481. Illustration:
  482. >>> import matplotlib.pyplot as plt
  483. >>> xp = np.linspace(-2, 6, 100)
  484. >>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')
  485. >>> plt.ylim(-2,2)
  486. (-2, 2)
  487. >>> plt.show()
  488. """
  489. order = int(deg) + 1
  490. x = NX.asarray(x) + 0.0
  491. y = NX.asarray(y) + 0.0
  492. # check arguments.
  493. if deg < 0:
  494. raise ValueError("expected deg >= 0")
  495. if x.ndim != 1:
  496. raise TypeError("expected 1D vector for x")
  497. if x.size == 0:
  498. raise TypeError("expected non-empty vector for x")
  499. if y.ndim < 1 or y.ndim > 2:
  500. raise TypeError("expected 1D or 2D array for y")
  501. if x.shape[0] != y.shape[0]:
  502. raise TypeError("expected x and y to have same length")
  503. # set rcond
  504. if rcond is None:
  505. rcond = len(x)*finfo(x.dtype).eps
  506. # set up least squares equation for powers of x
  507. lhs = vander(x, order)
  508. rhs = y
  509. # apply weighting
  510. if w is not None:
  511. w = NX.asarray(w) + 0.0
  512. if w.ndim != 1:
  513. raise TypeError("expected a 1-d array for weights")
  514. if w.shape[0] != y.shape[0]:
  515. raise TypeError("expected w and y to have the same length")
  516. lhs *= w[:, NX.newaxis]
  517. if rhs.ndim == 2:
  518. rhs *= w[:, NX.newaxis]
  519. else:
  520. rhs *= w
  521. # scale lhs to improve condition number and solve
  522. scale = NX.sqrt((lhs*lhs).sum(axis=0))
  523. lhs /= scale
  524. c, resids, rank, s = lstsq(lhs, rhs, rcond)
  525. c = (c.T/scale).T # broadcast scale coefficients
  526. # warn on rank reduction, which indicates an ill conditioned matrix
  527. if rank != order and not full:
  528. msg = "Polyfit may be poorly conditioned"
  529. warnings.warn(msg, RankWarning, stacklevel=4)
  530. if full:
  531. return c, resids, rank, s, rcond
  532. elif cov:
  533. Vbase = inv(dot(lhs.T, lhs))
  534. Vbase /= NX.outer(scale, scale)
  535. if cov == "unscaled":
  536. fac = 1
  537. else:
  538. if len(x) <= order:
  539. raise ValueError("the number of data points must exceed order "
  540. "to scale the covariance matrix")
  541. # note, this used to be: fac = resids / (len(x) - order - 2.0)
  542. # it was deciced that the "- 2" (originally justified by "Bayesian
  543. # uncertainty analysis") is not was the user expects
  544. # (see gh-11196 and gh-11197)
  545. fac = resids / (len(x) - order)
  546. if y.ndim == 1:
  547. return c, Vbase * fac
  548. else:
  549. return c, Vbase[:,:, NX.newaxis] * fac
  550. else:
  551. return c
  552. def _polyval_dispatcher(p, x):
  553. return (p, x)
  554. @array_function_dispatch(_polyval_dispatcher)
  555. def polyval(p, x):
  556. """
  557. Evaluate a polynomial at specific values.
  558. .. note::
  559. This forms part of the old polynomial API. Since version 1.4, the
  560. new polynomial API defined in `numpy.polynomial` is preferred.
  561. A summary of the differences can be found in the
  562. :doc:`transition guide </reference/routines.polynomials>`.
  563. If `p` is of length N, this function returns the value:
  564. ``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]``
  565. If `x` is a sequence, then ``p(x)`` is returned for each element of ``x``.
  566. If `x` is another polynomial then the composite polynomial ``p(x(t))``
  567. is returned.
  568. Parameters
  569. ----------
  570. p : array_like or poly1d object
  571. 1D array of polynomial coefficients (including coefficients equal
  572. to zero) from highest degree to the constant term, or an
  573. instance of poly1d.
  574. x : array_like or poly1d object
  575. A number, an array of numbers, or an instance of poly1d, at
  576. which to evaluate `p`.
  577. Returns
  578. -------
  579. values : ndarray or poly1d
  580. If `x` is a poly1d instance, the result is the composition of the two
  581. polynomials, i.e., `x` is "substituted" in `p` and the simplified
  582. result is returned. In addition, the type of `x` - array_like or
  583. poly1d - governs the type of the output: `x` array_like => `values`
  584. array_like, `x` a poly1d object => `values` is also.
  585. See Also
  586. --------
  587. poly1d: A polynomial class.
  588. Notes
  589. -----
  590. Horner's scheme [1]_ is used to evaluate the polynomial. Even so,
  591. for polynomials of high degree the values may be inaccurate due to
  592. rounding errors. Use carefully.
  593. If `x` is a subtype of `ndarray` the return value will be of the same type.
  594. References
  595. ----------
  596. .. [1] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng.
  597. trans. Ed.), *Handbook of Mathematics*, New York, Van Nostrand
  598. Reinhold Co., 1985, pg. 720.
  599. Examples
  600. --------
  601. >>> np.polyval([3,0,1], 5) # 3 * 5**2 + 0 * 5**1 + 1
  602. 76
  603. >>> np.polyval([3,0,1], np.poly1d(5))
  604. poly1d([76])
  605. >>> np.polyval(np.poly1d([3,0,1]), 5)
  606. 76
  607. >>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
  608. poly1d([76])
  609. """
  610. p = NX.asarray(p)
  611. if isinstance(x, poly1d):
  612. y = 0
  613. else:
  614. x = NX.asanyarray(x)
  615. y = NX.zeros_like(x)
  616. for i in range(len(p)):
  617. y = y * x + p[i]
  618. return y
  619. def _binary_op_dispatcher(a1, a2):
  620. return (a1, a2)
  621. @array_function_dispatch(_binary_op_dispatcher)
  622. def polyadd(a1, a2):
  623. """
  624. Find the sum of two polynomials.
  625. .. note::
  626. This forms part of the old polynomial API. Since version 1.4, the
  627. new polynomial API defined in `numpy.polynomial` is preferred.
  628. A summary of the differences can be found in the
  629. :doc:`transition guide </reference/routines.polynomials>`.
  630. Returns the polynomial resulting from the sum of two input polynomials.
  631. Each input must be either a poly1d object or a 1D sequence of polynomial
  632. coefficients, from highest to lowest degree.
  633. Parameters
  634. ----------
  635. a1, a2 : array_like or poly1d object
  636. Input polynomials.
  637. Returns
  638. -------
  639. out : ndarray or poly1d object
  640. The sum of the inputs. If either input is a poly1d object, then the
  641. output is also a poly1d object. Otherwise, it is a 1D array of
  642. polynomial coefficients from highest to lowest degree.
  643. See Also
  644. --------
  645. poly1d : A one-dimensional polynomial class.
  646. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval
  647. Examples
  648. --------
  649. >>> np.polyadd([1, 2], [9, 5, 4])
  650. array([9, 6, 6])
  651. Using poly1d objects:
  652. >>> p1 = np.poly1d([1, 2])
  653. >>> p2 = np.poly1d([9, 5, 4])
  654. >>> print(p1)
  655. 1 x + 2
  656. >>> print(p2)
  657. 2
  658. 9 x + 5 x + 4
  659. >>> print(np.polyadd(p1, p2))
  660. 2
  661. 9 x + 6 x + 6
  662. """
  663. truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
  664. a1 = atleast_1d(a1)
  665. a2 = atleast_1d(a2)
  666. diff = len(a2) - len(a1)
  667. if diff == 0:
  668. val = a1 + a2
  669. elif diff > 0:
  670. zr = NX.zeros(diff, a1.dtype)
  671. val = NX.concatenate((zr, a1)) + a2
  672. else:
  673. zr = NX.zeros(abs(diff), a2.dtype)
  674. val = a1 + NX.concatenate((zr, a2))
  675. if truepoly:
  676. val = poly1d(val)
  677. return val
  678. @array_function_dispatch(_binary_op_dispatcher)
  679. def polysub(a1, a2):
  680. """
  681. Difference (subtraction) of two polynomials.
  682. .. note::
  683. This forms part of the old polynomial API. Since version 1.4, the
  684. new polynomial API defined in `numpy.polynomial` is preferred.
  685. A summary of the differences can be found in the
  686. :doc:`transition guide </reference/routines.polynomials>`.
  687. Given two polynomials `a1` and `a2`, returns ``a1 - a2``.
  688. `a1` and `a2` can be either array_like sequences of the polynomials'
  689. coefficients (including coefficients equal to zero), or `poly1d` objects.
  690. Parameters
  691. ----------
  692. a1, a2 : array_like or poly1d
  693. Minuend and subtrahend polynomials, respectively.
  694. Returns
  695. -------
  696. out : ndarray or poly1d
  697. Array or `poly1d` object of the difference polynomial's coefficients.
  698. See Also
  699. --------
  700. polyval, polydiv, polymul, polyadd
  701. Examples
  702. --------
  703. .. math:: (2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2)
  704. >>> np.polysub([2, 10, -2], [3, 10, -4])
  705. array([-1, 0, 2])
  706. """
  707. truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
  708. a1 = atleast_1d(a1)
  709. a2 = atleast_1d(a2)
  710. diff = len(a2) - len(a1)
  711. if diff == 0:
  712. val = a1 - a2
  713. elif diff > 0:
  714. zr = NX.zeros(diff, a1.dtype)
  715. val = NX.concatenate((zr, a1)) - a2
  716. else:
  717. zr = NX.zeros(abs(diff), a2.dtype)
  718. val = a1 - NX.concatenate((zr, a2))
  719. if truepoly:
  720. val = poly1d(val)
  721. return val
  722. @array_function_dispatch(_binary_op_dispatcher)
  723. def polymul(a1, a2):
  724. """
  725. Find the product of two polynomials.
  726. .. note::
  727. This forms part of the old polynomial API. Since version 1.4, the
  728. new polynomial API defined in `numpy.polynomial` is preferred.
  729. A summary of the differences can be found in the
  730. :doc:`transition guide </reference/routines.polynomials>`.
  731. Finds the polynomial resulting from the multiplication of the two input
  732. polynomials. Each input must be either a poly1d object or a 1D sequence
  733. of polynomial coefficients, from highest to lowest degree.
  734. Parameters
  735. ----------
  736. a1, a2 : array_like or poly1d object
  737. Input polynomials.
  738. Returns
  739. -------
  740. out : ndarray or poly1d object
  741. The polynomial resulting from the multiplication of the inputs. If
  742. either inputs is a poly1d object, then the output is also a poly1d
  743. object. Otherwise, it is a 1D array of polynomial coefficients from
  744. highest to lowest degree.
  745. See Also
  746. --------
  747. poly1d : A one-dimensional polynomial class.
  748. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval
  749. convolve : Array convolution. Same output as polymul, but has parameter
  750. for overlap mode.
  751. Examples
  752. --------
  753. >>> np.polymul([1, 2, 3], [9, 5, 1])
  754. array([ 9, 23, 38, 17, 3])
  755. Using poly1d objects:
  756. >>> p1 = np.poly1d([1, 2, 3])
  757. >>> p2 = np.poly1d([9, 5, 1])
  758. >>> print(p1)
  759. 2
  760. 1 x + 2 x + 3
  761. >>> print(p2)
  762. 2
  763. 9 x + 5 x + 1
  764. >>> print(np.polymul(p1, p2))
  765. 4 3 2
  766. 9 x + 23 x + 38 x + 17 x + 3
  767. """
  768. truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
  769. a1, a2 = poly1d(a1), poly1d(a2)
  770. val = NX.convolve(a1, a2)
  771. if truepoly:
  772. val = poly1d(val)
  773. return val
  774. def _polydiv_dispatcher(u, v):
  775. return (u, v)
  776. @array_function_dispatch(_polydiv_dispatcher)
  777. def polydiv(u, v):
  778. """
  779. Returns the quotient and remainder of polynomial division.
  780. .. note::
  781. This forms part of the old polynomial API. Since version 1.4, the
  782. new polynomial API defined in `numpy.polynomial` is preferred.
  783. A summary of the differences can be found in the
  784. :doc:`transition guide </reference/routines.polynomials>`.
  785. The input arrays are the coefficients (including any coefficients
  786. equal to zero) of the "numerator" (dividend) and "denominator"
  787. (divisor) polynomials, respectively.
  788. Parameters
  789. ----------
  790. u : array_like or poly1d
  791. Dividend polynomial's coefficients.
  792. v : array_like or poly1d
  793. Divisor polynomial's coefficients.
  794. Returns
  795. -------
  796. q : ndarray
  797. Coefficients, including those equal to zero, of the quotient.
  798. r : ndarray
  799. Coefficients, including those equal to zero, of the remainder.
  800. See Also
  801. --------
  802. poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub
  803. polyval
  804. Notes
  805. -----
  806. Both `u` and `v` must be 0-d or 1-d (ndim = 0 or 1), but `u.ndim` need
  807. not equal `v.ndim`. In other words, all four possible combinations -
  808. ``u.ndim = v.ndim = 0``, ``u.ndim = v.ndim = 1``,
  809. ``u.ndim = 1, v.ndim = 0``, and ``u.ndim = 0, v.ndim = 1`` - work.
  810. Examples
  811. --------
  812. .. math:: \\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25
  813. >>> x = np.array([3.0, 5.0, 2.0])
  814. >>> y = np.array([2.0, 1.0])
  815. >>> np.polydiv(x, y)
  816. (array([1.5 , 1.75]), array([0.25]))
  817. """
  818. truepoly = (isinstance(u, poly1d) or isinstance(v, poly1d))
  819. u = atleast_1d(u) + 0.0
  820. v = atleast_1d(v) + 0.0
  821. # w has the common type
  822. w = u[0] + v[0]
  823. m = len(u) - 1
  824. n = len(v) - 1
  825. scale = 1. / v[0]
  826. q = NX.zeros((max(m - n + 1, 1),), w.dtype)
  827. r = u.astype(w.dtype)
  828. for k in range(0, m-n+1):
  829. d = scale * r[k]
  830. q[k] = d
  831. r[k:k+n+1] -= d*v
  832. while NX.allclose(r[0], 0, rtol=1e-14) and (r.shape[-1] > 1):
  833. r = r[1:]
  834. if truepoly:
  835. return poly1d(q), poly1d(r)
  836. return q, r
  837. _poly_mat = re.compile(r"\*\*([0-9]*)")
  838. def _raise_power(astr, wrap=70):
  839. n = 0
  840. line1 = ''
  841. line2 = ''
  842. output = ' '
  843. while True:
  844. mat = _poly_mat.search(astr, n)
  845. if mat is None:
  846. break
  847. span = mat.span()
  848. power = mat.groups()[0]
  849. partstr = astr[n:span[0]]
  850. n = span[1]
  851. toadd2 = partstr + ' '*(len(power)-1)
  852. toadd1 = ' '*(len(partstr)-1) + power
  853. if ((len(line2) + len(toadd2) > wrap) or
  854. (len(line1) + len(toadd1) > wrap)):
  855. output += line1 + "\n" + line2 + "\n "
  856. line1 = toadd1
  857. line2 = toadd2
  858. else:
  859. line2 += partstr + ' '*(len(power)-1)
  860. line1 += ' '*(len(partstr)-1) + power
  861. output += line1 + "\n" + line2
  862. return output + astr[n:]
  863. @set_module('numpy')
  864. class poly1d:
  865. """
  866. A one-dimensional polynomial class.
  867. .. note::
  868. This forms part of the old polynomial API. Since version 1.4, the
  869. new polynomial API defined in `numpy.polynomial` is preferred.
  870. A summary of the differences can be found in the
  871. :doc:`transition guide </reference/routines.polynomials>`.
  872. A convenience class, used to encapsulate "natural" operations on
  873. polynomials so that said operations may take on their customary
  874. form in code (see Examples).
  875. Parameters
  876. ----------
  877. c_or_r : array_like
  878. The polynomial's coefficients, in decreasing powers, or if
  879. the value of the second parameter is True, the polynomial's
  880. roots (values where the polynomial evaluates to 0). For example,
  881. ``poly1d([1, 2, 3])`` returns an object that represents
  882. :math:`x^2 + 2x + 3`, whereas ``poly1d([1, 2, 3], True)`` returns
  883. one that represents :math:`(x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x -6`.
  884. r : bool, optional
  885. If True, `c_or_r` specifies the polynomial's roots; the default
  886. is False.
  887. variable : str, optional
  888. Changes the variable used when printing `p` from `x` to `variable`
  889. (see Examples).
  890. Examples
  891. --------
  892. Construct the polynomial :math:`x^2 + 2x + 3`:
  893. >>> p = np.poly1d([1, 2, 3])
  894. >>> print(np.poly1d(p))
  895. 2
  896. 1 x + 2 x + 3
  897. Evaluate the polynomial at :math:`x = 0.5`:
  898. >>> p(0.5)
  899. 4.25
  900. Find the roots:
  901. >>> p.r
  902. array([-1.+1.41421356j, -1.-1.41421356j])
  903. >>> p(p.r)
  904. array([ -4.44089210e-16+0.j, -4.44089210e-16+0.j]) # may vary
  905. These numbers in the previous line represent (0, 0) to machine precision
  906. Show the coefficients:
  907. >>> p.c
  908. array([1, 2, 3])
  909. Display the order (the leading zero-coefficients are removed):
  910. >>> p.order
  911. 2
  912. Show the coefficient of the k-th power in the polynomial
  913. (which is equivalent to ``p.c[-(i+1)]``):
  914. >>> p[1]
  915. 2
  916. Polynomials can be added, subtracted, multiplied, and divided
  917. (returns quotient and remainder):
  918. >>> p * p
  919. poly1d([ 1, 4, 10, 12, 9])
  920. >>> (p**3 + 4) / p
  921. (poly1d([ 1., 4., 10., 12., 9.]), poly1d([4.]))
  922. ``asarray(p)`` gives the coefficient array, so polynomials can be
  923. used in all functions that accept arrays:
  924. >>> p**2 # square of polynomial
  925. poly1d([ 1, 4, 10, 12, 9])
  926. >>> np.square(p) # square of individual coefficients
  927. array([1, 4, 9])
  928. The variable used in the string representation of `p` can be modified,
  929. using the `variable` parameter:
  930. >>> p = np.poly1d([1,2,3], variable='z')
  931. >>> print(p)
  932. 2
  933. 1 z + 2 z + 3
  934. Construct a polynomial from its roots:
  935. >>> np.poly1d([1, 2], True)
  936. poly1d([ 1., -3., 2.])
  937. This is the same polynomial as obtained by:
  938. >>> np.poly1d([1, -1]) * np.poly1d([1, -2])
  939. poly1d([ 1, -3, 2])
  940. """
  941. __hash__ = None
  942. @property
  943. def coeffs(self):
  944. """ The polynomial coefficients """
  945. return self._coeffs
  946. @coeffs.setter
  947. def coeffs(self, value):
  948. # allowing this makes p.coeffs *= 2 legal
  949. if value is not self._coeffs:
  950. raise AttributeError("Cannot set attribute")
  951. @property
  952. def variable(self):
  953. """ The name of the polynomial variable """
  954. return self._variable
  955. # calculated attributes
  956. @property
  957. def order(self):
  958. """ The order or degree of the polynomial """
  959. return len(self._coeffs) - 1
  960. @property
  961. def roots(self):
  962. """ The roots of the polynomial, where self(x) == 0 """
  963. return roots(self._coeffs)
  964. # our internal _coeffs property need to be backed by __dict__['coeffs'] for
  965. # scipy to work correctly.
  966. @property
  967. def _coeffs(self):
  968. return self.__dict__['coeffs']
  969. @_coeffs.setter
  970. def _coeffs(self, coeffs):
  971. self.__dict__['coeffs'] = coeffs
  972. # alias attributes
  973. r = roots
  974. c = coef = coefficients = coeffs
  975. o = order
  976. def __init__(self, c_or_r, r=False, variable=None):
  977. if isinstance(c_or_r, poly1d):
  978. self._variable = c_or_r._variable
  979. self._coeffs = c_or_r._coeffs
  980. if set(c_or_r.__dict__) - set(self.__dict__):
  981. msg = ("In the future extra properties will not be copied "
  982. "across when constructing one poly1d from another")
  983. warnings.warn(msg, FutureWarning, stacklevel=2)
  984. self.__dict__.update(c_or_r.__dict__)
  985. if variable is not None:
  986. self._variable = variable
  987. return
  988. if r:
  989. c_or_r = poly(c_or_r)
  990. c_or_r = atleast_1d(c_or_r)
  991. if c_or_r.ndim > 1:
  992. raise ValueError("Polynomial must be 1d only.")
  993. c_or_r = trim_zeros(c_or_r, trim='f')
  994. if len(c_or_r) == 0:
  995. c_or_r = NX.array([0], dtype=c_or_r.dtype)
  996. self._coeffs = c_or_r
  997. if variable is None:
  998. variable = 'x'
  999. self._variable = variable
  1000. def __array__(self, t=None):
  1001. if t:
  1002. return NX.asarray(self.coeffs, t)
  1003. else:
  1004. return NX.asarray(self.coeffs)
  1005. def __repr__(self):
  1006. vals = repr(self.coeffs)
  1007. vals = vals[6:-1]
  1008. return "poly1d(%s)" % vals
  1009. def __len__(self):
  1010. return self.order
  1011. def __str__(self):
  1012. thestr = "0"
  1013. var = self.variable
  1014. # Remove leading zeros
  1015. coeffs = self.coeffs[NX.logical_or.accumulate(self.coeffs != 0)]
  1016. N = len(coeffs)-1
  1017. def fmt_float(q):
  1018. s = '%.4g' % q
  1019. if s.endswith('.0000'):
  1020. s = s[:-5]
  1021. return s
  1022. for k in range(len(coeffs)):
  1023. if not iscomplex(coeffs[k]):
  1024. coefstr = fmt_float(real(coeffs[k]))
  1025. elif real(coeffs[k]) == 0:
  1026. coefstr = '%sj' % fmt_float(imag(coeffs[k]))
  1027. else:
  1028. coefstr = '(%s + %sj)' % (fmt_float(real(coeffs[k])),
  1029. fmt_float(imag(coeffs[k])))
  1030. power = (N-k)
  1031. if power == 0:
  1032. if coefstr != '0':
  1033. newstr = '%s' % (coefstr,)
  1034. else:
  1035. if k == 0:
  1036. newstr = '0'
  1037. else:
  1038. newstr = ''
  1039. elif power == 1:
  1040. if coefstr == '0':
  1041. newstr = ''
  1042. elif coefstr == 'b':
  1043. newstr = var
  1044. else:
  1045. newstr = '%s %s' % (coefstr, var)
  1046. else:
  1047. if coefstr == '0':
  1048. newstr = ''
  1049. elif coefstr == 'b':
  1050. newstr = '%s**%d' % (var, power,)
  1051. else:
  1052. newstr = '%s %s**%d' % (coefstr, var, power)
  1053. if k > 0:
  1054. if newstr != '':
  1055. if newstr.startswith('-'):
  1056. thestr = "%s - %s" % (thestr, newstr[1:])
  1057. else:
  1058. thestr = "%s + %s" % (thestr, newstr)
  1059. else:
  1060. thestr = newstr
  1061. return _raise_power(thestr)
  1062. def __call__(self, val):
  1063. return polyval(self.coeffs, val)
  1064. def __neg__(self):
  1065. return poly1d(-self.coeffs)
  1066. def __pos__(self):
  1067. return self
  1068. def __mul__(self, other):
  1069. if isscalar(other):
  1070. return poly1d(self.coeffs * other)
  1071. else:
  1072. other = poly1d(other)
  1073. return poly1d(polymul(self.coeffs, other.coeffs))
  1074. def __rmul__(self, other):
  1075. if isscalar(other):
  1076. return poly1d(other * self.coeffs)
  1077. else:
  1078. other = poly1d(other)
  1079. return poly1d(polymul(self.coeffs, other.coeffs))
  1080. def __add__(self, other):
  1081. other = poly1d(other)
  1082. return poly1d(polyadd(self.coeffs, other.coeffs))
  1083. def __radd__(self, other):
  1084. other = poly1d(other)
  1085. return poly1d(polyadd(self.coeffs, other.coeffs))
  1086. def __pow__(self, val):
  1087. if not isscalar(val) or int(val) != val or val < 0:
  1088. raise ValueError("Power to non-negative integers only.")
  1089. res = [1]
  1090. for _ in range(val):
  1091. res = polymul(self.coeffs, res)
  1092. return poly1d(res)
  1093. def __sub__(self, other):
  1094. other = poly1d(other)
  1095. return poly1d(polysub(self.coeffs, other.coeffs))
  1096. def __rsub__(self, other):
  1097. other = poly1d(other)
  1098. return poly1d(polysub(other.coeffs, self.coeffs))
  1099. def __div__(self, other):
  1100. if isscalar(other):
  1101. return poly1d(self.coeffs/other)
  1102. else:
  1103. other = poly1d(other)
  1104. return polydiv(self, other)
  1105. __truediv__ = __div__
  1106. def __rdiv__(self, other):
  1107. if isscalar(other):
  1108. return poly1d(other/self.coeffs)
  1109. else:
  1110. other = poly1d(other)
  1111. return polydiv(other, self)
  1112. __rtruediv__ = __rdiv__
  1113. def __eq__(self, other):
  1114. if not isinstance(other, poly1d):
  1115. return NotImplemented
  1116. if self.coeffs.shape != other.coeffs.shape:
  1117. return False
  1118. return (self.coeffs == other.coeffs).all()
  1119. def __ne__(self, other):
  1120. if not isinstance(other, poly1d):
  1121. return NotImplemented
  1122. return not self.__eq__(other)
  1123. def __getitem__(self, val):
  1124. ind = self.order - val
  1125. if val > self.order:
  1126. return 0
  1127. if val < 0:
  1128. return 0
  1129. return self.coeffs[ind]
  1130. def __setitem__(self, key, val):
  1131. ind = self.order - key
  1132. if key < 0:
  1133. raise ValueError("Does not support negative powers.")
  1134. if key > self.order:
  1135. zr = NX.zeros(key-self.order, self.coeffs.dtype)
  1136. self._coeffs = NX.concatenate((zr, self.coeffs))
  1137. ind = 0
  1138. self._coeffs[ind] = val
  1139. return
  1140. def __iter__(self):
  1141. return iter(self.coeffs)
  1142. def integ(self, m=1, k=0):
  1143. """
  1144. Return an antiderivative (indefinite integral) of this polynomial.
  1145. Refer to `polyint` for full documentation.
  1146. See Also
  1147. --------
  1148. polyint : equivalent function
  1149. """
  1150. return poly1d(polyint(self.coeffs, m=m, k=k))
  1151. def deriv(self, m=1):
  1152. """
  1153. Return a derivative of this polynomial.
  1154. Refer to `polyder` for full documentation.
  1155. See Also
  1156. --------
  1157. polyder : equivalent function
  1158. """
  1159. return poly1d(polyder(self.coeffs, m=m))
  1160. # Stuff to do on module import
  1161. warnings.simplefilter('always', RankWarning)