utils.py 887 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. try:
  2. import mpmath as mp
  3. except ImportError:
  4. pass
  5. try:
  6. from sympy.abc import x
  7. except ImportError:
  8. pass
  9. def lagrange_inversion(a):
  10. """Given a series
  11. f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
  12. use the Lagrange inversion formula to compute a series
  13. g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
  14. so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
  15. necessarily b[0] = 0 too.
  16. The algorithm is naive and could be improved, but speed isn't an
  17. issue here and it's easy to read.
  18. """
  19. n = len(a)
  20. f = sum(a[i]*x**i for i in range(n))
  21. h = (x/f).series(x, 0, n).removeO()
  22. hpower = [h**0]
  23. for k in range(n):
  24. hpower.append((hpower[-1]*h).expand())
  25. b = [mp.mpf(0)]
  26. for k in range(1, n):
  27. b.append(hpower[k].coeff(x, k - 1)/k)
  28. b = [mp.mpf(x) for x in b]
  29. return b