Infinite loop calculating the cubic root

I am trying to make a function that calculates the cubic root through the Newton method, but for some reason do I seem to have an infinite loop?

#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; } 
+4
source share
2 answers

You did not update your y variable during iteration. Also, using abs pretty dangerous, as it can be rounded to the nearest integer on some compilers.

EDIT

To understand what I mean: using abs with <math.h> can lead to implicit type conversion problems with different compilers (see comment below). Indeed, the C ++ style will use the <cmath> header, as suggested in the comments (thanks for this answer).

Minimal changes in 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; } 
+8
source

You can change

  Ynew = y-((y*y)-(x/y))/((2*y)+(x/(y*y))); 

to an equivalent but more recognizable expression

  Ynew = y*(y*y*y+2*x)/(2*y*y*y+x) 

which is the Halley method for f (y) = y ^ 3-x and has third-order convergence.

0
source

Source: https://habr.com/ru/post/1500284/


All Articles