如何用Python找到使给定函数(含Lambda示例)取最小值的x值?
Great questions! Let's work through this, starting with your specific lambda function example then covering the general case for any function.
For your quadratic function f = lambda x: x**2 + 3*x + 3
First off, this is a quadratic function in the form ax² + bx + c, which has an exact analytical solution for its minimum point. The minimum occurs at x = -b/(2a).
For your function, a = 1 and b = 3, so calculating it is straightforward:
a = 1 b = 3 min_x = -b / (2 * a) print(min_x) # Outputs -1.5
If you plug this back into the function to verify: (-1.5)**2 + 3*(-1.5) + 3 = 2.25 - 4.5 + 3 = 0.75, which is indeed the smallest possible value of the function.
General case: Finding the x that minimizes any function f(x)
If you're dealing with a function that doesn't have an easy analytical solution (like complex nonlinear functions), numerical optimization is the way to go. Python's scipy library has great tools for this.
Here's how to do it:
- First, install
scipyif you haven't already:
pip install scipy
- Use
scipy.optimize.minimize_scalarfor single-variable functions (this works perfectly for your example too):
from scipy.optimize import minimize_scalar # Define your function (works for any single-variable continuous function) f = lambda x: x**2 + 3*x + 3 # Run the optimization optimization_result = minimize_scalar(f) # Extract the x value that gives the minimum print("x at minimum:", optimization_result.x) # Prints -1.5 print("Minimum function value:", optimization_result.fun) # Prints 0.75
A few notes:
- If your function has multiple local minima,
minimize_scalarmight find a local minimum instead of the global one. You can adjust themethodparameter (trymethod='brent'ormethod='golden') to tweak the algorithm, or provide bounds if you know where the global minimum lies. - For multi-variable functions, use
scipy.optimize.minimizeinstead ofminimize_scalar.
内容的提问来源于stack exchange,提问作者vverdic

