""" Exercise 3.8 from "A primer on... Use the standard formula for a quadratic eq, x = -b +- sqrt(b**2 - 4*a*c)/(2*a) But test the sign of the argument to the sqrt function and use math if it is positive (real solution) otherwise cmath (complex solution). """ import math import cmath def roots(a, b, c): disc = b**2 - 4 * a * c if disc < 0: x1 = (-b + cmath.sqrt(disc))/ (2 * a) x2 = (-b - cmath.sqrt(disc))/ (2 * a) else: x1 = (-b + math.sqrt(disc))/ (2 * a) x2 = (-b - math.sqrt(disc))/ (2 * a) return x1, x2 def test_roots_float(): tol = 1e-10 a, b, c = 2, 3, 1 expected = -0.5, -1 computed = roots(a, b, c) for e, c in zip(expected, computed): assert abs(e-c) < tol def test_roots_complex(): tol = 1e-10 a, b, c = 1, 1, 1 expected = (-1 + cmath.sqrt(-3)) / 2, (-1 - cmath.sqrt(-3)) / 2 computed = roots(a, b, c) for e, c in zip(expected, computed): assert abs(e - c) < tol """ If we want to run the program in the normal way, for instance with "python roots_quadratic.py" from the command line, we need to call the test functions here""" test_roots_float() test_roots_complex() """ An even better alternative is to use pytest, which will automatically call all test functions, and we don't need to call them. See examples below. """ """ Standard run, no output since both tests pass: Terminal> python roots_quadratic.py """ """ Run with pytest Terminal> pytest roots_quadratic.py ============================= test session starts ============================== platform darwin -- Python 3.9.7, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 rootdir: /Users/sundnes/Desktop/IN1900_10_sept plugins: anyio-2.2.0, mock-3.10.0, cov-3.0.0 collected 1 item roots_quadratic.py . [100%] ============================== 1 passed in 0.02s =============================== """