Reputation: 3172
I have the following problem : I write my code with the Qt IDE. I was informed that when people try to compile it with other IDE's (like codeblocks, or visual studio) The output they get is different and that there are maufunctions. Any ideas what can be causing this ? I will give you an example:
This is Newton's Method with a function who's root is 2.83something. I get the same, correct calulations each time I run it in Qt. I get "nan" in code blocks and something irrelevant as well in visual studio. I don't understand, do I have a mistake somewhere in my code ? What can be causing this ?
#include <iostream>
#include <cmath> // we need the abs() function for this program
using namespace std;
const double EPS = 1e-10; // the "small enough" constant. global variable, because it is good programming style
double newton_theorem(double x)
{
double old_x = x; // asign the value of the previous iteration
double f_x1 = old_x*old_x - 8; // create the top side of the f(x[n+1] equation
double f_x2 = 2 * old_x; // create the bottom side
double new_x = old_x - f_x1 / f_x2; // calculate f(x[n+1])
//cout << new_x << endl; // remove the // from this line to see the result after each iteration
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
newton_theorem(new_x);
}
}// newton_theorem
int main()
{
cout << "This program will find the root of the function f(x) = x * x - 8" << endl;
cout << "Please enter the value of X : ";
double x;
cin >> x;
double root = newton_theorem(x);
cout << "The approximate root of the function is: " << root << endl;
return 0;
}//main
Upvotes: 1
Views: 340
Reputation: 258648
Yes, you run into undefined behavior:
if(abs(old_x - new_x) < EPS) // if the difference between the last and this iteration is insignificant, return the value as a correct answer;
{
return new_x;
}
else // if it isn't run the same function (with recursion YAY) with the latest iteration as a starting X;
{
/*return*/ newton_theorem(new_x); // <<--- HERE!
}
Missing a return
on the else
branch.
We could try to explain why Qt works (its compiler automatically puts the result of newton_theorem
in the return registry, or shares registries, or whatever), but the fact of the matter is anything can happen. Some compilers might behave the same on subsequent runs, some might crash all the time.
Upvotes: 3