gpt4 book ai didi

python - 编码西格玛公式?

转载 作者:太空狗 更新时间:2023-10-29 20:59:18 24 4
gpt4 key购买 nike

Python初学者,跑2.7

我找不到用 Pythonic 编写以下公式的方法。我的目标是拥有一个可以输入值的函数(在之前的尝试中,我只找到了一个高度重复的暴力解决方案)。

formula

必要信息:

如果您不知道 sigma 符号的含义:look here

# 'v' is the formula
# 'i' 'j' 'k' are actors with numerical attributes 'c' 's' and 'x'
# 'n' = length of the following lists (length is identical for all four lists)

values_1 = [Bob, Sue, Mary, Jo...] # i, j, and k are any 3 values drawn from this list
# under the condition that i != j != k

values_2 = [5,6,7,8...] # c is drawn from this list.
# if i = values_1[0], then c(i) = values_2[0].
# same for j and k

values_3 = [9,10,11,12...] # s is drawn from this list.
# if i = values_1[0], then s(i) = values_3[0]

values_4 = [13,14,15, 16..] # x is drawn from this list.
# if i = values_1[0], then x(i) = values_4[0].

def V (j,k):
#this is where I need help!

v_Bob_Sue = # this is where V(Bob, Sue) should go.
# this is what the math would look like in English:
# SUM of (c_Mary * s_Mary * ((abs(x_Mary - x_Sue) - abs(x_Mary - x_Bob)) / x's range))
# and (c_Jo * s_Jo * ((abs(x_Jo - x_Sue) - abs(x_Jo - x_Bob)) / x's range))

# Bob and Sue are the j and k value
# we do the formula with all the other actors (from values_1) who AREN'T Bob and Sue


v_Bob_Mary = # etc
v_Bob_Jo =
v_Sue_Bob =
v_Sue_Mary =
v_Sue_Jo =
v_Mary_Bob =
v_Mary_Sue =
v_Mary_Jo =
v_Jo_Bob =
v_Jo_Sue =
v_Jo_Mary =

最佳答案

至于“sigma”,计算起来很简单,因为它也被称为“sum”。在 python 中有一个内置函数:http://docs.python.org/library/functions.html#sum

至于您提供的公式,我认为您在这里真正想念的是列表或数组。 i、j 和 k 可以是 n 维数组的索引。我会为此使用 numpy 包:

import numpy as np

c = np.asarray(values_2)
s = np.asarray(values_3)
x = np.asarray(values_4)

def V(j, k):
return np.sum(c * s * (np.abs(x - x[j]) - np.abs(x - x[k])) / np.abs(x[-1] - x[0]))

此处 Bob 和 Sue 由 values_1 列表中的索引位置编码。这比使用字符串或类实例更容易。所以你会写:

v_Bob_Sue = V(0, 1)

如果你想自动创建变量 v_Bob_Sue 等你需要动态定义变量名。所以你需要 exec 语句如下:

for i in xrange(len(values_1)):
for j in xrange(len(values_1)):
exec("v_%s_%s = V(%u, %u)" % (values_1[i], values_1[j], i, j)

关于python - 编码西格玛公式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11830261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com