import math
import numpy as np
from ipywidgets import interactif not input('Load JupyterAI? [Y/n]').lower()=='n':
%reload_ext jupyter_aiIn 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.
We will improve the quadratic solver to return only one root when the discriminant is close enough to 0.
def iszero(x, y, z, *, rel_tol=1e-9):
# YOUR CODE HERE
raise NotImplementedError# tests
assert not iszero(1e-8, 0, 1)
assert iszero(1e-8, 1, 0, rel_tol=1e-7)
assert iszero(1e-8, 1, 10)# hidden testsdef get_roots(a, b, c, *, rel_tol=1e-9):
if iszero(d:=((y:=b**2)-(z:=4*a*c)), y, z, rel_tol=rel_tol):
# YOUR CODE HERE
raise NotImplementedError
return rootsSource
# 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, 1e-9, 0), 0.0).all()
assert np.isclose(get_roots(1, 1e-6, 0), (-1e-06, 0.0)).all()YOUR ANSWER HERE
Linear equation¶
YOUR ANSWER HERE
def get_roots(a, b, c, *, rel_tol=1e-9):
# YOUR CODE HERE
raise NotImplementedError
return rootsSource
# 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):
# YOUR CODE HERE
raise NotImplementedError
return rootsSource
# 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 NoneAfter 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))