In [3]:
def fun(x):
val = x**4-14*x**3+60*x**2-70*x
return val
In [28]:
# Importting required python libraries
import math
import numpy as np
from termcolor import colored
# Golden section search function
def golden_section_search(a,b,ro):
''' The number of iterations needed to reach the given range between two values,i.e|a-b|< epsilon
(1-ro)^N <= 0.3(final range)/2(given initial range)'''
N=math.ceil(np.log10(0.3/2)/np.log10(0.6181))
''' We will use iteration to arrive at the required range.
Since, for the first time we need to calculate 2 evaluation points, we will keep the first iteration
out of the iteration look'''
#Iteration : 1
a1 = a + ro*(b-a)
b1 = a + (1-ro)*(b-a)
f1= fun(a1)
print("Value of function evaluation on the left of the minimum:",f1,"\t")
f2 = fun(b1)
print("Value of function evaluation on the right of the minimum:",f1,"\t")
for i in range(1,N+2):
f1= fun(a1)
f2= fun(b1)
if abs(a-b) <= 0.3:
print("The final range between a & b : ",abs(b-a))
return
if f1 <= f2:
print("Current values of a & b","a:",a,"b:",b,"\t")
print("Iteration :",i,"value of function evaluation","f1: ",f1," f2: ",f2,"\t")
b=b1
b1=a1
a1 = a + ro*(b-a)
else:
print("Current values of a & b","a:",a,"b:",b,"\t")
print("Iteration :",i,"value of function evaluation","f1: ",f1," f2: ",f2,"\t")
a = a1
a1 = b1
b1 = a + (1-ro)*(b-a)
In [29]:
a=0
b=2
ro = 0.3819
golden_section_search(a,b,ro)
Value of function evaluation on the left of the minimum: -24.360539847524606 Value of function evaluation on the right of the minimum: -24.360539847524606 Current values of a & b a: 0 b: 2 Iteration : 1 value of function evaluation f1: -24.360539847524606 f2: -18.955293886084604 Current values of a & b a: 0 b: 1.2362 Iteration : 2 value of function evaluation f1: -21.09781971314749 f2: -24.360539847524606 Current values of a & b a: 0.47210478 b: 1.2362 Iteration : 3 value of function evaluation f1: -24.360539847524606 f2: -23.591352580102786 Current values of a & b a: 0.47210478 b: 0.9443920354819999 Iteration : 4 value of function evaluation f1: -23.83739668077605 f2: -24.360539847524606 The final range between a & b : 0.2919207526134241