RobotStudio event

RAPID: compare decimal numbers


VAR num var1 := 1.5708;
VAR num var2 := 1.5708;

IF var1 = var2 THEN
    TPWrite "Equal!"
ELSE TPWrite "Not equal!"
ENDIF

This code yields "Not equal!"


How can I compare these two values to get a result of equal?

Alyssa Wells2013-02-25 19:00:49

Comments

  • Hello Alyssa,

    The following code works as expected and gives "Equal!" when run in Robot Studio.

     

    MODULE MainModule
      VAR num var1 := 1.5708;
      VAR num var2 := 1.5708;

    Proc main()
    IF var1 = var2 THEN
        TPWrite "Equal!";
    ELSE
        TPWrite "Not equal!";
    ENDIF
    ENDPROC

    ENDMODULE

     

    image


  • Note that it is not recommended to compare floating point values with just a single "equal sign". It works for integers, but not for floats. Instead, you should judge two floats two be equal if they differ less than a very small constant value, epsilon, say. The value of epsilon should be defined with respect to the numerical accuracy of the data type, and the application. This is standard in numerical calculation and applies to all comparisons of floats done by computers, see the code example below.

    [CODE]MODULE MyModule
      
      VAR num var1 := 1.5708;
      VAR num var2 := 1.5708;
      CONST num EPS := 0.0001;

    Proc main()
    IF Abs(var1 - var2) < EPS THEN
        TPWrite "Equal!";
    ELSE
        TPWrite "Not equal!";
    ENDIF
    ENDPROC

    ENDMODULE[/CODE]


    If you are even more concerned with your numerical analysis you might want to take a look here.

    You might also want to use the dnum data type (double precision instead of single). There are new methods to operate on it. For example AbsDnum, instead of Abs. See the RAPID Reference manual included in RobotStudio for details.



    Henrik Berlin2013-02-26 15:02:39
    Henrik Berlin
    ABB
  • Another solution may be to use the Truncate function.
    MODULE MainModule
      VAR num var1 := 1.57087;
      VAR num var2 := 1.57082;
      VAR num var3 := 0;
      VAR num var4 := 0;
     
      PROC main()
          EqualTest;
      ENDPROC     

    Proc EqualTest()
    var3:=Trunc(var1Dec:=4);
    var4:=Trunc(var2Dec:=4);
    IF var3 = var4 THEN
        TPWrite "Equal!";
    ELSE
        TPWrite "Not equal!";
    ENDIF
    ENDPROC

    ENDMODULE
    j_proulx2013-02-27 18:10:54