Skip to content

Commit

Permalink
some forth and back with mean()
Browse files Browse the repository at this point in the history
  • Loading branch information
nschloe committed Feb 2, 2022
1 parent ecd26ea commit 9242c5e
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/npx/_mean.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,17 @@ def mean(x: ArrayLike, p: float = 1) -> np.ndarray:
if np.any(x < 0.0):
raise ValueError("p=0 only works with nonnegative x.")
return np.prod(np.power(x, 1 / n))
# alternative:
# return np.exp(np.mean(np.log(x)))
elif p == np.inf:
return np.max(np.abs(x))

if not isinstance(p, int) and np.any(x < 0.0):
raise ValueError("Non-integer p only work with nonnegative x.")

if np.all(x > 0.0):
# logsumexp trick to avoid overflow for large p
# only works for positive x though
return np.exp((_logsumexp(p * np.log(x)) - np.log(n)) / p)
else:
return (np.sum(x**p) / n) ** (1.0 / p)

if not isinstance(p, (int, np.integer)):
raise ValueError(f"Non-integer p (={p}) only work with nonnegative x.")

return (np.sum(x**p) / n) ** (1.0 / p)

0 comments on commit 9242c5e

Please sign in to comment.