chebyshev.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077
  1. """
  2. ====================================================
  3. Chebyshev Series (:mod:`numpy.polynomial.chebyshev`)
  4. ====================================================
  5. This module provides a number of objects (mostly functions) useful for
  6. dealing with Chebyshev series, including a `Chebyshev` class that
  7. encapsulates the usual arithmetic operations. (General information
  8. on how this module represents and works with such polynomials is in the
  9. docstring for its "parent" sub-package, `numpy.polynomial`).
  10. Classes
  11. -------
  12. .. autosummary::
  13. :toctree: generated/
  14. Chebyshev
  15. Constants
  16. ---------
  17. .. autosummary::
  18. :toctree: generated/
  19. chebdomain
  20. chebzero
  21. chebone
  22. chebx
  23. Arithmetic
  24. ----------
  25. .. autosummary::
  26. :toctree: generated/
  27. chebadd
  28. chebsub
  29. chebmulx
  30. chebmul
  31. chebdiv
  32. chebpow
  33. chebval
  34. chebval2d
  35. chebval3d
  36. chebgrid2d
  37. chebgrid3d
  38. Calculus
  39. --------
  40. .. autosummary::
  41. :toctree: generated/
  42. chebder
  43. chebint
  44. Misc Functions
  45. --------------
  46. .. autosummary::
  47. :toctree: generated/
  48. chebfromroots
  49. chebroots
  50. chebvander
  51. chebvander2d
  52. chebvander3d
  53. chebgauss
  54. chebweight
  55. chebcompanion
  56. chebfit
  57. chebpts1
  58. chebpts2
  59. chebtrim
  60. chebline
  61. cheb2poly
  62. poly2cheb
  63. chebinterpolate
  64. See also
  65. --------
  66. `numpy.polynomial`
  67. Notes
  68. -----
  69. The implementations of multiplication, division, integration, and
  70. differentiation use the algebraic identities [1]_:
  71. .. math ::
  72. T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\
  73. z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}.
  74. where
  75. .. math :: x = \\frac{z + z^{-1}}{2}.
  76. These identities allow a Chebyshev series to be expressed as a finite,
  77. symmetric Laurent series. In this module, this sort of Laurent series
  78. is referred to as a "z-series."
  79. References
  80. ----------
  81. .. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev
  82. Polynomials," *Journal of Statistical Planning and Inference 14*, 2008
  83. (https://web.archive.org/web/20080221202153/https://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4)
  84. """
  85. import numpy as np
  86. import numpy.linalg as la
  87. from numpy.core.multiarray import normalize_axis_index
  88. from . import polyutils as pu
  89. from ._polybase import ABCPolyBase
  90. __all__ = [
  91. 'chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd',
  92. 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', 'chebval',
  93. 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots',
  94. 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1',
  95. 'chebpts2', 'Chebyshev', 'chebval2d', 'chebval3d', 'chebgrid2d',
  96. 'chebgrid3d', 'chebvander2d', 'chebvander3d', 'chebcompanion',
  97. 'chebgauss', 'chebweight', 'chebinterpolate']
  98. chebtrim = pu.trimcoef
  99. #
  100. # A collection of functions for manipulating z-series. These are private
  101. # functions and do minimal error checking.
  102. #
  103. def _cseries_to_zseries(c):
  104. """Covert Chebyshev series to z-series.
  105. Covert a Chebyshev series to the equivalent z-series. The result is
  106. never an empty array. The dtype of the return is the same as that of
  107. the input. No checks are run on the arguments as this routine is for
  108. internal use.
  109. Parameters
  110. ----------
  111. c : 1-D ndarray
  112. Chebyshev coefficients, ordered from low to high
  113. Returns
  114. -------
  115. zs : 1-D ndarray
  116. Odd length symmetric z-series, ordered from low to high.
  117. """
  118. n = c.size
  119. zs = np.zeros(2*n-1, dtype=c.dtype)
  120. zs[n-1:] = c/2
  121. return zs + zs[::-1]
  122. def _zseries_to_cseries(zs):
  123. """Covert z-series to a Chebyshev series.
  124. Covert a z series to the equivalent Chebyshev series. The result is
  125. never an empty array. The dtype of the return is the same as that of
  126. the input. No checks are run on the arguments as this routine is for
  127. internal use.
  128. Parameters
  129. ----------
  130. zs : 1-D ndarray
  131. Odd length symmetric z-series, ordered from low to high.
  132. Returns
  133. -------
  134. c : 1-D ndarray
  135. Chebyshev coefficients, ordered from low to high.
  136. """
  137. n = (zs.size + 1)//2
  138. c = zs[n-1:].copy()
  139. c[1:n] *= 2
  140. return c
  141. def _zseries_mul(z1, z2):
  142. """Multiply two z-series.
  143. Multiply two z-series to produce a z-series.
  144. Parameters
  145. ----------
  146. z1, z2 : 1-D ndarray
  147. The arrays must be 1-D but this is not checked.
  148. Returns
  149. -------
  150. product : 1-D ndarray
  151. The product z-series.
  152. Notes
  153. -----
  154. This is simply convolution. If symmetric/anti-symmetric z-series are
  155. denoted by S/A then the following rules apply:
  156. S*S, A*A -> S
  157. S*A, A*S -> A
  158. """
  159. return np.convolve(z1, z2)
  160. def _zseries_div(z1, z2):
  161. """Divide the first z-series by the second.
  162. Divide `z1` by `z2` and return the quotient and remainder as z-series.
  163. Warning: this implementation only applies when both z1 and z2 have the
  164. same symmetry, which is sufficient for present purposes.
  165. Parameters
  166. ----------
  167. z1, z2 : 1-D ndarray
  168. The arrays must be 1-D and have the same symmetry, but this is not
  169. checked.
  170. Returns
  171. -------
  172. (quotient, remainder) : 1-D ndarrays
  173. Quotient and remainder as z-series.
  174. Notes
  175. -----
  176. This is not the same as polynomial division on account of the desired form
  177. of the remainder. If symmetric/anti-symmetric z-series are denoted by S/A
  178. then the following rules apply:
  179. S/S -> S,S
  180. A/A -> S,A
  181. The restriction to types of the same symmetry could be fixed but seems like
  182. unneeded generality. There is no natural form for the remainder in the case
  183. where there is no symmetry.
  184. """
  185. z1 = z1.copy()
  186. z2 = z2.copy()
  187. lc1 = len(z1)
  188. lc2 = len(z2)
  189. if lc2 == 1:
  190. z1 /= z2
  191. return z1, z1[:1]*0
  192. elif lc1 < lc2:
  193. return z1[:1]*0, z1
  194. else:
  195. dlen = lc1 - lc2
  196. scl = z2[0]
  197. z2 /= scl
  198. quo = np.empty(dlen + 1, dtype=z1.dtype)
  199. i = 0
  200. j = dlen
  201. while i < j:
  202. r = z1[i]
  203. quo[i] = z1[i]
  204. quo[dlen - i] = r
  205. tmp = r*z2
  206. z1[i:i+lc2] -= tmp
  207. z1[j:j+lc2] -= tmp
  208. i += 1
  209. j -= 1
  210. r = z1[i]
  211. quo[i] = r
  212. tmp = r*z2
  213. z1[i:i+lc2] -= tmp
  214. quo /= scl
  215. rem = z1[i+1:i-1+lc2].copy()
  216. return quo, rem
  217. def _zseries_der(zs):
  218. """Differentiate a z-series.
  219. The derivative is with respect to x, not z. This is achieved using the
  220. chain rule and the value of dx/dz given in the module notes.
  221. Parameters
  222. ----------
  223. zs : z-series
  224. The z-series to differentiate.
  225. Returns
  226. -------
  227. derivative : z-series
  228. The derivative
  229. Notes
  230. -----
  231. The zseries for x (ns) has been multiplied by two in order to avoid
  232. using floats that are incompatible with Decimal and likely other
  233. specialized scalar types. This scaling has been compensated by
  234. multiplying the value of zs by two also so that the two cancels in the
  235. division.
  236. """
  237. n = len(zs)//2
  238. ns = np.array([-1, 0, 1], dtype=zs.dtype)
  239. zs *= np.arange(-n, n+1)*2
  240. d, r = _zseries_div(zs, ns)
  241. return d
  242. def _zseries_int(zs):
  243. """Integrate a z-series.
  244. The integral is with respect to x, not z. This is achieved by a change
  245. of variable using dx/dz given in the module notes.
  246. Parameters
  247. ----------
  248. zs : z-series
  249. The z-series to integrate
  250. Returns
  251. -------
  252. integral : z-series
  253. The indefinite integral
  254. Notes
  255. -----
  256. The zseries for x (ns) has been multiplied by two in order to avoid
  257. using floats that are incompatible with Decimal and likely other
  258. specialized scalar types. This scaling has been compensated by
  259. dividing the resulting zs by two.
  260. """
  261. n = 1 + len(zs)//2
  262. ns = np.array([-1, 0, 1], dtype=zs.dtype)
  263. zs = _zseries_mul(zs, ns)
  264. div = np.arange(-n, n+1)*2
  265. zs[:n] /= div[:n]
  266. zs[n+1:] /= div[n+1:]
  267. zs[n] = 0
  268. return zs
  269. #
  270. # Chebyshev series functions
  271. #
  272. def poly2cheb(pol):
  273. """
  274. Convert a polynomial to a Chebyshev series.
  275. Convert an array representing the coefficients of a polynomial (relative
  276. to the "standard" basis) ordered from lowest degree to highest, to an
  277. array of the coefficients of the equivalent Chebyshev series, ordered
  278. from lowest to highest degree.
  279. Parameters
  280. ----------
  281. pol : array_like
  282. 1-D array containing the polynomial coefficients
  283. Returns
  284. -------
  285. c : ndarray
  286. 1-D array containing the coefficients of the equivalent Chebyshev
  287. series.
  288. See Also
  289. --------
  290. cheb2poly
  291. Notes
  292. -----
  293. The easy way to do conversions between polynomial basis sets
  294. is to use the convert method of a class instance.
  295. Examples
  296. --------
  297. >>> from numpy import polynomial as P
  298. >>> p = P.Polynomial(range(4))
  299. >>> p
  300. Polynomial([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
  301. >>> c = p.convert(kind=P.Chebyshev)
  302. >>> c
  303. Chebyshev([1. , 3.25, 1. , 0.75], domain=[-1., 1.], window=[-1., 1.])
  304. >>> P.chebyshev.poly2cheb(range(4))
  305. array([1. , 3.25, 1. , 0.75])
  306. """
  307. [pol] = pu.as_series([pol])
  308. deg = len(pol) - 1
  309. res = 0
  310. for i in range(deg, -1, -1):
  311. res = chebadd(chebmulx(res), pol[i])
  312. return res
  313. def cheb2poly(c):
  314. """
  315. Convert a Chebyshev series to a polynomial.
  316. Convert an array representing the coefficients of a Chebyshev series,
  317. ordered from lowest degree to highest, to an array of the coefficients
  318. of the equivalent polynomial (relative to the "standard" basis) ordered
  319. from lowest to highest degree.
  320. Parameters
  321. ----------
  322. c : array_like
  323. 1-D array containing the Chebyshev series coefficients, ordered
  324. from lowest order term to highest.
  325. Returns
  326. -------
  327. pol : ndarray
  328. 1-D array containing the coefficients of the equivalent polynomial
  329. (relative to the "standard" basis) ordered from lowest order term
  330. to highest.
  331. See Also
  332. --------
  333. poly2cheb
  334. Notes
  335. -----
  336. The easy way to do conversions between polynomial basis sets
  337. is to use the convert method of a class instance.
  338. Examples
  339. --------
  340. >>> from numpy import polynomial as P
  341. >>> c = P.Chebyshev(range(4))
  342. >>> c
  343. Chebyshev([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
  344. >>> p = c.convert(kind=P.Polynomial)
  345. >>> p
  346. Polynomial([-2., -8., 4., 12.], domain=[-1., 1.], window=[-1., 1.])
  347. >>> P.chebyshev.cheb2poly(range(4))
  348. array([-2., -8., 4., 12.])
  349. """
  350. from .polynomial import polyadd, polysub, polymulx
  351. [c] = pu.as_series([c])
  352. n = len(c)
  353. if n < 3:
  354. return c
  355. else:
  356. c0 = c[-2]
  357. c1 = c[-1]
  358. # i is the current degree of c1
  359. for i in range(n - 1, 1, -1):
  360. tmp = c0
  361. c0 = polysub(c[i - 2], c1)
  362. c1 = polyadd(tmp, polymulx(c1)*2)
  363. return polyadd(c0, polymulx(c1))
  364. #
  365. # These are constant arrays are of integer type so as to be compatible
  366. # with the widest range of other types, such as Decimal.
  367. #
  368. # Chebyshev default domain.
  369. chebdomain = np.array([-1, 1])
  370. # Chebyshev coefficients representing zero.
  371. chebzero = np.array([0])
  372. # Chebyshev coefficients representing one.
  373. chebone = np.array([1])
  374. # Chebyshev coefficients representing the identity x.
  375. chebx = np.array([0, 1])
  376. def chebline(off, scl):
  377. """
  378. Chebyshev series whose graph is a straight line.
  379. Parameters
  380. ----------
  381. off, scl : scalars
  382. The specified line is given by ``off + scl*x``.
  383. Returns
  384. -------
  385. y : ndarray
  386. This module's representation of the Chebyshev series for
  387. ``off + scl*x``.
  388. See Also
  389. --------
  390. numpy.polynomial.polynomial.polyline
  391. numpy.polynomial.legendre.legline
  392. numpy.polynomial.laguerre.lagline
  393. numpy.polynomial.hermite.hermline
  394. numpy.polynomial.hermite_e.hermeline
  395. Examples
  396. --------
  397. >>> import numpy.polynomial.chebyshev as C
  398. >>> C.chebline(3,2)
  399. array([3, 2])
  400. >>> C.chebval(-3, C.chebline(3,2)) # should be -3
  401. -3.0
  402. """
  403. if scl != 0:
  404. return np.array([off, scl])
  405. else:
  406. return np.array([off])
  407. def chebfromroots(roots):
  408. """
  409. Generate a Chebyshev series with given roots.
  410. The function returns the coefficients of the polynomial
  411. .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
  412. in Chebyshev form, where the `r_n` are the roots specified in `roots`.
  413. If a zero has multiplicity n, then it must appear in `roots` n times.
  414. For instance, if 2 is a root of multiplicity three and 3 is a root of
  415. multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
  416. roots can appear in any order.
  417. If the returned coefficients are `c`, then
  418. .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x)
  419. The coefficient of the last term is not generally 1 for monic
  420. polynomials in Chebyshev form.
  421. Parameters
  422. ----------
  423. roots : array_like
  424. Sequence containing the roots.
  425. Returns
  426. -------
  427. out : ndarray
  428. 1-D array of coefficients. If all roots are real then `out` is a
  429. real array, if some of the roots are complex, then `out` is complex
  430. even if all the coefficients in the result are real (see Examples
  431. below).
  432. See Also
  433. --------
  434. numpy.polynomial.polynomial.polyfromroots
  435. numpy.polynomial.legendre.legfromroots
  436. numpy.polynomial.laguerre.lagfromroots
  437. numpy.polynomial.hermite.hermfromroots
  438. numpy.polynomial.hermite_e.hermefromroots
  439. Examples
  440. --------
  441. >>> import numpy.polynomial.chebyshev as C
  442. >>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis
  443. array([ 0. , -0.25, 0. , 0.25])
  444. >>> j = complex(0,1)
  445. >>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis
  446. array([1.5+0.j, 0. +0.j, 0.5+0.j])
  447. """
  448. return pu._fromroots(chebline, chebmul, roots)
  449. def chebadd(c1, c2):
  450. """
  451. Add one Chebyshev series to another.
  452. Returns the sum of two Chebyshev series `c1` + `c2`. The arguments
  453. are sequences of coefficients ordered from lowest order term to
  454. highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
  455. Parameters
  456. ----------
  457. c1, c2 : array_like
  458. 1-D arrays of Chebyshev series coefficients ordered from low to
  459. high.
  460. Returns
  461. -------
  462. out : ndarray
  463. Array representing the Chebyshev series of their sum.
  464. See Also
  465. --------
  466. chebsub, chebmulx, chebmul, chebdiv, chebpow
  467. Notes
  468. -----
  469. Unlike multiplication, division, etc., the sum of two Chebyshev series
  470. is a Chebyshev series (without having to "reproject" the result onto
  471. the basis set) so addition, just like that of "standard" polynomials,
  472. is simply "component-wise."
  473. Examples
  474. --------
  475. >>> from numpy.polynomial import chebyshev as C
  476. >>> c1 = (1,2,3)
  477. >>> c2 = (3,2,1)
  478. >>> C.chebadd(c1,c2)
  479. array([4., 4., 4.])
  480. """
  481. return pu._add(c1, c2)
  482. def chebsub(c1, c2):
  483. """
  484. Subtract one Chebyshev series from another.
  485. Returns the difference of two Chebyshev series `c1` - `c2`. The
  486. sequences of coefficients are from lowest order term to highest, i.e.,
  487. [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
  488. Parameters
  489. ----------
  490. c1, c2 : array_like
  491. 1-D arrays of Chebyshev series coefficients ordered from low to
  492. high.
  493. Returns
  494. -------
  495. out : ndarray
  496. Of Chebyshev series coefficients representing their difference.
  497. See Also
  498. --------
  499. chebadd, chebmulx, chebmul, chebdiv, chebpow
  500. Notes
  501. -----
  502. Unlike multiplication, division, etc., the difference of two Chebyshev
  503. series is a Chebyshev series (without having to "reproject" the result
  504. onto the basis set) so subtraction, just like that of "standard"
  505. polynomials, is simply "component-wise."
  506. Examples
  507. --------
  508. >>> from numpy.polynomial import chebyshev as C
  509. >>> c1 = (1,2,3)
  510. >>> c2 = (3,2,1)
  511. >>> C.chebsub(c1,c2)
  512. array([-2., 0., 2.])
  513. >>> C.chebsub(c2,c1) # -C.chebsub(c1,c2)
  514. array([ 2., 0., -2.])
  515. """
  516. return pu._sub(c1, c2)
  517. def chebmulx(c):
  518. """Multiply a Chebyshev series by x.
  519. Multiply the polynomial `c` by x, where x is the independent
  520. variable.
  521. Parameters
  522. ----------
  523. c : array_like
  524. 1-D array of Chebyshev series coefficients ordered from low to
  525. high.
  526. Returns
  527. -------
  528. out : ndarray
  529. Array representing the result of the multiplication.
  530. Notes
  531. -----
  532. .. versionadded:: 1.5.0
  533. Examples
  534. --------
  535. >>> from numpy.polynomial import chebyshev as C
  536. >>> C.chebmulx([1,2,3])
  537. array([1. , 2.5, 1. , 1.5])
  538. """
  539. # c is a trimmed copy
  540. [c] = pu.as_series([c])
  541. # The zero series needs special treatment
  542. if len(c) == 1 and c[0] == 0:
  543. return c
  544. prd = np.empty(len(c) + 1, dtype=c.dtype)
  545. prd[0] = c[0]*0
  546. prd[1] = c[0]
  547. if len(c) > 1:
  548. tmp = c[1:]/2
  549. prd[2:] = tmp
  550. prd[0:-2] += tmp
  551. return prd
  552. def chebmul(c1, c2):
  553. """
  554. Multiply one Chebyshev series by another.
  555. Returns the product of two Chebyshev series `c1` * `c2`. The arguments
  556. are sequences of coefficients, from lowest order "term" to highest,
  557. e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
  558. Parameters
  559. ----------
  560. c1, c2 : array_like
  561. 1-D arrays of Chebyshev series coefficients ordered from low to
  562. high.
  563. Returns
  564. -------
  565. out : ndarray
  566. Of Chebyshev series coefficients representing their product.
  567. See Also
  568. --------
  569. chebadd, chebsub, chebmulx, chebdiv, chebpow
  570. Notes
  571. -----
  572. In general, the (polynomial) product of two C-series results in terms
  573. that are not in the Chebyshev polynomial basis set. Thus, to express
  574. the product as a C-series, it is typically necessary to "reproject"
  575. the product onto said basis set, which typically produces
  576. "unintuitive live" (but correct) results; see Examples section below.
  577. Examples
  578. --------
  579. >>> from numpy.polynomial import chebyshev as C
  580. >>> c1 = (1,2,3)
  581. >>> c2 = (3,2,1)
  582. >>> C.chebmul(c1,c2) # multiplication requires "reprojection"
  583. array([ 6.5, 12. , 12. , 4. , 1.5])
  584. """
  585. # c1, c2 are trimmed copies
  586. [c1, c2] = pu.as_series([c1, c2])
  587. z1 = _cseries_to_zseries(c1)
  588. z2 = _cseries_to_zseries(c2)
  589. prd = _zseries_mul(z1, z2)
  590. ret = _zseries_to_cseries(prd)
  591. return pu.trimseq(ret)
  592. def chebdiv(c1, c2):
  593. """
  594. Divide one Chebyshev series by another.
  595. Returns the quotient-with-remainder of two Chebyshev series
  596. `c1` / `c2`. The arguments are sequences of coefficients from lowest
  597. order "term" to highest, e.g., [1,2,3] represents the series
  598. ``T_0 + 2*T_1 + 3*T_2``.
  599. Parameters
  600. ----------
  601. c1, c2 : array_like
  602. 1-D arrays of Chebyshev series coefficients ordered from low to
  603. high.
  604. Returns
  605. -------
  606. [quo, rem] : ndarrays
  607. Of Chebyshev series coefficients representing the quotient and
  608. remainder.
  609. See Also
  610. --------
  611. chebadd, chebsub, chebmulx, chebmul, chebpow
  612. Notes
  613. -----
  614. In general, the (polynomial) division of one C-series by another
  615. results in quotient and remainder terms that are not in the Chebyshev
  616. polynomial basis set. Thus, to express these results as C-series, it
  617. is typically necessary to "reproject" the results onto said basis
  618. set, which typically produces "unintuitive" (but correct) results;
  619. see Examples section below.
  620. Examples
  621. --------
  622. >>> from numpy.polynomial import chebyshev as C
  623. >>> c1 = (1,2,3)
  624. >>> c2 = (3,2,1)
  625. >>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not
  626. (array([3.]), array([-8., -4.]))
  627. >>> c2 = (0,1,2,3)
  628. >>> C.chebdiv(c2,c1) # neither "intuitive"
  629. (array([0., 2.]), array([-2., -4.]))
  630. """
  631. # c1, c2 are trimmed copies
  632. [c1, c2] = pu.as_series([c1, c2])
  633. if c2[-1] == 0:
  634. raise ZeroDivisionError()
  635. # note: this is more efficient than `pu._div(chebmul, c1, c2)`
  636. lc1 = len(c1)
  637. lc2 = len(c2)
  638. if lc1 < lc2:
  639. return c1[:1]*0, c1
  640. elif lc2 == 1:
  641. return c1/c2[-1], c1[:1]*0
  642. else:
  643. z1 = _cseries_to_zseries(c1)
  644. z2 = _cseries_to_zseries(c2)
  645. quo, rem = _zseries_div(z1, z2)
  646. quo = pu.trimseq(_zseries_to_cseries(quo))
  647. rem = pu.trimseq(_zseries_to_cseries(rem))
  648. return quo, rem
  649. def chebpow(c, pow, maxpower=16):
  650. """Raise a Chebyshev series to a power.
  651. Returns the Chebyshev series `c` raised to the power `pow`. The
  652. argument `c` is a sequence of coefficients ordered from low to high.
  653. i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.``
  654. Parameters
  655. ----------
  656. c : array_like
  657. 1-D array of Chebyshev series coefficients ordered from low to
  658. high.
  659. pow : integer
  660. Power to which the series will be raised
  661. maxpower : integer, optional
  662. Maximum power allowed. This is mainly to limit growth of the series
  663. to unmanageable size. Default is 16
  664. Returns
  665. -------
  666. coef : ndarray
  667. Chebyshev series of power.
  668. See Also
  669. --------
  670. chebadd, chebsub, chebmulx, chebmul, chebdiv
  671. Examples
  672. --------
  673. >>> from numpy.polynomial import chebyshev as C
  674. >>> C.chebpow([1, 2, 3, 4], 2)
  675. array([15.5, 22. , 16. , ..., 12.5, 12. , 8. ])
  676. """
  677. # note: this is more efficient than `pu._pow(chebmul, c1, c2)`, as it
  678. # avoids converting between z and c series repeatedly
  679. # c is a trimmed copy
  680. [c] = pu.as_series([c])
  681. power = int(pow)
  682. if power != pow or power < 0:
  683. raise ValueError("Power must be a non-negative integer.")
  684. elif maxpower is not None and power > maxpower:
  685. raise ValueError("Power is too large")
  686. elif power == 0:
  687. return np.array([1], dtype=c.dtype)
  688. elif power == 1:
  689. return c
  690. else:
  691. # This can be made more efficient by using powers of two
  692. # in the usual way.
  693. zs = _cseries_to_zseries(c)
  694. prd = zs
  695. for i in range(2, power + 1):
  696. prd = np.convolve(prd, zs)
  697. return _zseries_to_cseries(prd)
  698. def chebder(c, m=1, scl=1, axis=0):
  699. """
  700. Differentiate a Chebyshev series.
  701. Returns the Chebyshev series coefficients `c` differentiated `m` times
  702. along `axis`. At each iteration the result is multiplied by `scl` (the
  703. scaling factor is for use in a linear change of variable). The argument
  704. `c` is an array of coefficients from low to high degree along each
  705. axis, e.g., [1,2,3] represents the series ``1*T_0 + 2*T_1 + 3*T_2``
  706. while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) +
  707. 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is
  708. ``y``.
  709. Parameters
  710. ----------
  711. c : array_like
  712. Array of Chebyshev series coefficients. If c is multidimensional
  713. the different axis correspond to different variables with the
  714. degree in each axis given by the corresponding index.
  715. m : int, optional
  716. Number of derivatives taken, must be non-negative. (Default: 1)
  717. scl : scalar, optional
  718. Each differentiation is multiplied by `scl`. The end result is
  719. multiplication by ``scl**m``. This is for use in a linear change of
  720. variable. (Default: 1)
  721. axis : int, optional
  722. Axis over which the derivative is taken. (Default: 0).
  723. .. versionadded:: 1.7.0
  724. Returns
  725. -------
  726. der : ndarray
  727. Chebyshev series of the derivative.
  728. See Also
  729. --------
  730. chebint
  731. Notes
  732. -----
  733. In general, the result of differentiating a C-series needs to be
  734. "reprojected" onto the C-series basis set. Thus, typically, the
  735. result of this function is "unintuitive," albeit correct; see Examples
  736. section below.
  737. Examples
  738. --------
  739. >>> from numpy.polynomial import chebyshev as C
  740. >>> c = (1,2,3,4)
  741. >>> C.chebder(c)
  742. array([14., 12., 24.])
  743. >>> C.chebder(c,3)
  744. array([96.])
  745. >>> C.chebder(c,scl=-1)
  746. array([-14., -12., -24.])
  747. >>> C.chebder(c,2,-1)
  748. array([12., 96.])
  749. """
  750. c = np.array(c, ndmin=1, copy=True)
  751. if c.dtype.char in '?bBhHiIlLqQpP':
  752. c = c.astype(np.double)
  753. cnt = pu._deprecate_as_int(m, "the order of derivation")
  754. iaxis = pu._deprecate_as_int(axis, "the axis")
  755. if cnt < 0:
  756. raise ValueError("The order of derivation must be non-negative")
  757. iaxis = normalize_axis_index(iaxis, c.ndim)
  758. if cnt == 0:
  759. return c
  760. c = np.moveaxis(c, iaxis, 0)
  761. n = len(c)
  762. if cnt >= n:
  763. c = c[:1]*0
  764. else:
  765. for i in range(cnt):
  766. n = n - 1
  767. c *= scl
  768. der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
  769. for j in range(n, 2, -1):
  770. der[j - 1] = (2*j)*c[j]
  771. c[j - 2] += (j*c[j])/(j - 2)
  772. if n > 1:
  773. der[1] = 4*c[2]
  774. der[0] = c[1]
  775. c = der
  776. c = np.moveaxis(c, 0, iaxis)
  777. return c
  778. def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
  779. """
  780. Integrate a Chebyshev series.
  781. Returns the Chebyshev series coefficients `c` integrated `m` times from
  782. `lbnd` along `axis`. At each iteration the resulting series is
  783. **multiplied** by `scl` and an integration constant, `k`, is added.
  784. The scaling factor is for use in a linear change of variable. ("Buyer
  785. beware": note that, depending on what one is doing, one may want `scl`
  786. to be the reciprocal of what one might expect; for more information,
  787. see the Notes section below.) The argument `c` is an array of
  788. coefficients from low to high degree along each axis, e.g., [1,2,3]
  789. represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]]
  790. represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) +
  791. 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
  792. Parameters
  793. ----------
  794. c : array_like
  795. Array of Chebyshev series coefficients. If c is multidimensional
  796. the different axis correspond to different variables with the
  797. degree in each axis given by the corresponding index.
  798. m : int, optional
  799. Order of integration, must be positive. (Default: 1)
  800. k : {[], list, scalar}, optional
  801. Integration constant(s). The value of the first integral at zero
  802. is the first value in the list, the value of the second integral
  803. at zero is the second value, etc. If ``k == []`` (the default),
  804. all constants are set to zero. If ``m == 1``, a single scalar can
  805. be given instead of a list.
  806. lbnd : scalar, optional
  807. The lower bound of the integral. (Default: 0)
  808. scl : scalar, optional
  809. Following each integration the result is *multiplied* by `scl`
  810. before the integration constant is added. (Default: 1)
  811. axis : int, optional
  812. Axis over which the integral is taken. (Default: 0).
  813. .. versionadded:: 1.7.0
  814. Returns
  815. -------
  816. S : ndarray
  817. C-series coefficients of the integral.
  818. Raises
  819. ------
  820. ValueError
  821. If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
  822. ``np.ndim(scl) != 0``.
  823. See Also
  824. --------
  825. chebder
  826. Notes
  827. -----
  828. Note that the result of each integration is *multiplied* by `scl`.
  829. Why is this important to note? Say one is making a linear change of
  830. variable :math:`u = ax + b` in an integral relative to `x`. Then
  831. :math:`dx = du/a`, so one will need to set `scl` equal to
  832. :math:`1/a`- perhaps not what one would have first thought.
  833. Also note that, in general, the result of integrating a C-series needs
  834. to be "reprojected" onto the C-series basis set. Thus, typically,
  835. the result of this function is "unintuitive," albeit correct; see
  836. Examples section below.
  837. Examples
  838. --------
  839. >>> from numpy.polynomial import chebyshev as C
  840. >>> c = (1,2,3)
  841. >>> C.chebint(c)
  842. array([ 0.5, -0.5, 0.5, 0.5])
  843. >>> C.chebint(c,3)
  844. array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, # may vary
  845. 0.00625 ])
  846. >>> C.chebint(c, k=3)
  847. array([ 3.5, -0.5, 0.5, 0.5])
  848. >>> C.chebint(c,lbnd=-2)
  849. array([ 8.5, -0.5, 0.5, 0.5])
  850. >>> C.chebint(c,scl=-2)
  851. array([-1., 1., -1., -1.])
  852. """
  853. c = np.array(c, ndmin=1, copy=True)
  854. if c.dtype.char in '?bBhHiIlLqQpP':
  855. c = c.astype(np.double)
  856. if not np.iterable(k):
  857. k = [k]
  858. cnt = pu._deprecate_as_int(m, "the order of integration")
  859. iaxis = pu._deprecate_as_int(axis, "the axis")
  860. if cnt < 0:
  861. raise ValueError("The order of integration must be non-negative")
  862. if len(k) > cnt:
  863. raise ValueError("Too many integration constants")
  864. if np.ndim(lbnd) != 0:
  865. raise ValueError("lbnd must be a scalar.")
  866. if np.ndim(scl) != 0:
  867. raise ValueError("scl must be a scalar.")
  868. iaxis = normalize_axis_index(iaxis, c.ndim)
  869. if cnt == 0:
  870. return c
  871. c = np.moveaxis(c, iaxis, 0)
  872. k = list(k) + [0]*(cnt - len(k))
  873. for i in range(cnt):
  874. n = len(c)
  875. c *= scl
  876. if n == 1 and np.all(c[0] == 0):
  877. c[0] += k[i]
  878. else:
  879. tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
  880. tmp[0] = c[0]*0
  881. tmp[1] = c[0]
  882. if n > 1:
  883. tmp[2] = c[1]/4
  884. for j in range(2, n):
  885. tmp[j + 1] = c[j]/(2*(j + 1))
  886. tmp[j - 1] -= c[j]/(2*(j - 1))
  887. tmp[0] += k[i] - chebval(lbnd, tmp)
  888. c = tmp
  889. c = np.moveaxis(c, 0, iaxis)
  890. return c
  891. def chebval(x, c, tensor=True):
  892. """
  893. Evaluate a Chebyshev series at points x.
  894. If `c` is of length `n + 1`, this function returns the value:
  895. .. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x)
  896. The parameter `x` is converted to an array only if it is a tuple or a
  897. list, otherwise it is treated as a scalar. In either case, either `x`
  898. or its elements must support multiplication and addition both with
  899. themselves and with the elements of `c`.
  900. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
  901. `c` is multidimensional, then the shape of the result depends on the
  902. value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
  903. x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
  904. scalars have shape (,).
  905. Trailing zeros in the coefficients will be used in the evaluation, so
  906. they should be avoided if efficiency is a concern.
  907. Parameters
  908. ----------
  909. x : array_like, compatible object
  910. If `x` is a list or tuple, it is converted to an ndarray, otherwise
  911. it is left unchanged and treated as a scalar. In either case, `x`
  912. or its elements must support addition and multiplication with
  913. with themselves and with the elements of `c`.
  914. c : array_like
  915. Array of coefficients ordered so that the coefficients for terms of
  916. degree n are contained in c[n]. If `c` is multidimensional the
  917. remaining indices enumerate multiple polynomials. In the two
  918. dimensional case the coefficients may be thought of as stored in
  919. the columns of `c`.
  920. tensor : boolean, optional
  921. If True, the shape of the coefficient array is extended with ones
  922. on the right, one for each dimension of `x`. Scalars have dimension 0
  923. for this action. The result is that every column of coefficients in
  924. `c` is evaluated for every element of `x`. If False, `x` is broadcast
  925. over the columns of `c` for the evaluation. This keyword is useful
  926. when `c` is multidimensional. The default value is True.
  927. .. versionadded:: 1.7.0
  928. Returns
  929. -------
  930. values : ndarray, algebra_like
  931. The shape of the return value is described above.
  932. See Also
  933. --------
  934. chebval2d, chebgrid2d, chebval3d, chebgrid3d
  935. Notes
  936. -----
  937. The evaluation uses Clenshaw recursion, aka synthetic division.
  938. Examples
  939. --------
  940. """
  941. c = np.array(c, ndmin=1, copy=True)
  942. if c.dtype.char in '?bBhHiIlLqQpP':
  943. c = c.astype(np.double)
  944. if isinstance(x, (tuple, list)):
  945. x = np.asarray(x)
  946. if isinstance(x, np.ndarray) and tensor:
  947. c = c.reshape(c.shape + (1,)*x.ndim)
  948. if len(c) == 1:
  949. c0 = c[0]
  950. c1 = 0
  951. elif len(c) == 2:
  952. c0 = c[0]
  953. c1 = c[1]
  954. else:
  955. x2 = 2*x
  956. c0 = c[-2]
  957. c1 = c[-1]
  958. for i in range(3, len(c) + 1):
  959. tmp = c0
  960. c0 = c[-i] - c1
  961. c1 = tmp + c1*x2
  962. return c0 + c1*x
  963. def chebval2d(x, y, c):
  964. """
  965. Evaluate a 2-D Chebyshev series at points (x, y).
  966. This function returns the values:
  967. .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y)
  968. The parameters `x` and `y` are converted to arrays only if they are
  969. tuples or a lists, otherwise they are treated as a scalars and they
  970. must have the same shape after conversion. In either case, either `x`
  971. and `y` or their elements must support multiplication and addition both
  972. with themselves and with the elements of `c`.
  973. If `c` is a 1-D array a one is implicitly appended to its shape to make
  974. it 2-D. The shape of the result will be c.shape[2:] + x.shape.
  975. Parameters
  976. ----------
  977. x, y : array_like, compatible objects
  978. The two dimensional series is evaluated at the points `(x, y)`,
  979. where `x` and `y` must have the same shape. If `x` or `y` is a list
  980. or tuple, it is first converted to an ndarray, otherwise it is left
  981. unchanged and if it isn't an ndarray it is treated as a scalar.
  982. c : array_like
  983. Array of coefficients ordered so that the coefficient of the term
  984. of multi-degree i,j is contained in ``c[i,j]``. If `c` has
  985. dimension greater than 2 the remaining indices enumerate multiple
  986. sets of coefficients.
  987. Returns
  988. -------
  989. values : ndarray, compatible object
  990. The values of the two dimensional Chebyshev series at points formed
  991. from pairs of corresponding values from `x` and `y`.
  992. See Also
  993. --------
  994. chebval, chebgrid2d, chebval3d, chebgrid3d
  995. Notes
  996. -----
  997. .. versionadded:: 1.7.0
  998. """
  999. return pu._valnd(chebval, c, x, y)
  1000. def chebgrid2d(x, y, c):
  1001. """
  1002. Evaluate a 2-D Chebyshev series on the Cartesian product of x and y.
  1003. This function returns the values:
  1004. .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * T_i(a) * T_j(b),
  1005. where the points `(a, b)` consist of all pairs formed by taking
  1006. `a` from `x` and `b` from `y`. The resulting points form a grid with
  1007. `x` in the first dimension and `y` in the second.
  1008. The parameters `x` and `y` are converted to arrays only if they are
  1009. tuples or a lists, otherwise they are treated as a scalars. In either
  1010. case, either `x` and `y` or their elements must support multiplication
  1011. and addition both with themselves and with the elements of `c`.
  1012. If `c` has fewer than two dimensions, ones are implicitly appended to
  1013. its shape to make it 2-D. The shape of the result will be c.shape[2:] +
  1014. x.shape + y.shape.
  1015. Parameters
  1016. ----------
  1017. x, y : array_like, compatible objects
  1018. The two dimensional series is evaluated at the points in the
  1019. Cartesian product of `x` and `y`. If `x` or `y` is a list or
  1020. tuple, it is first converted to an ndarray, otherwise it is left
  1021. unchanged and, if it isn't an ndarray, it is treated as a scalar.
  1022. c : array_like
  1023. Array of coefficients ordered so that the coefficient of the term of
  1024. multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
  1025. greater than two the remaining indices enumerate multiple sets of
  1026. coefficients.
  1027. Returns
  1028. -------
  1029. values : ndarray, compatible object
  1030. The values of the two dimensional Chebyshev series at points in the
  1031. Cartesian product of `x` and `y`.
  1032. See Also
  1033. --------
  1034. chebval, chebval2d, chebval3d, chebgrid3d
  1035. Notes
  1036. -----
  1037. .. versionadded:: 1.7.0
  1038. """
  1039. return pu._gridnd(chebval, c, x, y)
  1040. def chebval3d(x, y, z, c):
  1041. """
  1042. Evaluate a 3-D Chebyshev series at points (x, y, z).
  1043. This function returns the values:
  1044. .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z)
  1045. The parameters `x`, `y`, and `z` are converted to arrays only if
  1046. they are tuples or a lists, otherwise they are treated as a scalars and
  1047. they must have the same shape after conversion. In either case, either
  1048. `x`, `y`, and `z` or their elements must support multiplication and
  1049. addition both with themselves and with the elements of `c`.
  1050. If `c` has fewer than 3 dimensions, ones are implicitly appended to its
  1051. shape to make it 3-D. The shape of the result will be c.shape[3:] +
  1052. x.shape.
  1053. Parameters
  1054. ----------
  1055. x, y, z : array_like, compatible object
  1056. The three dimensional series is evaluated at the points
  1057. `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
  1058. any of `x`, `y`, or `z` is a list or tuple, it is first converted
  1059. to an ndarray, otherwise it is left unchanged and if it isn't an
  1060. ndarray it is treated as a scalar.
  1061. c : array_like
  1062. Array of coefficients ordered so that the coefficient of the term of
  1063. multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
  1064. greater than 3 the remaining indices enumerate multiple sets of
  1065. coefficients.
  1066. Returns
  1067. -------
  1068. values : ndarray, compatible object
  1069. The values of the multidimensional polynomial on points formed with
  1070. triples of corresponding values from `x`, `y`, and `z`.
  1071. See Also
  1072. --------
  1073. chebval, chebval2d, chebgrid2d, chebgrid3d
  1074. Notes
  1075. -----
  1076. .. versionadded:: 1.7.0
  1077. """
  1078. return pu._valnd(chebval, c, x, y, z)
  1079. def chebgrid3d(x, y, z, c):
  1080. """
  1081. Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.
  1082. This function returns the values:
  1083. .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)
  1084. where the points `(a, b, c)` consist of all triples formed by taking
  1085. `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
  1086. a grid with `x` in the first dimension, `y` in the second, and `z` in
  1087. the third.
  1088. The parameters `x`, `y`, and `z` are converted to arrays only if they
  1089. are tuples or a lists, otherwise they are treated as a scalars. In
  1090. either case, either `x`, `y`, and `z` or their elements must support
  1091. multiplication and addition both with themselves and with the elements
  1092. of `c`.
  1093. If `c` has fewer than three dimensions, ones are implicitly appended to
  1094. its shape to make it 3-D. The shape of the result will be c.shape[3:] +
  1095. x.shape + y.shape + z.shape.
  1096. Parameters
  1097. ----------
  1098. x, y, z : array_like, compatible objects
  1099. The three dimensional series is evaluated at the points in the
  1100. Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
  1101. list or tuple, it is first converted to an ndarray, otherwise it is
  1102. left unchanged and, if it isn't an ndarray, it is treated as a
  1103. scalar.
  1104. c : array_like
  1105. Array of coefficients ordered so that the coefficients for terms of
  1106. degree i,j are contained in ``c[i,j]``. If `c` has dimension
  1107. greater than two the remaining indices enumerate multiple sets of
  1108. coefficients.
  1109. Returns
  1110. -------
  1111. values : ndarray, compatible object
  1112. The values of the two dimensional polynomial at points in the Cartesian
  1113. product of `x` and `y`.
  1114. See Also
  1115. --------
  1116. chebval, chebval2d, chebgrid2d, chebval3d
  1117. Notes
  1118. -----
  1119. .. versionadded:: 1.7.0
  1120. """
  1121. return pu._gridnd(chebval, c, x, y, z)
  1122. def chebvander(x, deg):
  1123. """Pseudo-Vandermonde matrix of given degree.
  1124. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
  1125. `x`. The pseudo-Vandermonde matrix is defined by
  1126. .. math:: V[..., i] = T_i(x),
  1127. where `0 <= i <= deg`. The leading indices of `V` index the elements of
  1128. `x` and the last index is the degree of the Chebyshev polynomial.
  1129. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
  1130. matrix ``V = chebvander(x, n)``, then ``np.dot(V, c)`` and
  1131. ``chebval(x, c)`` are the same up to roundoff. This equivalence is
  1132. useful both for least squares fitting and for the evaluation of a large
  1133. number of Chebyshev series of the same degree and sample points.
  1134. Parameters
  1135. ----------
  1136. x : array_like
  1137. Array of points. The dtype is converted to float64 or complex128
  1138. depending on whether any of the elements are complex. If `x` is
  1139. scalar it is converted to a 1-D array.
  1140. deg : int
  1141. Degree of the resulting matrix.
  1142. Returns
  1143. -------
  1144. vander : ndarray
  1145. The pseudo Vandermonde matrix. The shape of the returned matrix is
  1146. ``x.shape + (deg + 1,)``, where The last index is the degree of the
  1147. corresponding Chebyshev polynomial. The dtype will be the same as
  1148. the converted `x`.
  1149. """
  1150. ideg = pu._deprecate_as_int(deg, "deg")
  1151. if ideg < 0:
  1152. raise ValueError("deg must be non-negative")
  1153. x = np.array(x, copy=False, ndmin=1) + 0.0
  1154. dims = (ideg + 1,) + x.shape
  1155. dtyp = x.dtype
  1156. v = np.empty(dims, dtype=dtyp)
  1157. # Use forward recursion to generate the entries.
  1158. v[0] = x*0 + 1
  1159. if ideg > 0:
  1160. x2 = 2*x
  1161. v[1] = x
  1162. for i in range(2, ideg + 1):
  1163. v[i] = v[i-1]*x2 - v[i-2]
  1164. return np.moveaxis(v, 0, -1)
  1165. def chebvander2d(x, y, deg):
  1166. """Pseudo-Vandermonde matrix of given degrees.
  1167. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  1168. points `(x, y)`. The pseudo-Vandermonde matrix is defined by
  1169. .. math:: V[..., (deg[1] + 1)*i + j] = T_i(x) * T_j(y),
  1170. where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
  1171. `V` index the points `(x, y)` and the last index encodes the degrees of
  1172. the Chebyshev polynomials.
  1173. If ``V = chebvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
  1174. correspond to the elements of a 2-D coefficient array `c` of shape
  1175. (xdeg + 1, ydeg + 1) in the order
  1176. .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
  1177. and ``np.dot(V, c.flat)`` and ``chebval2d(x, y, c)`` will be the same
  1178. up to roundoff. This equivalence is useful both for least squares
  1179. fitting and for the evaluation of a large number of 2-D Chebyshev
  1180. series of the same degrees and sample points.
  1181. Parameters
  1182. ----------
  1183. x, y : array_like
  1184. Arrays of point coordinates, all of the same shape. The dtypes
  1185. will be converted to either float64 or complex128 depending on
  1186. whether any of the elements are complex. Scalars are converted to
  1187. 1-D arrays.
  1188. deg : list of ints
  1189. List of maximum degrees of the form [x_deg, y_deg].
  1190. Returns
  1191. -------
  1192. vander2d : ndarray
  1193. The shape of the returned matrix is ``x.shape + (order,)``, where
  1194. :math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same
  1195. as the converted `x` and `y`.
  1196. See Also
  1197. --------
  1198. chebvander, chebvander3d, chebval2d, chebval3d
  1199. Notes
  1200. -----
  1201. .. versionadded:: 1.7.0
  1202. """
  1203. return pu._vander_nd_flat((chebvander, chebvander), (x, y), deg)
  1204. def chebvander3d(x, y, z, deg):
  1205. """Pseudo-Vandermonde matrix of given degrees.
  1206. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
  1207. points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
  1208. then The pseudo-Vandermonde matrix is defined by
  1209. .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z),
  1210. where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
  1211. indices of `V` index the points `(x, y, z)` and the last index encodes
  1212. the degrees of the Chebyshev polynomials.
  1213. If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
  1214. of `V` correspond to the elements of a 3-D coefficient array `c` of
  1215. shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
  1216. .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
  1217. and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be the
  1218. same up to roundoff. This equivalence is useful both for least squares
  1219. fitting and for the evaluation of a large number of 3-D Chebyshev
  1220. series of the same degrees and sample points.
  1221. Parameters
  1222. ----------
  1223. x, y, z : array_like
  1224. Arrays of point coordinates, all of the same shape. The dtypes will
  1225. be converted to either float64 or complex128 depending on whether
  1226. any of the elements are complex. Scalars are converted to 1-D
  1227. arrays.
  1228. deg : list of ints
  1229. List of maximum degrees of the form [x_deg, y_deg, z_deg].
  1230. Returns
  1231. -------
  1232. vander3d : ndarray
  1233. The shape of the returned matrix is ``x.shape + (order,)``, where
  1234. :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will
  1235. be the same as the converted `x`, `y`, and `z`.
  1236. See Also
  1237. --------
  1238. chebvander, chebvander3d, chebval2d, chebval3d
  1239. Notes
  1240. -----
  1241. .. versionadded:: 1.7.0
  1242. """
  1243. return pu._vander_nd_flat((chebvander, chebvander, chebvander), (x, y, z), deg)
  1244. def chebfit(x, y, deg, rcond=None, full=False, w=None):
  1245. """
  1246. Least squares fit of Chebyshev series to data.
  1247. Return the coefficients of a Chebyshev series of degree `deg` that is the
  1248. least squares fit to the data values `y` given at points `x`. If `y` is
  1249. 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
  1250. fits are done, one for each column of `y`, and the resulting
  1251. coefficients are stored in the corresponding columns of a 2-D return.
  1252. The fitted polynomial(s) are in the form
  1253. .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x),
  1254. where `n` is `deg`.
  1255. Parameters
  1256. ----------
  1257. x : array_like, shape (M,)
  1258. x-coordinates of the M sample points ``(x[i], y[i])``.
  1259. y : array_like, shape (M,) or (M, K)
  1260. y-coordinates of the sample points. Several data sets of sample
  1261. points sharing the same x-coordinates can be fitted at once by
  1262. passing in a 2D-array that contains one dataset per column.
  1263. deg : int or 1-D array_like
  1264. Degree(s) of the fitting polynomials. If `deg` is a single integer,
  1265. all terms up to and including the `deg`'th term are included in the
  1266. fit. For NumPy versions >= 1.11.0 a list of integers specifying the
  1267. degrees of the terms to include may be used instead.
  1268. rcond : float, optional
  1269. Relative condition number of the fit. Singular values smaller than
  1270. this relative to the largest singular value will be ignored. The
  1271. default value is len(x)*eps, where eps is the relative precision of
  1272. the float type, about 2e-16 in most cases.
  1273. full : bool, optional
  1274. Switch determining nature of return value. When it is False (the
  1275. default) just the coefficients are returned, when True diagnostic
  1276. information from the singular value decomposition is also returned.
  1277. w : array_like, shape (`M`,), optional
  1278. Weights. If not None, the contribution of each point
  1279. ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
  1280. weights are chosen so that the errors of the products ``w[i]*y[i]``
  1281. all have the same variance. The default value is None.
  1282. .. versionadded:: 1.5.0
  1283. Returns
  1284. -------
  1285. coef : ndarray, shape (M,) or (M, K)
  1286. Chebyshev coefficients ordered from low to high. If `y` was 2-D,
  1287. the coefficients for the data in column k of `y` are in column
  1288. `k`.
  1289. [residuals, rank, singular_values, rcond] : list
  1290. These values are only returned if `full` = True
  1291. resid -- sum of squared residuals of the least squares fit
  1292. rank -- the numerical rank of the scaled Vandermonde matrix
  1293. sv -- singular values of the scaled Vandermonde matrix
  1294. rcond -- value of `rcond`.
  1295. For more details, see `numpy.linalg.lstsq`.
  1296. Warns
  1297. -----
  1298. RankWarning
  1299. The rank of the coefficient matrix in the least-squares fit is
  1300. deficient. The warning is only raised if `full` = False. The
  1301. warnings can be turned off by
  1302. >>> import warnings
  1303. >>> warnings.simplefilter('ignore', np.RankWarning)
  1304. See Also
  1305. --------
  1306. numpy.polynomial.polynomial.polyfit
  1307. numpy.polynomial.legendre.legfit
  1308. numpy.polynomial.laguerre.lagfit
  1309. numpy.polynomial.hermite.hermfit
  1310. numpy.polynomial.hermite_e.hermefit
  1311. chebval : Evaluates a Chebyshev series.
  1312. chebvander : Vandermonde matrix of Chebyshev series.
  1313. chebweight : Chebyshev weight function.
  1314. numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
  1315. scipy.interpolate.UnivariateSpline : Computes spline fits.
  1316. Notes
  1317. -----
  1318. The solution is the coefficients of the Chebyshev series `p` that
  1319. minimizes the sum of the weighted squared errors
  1320. .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
  1321. where :math:`w_j` are the weights. This problem is solved by setting up
  1322. as the (typically) overdetermined matrix equation
  1323. .. math:: V(x) * c = w * y,
  1324. where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
  1325. coefficients to be solved for, `w` are the weights, and `y` are the
  1326. observed values. This equation is then solved using the singular value
  1327. decomposition of `V`.
  1328. If some of the singular values of `V` are so small that they are
  1329. neglected, then a `RankWarning` will be issued. This means that the
  1330. coefficient values may be poorly determined. Using a lower order fit
  1331. will usually get rid of the warning. The `rcond` parameter can also be
  1332. set to a value smaller than its default, but the resulting fit may be
  1333. spurious and have large contributions from roundoff error.
  1334. Fits using Chebyshev series are usually better conditioned than fits
  1335. using power series, but much can depend on the distribution of the
  1336. sample points and the smoothness of the data. If the quality of the fit
  1337. is inadequate splines may be a good alternative.
  1338. References
  1339. ----------
  1340. .. [1] Wikipedia, "Curve fitting",
  1341. https://en.wikipedia.org/wiki/Curve_fitting
  1342. Examples
  1343. --------
  1344. """
  1345. return pu._fit(chebvander, x, y, deg, rcond, full, w)
  1346. def chebcompanion(c):
  1347. """Return the scaled companion matrix of c.
  1348. The basis polynomials are scaled so that the companion matrix is
  1349. symmetric when `c` is a Chebyshev basis polynomial. This provides
  1350. better eigenvalue estimates than the unscaled case and for basis
  1351. polynomials the eigenvalues are guaranteed to be real if
  1352. `numpy.linalg.eigvalsh` is used to obtain them.
  1353. Parameters
  1354. ----------
  1355. c : array_like
  1356. 1-D array of Chebyshev series coefficients ordered from low to high
  1357. degree.
  1358. Returns
  1359. -------
  1360. mat : ndarray
  1361. Scaled companion matrix of dimensions (deg, deg).
  1362. Notes
  1363. -----
  1364. .. versionadded:: 1.7.0
  1365. """
  1366. # c is a trimmed copy
  1367. [c] = pu.as_series([c])
  1368. if len(c) < 2:
  1369. raise ValueError('Series must have maximum degree of at least 1.')
  1370. if len(c) == 2:
  1371. return np.array([[-c[0]/c[1]]])
  1372. n = len(c) - 1
  1373. mat = np.zeros((n, n), dtype=c.dtype)
  1374. scl = np.array([1.] + [np.sqrt(.5)]*(n-1))
  1375. top = mat.reshape(-1)[1::n+1]
  1376. bot = mat.reshape(-1)[n::n+1]
  1377. top[0] = np.sqrt(.5)
  1378. top[1:] = 1/2
  1379. bot[...] = top
  1380. mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5
  1381. return mat
  1382. def chebroots(c):
  1383. """
  1384. Compute the roots of a Chebyshev series.
  1385. Return the roots (a.k.a. "zeros") of the polynomial
  1386. .. math:: p(x) = \\sum_i c[i] * T_i(x).
  1387. Parameters
  1388. ----------
  1389. c : 1-D array_like
  1390. 1-D array of coefficients.
  1391. Returns
  1392. -------
  1393. out : ndarray
  1394. Array of the roots of the series. If all the roots are real,
  1395. then `out` is also real, otherwise it is complex.
  1396. See Also
  1397. --------
  1398. numpy.polynomial.polynomial.polyroots
  1399. numpy.polynomial.legendre.legroots
  1400. numpy.polynomial.laguerre.lagroots
  1401. numpy.polynomial.hermite.hermroots
  1402. numpy.polynomial.hermite_e.hermeroots
  1403. Notes
  1404. -----
  1405. The root estimates are obtained as the eigenvalues of the companion
  1406. matrix, Roots far from the origin of the complex plane may have large
  1407. errors due to the numerical instability of the series for such
  1408. values. Roots with multiplicity greater than 1 will also show larger
  1409. errors as the value of the series near such points is relatively
  1410. insensitive to errors in the roots. Isolated roots near the origin can
  1411. be improved by a few iterations of Newton's method.
  1412. The Chebyshev series basis polynomials aren't powers of `x` so the
  1413. results of this function may seem unintuitive.
  1414. Examples
  1415. --------
  1416. >>> import numpy.polynomial.chebyshev as cheb
  1417. >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots
  1418. array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) # may vary
  1419. """
  1420. # c is a trimmed copy
  1421. [c] = pu.as_series([c])
  1422. if len(c) < 2:
  1423. return np.array([], dtype=c.dtype)
  1424. if len(c) == 2:
  1425. return np.array([-c[0]/c[1]])
  1426. # rotated companion matrix reduces error
  1427. m = chebcompanion(c)[::-1,::-1]
  1428. r = la.eigvals(m)
  1429. r.sort()
  1430. return r
  1431. def chebinterpolate(func, deg, args=()):
  1432. """Interpolate a function at the Chebyshev points of the first kind.
  1433. Returns the Chebyshev series that interpolates `func` at the Chebyshev
  1434. points of the first kind in the interval [-1, 1]. The interpolating
  1435. series tends to a minmax approximation to `func` with increasing `deg`
  1436. if the function is continuous in the interval.
  1437. .. versionadded:: 1.14.0
  1438. Parameters
  1439. ----------
  1440. func : function
  1441. The function to be approximated. It must be a function of a single
  1442. variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
  1443. extra arguments passed in the `args` parameter.
  1444. deg : int
  1445. Degree of the interpolating polynomial
  1446. args : tuple, optional
  1447. Extra arguments to be used in the function call. Default is no extra
  1448. arguments.
  1449. Returns
  1450. -------
  1451. coef : ndarray, shape (deg + 1,)
  1452. Chebyshev coefficients of the interpolating series ordered from low to
  1453. high.
  1454. Examples
  1455. --------
  1456. >>> import numpy.polynomial.chebyshev as C
  1457. >>> C.chebfromfunction(lambda x: np.tanh(x) + 0.5, 8)
  1458. array([ 5.00000000e-01, 8.11675684e-01, -9.86864911e-17,
  1459. -5.42457905e-02, -2.71387850e-16, 4.51658839e-03,
  1460. 2.46716228e-17, -3.79694221e-04, -3.26899002e-16])
  1461. Notes
  1462. -----
  1463. The Chebyshev polynomials used in the interpolation are orthogonal when
  1464. sampled at the Chebyshev points of the first kind. If it is desired to
  1465. constrain some of the coefficients they can simply be set to the desired
  1466. value after the interpolation, no new interpolation or fit is needed. This
  1467. is especially useful if it is known apriori that some of coefficients are
  1468. zero. For instance, if the function is even then the coefficients of the
  1469. terms of odd degree in the result can be set to zero.
  1470. """
  1471. deg = np.asarray(deg)
  1472. # check arguments.
  1473. if deg.ndim > 0 or deg.dtype.kind not in 'iu' or deg.size == 0:
  1474. raise TypeError("deg must be an int")
  1475. if deg < 0:
  1476. raise ValueError("expected deg >= 0")
  1477. order = deg + 1
  1478. xcheb = chebpts1(order)
  1479. yfunc = func(xcheb, *args)
  1480. m = chebvander(xcheb, deg)
  1481. c = np.dot(m.T, yfunc)
  1482. c[0] /= order
  1483. c[1:] /= 0.5*order
  1484. return c
  1485. def chebgauss(deg):
  1486. """
  1487. Gauss-Chebyshev quadrature.
  1488. Computes the sample points and weights for Gauss-Chebyshev quadrature.
  1489. These sample points and weights will correctly integrate polynomials of
  1490. degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
  1491. the weight function :math:`f(x) = 1/\\sqrt{1 - x^2}`.
  1492. Parameters
  1493. ----------
  1494. deg : int
  1495. Number of sample points and weights. It must be >= 1.
  1496. Returns
  1497. -------
  1498. x : ndarray
  1499. 1-D ndarray containing the sample points.
  1500. y : ndarray
  1501. 1-D ndarray containing the weights.
  1502. Notes
  1503. -----
  1504. .. versionadded:: 1.7.0
  1505. The results have only been tested up to degree 100, higher degrees may
  1506. be problematic. For Gauss-Chebyshev there are closed form solutions for
  1507. the sample points and weights. If n = `deg`, then
  1508. .. math:: x_i = \\cos(\\pi (2 i - 1) / (2 n))
  1509. .. math:: w_i = \\pi / n
  1510. """
  1511. ideg = pu._deprecate_as_int(deg, "deg")
  1512. if ideg <= 0:
  1513. raise ValueError("deg must be a positive integer")
  1514. x = np.cos(np.pi * np.arange(1, 2*ideg, 2) / (2.0*ideg))
  1515. w = np.ones(ideg)*(np.pi/ideg)
  1516. return x, w
  1517. def chebweight(x):
  1518. """
  1519. The weight function of the Chebyshev polynomials.
  1520. The weight function is :math:`1/\\sqrt{1 - x^2}` and the interval of
  1521. integration is :math:`[-1, 1]`. The Chebyshev polynomials are
  1522. orthogonal, but not normalized, with respect to this weight function.
  1523. Parameters
  1524. ----------
  1525. x : array_like
  1526. Values at which the weight function will be computed.
  1527. Returns
  1528. -------
  1529. w : ndarray
  1530. The weight function at `x`.
  1531. Notes
  1532. -----
  1533. .. versionadded:: 1.7.0
  1534. """
  1535. w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x))
  1536. return w
  1537. def chebpts1(npts):
  1538. """
  1539. Chebyshev points of the first kind.
  1540. The Chebyshev points of the first kind are the points ``cos(x)``,
  1541. where ``x = [pi*(k + .5)/npts for k in range(npts)]``.
  1542. Parameters
  1543. ----------
  1544. npts : int
  1545. Number of sample points desired.
  1546. Returns
  1547. -------
  1548. pts : ndarray
  1549. The Chebyshev points of the first kind.
  1550. See Also
  1551. --------
  1552. chebpts2
  1553. Notes
  1554. -----
  1555. .. versionadded:: 1.5.0
  1556. """
  1557. _npts = int(npts)
  1558. if _npts != npts:
  1559. raise ValueError("npts must be integer")
  1560. if _npts < 1:
  1561. raise ValueError("npts must be >= 1")
  1562. x = np.linspace(-np.pi, 0, _npts, endpoint=False) + np.pi/(2*_npts)
  1563. return np.cos(x)
  1564. def chebpts2(npts):
  1565. """
  1566. Chebyshev points of the second kind.
  1567. The Chebyshev points of the second kind are the points ``cos(x)``,
  1568. where ``x = [pi*k/(npts - 1) for k in range(npts)]``.
  1569. Parameters
  1570. ----------
  1571. npts : int
  1572. Number of sample points desired.
  1573. Returns
  1574. -------
  1575. pts : ndarray
  1576. The Chebyshev points of the second kind.
  1577. Notes
  1578. -----
  1579. .. versionadded:: 1.5.0
  1580. """
  1581. _npts = int(npts)
  1582. if _npts != npts:
  1583. raise ValueError("npts must be integer")
  1584. if _npts < 2:
  1585. raise ValueError("npts must be >= 2")
  1586. x = np.linspace(-np.pi, 0, _npts)
  1587. return np.cos(x)
  1588. #
  1589. # Chebyshev series class
  1590. #
  1591. class Chebyshev(ABCPolyBase):
  1592. """A Chebyshev series class.
  1593. The Chebyshev class provides the standard Python numerical methods
  1594. '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
  1595. methods listed below.
  1596. Parameters
  1597. ----------
  1598. coef : array_like
  1599. Chebyshev coefficients in order of increasing degree, i.e.,
  1600. ``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``.
  1601. domain : (2,) array_like, optional
  1602. Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
  1603. to the interval ``[window[0], window[1]]`` by shifting and scaling.
  1604. The default value is [-1, 1].
  1605. window : (2,) array_like, optional
  1606. Window, see `domain` for its use. The default value is [-1, 1].
  1607. .. versionadded:: 1.6.0
  1608. """
  1609. # Virtual Functions
  1610. _add = staticmethod(chebadd)
  1611. _sub = staticmethod(chebsub)
  1612. _mul = staticmethod(chebmul)
  1613. _div = staticmethod(chebdiv)
  1614. _pow = staticmethod(chebpow)
  1615. _val = staticmethod(chebval)
  1616. _int = staticmethod(chebint)
  1617. _der = staticmethod(chebder)
  1618. _fit = staticmethod(chebfit)
  1619. _line = staticmethod(chebline)
  1620. _roots = staticmethod(chebroots)
  1621. _fromroots = staticmethod(chebfromroots)
  1622. @classmethod
  1623. def interpolate(cls, func, deg, domain=None, args=()):
  1624. """Interpolate a function at the Chebyshev points of the first kind.
  1625. Returns the series that interpolates `func` at the Chebyshev points of
  1626. the first kind scaled and shifted to the `domain`. The resulting series
  1627. tends to a minmax approximation of `func` when the function is
  1628. continuous in the domain.
  1629. .. versionadded:: 1.14.0
  1630. Parameters
  1631. ----------
  1632. func : function
  1633. The function to be interpolated. It must be a function of a single
  1634. variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
  1635. extra arguments passed in the `args` parameter.
  1636. deg : int
  1637. Degree of the interpolating polynomial.
  1638. domain : {None, [beg, end]}, optional
  1639. Domain over which `func` is interpolated. The default is None, in
  1640. which case the domain is [-1, 1].
  1641. args : tuple, optional
  1642. Extra arguments to be used in the function call. Default is no
  1643. extra arguments.
  1644. Returns
  1645. -------
  1646. polynomial : Chebyshev instance
  1647. Interpolating Chebyshev instance.
  1648. Notes
  1649. -----
  1650. See `numpy.polynomial.chebfromfunction` for more details.
  1651. """
  1652. if domain is None:
  1653. domain = cls.domain
  1654. xfunc = lambda x: func(pu.mapdomain(x, cls.window, domain), *args)
  1655. coef = chebinterpolate(xfunc, deg)
  1656. return cls(coef, domain=domain)
  1657. # Virtual properties
  1658. domain = np.array(chebdomain)
  1659. window = np.array(chebdomain)
  1660. basis_name = 'T'