Im getting the wrong roots when running the program. The maths the program is based on is in the attatched image.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define pi 3.14159265
int sign(float s);
int main()
{
float a1, a2, a3, x1, x2, x3, s, q, th, s_sq, q_cub, a1_sq, a1_cub, s_abs;
printf("The cubic equation has the form x^3 + a1x^2 + a2x + a3 = 0\n");
printf("Enter a1: ");
scanf("%f", &a1);
printf("\nEnter a2: ");
scanf("%f", &a2);
printf("\nEnter a3: ");
scanf("%f", &a3);
a1_cub = pow(a1, 3);
a1_sq = pow(a1, 2);
/* calculate q and s */
q = ( a1_sq - (3 * a2) ) / 9;
s = ( (2 * a1_cub) - (9 * (a1*a2) ) + (27 * a3) ) / 54;
/* get square / cube of s and q */
s_sq = pow(s, 2);
q_cub = pow(q, 3);
s_abs = fabs(s);
/* ****** */
th = acos( (s/(sqrt(q_cub)) )); /* calculate theta */
if( (q_cub - s_sq) >= 0) /* cubic equation has 3 roots */
{
x1 = ((-2)*(sqrt(q))*(th/3)) - (a1/3);
x2 = ((-2)*(sqrt(q))*((th + (2*pi))/3)) - (a1/3);
x3 = ((-2)*(sqrt(q))*((th + (4*pi))/3)) - (a1/3);
printf("\nx1 = %f\nx2 = %f\nx3 = %f\n", x1, x2, x3);
}
else if( (s_sq - q_cub) > 0 ) /* cubic equation has 1 root */
{
float part1 = sqrt(s_sq - q_cub) + s_abs;
x1 = -(sign(s)) * ( (pow(part1, (1/3))) + (q/(pow(part1, (1/3)))) ) - (a3/3);
printf("\nx1 = %f", x1);
}
else
{
printf("something crap happened\n");
}
system("pause");
return 0;
}
int sign(float s)
{
if(s > 0)
{
return 1;
}
else if(s < 0)
{
return -1;
}
}