Trying to calc solution to cubic
Ok this is what ive done so far:
Code:
/*
** Solve a cubic polynomial
** By xxxxxxxxxxxxxxxx
*/
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
float a1,a2,a3,b,c,d,G,roots,S,x1,x2,x3, C, theta, P, Q;
int main(int argc, char* argv[])
{
printf("Please enter the coefficient of x^2:");
scanf("%f",&a1);
printf("Please enter the coefficient of x:");
scanf("%f",&a2);
printf("Please enter the constant term:");
scanf("%f",&a3);
Q=((a1*a1-3*a2)/9);
S = ((2*a1*a1*a1)-(9*a1*a2+(27*a3)))/54;
theta=acos(S/sqrt(Q*Q*Q));
P= pow ( (sqrt( (S*S)-(Q*Q*Q)+fabs(S) )), 1/3);
C = ((Q*Q*Q)-(S*S));
if (C<=0)
{
theta=acos(S/sqrt(Q*Q*Q));
x1 = (((-2*sqrt(Q))*(cos(theta/3))) - a1)/3;
x2 = ((-2*sqrt(Q))*(cos((theta+2*3.1412)))/3) - a1/3;
x3 = ((-2*sqrt(Q))*(cos((theta+4*3.1412)))/3) - a1/3;
printf("First root: %f.\n", x1);
printf("Second root: %f.\n", x2);
printf("Third root: %f.\n", x3);
}
else {
if(G>0) {
x1 = -G*(P + (Q/P))-(a1/3);
printf("Only root: %f.\n", x1);
} else {
x1 = G*(P + (Q/P))-(a1/3);
}
printf("There is only one single root: %f.\n", x1);
}
return(0);
}
However it doesnt work for all values? More importantly I get this also:
Please enter the coefficient of x^2:9
Please enter the coefficient of x:9
Please enter the constant term:9
There is only one single root: -1.#IND00.
Press any key to continue
I got that with 9,9,9. What does -1.#IND00 mean?
Any help would be greatly appreciated.