Skip to content

Instantly share code, notes, and snippets.

@XerxesZorgon
Created April 14, 2022 18:36
Embed
What would you like to do?
% Solves the depressed cubic equation x^3 + Ax + B = 0
% Ref: http://www.sosmath.com/algebra/factor/fac11/fac11.html
%
% Input(s)
% A,B: Coefficients of depressed cubic
%
% Output(s)
% x: Solution to the equation
%
% Example:
% depressedCubic(6,20)
% ans = 2
% Check: 2^3 + 6*2 = 20
%
% See also:
%
%
% Dependencies: None
%
%
% Written by: John Peach 10-Apr-2022
% Wild Peaches
%
% Revisions:
function x = depressedCubic(A,B)
% Equation is of the form x^3 + Ax = B
% Solution is x = s - t where
% 3st = A
% s^3 - t^3 = B
% Substitute t = A/(3s) in second equation to get
% s^3 - A^3/(27s^3) = B
% Let u = s^3, and solve quadratic
% u^2 - Bu - A^3/27 = 0
D = sqrt(B^2+4*A^3/27);
u = [B + D; B - D]/2;
% Substitute back into s
s = u.^(1/3);
% Keep only the real, nonzero roots
if ~isreal(s(2)) || abs(s(2)) < sqrt(eps)
s(2) = [];
end;
if ~isreal(s(1)) || abs(s(1)) < sqrt(eps)
s(1) = [];
end;
% Solve for x
t = A./(3*s);
x = s - t;
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment