首页 > 解决方案 > 需要帮助将公式 D=2∑ni=1{Ylog[YE(Y)]−[Y−E(Y)]} 转换为 python 代码

问题描述

我需要一些帮助才能将公式转换为 python 代码。

D=2∑ni=1{Ylog[YE(Y)]−[Y−E(Y)]}

在此处输入图像描述

标签: pythonpython-3.xstatistics

解决方案


假设您已经解决了计算像 Y 这样的随机变量的平均值的问题。所以,我假设您有一个名为的东西mean(sample: list),它接收 RV(随机变量)Y 所采用的值列表。

现在,要将公式转换为代码,可能有很多方法。我个人更喜欢那些更容易阅读和理解的。

import math


sample = [] # Whatever values your RV takes
mean_of_Y = mean(sample)
D = 0

# This part will make the summation - obs stands for observation
for obs in sample:
    D += obs*math.log(obs/mean_of_Y, 10) - (obs - mean_of_Y)
    # I made the assumption that the log's base is 10

# Now we need to multiply it by 2
D = D*2

# If you want to see it
print(D)

推荐阅读