Hey again!!
As I was posting this I was trying to solve the problem of why this program didn't do what it was supposed to. I've now managed to fix it, so instead I'm posting the program as a curio.
To explain a little of what's going on, the program is trying to solve specifically cubic equations (with an x3 term in them) using the Newton-Raphson method. I've done this by defining the necessary functions at the bottom and using them in the main for-loop. The program returns the equation and a single root. By picking cubic equations I can guarantee at least one real root and since cubic curves are nice I should always get a reasonable answer.
// Program that will find an approximate solution to a cubic equation with coefficients defined by the user.
// The method used is the Newton-Raphson method, as this avoids the need to know where exactly the root lies.
#include <iostream>
#include <cmath>
using namespace std;
float Function(float number1, float number2, float number3, float constant, float root) ;
float Derivative(float number1, float number2, float number3, float root);
int main()
{
float number1, number2, number3, constant, guess, iteration, newguess, root;
cout << "This program will help find a root of a user-defined cubic equation." << endl;
cout << "Please enter four coefficients for the equation." << endl << "Include a single space between each number, and hit enter only after inputting all the numbers: ";
cin >> number1 >> number2 >> number3 >> constant;
cout << endl;
cout << "Please enter an initial guess and the number of iterations to perform. " << endl ;
cout << "Include a single space between the numbers and don't hit enter until you've input both numbers: " ;
cin >> guess >> iteration ;
newguess=0;
for (int i=1; i<=iteration; i++) {
newguess = guess - (Function(number1, number2, number3, constant, guess))/(Derivative(number1, number2, number3, guess)) ;
guess = newguess;
}
root = guess;
cout << "There is a root of the equation " << number1 << "*x^3 + " << number2 << "*x^2 + " << number3 << "*x + " << constant << " at x = " << root << "." << endl;
return 0;
}
// Definitions of functions used
float Function(float number1, float number2, float number3, float constant, float root)
{
float function;
function = number1*root*root*root + number2*root*root + number3*root + constant ;
return function ;
}
float Derivative(float number1, float number2, float number3, float root)
{
float derivative ;
derivative = 3*number1*root*root + 2*number2*root + number1 ;
return derivative ;
}