1. def f(x): """ Evaluates function `f(x) = x^2 - 15 \sin(x * \pi/3)` Parameters ---------- x : array_like Input(s) to the function Returns ------- out : ndarray Function `f`, evaluated at point(s) x """ # your code here 2. def grad_f(x): """ Evaluates gradient of a function `f(x) = x^2 - 15 \sin(x * \pi/3)` Parameters ---------- x : array_like Point(s) at which gradient should be avalueated Returns ------- out : ndarray Gradient of the function `f` evaluaed at point(s) x """ # your code here # TEST 1. f(x) assert f(0.) == 0. assert np.allclose(f(np.array([2.5, 7.5])), np.array([-1.25, 41.25])) assert np.allclose(f(np.arange(-10, 10, 1)), np.arange(-10, 10, 1)**2 - 15*np.sin(np.pi/3*np.arange(-10, 10, 1))) x_min = 1.33668375 assert np.allclose(f(x_min), -12.9944407) # TEST 2. grad_f(x) assert np.allclose(grad_f(0.), -15.7079) assert isinstance(grad_f(0.), float) assert np.allclose(grad_f(0), - 5*np.pi*np.cos(0)), 'Gradient at point 0 is wrong' assert np.allclose(grad_f(np.arange(-10, 10, 1)), 2*np.arange(-10, 10, 1) - 5*np.pi*np.cos(np.pi/3*np.arange(-10, 10, 1))) x_min = 1.33668375 assert np.allclose(grad_f(x_min), 0, atol=1e-05)
1. def f(x):
"""
Evaluates function `f(x) = x^2 - 15 \sin(x * \pi/3)`
Parameters
----------
x : array_like
Input(s) to the function
Returns
-------
out : ndarray
Function `f`, evaluated at point(s) x
"""
# your code here
2. def grad_f(x):
"""
Evaluates gradient of a function `f(x) = x^2 - 15 \sin(x * \pi/3)`
Parameters
----------
x : array_like
Point(s) at which gradient should be avalueated
Returns
-------
out : ndarray
Gradient of the function `f` evaluaed at point(s) x
"""
# your code here
# TEST 1. f(x)
assert f(0.) == 0.
assert np.allclose(f(np.array([2.5, 7.5])), np.array([-1.25, 41.25]))
assert np.allclose(f(np.arange(-10, 10, 1)), np.arange(-10, 10, 1)**2 - 15*np.sin(np.pi/3*np.arange(-10, 10, 1)))
x_min = 1.33668375
assert np.allclose(f(x_min), -12.9944407)
# TEST 2. grad_f(x)
assert np.allclose(grad_f(0.), -15.7079)
assert isinstance(grad_f(0.), float)
assert np.allclose(grad_f(0), - 5*np.pi*np.cos(0)), 'Gradient at point 0 is wrong'
assert np.allclose(grad_f(np.arange(-10, 10, 1)), 2*np.arange(-10, 10, 1) - 5*np.pi*np.cos(np.pi/3*np.arange(-10, 10, 1)))
x_min = 1.33668375
assert np.allclose(grad_f(x_min), 0, atol=1e-05)
Step by step
Solved in 3 steps with 1 images