lambertw.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """Compute a Pade approximation for the principal branch of the
  2. Lambert W function around 0 and compare it to various other
  3. approximations.
  4. """
  5. import numpy as np
  6. try:
  7. import mpmath
  8. import matplotlib.pyplot as plt
  9. except ImportError:
  10. pass
  11. def lambertw_pade():
  12. derivs = [mpmath.diff(mpmath.lambertw, 0, n=n) for n in range(6)]
  13. p, q = mpmath.pade(derivs, 3, 2)
  14. return p, q
  15. def main():
  16. print(__doc__)
  17. with mpmath.workdps(50):
  18. p, q = lambertw_pade()
  19. p, q = p[::-1], q[::-1]
  20. print(f"p = {p}")
  21. print(f"q = {q}")
  22. x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75)
  23. x, y = np.meshgrid(x, y)
  24. z = x + 1j*y
  25. lambertw_std = []
  26. for z0 in z.flatten():
  27. lambertw_std.append(complex(mpmath.lambertw(z0)))
  28. lambertw_std = np.array(lambertw_std).reshape(x.shape)
  29. fig, axes = plt.subplots(nrows=3, ncols=1)
  30. # Compare Pade approximation to true result
  31. p = np.array([float(p0) for p0 in p])
  32. q = np.array([float(q0) for q0 in q])
  33. pade_approx = np.polyval(p, z)/np.polyval(q, z)
  34. pade_err = abs(pade_approx - lambertw_std)
  35. axes[0].pcolormesh(x, y, pade_err)
  36. # Compare two terms of asymptotic series to true result
  37. asy_approx = np.log(z) - np.log(np.log(z))
  38. asy_err = abs(asy_approx - lambertw_std)
  39. axes[1].pcolormesh(x, y, asy_err)
  40. # Compare two terms of the series around the branch point to the
  41. # true result
  42. p = np.sqrt(2*(np.exp(1)*z + 1))
  43. series_approx = -1 + p - p**2/3
  44. series_err = abs(series_approx - lambertw_std)
  45. im = axes[2].pcolormesh(x, y, series_err)
  46. fig.colorbar(im, ax=axes.ravel().tolist())
  47. plt.show()
  48. fig, ax = plt.subplots(nrows=1, ncols=1)
  49. pade_better = pade_err < asy_err
  50. im = ax.pcolormesh(x, y, pade_better)
  51. t = np.linspace(-0.3, 0.3)
  52. ax.plot(-2.5*abs(t) - 0.2, t, 'r')
  53. fig.colorbar(im, ax=ax)
  54. plt.show()
  55. if __name__ == '__main__':
  56. main()