Search code examples
pythonnumpyscipylinear-algebradifferential-evolution

Scipy.optimize differential_evolution Index error: tuple index out of range


I have a smooth function f(x) = sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2) The task is to find a minimum of a non-smooth function h(x) = int(f(x)) on the interval of 1 to 30. In other words, each value of f (x) is converted to type int and the function takes only integer values.

I am using 2 methods to find a minimum from scipy.optimize: minimize and differential_evolution. The minimize gives me the result of -5 whereas differential_evolution gives Index error: tuple index out of range The question is why and what is wrong?

Here is the code:

import math
import numpy as np
from scipy.optimize import minimize
from scipy.optimize import differential_evolution
from scipy.linalg import *
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x / 5.0) * np.exp(x / 10.0) + 5 * np.exp((-x / 2.0))

def h(x):
    return f(x).astype(int)

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()


#res = minimize(h, 30, method='BFGS')
#print res

res = differential_evolution(h, [1, 30])
print res

Solution

  • That's because the bounds parameter of differential_evolution expects a sequence of (min, max) pairs. Given that you only have a pair of min and max values for x, you can do the following:

    res = differential_evolution(h, [(1, 30)])
    print res
    

    which would result in:

         fun: -11.0
     message: 'Optimization terminated successfully.'
        nfev: 92
         nit: 5
     success: True
           x: array([ 25.76747524])
    

    For more information, please see the official documentation: https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.optimize.differential_evolution.html

    I hope this helps.