Skip to content

Percentile function into statistics module #144585

@matterhorn3838-web

Description

@matterhorn3838-web

Feature or enhancement

Proposal:

import math


def nth_percentile(data: list, n: int):
    """
    Calculate the nth percentile of a dataset.
    :param data: List of numerical values
    :param n: Percentile (0–100)
    :return: The nth percentile value
    """
    if not data:
        raise ValueError("Data list cannot be empty")
    if not 0 <= n <= 100:
        raise ValueError("Percentile must be between 0 and 100")
    sorted_data = sorted(data)
    k = (n / 100) * (len(sorted_data) - 1)
    lower = math.floor(k)
    upper = math.ceil(k)
    if lower == upper:
        return sorted_data[int(k)]
    return sorted_data[lower] + (k - lower) * (sorted_data[upper] - sorted_data[lower])

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions