## Svenn's algorithm

``````

In [5]:

import numpy as np
import matplotlib.pyplot as plt

%pylab inline

``````
``````

Populating the interactive namespace from numpy and matplotlib

``````
``````

In [6]:

x0 = 0  # starting point
h = 0.5  # step

def func(x):
return - (3 - np.power(x, 2)) * x  # our function

``````
``````

In [7]:

fig, ax = plt.subplots()
x = np.linspace(-3, 3, 100)
y = func(x)
ax.plot(x, y)
ax.grid(True)

``````
``````

``````
``````

In [9]:

def optimize_svenn(x0, h):
f0 = func(x0)
f0_sub = func(x0 - h)

xk1 = lambda xk0, t, k: (xk0 + 2.0 ** k * t)

if (f0 >= f0_sub) and (f0 >= f0_add):
return (None, None)
elif (f0 <= f0_sub) and (f0 <= f0_add):
return (x0 - h, x0 + h)
elif (f0 <= f0_sub) and (f0 >= f0_add):
a = x0
elif (f0 >= f0_sub) and (f0 <= f0_add):
h = -h
b = x0

k = 1
x1 = x0 + h
x2 = xk1(x1, h, k)
f1 = func(x1)
f2 = func(x2)

while f2 < f1:
if (h > 0):
a = x1
else:
b = x1
k += 1

x1, f1 = x2, f2
x2 = xk1(x1, h, k)
f2 = func(x2)

if (h > 0):
b = x2
else:
a = x2

return a, b

a, b = optimize_svenn(x0, h)

if a is not None and b is not None:
fa, fb = func(a), func(b)
ax.plot([a], [fa], "ro")
ax.text(a, fa - 2, "a")
ax.plot([b], [fb], "ro")
ax.text(b, fb - 2, "b")
print "a = {0}".format(a)
print "b = {0}".format(b)
else:
print "Function is not unimodal"

fig

``````
``````

a = 0
b = 1.5

Out[9]:

``````
``````

In [ ]:

``````