LoginSignup
0
1

More than 1 year has passed since last update.

Pythonを用いて母比率の信頼区間を求める 〜ナンパの成功確率〜

Last updated at Posted at 2022-06-18

はじめに

Pythonを用いて、母比率の信頼区間を求めます。

設定

R君は通算1000回のナンパ経験があり、そのうち230回成功しているとします。
その場合のナンパ成功の母比率を求めます。

統計学の知識

scipyを使う場合

コード

main.py
"""ナンパの成功確率を推定する"""
import math
from typing import Dict

from scipy.stats import binomtest


if __name__ == "__main__":
    # ナンパ回数
    num_of_hitting_on = 1000
    # ナンパの成功回数
    num_of_success = 230

    result = binomtest(num_of_success, num_of_hitting_on)
    low_population_ration = math.floor(result.proportion_ci().low * 100)
    high_population_ration = math.floor(result.proportion_ci().high * 100)
    print("ナンパの成功確率は{}%以上{}%未満です。".format(low_population_ration, high_population_ration))

結果

ナンパの成功確率は20%以上25%未満です。

scipyを使わない場合

コード

main.py
"""ナンパの成功確率を推定する"""
import math
from typing import Dict

def estimate_populaton_proportion(sample_proportion: float, trial_num: int) -> Dict[int, int]:
    """標本比率と試行回数から母比率を推定する。

    Args:
        sample_proportion (float): 標本比率
        trial_num (int): 試行回数

    Returns:
        dict: 信頼区間95%にて、最大・最小の母比率を%で返す。
    """
    low_population_proportion = math.floor((sample_proportion - \
                                1.96 * math.sqrt(sample_proportion * (1 - sample_proportion) / trial_num)) * 100)
    high_population_proportion = math.floor((sample_proportion + \
                                1.96 * math.sqrt(sample_proportion * (1 - sample_proportion) / trial_num)) * 100)
    population_ratio = {"low": low_population_proportion, "high": high_population_proportion}
    return population_ratio


if __name__ == "__main__":
    # ナンパ回数
    num_of_hitting_on = 1000
    # ナンパの成功回数
    num_of_success = 230
    # ナンパの成功確率(母比率)
    success_proportion_of_hitting_on = num_of_success / num_of_hitting_on

    hitting_on_population_ration = estimate_populaton_proportion(sample_proportion=success_proportion_of_hitting_on, trial_num=num_of_hitting_on)
    print("ナンパの成功確率は{}%以上{}%未満です。".format(hitting_on_population_ration["low"], hitting_on_population_ration["high"]))

結果

ナンパの成功確率は20%以上25%未満です。

考察

1000回ものナンパ経験のあるR君ですが、それでも推定の結果に5%も幅が出てしまいました。R君にはもっとナンパを頑張ってもらいたいものです。

おわりに

3本目の記事になりました。コメントなど頂けますと幸いです。
ご覧いただき、ありがとうございました!

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1