[ad_1]

I recently learned a bit of C and wanted to write a program that would solve cubic equations by first finding two roots using the Newton-Raphson method, and then the third using one of the Vieta equations.

The code I ended up writing is below. The problem is that the code doesn’t work for many cubic equations, such as 2x^3 + 7x^2 – 2x – 1 = 0. To me, it seems that whenever the value of x in the newton-raphson formula is negative, the program often breaks after spitting out the first root (which it has always done till now successfully).

Any tips on how to make the code work?

Note that this is the second program I’ve ever worked on in code (apart from a little bit of java a few years ago).

```
#include <stdio.h>
#include <math.h>
int main(){
int HighestPower;
double a;
double b;
double c;
double d;
HighestPower = 3;
printf("This program solves for the real roots of a cubic equation in the form: ax^3+bx^2+cx+d=0\n");
printf("What is the the coefficient of the %d power term?", HighestPower);
scanf("%lf", &a);
int SecondHighestPower = HighestPower - 1;
printf("What is the the coefficient of the %d power term?", SecondHighestPower);
scanf("%lf", &b);
int ThirdHighestPower = SecondHighestPower - 1;
printf("What is the coefficient of the %d power term?", ThirdHighestPower);
scanf("%lf", &c);
int FourthHighestPower = ThirdHighestPower - 1;
printf("What is the coefficient of the %d power term?", FourthHighestPower);
scanf("%lf", &d);
printf("So your equation is: %1.1lfx^%d + ", a, HighestPower);
printf("%1.1lfx^%d + ", b, SecondHighestPower);
printf("%1.1lfx^%d + ", c, ThirdHighestPower);
printf("%1.1lf\n", d, FourthHighestPower);
printf("Solve the equation?\n");
system("pause");
// Newton-Raphson method to find first root:
double x;
x = 1000;
double fx = a*x*x*x + b*x*x + c*x + d;
double dydx = 3*a*x*x + 2*b*x + c;
x = x - fx/dydx;
fx = a * x*x*x + b * x*x + c * x + d;
dydx = 3 * a * x * x + 2 * b * x + c;
while (fx != 0) {
x = x - fx/dydx;
fx = a*x*x*x + b*x*x + c*x + d;
dydx = 3*a*x*x + 2*b*x + c;
}
printf("solutions are:\n%lf\n", x);
double root1 = x; // (First root)
// Tries x=0 in Newton-Raphson to try and find second root:
x = 0;
fx = a*x*x*x + b*x*x + c*x + d;
dydx = 3*a*x*x + 2*b*x + c;
x = x - fx/dydx;
while (fx != 0) {
x = x - fx/dydx;
fx = a*x*x*x + b*x*x + c*x + d;
dydx = 3*a*x*x + 2*b*x + c;
}
double root2 = x; // (Root found using x=0)
if (root2 == root1) { // Checks if root found using x=0 is a new root
x = -100; // If not, tries x = -100 to get a root.
fx = a*x*x*x + b*x*x + c*x + d;
dydx = 3*a*x*x + 2*b*x + c;
while (fx != 0) {
x = x - fx/dydx;
fx = a*x*x*x + b*x*x + c*x + d;
dydx = 3*a*x*x + 2*b*x + c;
}
root2 = x;
if (root2 == root1) {
printf("No luck.");
}
printf("%lf\n", x);
} else {
printf("%lf\n", root2);
}
//Last root (Using Vieta formula):
double ba = -b/a;
double root3 = ba - root1 - root2;
printf("%lf\n", root3);
system("pause");
return 0;
}
```

[ad_2]