Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop calculating cubic root

I'm trying to make a function that calculates the cubic root through Newton's method but I seem to have an infinite loop here for some reason?

#include <iostream>
#include <math.h>

using namespace std;

double CubicRoot(double x, double e);

int main()
{
    cout << CubicRoot(5,0.00001);
}

double CubicRoot(double x, double e)
{
    double y = x;
    double Ynew;
    do 
    {
        Ynew = y-((y*y)-(x/y))/((2*y)+(x/(y*y)));
        cout << Ynew;

    } while (abs(Ynew-y)/y>=e);

    return Ynew;
}
like image 638
Konsowa Avatar asked Sep 03 '13 11:09

Konsowa


1 Answers

You have not updated your y variable while iteration. Also using abs is quite dangerous as it could round to integer on some compilers.

EDIT

To clarify what I've mean: using abs with <math.h> could cause implicit type conversion problems with different compiles (see comment below). And truly c++ style would be using the <cmath> header as suggested in comments (thanks for that response).

The minimum changes to your code will be:

double CubicRoot(double x, double e)
{
    double y = x;
    double Ynew = x;
    do 
    {
        y = Ynew;
        Ynew = y-((y*y)-(x/y))/((2*y)+(x/(y*y)));
        cout << Ynew;

    } while (fabs(Ynew-y)/y>=e);
    return Ynew;
}
like image 69
Pavel K Avatar answered Sep 27 '22 20:09

Pavel K