polynomial.py 48 KB

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