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
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
Actually he seems to be converting doubles to int's - even worse.
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.
still has warnings
What is your current code, and what are the current warnings?
Got it working
Any improvements needed?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;
}
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.)
You could use abs() from <cmath> instead of implementing abdDiff(), but if your goal is to avoid using stuff from <cmath> entirely then change (a-b)*-1 to (b-a). You could also pull guess = ((U - L)/2) + L; to after the if and else blocks. Oh, and your indentation could be more consistent.Quote:
Any improvements needed?
What do you mean by pulling guess = ((U - L)/2) + L?
ahhhhhh
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;
as stated several times, don't compare 'double' values with integer values. The condition is not correct.Quote:
Code:if (x == 0 || x == 1)
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.