0
#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})))

I don't know why don't run? If i run, only show up the message " 'Float' object is not iterable. where i mistake? Please teach me the mistake

3
  • 5
    Include the full error traceback. Commented Feb 5, 2017 at 2:20
  • 1
    always put FULL error message in QUESTION. Commented Feb 5, 2017 at 3:42
  • Possible duplicate of this SO question. Commented Feb 5, 2017 at 9:41

1 Answer 1

0

Problem is flx.subs({x_old}) - it should be {x: x_old} or something similar.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.