This site solves cubic equations, and has the equations it uses
I wrote this function to get the same results but it's not working
void cubicFormula(float a, float b, float c, float d, float *results)
{
float a2 = a*a;
float b2 = b*b;
float b3 = b2*b;
float q = (3*c- b2)/9;
float q2 = q*q;
float q3 = q2*q;
float r = -27*d + b*(9*c-2*b2);
float r2 = r*r;
float discriminant = q3 + r2;
float s = r + sqrtf(discriminant);
float t = r - sqrtf(discriminant);
float term1 = powf((-t + s)/2, 1/3.);
float r13= 2 * sqrtf(q);
results[0] = (- term1 + r13 * cosf(q3/3));
results[1] = (- term1 + r13 * cosf(q3 + (2*M_PI)/3));
results[2] = (- term1 + r13 * cosf(q3 + (4*M_PI)/3));
}
What could be the problem, is there something I am missing?
Update:
For instance, using these values
a = -1.000000;
b = 36.719475;
c = -334.239960;
d = 629.877808;
The discriminant is less then zero, so r13 is nan
But the site mentioned above and a couple of online solvers I've tested find the three roots
23.775687816485593
2.548516232734247
10.395270950780164
All of them real numbers
a
,b
,c
andd
are you using? Not all cubic equations have 3 real roots. – Iambus