I have a program I’m writing in which the user has the option to choose between solving a cubic function for either second or third degree polynomials. Once choosing, the program applies a number of formulas, including: solving the 2nd degree discriminant, the quadratic formula, the formula for polynomials of the second degree, Cardano’s analogous method of third degree polynomials, and the standard cubic formula (basically, the first four formulas on this page).
Here’s my code:
import math
def deg3():
print("This is a third degree polynomial calculator.")
print("Please enter four numbers.")
a = int(input())
b = int(input())
c = int(input())
d = int(input())
# Apply Cardano's compressed method to find x root, broken up into different variables.
p = (-1 * b)/(3 * a)
q = p ** 3 + (b * c - (3 * a * d))/ (6 * (a ** 2))
r = c / (3 * a)
x = (q + (q**2 + (r - p**2)**3) **1/2) **1/3 + (q + (q**2 + (r - p**2)**3) **1/2) **1/3 + p
print("The root is:", x)
# Applies final cubic formula, and returns.
total = (a * x**3) + (b * x**2) + (c * x) + d
total = round(total, 3)
return total
# If discr > 0, then the equation has three distinct real roots.
# If discr = 0, then the equation has a multiple root and all its roots are real.
# If discr < 0, then the equation has one real root and
# two nonreal complex conjugate roots.
Now it easily returns a total. The computation is correct, but I’m still trying to wrap my brain around the analogous formula. What is the discriminant part of the equation? How do I find potential roots, like I do with the quadratic formula? Probably a no-brainer question, but I want to understand the process better.
First, there are many differences between your cubic function and the equation on the site you link to. Among the most notable:
Your order of operations is off: a line like:
should be:
otherwise, a term like
27 * a**3won’t end up in the denominator- it will instead be seen as 27 in the denominator anda**3afterwards.You never include a cube root, even though there are two in the equation you link to.
You do
x * 2 - small, but the two items added together in the equation are not identical- one has a plus sign where the other has a minus.However, even if you fix all the issues with the function, you will still get a math domain error when trying to solve many cubic equations. Note this paragraph from your link:
Solving cubic equations requires dealing with complex numbers (though only temporarily- as noted, they’ll cancel out), so you can’t use
math.sqrtto solve it. You might be interested in the cmath package.