Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cmath
- def solve_cubic(a, b, c, d):
- # Make the coefficients compatible with the reduced form x^3 + px + q = 0
- f = ((3 * c / a) - ((b ** 2) / (a ** 2))) / 3
- g = ((2 * (b ** 3) / (a ** 3)) - (9 * b * c / (a ** 2)) + (27 * d / a)) / 27
- h = ((g ** 2) / 4) + ((f ** 3) / 27)
- # Determine the number of roots
- if h > 0:
- R = -(g / 2) + cmath.sqrt(h)
- S = cmath.cbrt(R)
- T = -(g / 2) - cmath.sqrt(h)
- U = cmath.cbrt(T)
- x1 = (S + U) - (b / (3 * a))
- return [x1]
- elif f == 0 and g == 0 and h == 0:
- x1 = -(d / a) ** (1/3)
- return [x1]
- elif h <= 0:
- i = cmath.sqrt(((g ** 2) / 4) - h)
- j = cmath.cbrt(i)
- k = cmath.acos(-(g / (2 * i)))
- L = j * -1
- M = cmath.cos(k / 3)
- N = cmath.sqrt(3) * cmath.sin(k / 3)
- P = -(b / (3 * a))
- x1 = 2 * j * cmath.cos(k / 3) - (b / (3 * a))
- x2 = L * (M + N) + P
- x3 = L * (M - N) + P
- return [x1, x2, x3]
- # Coefficients of the cubic equation: ax^3 + bx^2 + cx + d = 0
- a = 2
- b = -4
- c = -22
- d = 24
- # Solve the cubic equation
- roots = solve_cubic(a, b, c, d)
- # Display the roots
- print("The roots of the cubic equation are:", roots)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement