sqrt function

This is a discussion on sqrt function within the C++ Programming forums, part of the General Programming Boards category; 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); ...

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    70

    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

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    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!";
    }
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    jasondoucette.com JasonD's Avatar
    Join Date
    Mar 2003
    Posts
    278
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  3. dllimport function not allowed
    By steve1_rm in forum C++ Programming
    Replies: 5
    Last Post: 03-11-2008, 03:33 AM
  4. Question..
    By pode in forum Windows Programming
    Replies: 12
    Last Post: 12-19-2004, 06:05 PM
  5. Sqrt() Function
    By tmoney$ in forum C Programming
    Replies: 4
    Last Post: 04-22-2003, 04:31 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21