CS1302 Introduction to Computer Programming
import math
import numpy as np
from ipywidgets import interactIn 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 get_roots(a, b, c):
d = b**2 - 4 * a * c # discriminant
if math.isclose(d, 0):
# YOUR CODE HERE
raise NotImplementedError()
return roots# 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()# hidden testsYOUR ANSWER HERE
Linear equation¶
YOUR ANSWER HERE
def get_roots(a, b, c):
d = b**2 - 4 * a * c
# YOUR CODE HERE
raise NotImplementedError()
return roots# 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()# hidden testsDegenerate cases¶
What if ? In this case, the equation becomes
which is always satisfied if but never satisfied if .
def get_roots(a, b, c):
d = b**2 - 4 * a * c
# YOUR CODE HERE
raise NotImplementedError()
return roots# 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# hidden testsAfter 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))