import numpy as np
import matplotlib.pyplot as plt
def multimodal(x):
fn_val = np.sin((7*x)/3) + np.log(x) - 0.5*x
return np.round(fn_val, 5)
x = np.linspace(1,10,100)
y = multimodal(x)
plt.plot(x, y)
x = np.linspace(1,10,100)
y = multimodal(x)
plt.plot(x, y)
def initial_bracket(a, s = 1e-2, k = 2):
ya = multimodal(a)
# intian b
b, yb = a + s, multimodal(a + s)
# exchange values if y(a) < y(b)
if ya < yb:
a, b = b, a
# confirm fn values
ya, yb = multimodal(a), multimodal(b)
# loop for finding the interval
while True:
c, yc = b+s, multimodal(b+s)
if yc > yb:
if a > c:
a, c = c, a
break
else:
a, ya, b, yb = b, yb, c, yc
s *= k
return a, c
def initial_brackets(ll, ul):
a = ll + (ul-ll) * np.random.rand()
while True:
a0, b0 = initial_bracket(a)
if a0 != b0:
break
return a0, b0
a0, b0 = initial_brackets(1, 10)
print(f'a={a0} and f(a) = {multimodal(a0)}')
print(f'c={b0} and f(c) = {multimodal(b0)}')
x = np.linspace(a0, b0,20)
y = multimodal(x)
plt.plot(x, y)
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
N = 10
a, b = a0, b0
ratio = fibonacci(N)/fibonacci(N+1)
x1 = a + (b-a)*(1- ratio)
x2 = a + (b-a)*ratio
y1, y2 = multimodal(x1), multimodal(x2)
x = np.linspace(a0,b0,100)
y = multimodal(x)
plt.plot(x, y)
plt.axvline(x=x1, color='red')
plt.axvline(x=x2, color='red')
fig = plt.figure(figsize=(100, 100))
while N > 2:
new_ratio = fibonacci(N-1)/fibonacci(N)
if y1 < y2:
b = x2
x2, y2 = x1, y1
x1 = a + (b-a)*(1- new_ratio)
y1 = multimodal(x1)
else:
a = x1
x1, y1 = x2, y2
x2 = a + (b-a)*new_ratio
y2 = multimodal(x2)
x = np.linspace(a0,b0,1000)
y = multimodal(x)
plt.subplot(4, 2, 11-N)
plt.plot(x, y)
plt.axvline(x=a, color='red')
plt.axvline(x=b, color='red')
N = N -1
if y1 < y2:
b = x2
else:
a = x1
x = np.linspace(a0,b0,1000)
y = multimodal(x)
fig = plt.figure(figsize=(40, 20))
plt.plot(x, y)
plt.axvline(x=a, color='red')
plt.axvline(x=b, color='red')
plt.show()
def multimodal(x):
fn_val = np.sin((7*x)/3) - 0.5*x
return np.round(fn_val, 5)
x = np.linspace(1,10,100)
y = multimodal(x)
plt.plot(x, y)