循环不会每次都运行(Python)

时间:2017-11-03 08:19:28

标签: python python-3.x

我正在尝试使用Python 3.x和PyCharm创建渐变下降。 代码不优雅,但它确实有效。但在运行了几次后,“for”循环停止工作。 我认为它可能是一个内存问题或类似的事情,但如果是,我不知道如何解决它。

thrust_forward()
thrust = neu['d']
thrust_new = 0    

def back_and_forward():
    randomize_steps_effect()
    thrust_backward()
    thrust_forward()

    global thrust_new
    thrust_new = neu['d']

iterations = 5000000

def start_process():
    print('')
    print('Progress:')
    for i in range (0,iterations):
        global thrust_new
        global thrust

        while thrust_new < thrust:
           back_and_forward()

        thrust = thrust_new
        if i%(iterations/100) == 0:
            print('|', sep = '', end='', flush=True)


    print('')
    print('Final: P = ' +str(thrust/9.8) + str(prm))



start_process()

主要参数存储在词典中:

#Parametres
    prm = {
        'm':3, #kg/s
        ...
        'ph':-50000 #Pa
    }


    #Parameters steps
    stp = {
        'a':0.01,
        ...
        'ph':50 #Pa
    }
    #Additional vars
    neu = {
        'a':0,
        ...
        'd':0
    }

步骤有随机化函数,因此“推力”最终会增加,而循环中断:

    #Randomize steps
    def randomize_steps_effect():
        for key, values in stp.items():
            r = random.randint(0,3)
            if r != 0 and (key != 'm' or key != 'w'):
                stp[key] *= -1

前进和后退功能:

def thrust_forward():
    neu['a'] = forward_multiply(prm['m'],prm['w'])
    neu['c'] = forward_add(prm['pa'],prm['ph'])
    neu['b'] = forward_multiply(neu['c'],prm['Fa'])
    neu['d'] = forward_add(neu['a'],neu['b'])

def thrust_backward():
    global max_w

    neu['a'] += stp['a'] * backward_add()
    neu['b'] += stp['b'] * backward_add()
    prm['Fa'] += stp['Fa'] * backward_multiply_F_wrt_b(prm['Fa'],neu['c'])
    neu['c'] += stp['c'] * backward_multiply_F_wrt_b(neu['c'],prm['Fa'])
    prm['pa'] += stp['pa'] * backward_add()
    prm['ph'] += stp['ph'] * backward_add()
    prm['m'] += stp['m'] * backward_multiply_F_wrt_b(prm['m'],prm['w'])
    if prm['w'] >= max_w:
        stp['w'] = 0
    prm['w'] += stp['w'] * backward_multiply_F_wrt_b(prm['w'],prm['m'])

1 个答案:

答案 0 :(得分:0)

你是什么意思&#34; for循环停止工作&#34; ?它在给定的迭代中阻塞,或者你得到一个运行时异常,或者你是否停止看到渐变的改进?

如果它在迭代时阻塞肯定是因为你的内部循环永远不会结束 while P_new < P: 因为你的P_new不断减少

但是,我看到的问题是当你执行P = P_new然后问P_new < P时,最后一个语句总是为假。

如果您可以显示前向和后向功能中包含的代码,我们可以帮助您

正如杰里米所说,你也应该避免使用全局变量

相关问题