polynomial.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  1. """
  2. =================================================
  3. Power Series (:mod:`numpy.polynomial.polynomial`)
  4. =================================================
  5. This module provides a number of objects (mostly functions) useful for
  6. dealing with polynomials, including a `Polynomial` class that
  7. encapsulates the usual arithmetic operations. (General information
  8. on how this module represents and works with polynomial objects is in
  9. the docstring for its "parent" sub-package, `numpy.polynomial`).
  10. Classes
  11. -------
  12. .. autosummary::
  13. :toctree: generated/
  14. Polynomial
  15. Constants
  16. ---------
  17. .. autosummary::
  18. :toctree: generated/
  19. polydomain
  20. polyzero
  21. polyone
  22. polyx
  23. Arithmetic
  24. ----------
  25. .. autosummary::
  26. :toctree: generated/
  27. polyadd
  28. polysub
  29. polymulx
  30. polymul
  31. polydiv
  32. polypow
  33. polyval
  34. polyval2d
  35. polyval3d
  36. polygrid2d
  37. polygrid3d
  38. Calculus
  39. --------
  40. .. autosummary::
  41. :toctree: generated/
  42. polyder
  43. polyint
  44. Misc Functions
  45. --------------
  46. .. autosummary::
  47. :toctree: generated/
  48. polyfromroots
  49. polyroots
  50. polyvalfromroots
  51. polyvander
  52. polyvander2d
  53. polyvander3d
  54. polycompanion
  55. polyfit
  56. polytrim
  57. polyline
  58. See Also
  59. --------
  60. `numpy.polynomial`
  61. """
  62. __all__ = [
  63. 'polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', 'polyadd',
  64. 'polysub', 'polymulx', 'polymul', 'polydiv', 'polypow', 'polyval',
  65. 'polyvalfromroots', 'polyder', 'polyint', 'polyfromroots', 'polyvander',
  66. 'polyfit', 'polytrim', 'polyroots', 'Polynomial', 'polyval2d', 'polyval3d',
  67. 'polygrid2d', 'polygrid3d', 'polyvander2d', 'polyvander3d']
  68. import numpy as np
  69. import numpy.linalg as la
  70. from numpy.core.multiarray import normalize_axis_index
  71. from . import polyutils as pu
  72. from ._polybase import ABCPolyBase
  73. polytrim = pu.trimcoef
  74. #
  75. # These are constant arrays are of integer type so as to be compatible
  76. # with the widest range of other types, such as Decimal.
  77. #
  78. # Polynomial default domain.
  79. polydomain = np.array([-1, 1])
  80. # Polynomial coefficients representing zero.
  81. polyzero = np.array([0])
  82. # Polynomial coefficients representing one.
  83. polyone = np.array([1])
  84. # Polynomial coefficients representing the identity x.
  85. polyx = np.array([0, 1])
  86. #
  87. # Polynomial series functions
  88. #
  89. def polyline(off, scl):
  90. """
  91. Returns an array representing a linear polynomial.
  92. Parameters
  93. ----------
  94. off, scl : scalars
  95. The "y-intercept" and "slope" of the line, respectively.
  96. Returns
  97. -------
  98. y : ndarray
  99. This module's representation of the linear polynomial ``off +
  100. scl*x``.
  101. See Also
  102. --------
  103. chebline
  104. Examples
  105. --------
  106. >>> from numpy.polynomial import polynomial as P
  107. >>> P.polyline(1,-1)
  108. array([ 1, -1])
  109. >>> P.polyval(1, P.polyline(1,-1)) # should be 0
  110. 0.0
  111. """
  112. if scl != 0:
  113. return np.array([off, scl])
  114. else:
  115. return np.array([off])
  116. def polyfromroots(roots):
  117. """
  118. Generate a monic polynomial with given roots.
  119. Return the coefficients of the polynomial
  120. .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
  121. where the `r_n` are the roots specified in `roots`. If a zero has
  122. multiplicity n, then it must appear in `roots` n times. For instance,
  123. if 2 is a root of multiplicity three and 3 is a root of multiplicity 2,
  124. then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear
  125. in any order.
  126. If the returned coefficients are `c`, then
  127. .. math:: p(x) = c_0 + c_1 * x + ... + x^n
  128. The coefficient of the last term is 1 for monic polynomials in this
  129. form.
  130. Parameters
  131. ----------
  132. roots : array_like
  133. Sequence containing the roots.
  134. Returns
  135. -------
  136. out : ndarray
  137. 1-D array of the polynomial's coefficients If all the roots are
  138. real, then `out` is also real, otherwise it is complex. (see
  139. Examples below).
  140. See Also
  141. --------
  142. chebfromroots, legfromroots, lagfromroots, hermfromroots
  143. hermefromroots
  144. Notes
  145. -----
  146. The coefficients are determined by multiplying together linear factors
  147. of the form `(x - r_i)`, i.e.
  148. .. math:: p(x) = (x - r_0) (x - r_1) ... (x - r_n)
  149. where ``n == len(roots) - 1``; note that this implies that `1` is always
  150. returned for :math:`a_n`.
  151. Examples
  152. --------
  153. >>> from numpy.polynomial import polynomial as P
  154. >>> P.polyfromroots((-1,0,1)) # x(x - 1)(x + 1) = x^3 - x
  155. array([ 0., -1., 0., 1.])
  156. >>> j = complex(0,1)
  157. >>> P.polyfromroots((-j,j)) # complex returned, though values are real
  158. array([1.+0.j, 0.+0.j, 1.+0.j])
  159. """
  160. return pu._fromroots(polyline, polymul, roots)
  161. def polyadd(c1, c2):
  162. """
  163. Add one polynomial to another.
  164. Returns the sum of two polynomials `c1` + `c2`. The arguments are
  165. sequences of coefficients from lowest order term to highest, i.e.,
  166. [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.
  167. Parameters
  168. ----------
  169. c1, c2 : array_like
  170. 1-D arrays of polynomial coefficients ordered from low to high.
  171. Returns
  172. -------
  173. out : ndarray
  174. The coefficient array representing their sum.
  175. See Also
  176. --------
  177. polysub, polymulx, polymul, polydiv, polypow
  178. Examples
  179. --------
  180. >>> from numpy.polynomial import polynomial as P
  181. >>> c1 = (1,2,3)
  182. >>> c2 = (3,2,1)
  183. >>> sum = P.polyadd(c1,c2); sum
  184. array([4., 4., 4.])
  185. >>> P.polyval(2, sum) # 4 + 4(2) + 4(2**2)
  186. 28.0
  187. """
  188. return pu._add(c1, c2)
  189. def polysub(c1, c2):
  190. """
  191. Subtract one polynomial from another.
  192. Returns the difference of two polynomials `c1` - `c2`. The arguments
  193. are sequences of coefficients from lowest order term to highest, i.e.,
  194. [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.
  195. Parameters
  196. ----------
  197. c1, c2 : array_like
  198. 1-D arrays of polynomial coefficients ordered from low to
  199. high.
  200. Returns
  201. -------
  202. out : ndarray
  203. Of coefficients representing their difference.
  204. See Also
  205. --------
  206. polyadd, polymulx, polymul, polydiv, polypow
  207. Examples
  208. --------
  209. >>> from numpy.polynomial import polynomial as P
  210. >>> c1 = (1,2,3)
  211. >>> c2 = (3,2,1)
  212. >>> P.polysub(c1,c2)
  213. array([-2., 0., 2.])
  214. >>> P.polysub(c2,c1) # -P.polysub(c1,c2)
  215. array([ 2., 0., -2.])
  216. """
  217. return pu._sub(c1, c2)
  218. def polymulx(c):
  219. """Multiply a polynomial by x.
  220. Multiply the polynomial `c` by x, where x is the independent
  221. variable.
  222. Parameters
  223. ----------
  224. c : array_like
  225. 1-D array of polynomial coefficients ordered from low to
  226. high.
  227. Returns
  228. -------
  229. out : ndarray
  230. Array representing the result of the multiplication.
  231. See Also
  232. --------
  233. polyadd, polysub, polymul, polydiv, polypow
  234. Notes
  235. -----
  236. .. versionadded:: 1.5.0
  237. """
  238. # c is a trimmed copy
  239. [c] = pu.as_series([c])
  240. # The zero series needs special treatment
  241. if len(c) == 1 and c[0] == 0:
  242. return c
  243. prd = np.empty(len(c) + 1, dtype=c.dtype)
  244. prd[0] = c[0]*0
  245. prd[1:] = c
  246. return prd
  247. def polymul(c1, c2):
  248. """
  249. Multiply one polynomial by another.
  250. Returns the product of two polynomials `c1` * `c2`. The arguments are
  251. sequences of coefficients, from lowest order term to highest, e.g.,
  252. [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2.``
  253. Parameters
  254. ----------
  255. c1, c2 : array_like
  256. 1-D arrays of coefficients representing a polynomial, relative to the
  257. "standard" basis, and ordered from lowest order term to highest.
  258. Returns
  259. -------
  260. out : ndarray
  261. Of the coefficients of their product.
  262. See Also
  263. --------
  264. polyadd, polysub, polymulx, polydiv, polypow
  265. Examples
  266. --------
  267. >>> from numpy.polynomial import polynomial as P
  268. >>> c1 = (1,2,3)
  269. >>> c2 = (3,2,1)
  270. >>> P.polymul(c1,c2)
  271. array([ 3., 8., 14., 8., 3.])
  272. """
  273. # c1, c2 are trimmed copies
  274. [c1, c2] = pu.as_series([c1, c2])
  275. ret = np.convolve(c1, c2)
  276. return pu.trimseq(ret)
  277. def polydiv(c1, c2):
  278. """
  279. Divide one polynomial by another.
  280. Returns the quotient-with-remainder of two polynomials `c1` / `c2`.
  281. The arguments are sequences of coefficients, from lowest order term
  282. to highest, e.g., [1,2,3] represents ``1 + 2*x + 3*x**2``.
  283. Parameters
  284. ----------
  285. c1, c2 : array_like
  286. 1-D arrays of polynomial coefficients ordered from low to high.
  287. Returns
  288. -------
  289. [quo, rem] : ndarrays
  290. Of coefficient series representing the quotient and remainder.
  291. See Also
  292. --------
  293. polyadd, polysub, polymulx, polymul, polypow
  294. Examples
  295. --------
  296. >>> from numpy.polynomial import polynomial as P
  297. >>> c1 = (1,2,3)
  298. >>> c2 = (3,2,1)
  299. >>> P.polydiv(c1,c2)
  300. (array([3.]), array([-8., -4.]))
  301. >>> P.polydiv(c2,c1)
  302. (array([ 0.33333333]), array([ 2.66666667, 1.33333333])) # may vary
  303. """
  304. # c1, c2 are trimmed copies
  305. [c1, c2] = pu.as_series([c1, c2])
  306. if c2[-1] == 0:
  307. raise ZeroDivisionError()
  308. # note: this is more efficient than `pu._div(polymul, c1, c2)`
  309. lc1 = len(c1)
  310. lc2 = len(c2)
  311. if lc1 < lc2:
  312. return c1[:1]*0, c1
  313. elif lc2 == 1:
  314. return c1/c2[-1], c1[:1]*0
  315. else:
  316. dlen = lc1 - lc2
  317. scl = c2[-1]
  318. c2 = c2[:-1]/scl
  319. i = dlen
  320. j = lc1 - 1
  321. while i >= 0:
  322. c1[i:j] -= c2*c1[j]
  323. i -= 1
  324. j -= 1
  325. return c1[j+1:]/scl, pu.trimseq(c1[:j+1])
  326. def polypow(c, pow, maxpower=None):
  327. """Raise a polynomial to a power.
  328. Returns the polynomial `c` raised to the power `pow`. The argument
  329. `c` is a sequence of coefficients ordered from low to high. i.e.,
  330. [1,2,3] is the series ``1 + 2*x + 3*x**2.``
  331. Parameters
  332. ----------
  333. c : array_like
  334. 1-D array of array of series coefficients ordered from low to
  335. high degree.
  336. pow : integer
  337. Power to which the series will be raised
  338. maxpower : integer, optional
  339. Maximum power allowed. This is mainly to limit growth of the series
  340. to unmanageable size. Default is 16
  341. Returns
  342. -------
  343. coef : ndarray
  344. Power series of power.
  345. See Also
  346. --------
  347. polyadd, polysub, polymulx, polymul, polydiv
  348. Examples
  349. --------
  350. >>> from numpy.polynomial import polynomial as P
  351. >>> P.polypow([1,2,3], 2)
  352. array([ 1., 4., 10., 12., 9.])
  353. """
  354. # note: this is more efficient than `pu._pow(polymul, c1, c2)`, as it
  355. # avoids calling `as_series` repeatedly
  356. return pu._pow(np.convolve, c, pow, maxpower)
  357. def polyder(c, m=1, scl=1, axis=0):
  358. """
  359. Differentiate a polynomial.
  360. Returns the polynomial coefficients `c` differentiated `m` times along
  361. `axis`. At each iteration the result is multiplied by `scl` (the
  362. scaling factor is for use in a linear change of variable). The
  363. argument `c` is an array of coefficients from low to high degree along
  364. each axis, e.g., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``
  365. while [[1,2],[1,2]] represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is
  366. ``x`` and axis=1 is ``y``.
  367. Parameters
  368. ----------
  369. c : array_like
  370. Array of polynomial coefficients. If c is multidimensional the
  371. different axis correspond to different variables with the degree
  372. in each axis given by the corresponding index.
  373. m : int, optional
  374. Number of derivatives taken, must be non-negative. (Default: 1)
  375. scl : scalar, optional
  376. Each differentiation is multiplied by `scl`. The end result is
  377. multiplication by ``scl**m``. This is for use in a linear change
  378. of variable. (Default: 1)
  379. axis : int, optional
  380. Axis over which the derivative is taken. (Default: 0).
  381. .. versionadded:: 1.7.0
  382. Returns
  383. -------
  384. der : ndarray
  385. Polynomial coefficients of the derivative.
  386. See Also
  387. --------
  388. polyint
  389. Examples
  390. --------
  391. >>> from numpy.polynomial import polynomial as P
  392. >>> c = (1,2,3,4) # 1 + 2x + 3x**2 + 4x**3
  393. >>> P.polyder(c) # (d/dx)(c) = 2 + 6x + 12x**2
  394. array([ 2., 6., 12.])
  395. >>> P.polyder(c,3) # (d**3/dx**3)(c) = 24
  396. array([24.])
  397. >>> P.polyder(c,scl=-1) # (d/d(-x))(c) = -2 - 6x - 12x**2
  398. array([ -2., -6., -12.])
  399. >>> P.polyder(c,2,-1) # (d**2/d(-x)**2)(c) = 6 + 24x
  400. array([ 6., 24.])
  401. """
  402. c = np.array(c, ndmin=1, copy=True)
  403. if c.dtype.char in '?bBhHiIlLqQpP':
  404. # astype fails with NA
  405. c = c + 0.0
  406. cdt = c.dtype
  407. cnt = pu._deprecate_as_int(m, "the order of derivation")
  408. iaxis = pu._deprecate_as_int(axis, "the axis")
  409. if cnt < 0:
  410. raise ValueError("The order of derivation must be non-negative")
  411. iaxis = normalize_axis_index(iaxis, c.ndim)
  412. if cnt == 0:
  413. return c
  414. c = np.moveaxis(c, iaxis, 0)
  415. n = len(c)
  416. if cnt >= n:
  417. c = c[:1]*0
  418. else:
  419. for i in range(cnt):
  420. n = n - 1
  421. c *= scl
  422. der = np.empty((n,) + c.shape[1:], dtype=cdt)
  423. for j in range(n, 0, -1):
  424. der[j - 1] = j*c[j]
  425. c = der
  426. c = np.moveaxis(c, 0, iaxis)
  427. return c
  428. def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
  429. """
  430. Integrate a polynomial.
  431. Returns the polynomial coefficients `c` integrated `m` times from
  432. `lbnd` along `axis`. At each iteration the resulting series is
  433. **multiplied** by `scl` and an integration constant, `k`, is added.
  434. The scaling factor is for use in a linear change of variable. ("Buyer
  435. beware": note that, depending on what one is doing, one may want `scl`
  436. to be the reciprocal of what one might expect; for more information,
  437. see the Notes section below.) The argument `c` is an array of
  438. coefficients, from low to high degree along each axis, e.g., [1,2,3]
  439. represents the polynomial ``1 + 2*x + 3*x**2`` while [[1,2],[1,2]]
  440. represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is ``x`` and axis=1 is
  441. ``y``.
  442. Parameters
  443. ----------
  444. c : array_like
  445. 1-D array of polynomial coefficients, ordered from low to high.
  446. m : int, optional
  447. Order of integration, must be positive. (Default: 1)
  448. k : {[], list, scalar}, optional
  449. Integration constant(s). The value of the first integral at zero
  450. is the first value in the list, the value of the second integral
  451. at zero is the second value, etc. If ``k == []`` (the default),
  452. all constants are set to zero. If ``m == 1``, a single scalar can
  453. be given instead of a list.
  454. lbnd : scalar, optional
  455. The lower bound of the integral. (Default: 0)
  456. scl : scalar, optional
  457. Following each integration the result is *multiplied* by `scl`
  458. before the integration constant is added. (Default: 1)
  459. axis : int, optional
  460. Axis over which the integral is taken. (Default: 0).
  461. .. versionadded:: 1.7.0
  462. Returns
  463. -------
  464. S : ndarray
  465. Coefficient array of the integral.
  466. Raises
  467. ------
  468. ValueError
  469. If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
  470. ``np.ndim(scl) != 0``.
  471. See Also
  472. --------
  473. polyder
  474. Notes
  475. -----
  476. Note that the result of each integration is *multiplied* by `scl`. Why
  477. is this important to note? Say one is making a linear change of
  478. variable :math:`u = ax + b` in an integral relative to `x`. Then
  479. :math:`dx = du/a`, so one will need to set `scl` equal to
  480. :math:`1/a` - perhaps not what one would have first thought.
  481. Examples
  482. --------
  483. >>> from numpy.polynomial import polynomial as P
  484. >>> c = (1,2,3)
  485. >>> P.polyint(c) # should return array([0, 1, 1, 1])
  486. array([0., 1., 1., 1.])
  487. >>> P.polyint(c,3) # should return array([0, 0, 0, 1/6, 1/12, 1/20])
  488. array([ 0. , 0. , 0. , 0.16666667, 0.08333333, # may vary
  489. 0.05 ])
  490. >>> P.polyint(c,k=3) # should return array([3, 1, 1, 1])
  491. array([3., 1., 1., 1.])
  492. >>> P.polyint(c,lbnd=-2) # should return array([6, 1, 1, 1])
  493. array([6., 1., 1., 1.])
  494. >>> P.polyint(c,scl=-2) # should return array([0, -2, -2, -2])
  495. array([ 0., -2., -2., -2.])
  496. """
  497. c = np.array(c, ndmin=1, copy=True)
  498. if c.dtype.char in '?bBhHiIlLqQpP':
  499. # astype doesn't preserve mask attribute.
  500. c = c + 0.0
  501. cdt = c.dtype
  502. if not np.iterable(k):
  503. k = [k]
  504. cnt = pu._deprecate_as_int(m, "the order of integration")
  505. iaxis = pu._deprecate_as_int(axis, "the axis")
  506. if cnt < 0:
  507. raise ValueError("The order of integration must be non-negative")
  508. if len(k) > cnt:
  509. raise ValueError("Too many integration constants")
  510. if np.ndim(lbnd) != 0:
  511. raise ValueError("lbnd must be a scalar.")
  512. if np.ndim(scl) != 0:
  513. raise ValueError("scl must be a scalar.")
  514. iaxis = normalize_axis_index(iaxis, c.ndim)
  515. if cnt == 0:
  516. return c
  517. k = list(k) + [0]*(cnt - len(k))
  518. c = np.moveaxis(c, iaxis, 0)
  519. for i in range(cnt):
  520. n = len(c)
  521. c *= scl
  522. if n == 1 and np.all(c[0] == 0):
  523. c[0] += k[i]
  524. else:
  525. tmp = np.empty((n + 1,) + c.shape[1:], dtype=cdt)
  526. tmp[0] = c[0]*0
  527. tmp[1] = c[0]
  528. for j in range(1, n):
  529. tmp[j + 1] = c[j]/(j + 1)
  530. tmp[0] += k[i] - polyval(lbnd, tmp)
  531. c = tmp
  532. c = np.moveaxis(c, 0, iaxis)
  533. return c
  534. def polyval(x, c, tensor=True):
  535. """
  536. Evaluate a polynomial at points x.
  537. If `c` is of length `n + 1`, this function returns the value
  538. .. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n
  539. The parameter `x` is converted to an array only if it is a tuple or a
  540. list, otherwise it is treated as a scalar. In either case, either `x`
  541. or its elements must support multiplication and addition both with
  542. themselves and with the elements of `c`.
  543. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
  544. `c` is multidimensional, then the shape of the result depends on the
  545. value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
  546. x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
  547. scalars have shape (,).
  548. Trailing zeros in the coefficients will be used in the evaluation, so
  549. they should be avoided if efficiency is a concern.
  550. Parameters
  551. ----------
  552. x : array_like, compatible object
  553. If `x` is a list or tuple, it is converted to an ndarray, otherwise
  554. it is left unchanged and treated as a scalar. In either case, `x`
  555. or its elements must support addition and multiplication with
  556. with themselves and with the elements of `c`.
  557. c : array_like
  558. Array of coefficients ordered so that the coefficients for terms of
  559. degree n are contained in c[n]. If `c` is multidimensional the
  560. remaining indices enumerate multiple polynomials. In the two
  561. dimensional case the coefficients may be thought of as stored in
  562. the columns of `c`.
  563. tensor : boolean, optional
  564. If True, the shape of the coefficient array is extended with ones
  565. on the right, one for each dimension of `x`. Scalars have dimension 0
  566. for this action. The result is that every column of coefficients in
  567. `c` is evaluated for every element of `x`. If False, `x` is broadcast
  568. over the columns of `c` for the evaluation. This keyword is useful
  569. when `c` is multidimensional. The default value is True.
  570. .. versionadded:: 1.7.0
  571. Returns
  572. -------
  573. values : ndarray, compatible object
  574. The shape of the returned array is described above.
  575. See Also
  576. --------
  577. polyval2d, polygrid2d, polyval3d, polygrid3d
  578. Notes
  579. -----
  580. The evaluation uses Horner's method.
  581. Examples
  582. --------
  583. >>> from numpy.polynomial.polynomial import polyval
  584. >>> polyval(1, [1,2,3])
  585. 6.0
  586. >>> a = np.arange(4).reshape(2,2)
  587. >>> a
  588. array([[0, 1],
  589. [2, 3]])
  590. >>> polyval(a, [1,2,3])
  591. array([[ 1., 6.],
  592. [17., 34.]])
  593. >>> coef = np.arange(4).reshape(2,2) # multidimensional coefficients
  594. >>> coef
  595. array([[0, 1],
  596. [2, 3]])
  597. >>> polyval([1,2], coef, tensor=True)
  598. array([[2., 4.],
  599. [4., 7.]])
  600. >>> polyval([1,2], coef, tensor=False)
  601. array([2., 7.])
  602. """
  603. c = np.array(c, ndmin=1, copy=False)
  604. if c.dtype.char in '?bBhHiIlLqQpP':
  605. # astype fails with NA
  606. c = c + 0.0
  607. if isinstance(x, (tuple, list)):
  608. x = np.asarray(x)
  609. if isinstance(x, np.ndarray) and tensor:
  610. c = c.reshape(c.shape + (1,)*x.ndim)
  611. c0 = c[-1] + x*0
  612. for i in range(2, len(c) + 1):
  613. c0 = c[-i] + c0*x
  614. return c0
  615. def polyvalfromroots(x, r, tensor=True):
  616. """
  617. Evaluate a polynomial specified by its roots at points x.
  618. If `r` is of length `N`, this function returns the value
  619. .. math:: p(x) = \\prod_{n=1}^{N} (x - r_n)
  620. The parameter `x` is converted to an array only if it is a tuple or a
  621. list, otherwise it is treated as a scalar. In either case, either `x`
  622. or its elements must support multiplication and addition both with
  623. themselves and with the elements of `r`.
  624. If `r` is a 1-D array, then `p(x)` will have the same shape as `x`. If `r`
  625. is multidimensional, then the shape of the result depends on the value of
  626. `tensor`. If `tensor is ``True`` the shape will be r.shape[1:] + x.shape;
  627. that is, each polynomial is evaluated at every value of `x`. If `tensor` is
  628. ``False``, the shape will be r.shape[1:]; that is, each polynomial is
  629. evaluated only for the corresponding broadcast value of `x`. Note that
  630. scalars have shape (,).
  631. .. versionadded:: 1.12
  632. Parameters
  633. ----------
  634. x : array_like, compatible object
  635. If `x` is a list or tuple, it is converted to an ndarray, otherwise
  636. it is left unchanged and treated as a scalar. In either case, `x`
  637. or its elements must support addition and multiplication with
  638. with themselves and with the elements of `r`.
  639. r : array_like
  640. Array of roots. If `r` is multidimensional the first index is the
  641. root index, while the remaining indices enumerate multiple
  642. polynomials. For instance, in the two dimensional case the roots
  643. of each polynomial may be thought of as stored in the columns of `r`.
  644. tensor : boolean, optional
  645. If True, the shape of the roots array is extended with ones on the
  646. right, one for each dimension of `x`. Scalars have dimension 0 for this
  647. action. The result is that every column of coefficients in `r` is
  648. evaluated for every element of `x`. If False, `x` is broadcast over the
  649. columns of `r` for the evaluation. This keyword is useful when `r` is
  650. multidimensional. The default value is True.
  651. Returns
  652. -------
  653. values : ndarray, compatible object
  654. The shape of the returned array is described above.
  655. See Also
  656. --------
  657. polyroots, polyfromroots, polyval
  658. Examples
  659. --------
  660. >>> from numpy.polynomial.polynomial import polyvalfromroots
  661. >>> polyvalfromroots(1, [1,2,3])
  662. 0.0
  663. >>> a = np.arange(4).reshape(2,2)
  664. >>> a
  665. array([[0, 1],
  666. [2, 3]])
  667. >>> polyvalfromroots(a, [-1, 0, 1])
  668. array([[-0., 0.],
  669. [ 6., 24.]])
  670. >>> r = np.arange(-2, 2).reshape(2,2) # multidimensional coefficients
  671. >>> r # each column of r defines one polynomial
  672. array([[-2, -1],
  673. [ 0, 1]])
  674. >>> b = [-2, 1]
  675. >>> polyvalfromroots(b, r, tensor=True)
  676. array([[-0., 3.],
  677. [ 3., 0.]])
  678. >>> polyvalfromroots(b, r, tensor=False)
  679. array([-0., 0.])
  680. """
  681. r = np.array(r, ndmin=1, copy=False)
  682. if r.dtype.char in '?bBhHiIlLqQpP':
  683. r = r.astype(np.double)
  684. if isinstance(x, (tuple, list)):
  685. x = np.asarray(x)
  686. if isinstance(x, np.ndarray):
  687. if tensor:
  688. r = r.reshape(r.shape + (1,)*x.ndim)
  689. elif x.ndim >= r.ndim:
  690. raise ValueError("x.ndim must be < r.ndim when tensor == False")
  691. return np.prod(x - r, axis=0)
  692. def polyval2d(x, y, c):
  693. """
  694. Evaluate a 2-D polynomial at points (x, y).
  695. This function returns the value
  696. .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j
  697. The parameters `x` and `y` are converted to arrays only if they are
  698. tuples or a lists, otherwise they are treated as a scalars and they
  699. must have the same shape after conversion. In either case, either `x`
  700. and `y` or their elements must support multiplication and addition both
  701. with themselves and with the elements of `c`.
  702. If `c` has fewer than two dimensions, ones are implicitly appended to
  703. its shape to make it 2-D. The shape of the result will be c.shape[2:] +
  704. x.shape.
  705. Parameters
  706. ----------
  707. x, y : array_like, compatible objects
  708. The two dimensional series is evaluated at the points `(x, y)`,
  709. where `x` and `y` must have the same shape. If `x` or `y` is a list
  710. or tuple, it is first converted to an ndarray, otherwise it is left
  711. unchanged and, if it isn't an ndarray, it is treated as a scalar.
  712. c : array_like
  713. Array of coefficients ordered so that the coefficient of the term
  714. of multi-degree i,j is contained in `c[i,j]`. If `c` has
  715. dimension greater than two the remaining indices enumerate multiple
  716. sets of coefficients.
  717. Returns
  718. -------
  719. values : ndarray, compatible object
  720. The values of the two dimensional polynomial at points formed with
  721. pairs of corresponding values from `x` and `y`.
  722. See Also
  723. --------
  724. polyval, polygrid2d, polyval3d, polygrid3d
  725. Notes
  726. -----
  727. .. versionadded:: 1.7.0
  728. """
  729. return pu._valnd(polyval, c, x, y)
  730. def polygrid2d(x, y, c):
  731. """
  732. Evaluate a 2-D polynomial on the Cartesian product of x and y.
  733. This function returns the values:
  734. .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * a^i * b^j
  735. where the points `(a, b)` consist of all pairs formed by taking
  736. `a` from `x` and `b` from `y`. The resulting points form a grid with
  737. `x` in the first dimension and `y` in the second.
  738. The parameters `x` and `y` are converted to arrays only if they are
  739. tuples or a lists, otherwise they are treated as a scalars. In either
  740. case, either `x` and `y` or their elements must support multiplication
  741. and addition both with themselves and with the elements of `c`.
  742. If `c` has fewer than two dimensions, ones are implicitly appended to
  743. its shape to make it 2-D. The shape of the result will be c.shape[2:] +
  744. x.shape + y.shape.
  745. Parameters
  746. ----------
  747. x, y : array_like, compatible objects
  748. The two dimensional series is evaluated at the points in the
  749. Cartesian product of `x` and `y`. If `x` or `y` is a list or
  750. tuple, it is first converted to an ndarray, otherwise it is left
  751. unchanged and, if it isn't an ndarray, it is treated as a scalar.
  752. c : array_like
  753. Array of coefficients ordered so that the coefficients for terms of
  754. degree i,j are contained in ``c[i,j]``. If `c` has dimension
  755. greater than two the remaining indices enumerate multiple sets of
  756. coefficients.
  757. Returns
  758. -------
  759. values : ndarray, compatible object
  760. The values of the two dimensional polynomial at points in the Cartesian
  761. product of `x` and `y`.
  762. See Also
  763. --------
  764. polyval, polyval2d, polyval3d, polygrid3d
  765. Notes
  766. -----
  767. .. versionadded:: 1.7.0
  768. """
  769. return pu._gridnd(polyval, c, x, y)
  770. def polyval3d(x, y, z, c):
  771. """
  772. Evaluate a 3-D polynomial at points (x, y, z).
  773. This function returns the values:
  774. .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * x^i * y^j * z^k
  775. The parameters `x`, `y`, and `z` are converted to arrays only if
  776. they are tuples or a lists, otherwise they are treated as a scalars and
  777. they must have the same shape after conversion. In either case, either
  778. `x`, `y`, and `z` or their elements must support multiplication and
  779. addition both with themselves and with the elements of `c`.
  780. If `c` has fewer than 3 dimensions, ones are implicitly appended to its
  781. shape to make it 3-D. The shape of the result will be c.shape[3:] +
  782. x.shape.
  783. Parameters
  784. ----------
  785. x, y, z : array_like, compatible object
  786. The three dimensional series is evaluated at the points
  787. `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
  788. any of `x`, `y`, or `z` is a list or tuple, it is first converted
  789. to an ndarray, otherwise it is left unchanged and if it isn't an
  790. ndarray it is treated as a scalar.
  791. c : array_like
  792. Array of coefficients ordered so that the coefficient of the term of
  793. multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
  794. greater than 3 the remaining indices enumerate multiple sets of
  795. coefficients.
  796. Returns
  797. -------
  798. values : ndarray, compatible object
  799. The values of the multidimensional polynomial on points formed with
  800. triples of corresponding values from `x`, `y`, and `z`.
  801. See Also
  802. --------
  803. polyval, polyval2d, polygrid2d, polygrid3d
  804. Notes
  805. -----
  806. .. versionadded:: 1.7.0
  807. """
  808. return pu._valnd(polyval, c, x, y, z)
  809. def polygrid3d(x, y, z, c):
  810. """
  811. Evaluate a 3-D polynomial on the Cartesian product of x, y and z.
  812. This function returns the values:
  813. .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * a^i * b^j * c^k
  814. where the points `(a, b, c)` consist of all triples formed by taking
  815. `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
  816. a grid with `x` in the first dimension, `y` in the second, and `z` in
  817. the third.
  818. The parameters `x`, `y`, and `z` are converted to arrays only if they
  819. are tuples or a lists, otherwise they are treated as a scalars. In
  820. either case, either `x`, `y`, and `z` or their elements must support
  821. multiplication and addition both with themselves and with the elements
  822. of `c`.
  823. If `c` has fewer than three dimensions, ones are implicitly appended to
  824. its shape to make it 3-D. The shape of the result will be c.shape[3:] +
  825. x.shape + y.shape + z.shape.
  826. Parameters
  827. ----------
  828. x, y, z : array_like, compatible objects
  829. The three dimensional series is evaluated at the points in the
  830. Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
  831. list or tuple, it is first converted to an ndarray, otherwise it is
  832. left unchanged and, if it isn't an ndarray, it is treated as a
  833. scalar.
  834. c : array_like
  835. Array of coefficients ordered so that the coefficients for terms of
  836. degree i,j are contained in ``c[i,j]``. If `c` has dimension
  837. greater than two the remaining indices enumerate multiple sets of
  838. coefficients.
  839. Returns
  840. -------
  841. values : ndarray, compatible object
  842. The values of the two dimensional polynomial at points in the Cartesian
  843. product of `x` and `y`.
  844. See Also
  845. --------
  846. polyval, polyval2d, polygrid2d, polyval3d
  847. Notes
  848. -----
  849. .. versionadded:: 1.7.0
  850. """
  851. return pu._gridnd(polyval, c, x, y, z)
  852. def polyvander(x, deg):
  853. """Vandermonde matrix of given degree.
  854. Returns the Vandermonde matrix of degree `deg` and sample points
  855. `x`. The Vandermonde matrix is defined by
  856. .. math:: V[..., i] = x^i,
  857. where `0 <= i <= deg`. The leading indices of `V` index the elements of
  858. `x` and the last index is the power of `x`.
  859. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
  860. matrix ``V = polyvander(x, n)``, then ``np.dot(V, c)`` and
  861. ``polyval(x, c)`` are the same up to roundoff. This equivalence is
  862. useful both for least squares fitting and for the evaluation of a large
  863. number of polynomials of the same degree and sample points.
  864. Parameters
  865. ----------
  866. x : array_like
  867. Array of points. The dtype is converted to float64 or complex128
  868. depending on whether any of the elements are complex. If `x` is
  869. scalar it is converted to a 1-D array.
  870. deg : int
  871. Degree of the resulting matrix.
  872. Returns
  873. -------
  874. vander : ndarray.
  875. The Vandermonde matrix. The shape of the returned matrix is
  876. ``x.shape + (deg + 1,)``, where the last index is the power of `x`.
  877. The dtype will be the same as the converted `x`.
  878. See Also
  879. --------
  880. polyvander2d, polyvander3d
  881. """
  882. ideg = pu._deprecate_as_int(deg, "deg")
  883. if ideg < 0:
  884. raise ValueError("deg must be non-negative")
  885. x = np.array(x, copy=False, ndmin=1) + 0.0
  886. dims = (ideg + 1,) + x.shape
  887. dtyp = x.dtype
  888. v = np.empty(dims, dtype=dtyp)
  889. v[0] = x*0 + 1
  890. if ideg > 0:
  891. v[1] = x
  892. for i in range(2, ideg + 1):
  893. v[i] = v[i-1]*x
  894. return np.moveaxis(v, 0, -1)
  895. def polyvander2d(x, y, deg):
  896. """Pseudo-Vandermonde matrix of given degrees.
  897. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  898. points `(x, y)`. The pseudo-Vandermonde matrix is defined by
  899. .. math:: V[..., (deg[1] + 1)*i + j] = x^i * y^j,
  900. where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
  901. `V` index the points `(x, y)` and the last index encodes the powers of
  902. `x` and `y`.
  903. If ``V = polyvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
  904. correspond to the elements of a 2-D coefficient array `c` of shape
  905. (xdeg + 1, ydeg + 1) in the order
  906. .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
  907. and ``np.dot(V, c.flat)`` and ``polyval2d(x, y, c)`` will be the same
  908. up to roundoff. This equivalence is useful both for least squares
  909. fitting and for the evaluation of a large number of 2-D polynomials
  910. of the same degrees and sample points.
  911. Parameters
  912. ----------
  913. x, y : array_like
  914. Arrays of point coordinates, all of the same shape. The dtypes
  915. will be converted to either float64 or complex128 depending on
  916. whether any of the elements are complex. Scalars are converted to
  917. 1-D arrays.
  918. deg : list of ints
  919. List of maximum degrees of the form [x_deg, y_deg].
  920. Returns
  921. -------
  922. vander2d : ndarray
  923. The shape of the returned matrix is ``x.shape + (order,)``, where
  924. :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same
  925. as the converted `x` and `y`.
  926. See Also
  927. --------
  928. polyvander, polyvander3d, polyval2d, polyval3d
  929. """
  930. return pu._vander_nd_flat((polyvander, polyvander), (x, y), deg)
  931. def polyvander3d(x, y, z, deg):
  932. """Pseudo-Vandermonde matrix of given degrees.
  933. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  934. points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
  935. then The pseudo-Vandermonde matrix is defined by
  936. .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = x^i * y^j * z^k,
  937. where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
  938. indices of `V` index the points `(x, y, z)` and the last index encodes
  939. the powers of `x`, `y`, and `z`.
  940. If ``V = polyvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
  941. of `V` correspond to the elements of a 3-D coefficient array `c` of
  942. shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
  943. .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
  944. and ``np.dot(V, c.flat)`` and ``polyval3d(x, y, z, c)`` will be the
  945. same up to roundoff. This equivalence is useful both for least squares
  946. fitting and for the evaluation of a large number of 3-D polynomials
  947. of the same degrees and sample points.
  948. Parameters
  949. ----------
  950. x, y, z : array_like
  951. Arrays of point coordinates, all of the same shape. The dtypes will
  952. be converted to either float64 or complex128 depending on whether
  953. any of the elements are complex. Scalars are converted to 1-D
  954. arrays.
  955. deg : list of ints
  956. List of maximum degrees of the form [x_deg, y_deg, z_deg].
  957. Returns
  958. -------
  959. vander3d : ndarray
  960. The shape of the returned matrix is ``x.shape + (order,)``, where
  961. :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will
  962. be the same as the converted `x`, `y`, and `z`.
  963. See Also
  964. --------
  965. polyvander, polyvander3d, polyval2d, polyval3d
  966. Notes
  967. -----
  968. .. versionadded:: 1.7.0
  969. """
  970. return pu._vander_nd_flat((polyvander, polyvander, polyvander), (x, y, z), deg)
  971. def polyfit(x, y, deg, rcond=None, full=False, w=None):
  972. """
  973. Least-squares fit of a polynomial to data.
  974. Return the coefficients of a polynomial of degree `deg` that is the
  975. least squares fit to the data values `y` given at points `x`. If `y` is
  976. 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
  977. fits are done, one for each column of `y`, and the resulting
  978. coefficients are stored in the corresponding columns of a 2-D return.
  979. The fitted polynomial(s) are in the form
  980. .. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n,
  981. where `n` is `deg`.
  982. Parameters
  983. ----------
  984. x : array_like, shape (`M`,)
  985. x-coordinates of the `M` sample (data) points ``(x[i], y[i])``.
  986. y : array_like, shape (`M`,) or (`M`, `K`)
  987. y-coordinates of the sample points. Several sets of sample points
  988. sharing the same x-coordinates can be (independently) fit with one
  989. call to `polyfit` by passing in for `y` a 2-D array that contains
  990. one data set per column.
  991. deg : int or 1-D array_like
  992. Degree(s) of the fitting polynomials. If `deg` is a single integer
  993. all terms up to and including the `deg`'th term are included in the
  994. fit. For NumPy versions >= 1.11.0 a list of integers specifying the
  995. degrees of the terms to include may be used instead.
  996. rcond : float, optional
  997. Relative condition number of the fit. Singular values smaller
  998. than `rcond`, relative to the largest singular value, will be
  999. ignored. The default value is ``len(x)*eps``, where `eps` is the
  1000. relative precision of the platform's float type, about 2e-16 in
  1001. most cases.
  1002. full : bool, optional
  1003. Switch determining the nature of the return value. When ``False``
  1004. (the default) just the coefficients are returned; when ``True``,
  1005. diagnostic information from the singular value decomposition (used
  1006. to solve the fit's matrix equation) is also returned.
  1007. w : array_like, shape (`M`,), optional
  1008. Weights. If not None, the contribution of each point
  1009. ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
  1010. weights are chosen so that the errors of the products ``w[i]*y[i]``
  1011. all have the same variance. The default value is None.
  1012. .. versionadded:: 1.5.0
  1013. Returns
  1014. -------
  1015. coef : ndarray, shape (`deg` + 1,) or (`deg` + 1, `K`)
  1016. Polynomial coefficients ordered from low to high. If `y` was 2-D,
  1017. the coefficients in column `k` of `coef` represent the polynomial
  1018. fit to the data in `y`'s `k`-th column.
  1019. [residuals, rank, singular_values, rcond] : list
  1020. These values are only returned if `full` = True
  1021. resid -- sum of squared residuals of the least squares fit
  1022. rank -- the numerical rank of the scaled Vandermonde matrix
  1023. sv -- singular values of the scaled Vandermonde matrix
  1024. rcond -- value of `rcond`.
  1025. For more details, see `linalg.lstsq`.
  1026. Raises
  1027. ------
  1028. RankWarning
  1029. Raised if the matrix in the least-squares fit is rank deficient.
  1030. The warning is only raised if `full` == False. The warnings can
  1031. be turned off by:
  1032. >>> import warnings
  1033. >>> warnings.simplefilter('ignore', np.RankWarning)
  1034. See Also
  1035. --------
  1036. chebfit, legfit, lagfit, hermfit, hermefit
  1037. polyval : Evaluates a polynomial.
  1038. polyvander : Vandermonde matrix for powers.
  1039. linalg.lstsq : Computes a least-squares fit from the matrix.
  1040. scipy.interpolate.UnivariateSpline : Computes spline fits.
  1041. Notes
  1042. -----
  1043. The solution is the coefficients of the polynomial `p` that minimizes
  1044. the sum of the weighted squared errors
  1045. .. math :: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
  1046. where the :math:`w_j` are the weights. This problem is solved by
  1047. setting up the (typically) over-determined matrix equation:
  1048. .. math :: V(x) * c = w * y,
  1049. where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
  1050. coefficients to be solved for, `w` are the weights, and `y` are the
  1051. observed values. This equation is then solved using the singular value
  1052. decomposition of `V`.
  1053. If some of the singular values of `V` are so small that they are
  1054. neglected (and `full` == ``False``), a `RankWarning` will be raised.
  1055. This means that the coefficient values may be poorly determined.
  1056. Fitting to a lower order polynomial will usually get rid of the warning
  1057. (but may not be what you want, of course; if you have independent
  1058. reason(s) for choosing the degree which isn't working, you may have to:
  1059. a) reconsider those reasons, and/or b) reconsider the quality of your
  1060. data). The `rcond` parameter can also be set to a value smaller than
  1061. its default, but the resulting fit may be spurious and have large
  1062. contributions from roundoff error.
  1063. Polynomial fits using double precision tend to "fail" at about
  1064. (polynomial) degree 20. Fits using Chebyshev or Legendre series are
  1065. generally better conditioned, but much can still depend on the
  1066. distribution of the sample points and the smoothness of the data. If
  1067. the quality of the fit is inadequate, splines may be a good
  1068. alternative.
  1069. Examples
  1070. --------
  1071. >>> np.random.seed(123)
  1072. >>> from numpy.polynomial import polynomial as P
  1073. >>> x = np.linspace(-1,1,51) # x "data": [-1, -0.96, ..., 0.96, 1]
  1074. >>> y = x**3 - x + np.random.randn(len(x)) # x^3 - x + N(0,1) "noise"
  1075. >>> c, stats = P.polyfit(x,y,3,full=True)
  1076. >>> np.random.seed(123)
  1077. >>> c # c[0], c[2] should be approx. 0, c[1] approx. -1, c[3] approx. 1
  1078. array([ 0.01909725, -1.30598256, -0.00577963, 1.02644286]) # may vary
  1079. >>> stats # note the large SSR, explaining the rather poor results
  1080. [array([ 38.06116253]), 4, array([ 1.38446749, 1.32119158, 0.50443316, # may vary
  1081. 0.28853036]), 1.1324274851176597e-014]
  1082. Same thing without the added noise
  1083. >>> y = x**3 - x
  1084. >>> c, stats = P.polyfit(x,y,3,full=True)
  1085. >>> c # c[0], c[2] should be "very close to 0", c[1] ~= -1, c[3] ~= 1
  1086. array([-6.36925336e-18, -1.00000000e+00, -4.08053781e-16, 1.00000000e+00])
  1087. >>> stats # note the minuscule SSR
  1088. [array([ 7.46346754e-31]), 4, array([ 1.38446749, 1.32119158, # may vary
  1089. 0.50443316, 0.28853036]), 1.1324274851176597e-014]
  1090. """
  1091. return pu._fit(polyvander, x, y, deg, rcond, full, w)
  1092. def polycompanion(c):
  1093. """
  1094. Return the companion matrix of c.
  1095. The companion matrix for power series cannot be made symmetric by
  1096. scaling the basis, so this function differs from those for the
  1097. orthogonal polynomials.
  1098. Parameters
  1099. ----------
  1100. c : array_like
  1101. 1-D array of polynomial coefficients ordered from low to high
  1102. degree.
  1103. Returns
  1104. -------
  1105. mat : ndarray
  1106. Companion matrix of dimensions (deg, deg).
  1107. Notes
  1108. -----
  1109. .. versionadded:: 1.7.0
  1110. """
  1111. # c is a trimmed copy
  1112. [c] = pu.as_series([c])
  1113. if len(c) < 2:
  1114. raise ValueError('Series must have maximum degree of at least 1.')
  1115. if len(c) == 2:
  1116. return np.array([[-c[0]/c[1]]])
  1117. n = len(c) - 1
  1118. mat = np.zeros((n, n), dtype=c.dtype)
  1119. bot = mat.reshape(-1)[n::n+1]
  1120. bot[...] = 1
  1121. mat[:, -1] -= c[:-1]/c[-1]
  1122. return mat
  1123. def polyroots(c):
  1124. """
  1125. Compute the roots of a polynomial.
  1126. Return the roots (a.k.a. "zeros") of the polynomial
  1127. .. math:: p(x) = \\sum_i c[i] * x^i.
  1128. Parameters
  1129. ----------
  1130. c : 1-D array_like
  1131. 1-D array of polynomial coefficients.
  1132. Returns
  1133. -------
  1134. out : ndarray
  1135. Array of the roots of the polynomial. If all the roots are real,
  1136. then `out` is also real, otherwise it is complex.
  1137. See Also
  1138. --------
  1139. chebroots
  1140. Notes
  1141. -----
  1142. The root estimates are obtained as the eigenvalues of the companion
  1143. matrix, Roots far from the origin of the complex plane may have large
  1144. errors due to the numerical instability of the power series for such
  1145. values. Roots with multiplicity greater than 1 will also show larger
  1146. errors as the value of the series near such points is relatively
  1147. insensitive to errors in the roots. Isolated roots near the origin can
  1148. be improved by a few iterations of Newton's method.
  1149. Examples
  1150. --------
  1151. >>> import numpy.polynomial.polynomial as poly
  1152. >>> poly.polyroots(poly.polyfromroots((-1,0,1)))
  1153. array([-1., 0., 1.])
  1154. >>> poly.polyroots(poly.polyfromroots((-1,0,1))).dtype
  1155. dtype('float64')
  1156. >>> j = complex(0,1)
  1157. >>> poly.polyroots(poly.polyfromroots((-j,0,j)))
  1158. array([ 0.00000000e+00+0.j, 0.00000000e+00+1.j, 2.77555756e-17-1.j]) # may vary
  1159. """
  1160. # c is a trimmed copy
  1161. [c] = pu.as_series([c])
  1162. if len(c) < 2:
  1163. return np.array([], dtype=c.dtype)
  1164. if len(c) == 2:
  1165. return np.array([-c[0]/c[1]])
  1166. # rotated companion matrix reduces error
  1167. m = polycompanion(c)[::-1,::-1]
  1168. r = la.eigvals(m)
  1169. r.sort()
  1170. return r
  1171. #
  1172. # polynomial class
  1173. #
  1174. class Polynomial(ABCPolyBase):
  1175. """A power series class.
  1176. The Polynomial class provides the standard Python numerical methods
  1177. '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
  1178. attributes and methods listed in the `ABCPolyBase` documentation.
  1179. Parameters
  1180. ----------
  1181. coef : array_like
  1182. Polynomial coefficients in order of increasing degree, i.e.,
  1183. ``(1, 2, 3)`` give ``1 + 2*x + 3*x**2``.
  1184. domain : (2,) array_like, optional
  1185. Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
  1186. to the interval ``[window[0], window[1]]`` by shifting and scaling.
  1187. The default value is [-1, 1].
  1188. window : (2,) array_like, optional
  1189. Window, see `domain` for its use. The default value is [-1, 1].
  1190. .. versionadded:: 1.6.0
  1191. """
  1192. # Virtual Functions
  1193. _add = staticmethod(polyadd)
  1194. _sub = staticmethod(polysub)
  1195. _mul = staticmethod(polymul)
  1196. _div = staticmethod(polydiv)
  1197. _pow = staticmethod(polypow)
  1198. _val = staticmethod(polyval)
  1199. _int = staticmethod(polyint)
  1200. _der = staticmethod(polyder)
  1201. _fit = staticmethod(polyfit)
  1202. _line = staticmethod(polyline)
  1203. _roots = staticmethod(polyroots)
  1204. _fromroots = staticmethod(polyfromroots)
  1205. # Virtual properties
  1206. nickname = 'poly'
  1207. domain = np.array(polydomain)
  1208. window = np.array(polydomain)
  1209. basis_name = None
  1210. @staticmethod
  1211. def _repr_latex_term(i, arg_str, needs_parens):
  1212. if needs_parens:
  1213. arg_str = rf"\left({arg_str}\right)"
  1214. if i == 0:
  1215. return '1'
  1216. elif i == 1:
  1217. return arg_str
  1218. else:
  1219. return f"{arg_str}^{{{i}}}"