1. ## Cubic equation program not giving me right answers

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;
}

}``` 2. Any example input, output, and expected output values? One potential problem for the single root solution is that 1/3 will be evaluated as 0. 3. im testing my results with the results from this website

http://www.agolda.com/CubicEquation.html

which seem to be accurate

I changed the (1/3)'s to (0.334)'s and the results are still wrong 4. > (1/3)
This sub-expression will be evaluated as integers, giving 0

> int sign(float s)
What does this return when s == 0 ?

> x1 = ((-2)*(sqrt(q))*(th/3)) - (a1/3);
Your graphic contains a cos() as well 5. > x1 = ((-2)*(sqrt(q))*(th/3)) - (a1/3);
Your graphic contains a cos() as well

ARGH! Thanks...that was a really stupid mistake, a pretty much rewrote the code like 3 times trying to fix it 6. Did that fix it? 7. it worked for a few but when I tried

a1 = -4
a2 = -1
a3 = -20

I get an incorrect result 8. x1 = -(whatever) ... a1 => a1 = -(x1 whatever...)

are they the right numbers, but with the wrong signs? 9. I assume theyre right...i just followed the information i was given (that image i attacthed) Popular pages Recent additions 