Example #1
0
    """ move step_size in the direction from v """
    return [v_i + step_size * direction_i
        for v_i, direction_i in zip(v, direction)]
            
def sum_of_squares_gradient(v):
    return [2 * v_i for v_i in v]
    
# pick a random starting point
v = [random.randint(-10, 10) for i in range(3)]

tolerance = 0.0000001

while True:
    gradient = sum_of_squares_gradient(v)     # compute the gradient at v
    next_v = step(v, gradient, -0.01)         # take a negative gradient step
    if la.distance(next_v, v) < tolerance:
        break
    v = next_v                                # continue if we're not

print(v)

def safe(f):
    """ return a new function that's the same as f,
    except that it outputs infinity whenever f produces an error """
    def safe_f(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except:
            return float('inf')  # this means infinity in Python
    return safe_f