Search code examples
pythonscipyscipy-optimizescipy-optimize-minimizefunction-fitting

Minimizing function in terms of integral - scipy


I want to find the parameter of a function that will result in a specific integral value in a defined interval. To make things simpler, the example below considers the function to be a straight line, and the parameter I want to find is the slope m. I use scipy.integrate.quad to integrate and was trying to use scipy.integrate.minimize to find the slope:

from scipy.integrate import quad
from scipy.optimize import minimize

IntegralValue = 10
initial_guess = 0.1

def function(m):
    intgrl, abserr = quad(lambda x: m*x, 0, 10) # interval from 0 to 10
    return intgrl - IntegralValue
res = minimize(function, initial_guess, method='nelder-mead',options={'xtol': 1e-8, 'disp': True})

print(res.x)

A simple 0.2 should be the result (function(0.2) results in 0), but for some reason I get a warning that the "maximum number of function evaluations has been exceeded" and the output is something that doesn't make sense (-6.338253e+27). Default minimize method also did not work. Maybe I am missing something or misunderstood, but I couldn't figure it out. I appreciate the help. I am using Python 3.7.10 on Windows 10.


Solution

  • The minimum is of course negative infinity. To get a zero, I just had to constrain the problem to non negative values, as commented by @ForceBru and @joni. Thanks!

    EDIT

    here is the final functional full code:

    from scipy.integrate import quad
    from scipy.optimize import minimize
    
    IntegralValue = 10
    initial_guess = 0.1
    
    def function(m):
        intgrl, abserr = quad(lambda x: m*x, 0, 10) # interval from 0 to 10
        return abs(intgrl - IntegralValue)
    res = minimize(function, initial_guess, method='nelder-mead',options={'xtol': 1e-8, 'disp': True})
    
    print(res.x)