Challenge - 5 Problems
Minimize Scalar Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
Output of minimize_scalar on a quadratic function
What is the output of the following code snippet using
minimize_scalar from scipy.optimize?SciPy
from scipy.optimize import minimize_scalar result = minimize_scalar(lambda x: (x - 3)**2 + 4) print(round(result.x, 2))
Attempts:
2 left
💡 Hint
Think about where the function (x - 3)^2 + 4 reaches its lowest value.
✗ Incorrect
The function (x - 3)^2 + 4 has its minimum at x = 3 because the squared term is zero there, making the function value 4, which is the lowest possible.
❓ data_output
intermediate1:30remaining
Number of iterations in minimize_scalar
How many iterations does
minimize_scalar take to minimize the function f(x) = (x - 1)**4 using the default method?SciPy
from scipy.optimize import minimize_scalar result = minimize_scalar(lambda x: (x - 1)**4) print(result.nit)
Attempts:
2 left
💡 Hint
Check the
nit attribute in the result object.✗ Incorrect
The default method 'brent' typically takes around 20 iterations for this smooth quartic function to converge.
🔧 Debug
advanced2:00remaining
Identify the error in minimize_scalar usage
What error does the following code raise when run?
SciPy
from scipy.optimize import minimize_scalar def f(x, y): return (x - 2)**2 + (y - 3)**2 result = minimize_scalar(f) print(result.x)
Attempts:
2 left
💡 Hint
minimize_scalar expects a function of a single variable.
✗ Incorrect
minimize_scalar only works with functions of one variable. Here, f expects two arguments, but minimize_scalar passes only one, causing a TypeError about argument count.
🧠 Conceptual
advanced1:30remaining
Choosing method in minimize_scalar
Which method in
minimize_scalar is best suited for minimizing a smooth unimodal function without bounds?Attempts:
2 left
💡 Hint
The default method is often a good choice for smooth functions.
✗ Incorrect
The 'brent' method is the default and is efficient for smooth unimodal functions without bounds. 'bounded' requires bounds, 'golden' is slower, and 'newton' requires derivative info.
🚀 Application
expert2:30remaining
Find minimum of a noisy function with bounds
You want to minimize the function
f(x) = (x - 2)**2 + noise where noise is random normal noise with mean 0 and std 0.1. You want to restrict x between 0 and 4. Which code snippet correctly uses minimize_scalar to find the minimum?SciPy
import numpy as np from scipy.optimize import minimize_scalar def f(x): noise = np.random.normal(0, 0.1) return (x - 2)**2 + noise
Attempts:
2 left
💡 Hint
To use bounds, you must specify the 'bounded' method explicitly.
✗ Incorrect
The 'bounded' method requires bounds and is the only method that accepts the bounds argument. Other methods ignore bounds or raise errors if bounds are given without 'bounded'.