Python错误=> '浮动'对象不可迭代

时间:2017-02-05 02:14:20

标签: python sympy

#Grdient acent
from sympy import Derivative, Symbol, sympify, solve
from sympy.core.sympify import SympifyError
def grad_ascent(x0, flx, x):

    if not solve(flx):
        print('Cannot continue, solution for {0}=0 does not exist'.format(flx))
        return
    epsilon= 1e-6
    step_size= 1e-4
    x_old= x0
    x_new= x_old+step_size*flx.subs({x: x_old}).evalf()
    while abs(x_old-x_new)>epsilon:
        x_old= x_new
        x_new= x_old+step_size*flx.subs({x_old}).evalf()
    return x_new

if __name__=='__main__':

    f=input('Enter a function in one variable: ')
    var=input('Enter the variable to differenriate with respect to: ')
    var0=float(input('Enter the initial value of the variable: '))
    try:
        f=sympify(f)
    except SympifyError:
        print("Invalid function entered ")
    else:
        var=Symbol(var)
        d=Derivative(f, var).doit()
        var_max=grad_ascent(var0, d, var)
        if var_max:
            print('{0}:{1}'.format(var.name, var_max))
            print('Maximum value: {0}'.format(f.subs({var:var_max})))

我不知道为什么不跑? 如果我跑,只显示消息" '浮动'对象不可迭代。 哪里弄错了?请教我错误

1 个答案:

答案 0 :(得分:0)

问题是flx.subs({x_old}) - 它应该是{x: x_old}或类似的东西。