x values of percentiles of a function y

Viewed 51

I have a general function y(x) (not necessarily Gaussian). I would like to calculate percentiles of this function, preferably using np.percentile(), such that I get the x value of the percentile. For example, the x value for the 50th percentile (median). However, np.percentile() takes a distribution, not a function of some variable.

How would I compute percentiles, and various statistics (such as mean, std, median, etc.) of this function?

enter image description here

1 Answers

You could create a distribution that represents the function and then evaluate the statistical measures on the distribution.

import matplotlib.pyplot as plt
import numpy as np

# resolution of the function
x = np.arange(-1, 1, 0.001)

# define function (Gaussian)
sigma = 0.1
mu = 0.2
y = 1 / (sigma * (2 * np.pi)**0.5) * np.e**(-0.5 * ((x - mu) / sigma)**2)

# create mask to remove values near zero
mask = np.logical_not(np.isclose(y, 0, 1e-2, 1e-2))
x = x[mask]
y = y[mask]

# plot function
plt.scatter(x, y)

# evaluate stats
np.std(y)
np.percentile(y, 50)
np.mean(y)

The downside to this approach is the threshold to remove non-relevant values, in my example values around zero, has a large impact on the statistical measures.


I also looked around the SymPy docs but didn't see an implementation for this problem.

Related