2022-09-12 利用直方图求平均值的快捷算法

直方图的简单性质

  1. 横轴表示“分组”,纵轴表示“频率/组距”
  2. 每组的面积表示频率(即p_n = 组距 \times y_n
  3. 各组面积之和等于1(即频率之和为1)
    组距 \times (y_1 + y_2 + y_3 + \cdots + y_n) = \sum_{i=1}^{n} p_i = 1
  4. 各组中点值x_n近似为该组的平均值
  5. 样本的平均值\overline x等于
    \overline x = x_1 \cdot p_1 + x_2 \cdot p_2 + x_3 \cdot p_3 + \cdots + x_n \cdot p_n = \sum_{i=1}^{n} x_i\cdot p_i

简便算法

设组距为d
\begin{aligned} \overline x &= x_1 \cdot p_1 + x_2 \cdot p_2 + x_3 \cdot p_3 + \cdots + x_n \cdot p_n \\ &= x_1 \cdot p_1 + (x_1 + d) \cdot p_2 + (x_1 + 2d) \cdot p_3 + \cdots + (x_1 + (n-1)d) \cdot p_n \\ &= x_1 \cdot (p_1 + p_2 + p_3 + \cdots + p_n) + d \cdot (p_2 + 2p_3 + \cdots + (n-1)p_n) \\ &= x_1 + d \cdot (p_2 + 2p_3 + \cdots + (n-1)p_n) \\ &= x_1 + d \cdot (\sum_{i=2}^{n}p_i + \sum_{i=3}^{n}p_i + \cdots + \sum_{i=n}^{n}p_i) \\ &= x_1 + d \cdot \sum_{i=2}^{n}\sum_{j=i}^{n}p_j \end{aligned}

利用python实现以上算法

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2022/9/12 21:37
# @Author : 申炎
# @File : histogram_.py

"""histogram直方图求平均值算法"""

import numpy as np


class Myhistogram(object):
    def __init__(self):
        pass

    def mean(self, x, y):
        """
        求样本平均值
        :param x: 分组,列表[x0, x1, x2, ……, xn]
        :param y: 频率/组距, 列表[y1, y2, y3, ……, yn]
        :return: 平均值
        """
        d = x[1] - x[0]  # 组距
        x1 = (x[1] + x[0]) / 2  # 第一组中点值
        res = []
        n = len(y)  # 求分组
        for i in range(1, n):
            res.append(np.sum(y[i:]))

        return x1 + d ** 2 * np.sum(res)


if __name__ == '__main__':
    x = [i+0.5 for i in range(1, 8)]
    y = [0.15, 0.20, 0.30, 0.20, 0.10, 0.05]
    htg = Myhistogram()
    print(htg.mean(x, y))

利用下面例题的数据测试,结果吻合标准答案.甲的平均值\overline x = 4.05

例题(2019年高考新课标III卷理19题)

image.png

作为高考试题,答案需要手算,下面演示手动计算的方法(以甲为例)
第一组的中点值为2,组距为1
\begin{aligned} \overline x &= 2 + 1 \times (0.2 + 2 \times 0.3 + 3 \times 0.2 + 4 \times 0.1 + 5 \times 0.05)\\ &= 2 + (0.2+0.6+0.6+0.4+0.25)\\ &= 2 + 2.05\\ &= 4.05 \end{aligned}
因为高考试题的数据是经过反复斟酌的,必须要让考生在考试时间内完成计算,所以\sum_{i=2}^{n}\sum_{j=i}^{n}p_j总分的数据不会太复杂,利用这种方法可以加快计算速度。

练习

image.png

常规算法的列式与计算:
\begin{aligned} \overline x &= 34 \times 0.0025 \times 4 + 38 \times 0.0175 \times 4 + 42 \times 0.0425 \times 4 + 46 \times 0.0425 \times 4 + 48 \times 0.0425 \times 4 + 50 \times 0.0625 \times 4 + 54 \times 0.0625 \times 4 + 58 \times 0.02 \times 4\\ &= 34 \times 0.01 + 38 \times 0.07 + 42 \times 0.17 + 46 \times 0.17 + 50 \times 0.25 + 54 \times 0.25 + 58 \times 0.08\\ &= 48.6 \end{aligned}

采用快捷方法的列式与计算:
\begin{aligned} \overline x &= 34 + 4 \times (0.07 + 2 \times 0.17 + 3 \times 0.17 + 4 \times 0.25 + 5 \times 0.25 + 6 \times 0.08) \\ &= 34 + 4 \times (0.07 + 5 \times 0.17 + 9 \times 0.25 + 0.48) \\ &= 34 + 4 \times (0.07 + 0.85 + 2.25 + 0.48) \\ &= 34 + (2.2 + 3.4 + 9) \\ &= 48.6 \end{aligned}

由此可见,当数值简单时,计算量差异并不明显,但当数值复杂时,手动计算的优势就突显出来了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容