Because you are converting your double value to a float, so as soon as you get close enough to 3*3 is roughly 9, it will retrun 9-9 == 0 from your abs function [which by the way is a bad name, I'd call it absdiff or some such].

--

Mats

Printable View

- 07-30-2008matsp
Because you are converting your double value to a float, so as soon as you get close enough to 3*3 is roughly 9, it will retrun 9-9 == 0 from your abs function [which by the way is a bad name, I'd call it absdiff or some such].

--

Mats - 07-30-2008anon
Actually he seems to be converting doubles to int's - even worse.

- 07-30-2008matsp
- 07-30-2008NeonBlack
It's a bad idea to use the same names as standard library functions. There are functions named sqrt() and abs() in <cmath>. It was pointed out earlier, but it's worth restating that it's a VERY bad idea to use == or != with floating point numbers as it will produce inconsistent results.

- 07-30-2008freddyvorhees
still has warnings

- 07-30-2008laserlight
What is your current code, and what are the current warnings?

- 07-30-2008freddyvorhees
Got it working

Code:`#include <iostream>`

using namespace std;

double absDiff(double a,double b)

{

if ((a-b) < 0)

{

return (a-b)*-1;

}

else

{

return (a-b);

}

}

double sqrtNum(double x)

{

double U = x;

double L = 0;

double guess = x/2;

if (x == 0 || x == 1)

{

return x;

}

else

while (absDiff((guess*guess),x) > .000000000001)

if (guess*guess > x)

{

U = guess;

guess = ((U - L)/2) + L;

}

else

{

L = guess;

guess = ((U - L)/2) + L;

}

return guess;

}

int main()

{

cout<<"Root ";

cout<<sqrt(5)<<endl;

}

- 07-30-2008tabstop
You may want to do something special, in case someone decides to type sqrtNum(-1). (And notice, that you forgot to change your call in main to your function as opposed to the library function.)

- 07-30-2008laserlightQuote:

Any improvements needed?

- 07-30-2008freddyvorhees
What do you mean by pulling guess = ((U - L)/2) + L?

- 07-30-2008tabstop
- 07-30-2008freddyvorhees
ahhhhhh

- 07-30-2008freddyvorhees
Maybe like this?

Code:`if (x == 0 || x == 1)`

{

return x;

}

else

while (absDiff((guess*guess),x) > .0000001)

{

if (guess*guess > x)

U = guess;

else

L = guess;

}

guess = ((U - L)/2) + L;

return guess;

- 07-30-2008MarkZWEERSQuote:

Code:`if (x == 0 || x == 1)`

- 07-30-2008tabstop
Oh, and your initial guesses implicitly assume that 0 < sqrt(x) < x; this is not true if 0< x < 1. For instance, sqrt(0.25) = 0.5, and you won't find those numbers.