golden.py

import math as mt
def golden(f,a,b,tol=1.0e-10):
    # Golden section method for determining x
    # that minimizes the scalar function f(x).
    # The minimum must be bracketed in (a,b).
    c1 = (mt.sqrt(5.0)-1.0)/2.0
    c2 = 1.0 - c1
    nIt = int(mt.ceil(mt.log(tol/abs(a-b))/mt.log(c1)))
    # first step
    x1 = c1*a + c2*b
    x2 = c2*a + c1*b
    f1=f(x1)
    f2=f(x2)
    # iteration
    for i in range(nIt):
        if (f1 > f2):
            a = x1
            x1 = x2
            f1 = f2
            x2 = c2*a + c1*b
            f2=f(x2)
        else:
            b = x2
            x2 = x1
            f2 = f1
            x1 = c1*a + c2*b
            f1 = f(x1)
    if (f1<f2):
        return x1,f1
    else:
        return x2,f2

ex329.py

import numpy as np
import matplotlib.pyplot as plt
from golden import golden

def f(x):
    return (x**2 - 6.0*x + 12.0)/(x**2 + 6.0*x + 12.0)

a = 0.0
b=30.0
x = np.linspace(a,b,200)
y=f(x)
plt.plot(x,y)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
xMin,fMin = golden(f,a,b)
plt.scatter(xMin,fMin,c="red")
plt.savefig('ex329.png', dpi=72)
plt.show()
print("xMin=",xMin)
print("fMin=",fMin)

Discover more from Tips and Hints for Aerospace Engineers

Subscribe now to keep reading and get access to the full archive.

Continue reading