0
0
SciPydata~20 mins

Minimizing scalar functions (minimize_scalar) in SciPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Minimize Scalar Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1: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))
A0.0
B3.0
C4.0
D1.5
Attempts:
2 left
💡 Hint
Think about where the function (x - 3)^2 + 4 reaches its lowest value.
data_output
intermediate
1: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)
A20
B22
C15
D18
Attempts:
2 left
💡 Hint
Check the nit attribute in the result object.
🔧 Debug
advanced
2: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)
ATypeError: f() missing 1 required positional argument: 'y'
BNo error, prints the minimum x value
CValueError: too many input arguments
DTypeError: f() takes 2 positional arguments but 1 was given
Attempts:
2 left
💡 Hint
minimize_scalar expects a function of a single variable.
🧠 Conceptual
advanced
1:30remaining
Choosing method in minimize_scalar
Which method in minimize_scalar is best suited for minimizing a smooth unimodal function without bounds?
A'bounded'
B'golden'
C'brent'
D'newton'
Attempts:
2 left
💡 Hint
The default method is often a good choice for smooth functions.
🚀 Application
expert
2: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
Aminimize_scalar(f, bounds=(0, 4), method='bounded')
Bminimize_scalar(f, method='brent')
Cminimize_scalar(f, bounds=(0, 4))
Dminimize_scalar(f, method='golden', bounds=(0, 4))
Attempts:
2 left
💡 Hint
To use bounds, you must specify the 'bounded' method explicitly.