线性插值计算百分位数的C++示例

代码如下

#include <iostream>
#include <vector>
#include <algorithm>

double percentile_linear_interpolation(const std::vector<double>& data, double percentile) {
    // 确保百分位数在合理范围内
    if (percentile < 0.0 || percentile > 100.0) {
        throw std::invalid_argument("Invalid percentile value.");
    }

    // 创建临时数组并复制数据
    std::vector<double> sorted_data(data);
    
    // 对数据进行排序
    std::sort(sorted_data.begin(), sorted_data.end());

    // 计算目标索引位置(假设数据长度为N)
    int index = static_cast<int>((sorted_data.size() - 1) * percentile / 100);

    // 处理边界情况:如果百分位数正好落在整数索引上
    if (index == floor(index)) {
        return sorted_data[index];
    } else {
        // 使用线性插值
        double lower_val = sorted_data[static_cast<std::size_t>(floor(index))];
        double upper_val = sorted_data[static_cast<std::size_t>(ceil(index))];
        return lower_val + (upper_val - lower_val) * (index - floor(index));
    }
}

int main() {
    std::vector<double> data{30, 10, 40, 20, 50};
    double p25 = percentile_linear_interpolation(data, 25.0);
    std::cout << "25th percentile: " << p25 << std::endl;
    return 0;
}

 

posted @ 2024-02-19 16:44  阿坦  阅读(43)  评论(0编辑  收藏  举报