from __init__ import install_dependencies
await install_dependencies()
import math
import numpy as np
from ipywidgets import interact
In this notebook, we will improve the quadratic equation solver in the previous lab using conditional executions.
Discriminant¶
Recall that a quadratic equation is
where , , and are real-valued coefficients, and is the unknown variable.
def iszero(v, a, b, c, *, rel_tol=1e-9):
# YOUR CODE HERE
raise NotImplementedError
# tests
assert not iszero(1e-8, 0, 2, 1)
assert iszero(1e-8, 1, 0, 1, rel_tol=1e-7)
assert not iszero(5e-9, 1, 2, 0)
# hidden tests
def get_roots(a, b, c, *, rel_tol=1e-9):
d = b**2 - 4 * a * c # discriminant
if iszero(d, a, b, c, rel_tol=rel_tol):
# YOUR CODE HERE
raise NotImplementedError
return roots
Source
# tests
assert np.isclose(get_roots(1, 1, 0), (-1.0, 0.0)).all()
assert np.isclose(get_roots(1, 0, 0), 0.0).all()
YOUR ANSWER HERE
Linear equation¶
YOUR ANSWER HERE
def get_roots(a, b, c, *, rel_tol=1e-9):
d = b**2 - 4 * a * c
# YOUR CODE HERE
raise NotImplementedError
return roots
Source
# tests
assert np.isclose(get_roots(1, 1, 0), (-1.0, 0.0)).all()
assert np.isclose(get_roots(1, 0, 0), 0.0).all()
assert np.isclose(get_roots(1, -2, 1), 1.0).all()
assert np.isclose(get_roots(0, -2, 1), 0.5).all()
Degenerate cases¶
What if ? In this case, the equation becomes
which is always satisfied if but never satisfied if .
def get_roots(a, b, c, *, rel_tol=1e-9):
d = b**2 - 4 * a * c
# YOUR CODE HERE
raise NotImplementedError
return roots
Source
# tests
assert np.isclose(get_roots(1, 1, 0), (-1.0, 0.0)).all()
assert np.isclose(get_roots(1, 0, 0), 0.0).all()
assert np.isclose(get_roots(1, -2, 1), 1.0).all()
assert np.isclose(get_roots(0, -2, 1), 0.5).all()
assert np.isclose(get_roots(0, 0, 0), (-float('inf'), float('inf'))).all()
assert get_roots(0, 0, 1) is None
After you have complete the exercises, you can run your robust solver below:
# quadratic equations solver
@interact(a=(-10, 10, 1), b=(-10, 10, 1), c=(-10, 10, 1))
def quadratic_equation_solver(a=1, b=2, c=1):
print("Root(s):", get_roots(a, b, c))