Search code examples
pythonscipy-optimize-minimize

Python scipy minimization - Simple example not producing expected return


I am trying to use scipy to find the minimum value for a variable that satisfies a condition in a simple volume = length * width * height example. I am trying to find the height which produces a volume of 1300 given a length of 10 and a width of 10. The answer should be 13, but scipy is telling me x: 1.0000044152960563

from scipy.optimize import minimize_scalar

def objective_function(x):
    target = 1300
    length = 10
    width = 10
    (length * width * x) - target
    return x

res = minimize_scalar(objective_function, method='bounded', bounds=(1, 100))
res
print(x)

Can I use the x value produced outside the function?


Solution

  • I figured out what I was doing wrong. I needed to square the result to get a positive number, then take the square root.

    from scipy.optimize import minimize_scalar
    import math
    
    def objective_function(x):
        target = 1300
        length = 10
        width = 10
        return (math.sqrt(((length * width * x) - target) ** 2))
    
    res = minimize_scalar(objective_function, method='bounded', bounds=(1, 100))
    res.x