我设置了一个带有双for循环的函数来计算不同数组的总和。为什么我的函数总是返回0?

2024-09-28 22:23:57 发布

您现在位置:Python中文网/ 问答频道 /正文

SCD summation formula

我得到了一个用python编写代码的双重求和公式。基本上,我得到了30个不同的数组,它们的e和k值有不同的排列,对应于一个负电荷或一个正电荷。这些电荷在总和中是qm和qn,因此qm=-1和qn=1。e的相对位置表示为m,k的相对位置表示为n。这些是总和中的m和n。这些数组被命名为s1、s2、s3、s4等。。。一直到s30。我将在这里为s3和s4提供一个示例数组,这样您就知道我在说什么了

s3由s3 = np.array( ['k','e','k','k','k','e','k','k','e','e','k','k','e','e','k','e','k','e','k','e','k','e','e','k','k','k','e','e','k','e','k','e','k','e','k','k','k','e','e','k','e','k','e','e','k','k','e','e','e','e'])给出

s4由s4 = np.array( ['k','e','k','e','k','k','e','e','k','e','k','k','e','e','e','k','k','e','k','e','k','e','k','k','k','e','e','k','k','k','e','e','k','e','e','k','k','e','e','k','k','k','e','e','k','e','e','e','k','e'])给出

所以,现在我定义了寻找位置,为'k'的nμ值和'e'的mμ值。这些功能如下

对于mμ值

def m_value(position_num, array_name):
"""
same as for the n_value, except for 'e' instead of 'k'
"""
    cnt = 0
    for i in range(len(array_name)):
        if array_name[i]=='e':
            cnt+=1
        if cnt==position_num:
            return i+1
    return 0

对于n\U值

def n_value(position_num, array_name):
"""
this is a function to get all of the positions of 
'k' in the array entered.
    position_num = what number 'k' value you want (1st, 2nd, etc...)
    array_name = what scd row (s1, s2, etc...)
define the specific element of the array 
returns value of where the 'k' is in the given sequence
"""
    cnt = 0
    for i in range(len(array_name)):
        if array_name[i]=='k':
            cnt+=1
        if cnt==position_num:
            return i+1
    return 0

然后,我分别定义了e和k的电荷

charge_values = {'e' : -1, 'k' : 1}

e\u charge=电荷值['e'] k\u电荷=电荷值['k']

并定义了一个要计数的N值

N = 50

最后,我为函数编写了一个定义,根据给我的求和公式求和,定义为“SCD”。给你

def SCD(array_name):
"""
this should sum all of the elements in accordance with the
SCD summation formula. see notes to see full layout of 
formula and elements
"""
    summ = 0.0
    nposition_num=0
    mposition_num=0
    for m in range(2, N):
        summ = 0.0
        mposition_num = m_value(m, array_name)
        qm = mposition_num*e_charge
        for n in range (0, m-1):
            nposition_num= n_value(n, array_name)
            qn = nposition_num*k_charge
            summ += qm*qn*np.sqrt(m-n)
        summ += summ
    summ = (summ/float(N))     
    return summ

现在,一个主要问题出现了。无论是什么数组,SCD返回的值总是0.0。我知道这是不准确的,所以我想知道是什么逻辑或编码错误,我在这导致输出总是产生一个零。我是python新手,所以任何提示或想法都将不胜感激


Tags: ofthenameinforreturn定义value