Univariate Minimization Examples¶
Example Code¶
Representative script:
"""IMSL UVMIF example: minimize exp(x) - 5x using univariate bounded search.
Reproduces the IMSL UVMIF published example:
- Function: f(x) = exp(x) - 5x
- Starting point: x = 0
- Bound: 100
- Expected minimum at x = ln(5) ≈ 1.609, f ≈ -3.047
Outputs:
- Table printed to stdout
- SVG plot saved to test_output/demo_imsl_uvmif.svg
"""
from __future__ import annotations
from pathlib import Path
from typing import Dict
import matplotlib.pyplot as plt
import numpy as np
from optimization import minimize_univariate
def run_demo_imsl_uvmif() -> Dict[str, object]:
"""Run IMSL UVMIF example: minimize exp(x) - 5x.
Args:
None
Returns:
Dict[str, object]: Result dict with keys ``x_min`` (float),
``fval`` (float), and ``plot_path`` (str).
"""
def f(x: float) -> float:
return np.exp(x) - 5.0 * x
result = minimize_univariate(f, x_guess=0.0, bound=100.0, step=0.1, x_tol=1e-5, max_fev=200)
x_min = float(result.x[0])
fval = float(result.fval)
print("\nIMSL UVMIF Example: minimize exp(x) - 5x")
print("-" * 45)
print(f"{'Parameter':<20} {'Value':>15}")
print("-" * 45)
print(f"{'x (minimum)':<20} {x_min:>15.6f}")
print(f"{'f(x)':<20} {fval:>15.6f}")
print(f"{'ln(5) [exact]':<20} {np.log(5):>15.6f}")
print(f"{'f(ln5) [exact]':<20} {f(np.log(5)):>15.6f}")
print(f"{'Converged':<20} {str(result.success):>15}")
print(f"{'Function evals':<20} {result.n_fev:>15}")
print("-" * 45)
output_dir = Path("test_output")
output_dir.mkdir(parents=True, exist_ok=True)
plot_path = output_dir / "demo_imsl_uvmif.svg"
x_vals = np.linspace(-1.0, 4.0, 400)
y_vals = np.array([f(xi) for xi in x_vals])
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x_vals, y_vals, color="#1f77b4", linewidth=2.0, label=r"$f(x) = e^x - 5x$")
ax.axvline(x_min, color="#d62728", linestyle="--", linewidth=1.5, label=f"Minimum x≈{x_min:.4f}")
ax.scatter([x_min], [fval], color="#d62728", s=60, zorder=5)
ax.set_xlabel("x")
ax.set_ylabel("f(x)")
ax.set_title("IMSL UVMIF: Univariate Bounded Minimization")
ax.legend()
ax.grid(True, alpha=0.3)
fig.tight_layout()
fig.savefig(plot_path, format="svg")
plt.close(fig)
return {"x_min": x_min, "fval": fval, "plot_path": str(plot_path)}
if __name__ == "__main__":
run_demo_imsl_uvmif()
Input (Console)¶
Run the univariate minimization script from the package root:
python examples/example_imsl_uvmif.py
Plot Output¶
Generated SVG plot:
Output Console¶
Summary console output:
IMSL UVMIF Example: minimize exp(x) - 5x
---------------------------------------------
Parameter Value
---------------------------------------------
x (minimum) 1.609438
f(x) -3.047190
ln(5) [exact] 1.609438
f(ln5) [exact] -3.047190
Converged True
Function evals 20
---------------------------------------------