from numpy import *
from numpy.linalg import norm

def f(x, y):
    r = sqrt(x**2 + y**2)
    return -.4 + (x+15)/30. + (y+15)/40.+.5*sin(r)
    
def drdx(x, y, r):
    return (.5*(x**2 + y**2)**-.5)*(2*x)

def drdy(x, y, r):
    return (.5*(x**2 + y**2)**-.5)*(2*y)
    
def dfdx(x, y):
    r = sqrt(x**2 + y**2)
    return 1/30. + .5*cos(r)*drdx(x, y, r)
    
def dfdy(x, y):
    r = sqrt(x**2 + y**2)
    return 1/40. + .5*cos(r)*drdy(x, y, r)
    
def gradf(x, y):
    return array([dfdx(x, y), dfdy(x, y)])    
    

def grad_descent2(f, gradf, init_t, alpha):
    EPS = 1e-5
    prev_t = init_t-10*EPS
    t = init_t.copy()
    
    while norm(t - prev_t) >  EPS:
        prev_t = t.copy()
        t -= alpha*gradf(t[0], t[1])
        print t, f(t[0], t[1]), gradf(t[0], t[1])
    
    return t
    
    
grad_descent2(f, gradf, array([-10., -2.]), 1)    
    