Advertisement
bero_0401

_

Jul 18th, 2024
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | Source Code | 0 0
  1. import cmath
  2.  
  3. def solve_cubic(a, b, c, d):
  4.     # Make the coefficients compatible with the reduced form x^3 + px + q = 0
  5.     f = ((3 * c / a) - ((b ** 2) / (a ** 2))) / 3
  6.     g = ((2 * (b ** 3) / (a ** 3)) - (9 * b * c / (a ** 2)) + (27 * d / a)) / 27
  7.     h = ((g ** 2) / 4) + ((f ** 3) / 27)
  8.    
  9.     # Determine the number of roots
  10.     if h > 0:
  11.         R = -(g / 2) + cmath.sqrt(h)
  12.         S = cmath.cbrt(R)
  13.         T = -(g / 2) - cmath.sqrt(h)
  14.         U = cmath.cbrt(T)
  15.         x1 = (S + U) - (b / (3 * a))
  16.         return [x1]
  17.     elif f == 0 and g == 0 and h == 0:
  18.         x1 = -(d / a) ** (1/3)
  19.         return [x1]
  20.     elif h <= 0:
  21.         i = cmath.sqrt(((g ** 2) / 4) - h)
  22.         j = cmath.cbrt(i)
  23.         k = cmath.acos(-(g / (2 * i)))
  24.         L = j * -1
  25.         M = cmath.cos(k / 3)
  26.         N = cmath.sqrt(3) * cmath.sin(k / 3)
  27.         P = -(b / (3 * a))
  28.         x1 = 2 * j * cmath.cos(k / 3) - (b / (3 * a))
  29.         x2 = L * (M + N) + P
  30.         x3 = L * (M - N) + P
  31.         return [x1, x2, x3]
  32.  
  33. # Coefficients of the cubic equation: ax^3 + bx^2 + cx + d = 0
  34. a = 2
  35. b = -4
  36. c = -22
  37. d = 24
  38.  
  39. # Solve the cubic equation
  40. roots = solve_cubic(a, b, c, d)
  41.  
  42. # Display the roots
  43. print("The roots of the cubic equation are:", roots)
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement