Menu

strange behavior

Help
2016-03-11
2016-03-13
  • Carlos M. Pascal

    Clips 6.3, Win7 64biti

    The expression (= 0.4 (+ 0.2 0.2)) is true,
    but (= 0.4 (- 0.6 0.2)) is false. Why?

     
  • Gary Riley

    Gary Riley - 2016-03-11

    0.1 and its multiples are irrational in binary format so equality comparisons to these values can yield unexpected results. You'll get similar results in the C language underlying CLIPS:

    #include <stdio.h>
    
    int main()
      {
       printf("0.4 == (0.2 + 0.2) is %d\n", (int) (0.4 == (0.2 + 0.2)));
       printf("0.4 == (0.6 - 0.2) is %d\n", (int) (0.4 == (0.6 - 0.2)));
       return 0;
      }
    

    And in other languages such as Java:

    public class Test
      {
       public static void main(String args[])
         {  
          System.out.println("0.4 == (0.2 + 0.2) is " + (0.4 == (0.2 + 0.2)));
          System.out.println("0.4 == (0.6 - 0.2) is " + (0.4 == (0.6 - 0.2)));
         }  
      }
    

    Many languages support arbitrary precision decimal numbers (such as the BigDecimal class in Java) to address this issue.

    Some additional information can be found here: http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary

     

    Last edit: Gary Riley 2016-03-11
  • Carlos M. Pascal

    Thank you, Gary Riley!

    I have used an unorthodox solution

    (eq 0.4a (sym-cat (- 0.6 0.2) a))

     

Log in to post a comment.