I implemented fixed-point iteration in C++, and I forgot the return statement:
double fixedpoint(double g(double), double p0, double tol, double max_iter)
{
double p, error, i = 1;
do
{
p = g(p0);
error = std::abs(p - p0);
i++;
p0 = p;
} while (i < max_iter && error > tol);
// No return statement
}
Then I called the function:
/* g(x) = (3x^2 + 3)^(1/4) */
double g(double x)
{
return pow(3 * x * x + 3, 0.25);
}
int main()
{
// Test
double p0 = 1;
double tol = 1e-2;
int max_iter = 20;
double p = fixedpoint(g, p0, tol, max_iter);
cout << "Solve x = (3x^2 + 3)^(1/4) correct to within 1e-2 using fixed-point iteration:" << endl;
cout << "Solution: x = " << setiosflags(ios::fixed) << setprecision(6) << p << endl;
}
and I got the following result:
Solve x = (3x^2 + 3)^(1/4) correct to within 1e-2 using fixed-point iteration:
Solution: x = 0.005809
In fact, 0.005809 is the value of the error
variable (in the fixedpoint
function) at the last iteration. Why is that value returned?
I'm using GCC version 7.4.0. (Also I've checked Function not returning value, but cout displays it but it doesn't apply to me.)