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; }
source share