用5种方法求:y=t^3-2t+1的在区间[-3,5]之间的最小值。精度0.01的代码
时间: 2024-11-29 07:35:35 浏览: 15
要找函数 \( y = t^3 - 2t + 1 \) 在区间 \([-3, 5]\) 内的最小值,有多种数值计算方法可以实现,这里提供五种常见的搜索策略:
1. **二分法** (Bisection Method):
```python
import math
def bisection(f, a, b, precision=0.01):
if f(a)*f(b) >= 0:
return None # 函数在[a, b]无极值
while b-a > precision:
c = (a+b)/2
if f(c) * f(a) < 0:
b = c
else:
a = c
return c, f(c)
# 定义函数
def func(t):
return t**3 - 2*t + 1
min_value, min_t = bisection(func, -3, 5)
```
2. **牛顿迭代法** (Newton-Raphson Method):
```python
def newton_raphson(f, df, x0, precision=0.01):
while abs(f(x0)) > precision:
x0 -= f(x0) / df(x0)
return x0, f(x0)
def df(t):
return 3*t**2 - 2
min_t, _ = newton_raphson(func, df, 2) # 初始猜测点2
```
3. **梯度下降法** (Gradient Descent):
```python
def gradient_descent(f, df, initial_guess, learning_rate, precision=0.01):
x = initial_guess
while abs(f(x)) > precision:
x -= learning_rate * df(x)
return x, f(x)
min_t, _ = gradient_descent(func, df, 2, 0.01)
```
4. **黄金分割搜索** (Golden Section Search):
```python
from scipy.optimize import golden
def golden_search(f, a, b, precision=0.01):
phi = (math.sqrt(5) + 1) / 2
while (b - a) > precision:
a_, b_ = a + (phi - 1) * (b - a), a + phi * (b - a)
if f(a_) < f(b_):
b = b_
else:
a = a_
return (a + b) / 2, f((a + b) / 2)
min_t, _ = golden_search(func, -3, 5)
```
5. **数值优化库** (如Scipy的`minimize`):
```python
from scipy.optimize import minimize
def optimize_min(f, bounds):
result = minimize(f, x0=[2], method='SLSQP', bounds=bounds, options={'xtol': 0.01})
return result.x[0], result.fun
min_t, _ = optimize_min(lambda t: t**3 - 2*t + 1, ((-3, 5),))
```
上述代码中,每种方法都需要根据具体情况调整初始猜测、学习率等参数。运行完成后,`min_t`就是找到的最小值对应的 `t` 值。
阅读全文