Skip to content

Instantly share code, notes, and snippets.

@nschloe
Last active November 24, 2022 17:56
Show Gist options
  • Save nschloe/0d6d7b73fb1393f3e7fd912137dcc99a to your computer and use it in GitHub Desktop.
Save nschloe/0d6d7b73fb1393f3e7fd912137dcc99a to your computer and use it in GitHub Desktop.
plot generalized means
import numpy as np
import matplotlib.pyplot as plt
def agm(an, bn):
while np.any(abs(an - bn) > 1.0e-15):
an, bn = (an + bn) / 2, np.sqrt(an * bn)
return an
x = np.linspace(0, 4, 401)
plt.plot(x, np.maximum(1, x), label="inf mean (maximum)")
plt.plot(x, np.cbrt((1 + x ** 3) / 2), label="cubic mean")
plt.plot(x, np.sqrt((1 + x ** 2) / 2), label="root mean square")
plt.plot(x, (1 + x) / 2, label="arithmetic mean")
plt.plot(x, agm(1, x), linestyle=":", label="arithmetic–geometric mean")
plt.plot(x, np.sqrt(x), label="geometric mean")
plt.plot(x, 2 / (1 + 1 / x), label="harmonic mean")
plt.plot(x, np.minimum(1, x), label="-inf mean (minimum)")
plt.legend()
plt.xlim(0, 4)
plt.ylim(0, 3)
plt.grid()
plt.gca().set_aspect("equal")
plt.title("means of 1 and x")
plt.xlabel("x")
plt.savefig("means.png")
plt.show()
@nschloe
Copy link
Author

nschloe commented Nov 24, 2022

means

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment