Is it possible to solve Cubic equation without using sympy?
Example:
import sympy as sp
xp = 30
num = xp 4.44
sp.var('x, a, b, c, d')
Sol3 = sp.solve(0.0509 * x ** 3 0.0192 * x ** 2 3.68 * x - num, x)
The result is:
[6.07118098358257, -3.2241955998463 - 10.0524891203436*I, -3.2241955998463 10.0524891203436*I]
But I want to find a way to do it with numpy or without 3 part lib at all
I tried with numpy:
import numpy as np
coeff = [0.0509, 0.0192, 3.68, --4.44]
print(np.roots(coeff))
But the result is :
[ 0.40668245 8.54994773j 0.40668245-8.54994773j -1.19057511 0.j]
CodePudding user response:
In your numpy method you are making two slight mistakes with the final coefficient.
In the SymPy
example your last coefficient is - num
, this is, according to your code: -num = - (xp 4.44) = -(30 4.44) = -34.44
In your NumPy
example yout last coefficient is --4.44
, which is 4.44
and does not equal -34.33
.
If you edit the NumPy
code you will get:
import numpy as np
coeff = [0.0509, 0.0192, 3.68, -34.44]
print(np.roots(coeff))
[-3.2241956 10.05248912j -3.2241956 -10.05248912j
6.07118098 0.j ]
The answer are thus the same (note that NumPy
uses j
to indicate a complex number. SymPy
used I
)
CodePudding user response:
this Youtube video from mathologer could help understand it.