You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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:

  1. First, install scipy if you haven't already:
pip install scipy
  1. Use scipy.optimize.minimize_scalar for 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_scalar might find a local minimum instead of the global one. You can adjust the method parameter (try method='brent' or method='golden') to tweak the algorithm, or provide bounds if you know where the global minimum lies.
  • For multi-variable functions, use scipy.optimize.minimize instead of minimize_scalar.

内容的提问来源于stack exchange,提问作者vverdic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:11:45