Advertisement
Guest User

Cubic Equation

a guest
Sep 14th, 2015
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. from math import sqrt, acos, cos, pi
  2.  
  3. # Coefficients of x^3 + (C_1)x^2 + (C_2)x + C_3 = 0
  4. C = [1, # Coefficient C_1
  5. 1, # Coefficient C_2
  6. 1 # Coefficient C_3
  7. ]
  8. # Substitutions (see solution of Cubic equations:
  9. # mathworld.wolfram.com/CubicFormula.html )
  10. w = (3*C[1] - C[0]**2)/3.0
  11. q = (27*C[2] - 9*C[0]*C[1] + 2*C[0]**3)/27.0
  12. R_t = (w/3.0)**3 + (q/3.0)**2.0
  13. q_s = q/abs(q) #math.copysign(1, q)
  14.  
  15. if R_t < 0:
  16. Ratio = sqrt(((q/2.0)**2)/(-(w/3.0)**3))
  17. if abs(Ratio) < 1.0:
  18. phi = acos(Ratio)
  19. else:
  20. raise ValueError # Raise Math error if no solution
  21. #phi = math.degrees(math.acos(Ratio-2)+math.pi)
  22. # math.degrees(math.acos(Ratio-2))
  23. else:
  24. raise ValueError # Add this to your exception handling for when a solution does not exist.
  25. # Analytical expressions for roots:
  26. roots = [-2*q_s*sqrt(-w/3.0)*cos(phi/3.0 ) - C[0]/3.0,
  27. -2*q_s*sqrt(-w/3.0)*cos(phi/3.0 + 2*pi/3.0) - C[0]/3.0,
  28. 2*q_s*sqrt(-w/3.0)*cos(phi/3.0 + 4*pi/3.0) - C[0]/3.0
  29. ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement