-
sqrt function
Suppose I have this bit of code.
Code:
side1=distance(x1, why1, x2, y2);
side2=distance(x1, why1, x3, y3);
side3=distance(x2, y2, x3, y3);
tri_type(side1, side2, side3);
Code:
void tri_type(double first, double second, double third){
//function to see if triangle is scalene, isosceles, or equilateral
//parameters are the three side lengths of the triangle
if((first==second)&&(second==third)) cout<<"The triangle is equilateral."<<endl;
else if ((first!=second)&&(second!=third)&&(first!=third))
cout<<"The triangle is scalene."<<endl;
else cout<<"The triangle is isosceles."<<endl;
}
if the values for the three coordinates were. (0,0),(2,0) and (1, sqrt(3)) it should evaluate to an equalaterial triangle. Does the sqrt function do an approx.? or is the double not reading out to enough decimal places? Or other? In either case, how would I fix this?
Thanks
-Extol
-
First, sqrt(3) isn't an exact number.
Second, floating point numbers aren't always stored precisely.
Third, due to 2) you should never compare two floating point numbers using ==, but check if the difference is less than a small number, ie:
Code:
#define AllowedDiff 0.0001
if(abs(FloatNumber1 - FloatNumber2) < AllowedDiff)
{
cout << "The numbers are equal!";
}
-
He's right... for a simple example, try adding 0.1 to a sum that starts at zero 10 times, and then compare that to 1. You will see that the numbers are different no matter what float size you use.