If you understand the importance of the expression under the square root (i.e. the sign of the discriminant) you can rename one subexpression:
def quadratic_formula(a, b, c):
discriminant = b ** 2 - 4 * a * c
return [
(-b - math.sqrt(discriminant)) / (2 * a),
(-b + math.sqrt(discriminant)) / (2 * a)
]
Of course you can refactor it further with pointless stuff like denom = 2a, but that doesn't add much semantic value. So the above is more or less the vocabulary we have about quadratic equations today.
Loh's contribution is a specific way of refactoring the code by first dividing by a:
def quadratic_formula(a, b, c):
b = b / a
c = c / a
discriminant = b ** 2 - 4 * c
return [
-b / 2 - math.sqrt(discriminant) / 2,
-b / 2 + math.sqrt(discriminant) / 2
]
Which then unlocks the ability to talk about the subexpressions in relation to the roots (a la Vieta's formula):
def quadratic_formula(a, b, c):
b = b / a
c = c / a
sumOfRoots = -b
productOfRoots = c
averageRoot = sumOfRoots / 2
# Want roots [averageRoot - delta, averageRoot + delta]
# such that:
# productOfRoots == (averageRoot - delta) * (averageRoot + delta)
# == averageRoot ** 2 - delta ** 2
delta = math.sqrt(averageRoot ** 2 - productOfRoots)
return [
averageRoot - delta,
averageRoot + delta
]
Your code is no longer using single-letter variable names!
Comments
I think it's useful to think of this as refactoring code to make it more readable (and therefore more teachable).
If you're a memorizer, your code might as well be obfuscated code:
If you understand the importance of the expression under the square root (i.e. the sign of the discriminant) you can rename one subexpression: Of course you can refactor it further with pointless stuff like denom = 2a, but that doesn't add much semantic value. So the above is more or less the vocabulary we have about quadratic equations today.Loh's contribution is a specific way of refactoring the code by first dividing by a:
Which then unlocks the ability to talk about the subexpressions in relation to the roots (a la Vieta's formula): Your code is no longer using single-letter variable names!