utils.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from __future__ import division, print_function, absolute_import
  2. from scipy._lib._numpy_compat import suppress_warnings
  3. try:
  4. import mpmath as mp
  5. except ImportError:
  6. pass
  7. try:
  8. # Can remove when sympy #11255 is resolved; see
  9. # https://github.com/sympy/sympy/issues/11255
  10. with suppress_warnings() as sup:
  11. sup.filter(DeprecationWarning, "inspect.getargspec.. is deprecated")
  12. from sympy.abc import x
  13. except ImportError:
  14. pass
  15. def lagrange_inversion(a):
  16. """Given a series
  17. f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
  18. use the Lagrange inversion formula to compute a series
  19. g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
  20. so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
  21. necessarily b[0] = 0 too.
  22. The algorithm is naive and could be improved, but speed isn't an
  23. issue here and it's easy to read.
  24. """
  25. n = len(a)
  26. f = sum(a[i]*x**i for i in range(len(a)))
  27. h = (x/f).series(x, 0, n).removeO()
  28. hpower = [h**0]
  29. for k in range(n):
  30. hpower.append((hpower[-1]*h).expand())
  31. b = [mp.mpf(0)]
  32. for k in range(1, n):
  33. b.append(hpower[k].coeff(x, k - 1)/k)
  34. b = map(lambda x: mp.mpf(x), b)
  35. return b