_pade.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from __future__ import division, print_function, absolute_import
  2. from numpy import zeros, asarray, eye, poly1d, hstack, r_
  3. from scipy import linalg
  4. __all__ = ["pade"]
  5. def pade(an, m, n=None):
  6. """
  7. Return Pade approximation to a polynomial as the ratio of two polynomials.
  8. Parameters
  9. ----------
  10. an : (N,) array_like
  11. Taylor series coefficients.
  12. m : int
  13. The order of the returned approximating polynomial `q`.
  14. n : int, optional
  15. The order of the returned approximating polynomial `p`. By default,
  16. the order is ``len(an)-m``.
  17. Returns
  18. -------
  19. p, q : Polynomial class
  20. The Pade approximation of the polynomial defined by `an` is
  21. ``p(x)/q(x)``.
  22. Examples
  23. --------
  24. >>> from scipy.interpolate import pade
  25. >>> e_exp = [1.0, 1.0, 1.0/2.0, 1.0/6.0, 1.0/24.0, 1.0/120.0]
  26. >>> p, q = pade(e_exp, 2)
  27. >>> e_exp.reverse()
  28. >>> e_poly = np.poly1d(e_exp)
  29. Compare ``e_poly(x)`` and the Pade approximation ``p(x)/q(x)``
  30. >>> e_poly(1)
  31. 2.7166666666666668
  32. >>> p(1)/q(1)
  33. 2.7179487179487181
  34. """
  35. an = asarray(an)
  36. if n is None:
  37. n = len(an) - 1 - m
  38. if n < 0:
  39. raise ValueError("Order of q <m> must be smaller than len(an)-1.")
  40. if n < 0:
  41. raise ValueError("Order of p <n> must be greater than 0.")
  42. N = m + n
  43. if N > len(an)-1:
  44. raise ValueError("Order of q+p <m+n> must be smaller than len(an).")
  45. an = an[:N+1]
  46. Akj = eye(N+1, n+1)
  47. Bkj = zeros((N+1, m), 'd')
  48. for row in range(1, m+1):
  49. Bkj[row,:row] = -(an[:row])[::-1]
  50. for row in range(m+1, N+1):
  51. Bkj[row,:] = -(an[row-m:row])[::-1]
  52. C = hstack((Akj, Bkj))
  53. pq = linalg.solve(C, an)
  54. p = pq[:n+1]
  55. q = r_[1.0, pq[n+1:]]
  56. return poly1d(p[::-1]), poly1d(q[::-1])