Untitled

 avatar
unknown
python
4 years ago
1.8 kB
5
Indexable
# -*- coding: utf-8 -*-
"""
Created on Fri May 14 23:20:01 2021

@author: lenovo
"""

from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
from pylab import meshgrid
from numpy import arange
import numpy as np
import sys

def f(x):
    return 4 * x ** 4 - 4 * x ** 3 - 24 * x ** 2 + 16 * x + 52 

def anti_gradient_f(x):
    return 16 * x ** 3 - 12 * x ** 2 - 48 * x + 16

def steepest_descent(f, anti_gradient_f, initial_x, n_iterations=100, 
                     alpha=0.001, minimum_error=1e-14, epsilon=1e-14):
    x_list = []
    y_list = []
    compute_new_x = lambda gradient_f, current_x, alpha: current_x - alpha * gradient_f
    current_x = initial_x
    delta_f = epsilon
    k = 0
    try:
        while k < n_iterations and not(minimum_error and delta_f < epsilon):
            delta_f = f(current_x)
            x_list.append(current_x)
            y_list.append(delta_f)
            current_x = compute_new_x(anti_gradient_f(current_x), current_x, alpha)
            delta_f -= f(current_x)
            delta_f = abs(delta_f)
            print("Iteration", k, "-> x =", current_x, "with value f(x) =", f(current_x))
            k += 1
        return np.array(x_list), np.array(y_list)
    except OverflowError as error:
        print("Iteration", k, "-> Overflow")
        sys.exit() 
    
x = arange(-5.0, 5.0, 0.01)
Z = f(x)
fig = plt.figure()
plt.plot(x, Z, color='red')
x_list, y_list = steepest_descent(f, anti_gradient_f, -5)
for i in range(len(x_list) - 1):
    plt.quiver(x_list[i], y_list[i], x_list[i + 1] - x_list[i], y_list[i + 1] - y_list[i], scale_units='xy', angles='xy', scale=1, color='blue')
plt.title('$f(x, y) = 4 * x ^ 4 - 4 * x ^ 3 - 24 * x ^ 2 + 16 * x + 52$')
plt.show()
Editor is loading...