python – Solving a cubic function for second and third degree polynomials?
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:
big = (-1 *( b**3 / 27 * a**3) + (b * c / 6 * a**2) - (d / 2 * a))
big = (-1 *( b**3 / (27 * a**3)) + (b * c / (6 * a**2)) - (d / (2 * a)))
otherwise, a term like
27 * a**3wont end up in the denominator- it will instead be seen as 27 in the denominator and
You never include a cube root, even though there are two in the equation you link to.
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:
But if we apply Cardanos formula to this example, we use a=1, b=0, c=-15, d=-4, and we find that we need to take the square root of -109 in the resulting computation. Ultimately, the square roots of negative numbers would cancel out later in the computation, but that computation cant be understood by a calculus student without additional discussion of complex numbers.
Solving cubic equations requires dealing with complex numbers (though only temporarily- as noted, theyll cancel out), so you cant use
math.sqrt to solve it. You might be interested in the cmath package.