We use minimize_scalar to find the smallest value of a simple function. It helps us solve problems where we want to reduce cost, error, or any number to its lowest point.
0
0
Minimizing scalar functions (minimize_scalar) in SciPy
Introduction
Finding the best price to sell a product to maximize profit.
Minimizing the error in a simple prediction model.
Finding the shortest distance in a simple path problem.
Optimizing a single variable like time or temperature for best results.
Syntax
SciPy
from scipy.optimize import minimize_scalar result = minimize_scalar(function, bounds=(lower, upper), method='bounded')
The function is what you want to minimize. It must take one number and return one number.
The bounds set the search limits. Use method='bounded' to respect these limits.
Examples
Minimize a simple parabola without bounds.
SciPy
from scipy.optimize import minimize_scalar def f(x): return (x - 3) ** 2 result = minimize_scalar(f)
Minimize the same function but only between 0 and 5.
SciPy
from scipy.optimize import minimize_scalar def f(x): return (x - 3) ** 2 result = minimize_scalar(f, bounds=(0, 5), method='bounded')
Sample Program
This code finds the minimum of the function (x-2)^2 + 1. It prints the smallest value and where it happens.
SciPy
from scipy.optimize import minimize_scalar def cost(x): return (x - 2) ** 2 + 1 result = minimize_scalar(cost) print(f"Minimum value: {result.fun}") print(f"At x = {result.x}")
OutputSuccess
Important Notes
The function should be smooth and have one clear minimum for best results.
If you know the range where the minimum is, use bounds and method='bounded' for faster and safer search.
The result object has useful info like result.x (location) and result.fun (minimum value).
Summary
minimize_scalar helps find the lowest point of a simple function with one variable.
You can run it with or without limits on the variable.
It returns the minimum value and where it happens.