Clarify the difference in representation of numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vensriram
    New Member
    • Aug 2010
    • 48

    #1

    Clarify the difference in representation of numbers

    Code:
    void main()
    {
      float me = 0.7;
    if(me<0.7)
    printf("C");
    else
    printf("C++");
    }
    For the above code my compiler prints as C

    However for the code
    Code:
    void main()
    {
      float me = 1.7;
    if(me<1.7)
    printf("C");
    else
    printf("C++");
    my compile prints as C++.

    Hence kindly clarify why is the above difference?
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    and where do you change the values of me? ......to trigger the print op?

    Comment

    • vensriram
      New Member
      • Aug 2010
      • 48

      #3
      I am not changing the value of me anywhere.
      In the first program the if statement compares whether me(i.e.0.7) is lesser than 0.7 and the above decision turns true.

      In my next code the value of me is 1.7 and when i compared me(i.e. 1.7) with 1.7 the decision shows that me is greater than 1.7.

      At first i though me is float and if we speify a number with decimal point explicitly compiler will treat that as double and hence in the first case me<0.7. But this doesn't works for my second code. Hence kindly clarify

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Take a look at what every computer scientist should know about floating point.

        When assigning a value to me, the value is effectively cast to a float. When comparing me to a value, me is effectively cast to a double. When does changing from one floating point type to another change the value? It depends on implementation-dependent features of the underlying representation.

        Comment

        • haicp
          New Member
          • Sep 2010
          • 4

          #5
          In this kind of comaprisions, 99% of the time the else part of the if condition gets executed.

          In this example, when you try to compare 0.7 with 0.7, what actually happens internally is, one of the 0.7 is interpreted as 0.6999999999.

          Floating point representation is machine dependent.

          Even though there is not much of a difference between 0.7 and 0.6999999999, the if condition fails.

          You execute the same code on another machine, probably you will get another result.

          So, never use floating numbers for comparision.

          Comment

          Working...