The pth percentile is the value that p percent of the data sits at or below. The 50th percentile is the median; the 25th and 75th are the edges of the "middle half".
The trouble is that the exact spot you want usually falls between two data points, so you have to say precisely where. Use this rule — it's the one NumPy and pandas use by default:
That position is an index into the sorted list, counting from 0.
position lands exactly on a whole number, the answer is simply the value at that index.floor(position) and floor(position) + 1, so slide between those two neighbours by the leftover fraction:low + (high - low) * fraction.Task: write percentile(values, p) returning that value, rounded to 4 decimal places.
values is never empty and arrives in no particular order — sort it first.p runs from 0 to 100 inclusive. p = 0 gives the smallest value, p = 100 the largest.Worked example: for five sorted values and p = 25, position = 4 × 0.25 = 1.0 — a whole number, so you take the value at index 1 and no sliding is needed.