TorqueScript Logic Error

Author Topic: TorqueScript Logic Error  (Read 1042 times)

It seems like the > operator is not working correctly in certain cases.

Example:
Quote
==>$test = 5.3;
==>echo($test);
5.3
==>echo($test == 5.3);
1
==>echo($test < 5.3);
0
==>echo($test > 5.3);
1

==>echo($test > 5.2);
0
==>echo($test > 5.4);
0
==>echo(5.3 > 5.3);
0
==>echo(5.4 > 5.3);
1

This only happens if you are comparing a variable to a decimal number. Try it yourself and see if the same thing happens.

Other operators aren't working for me either...

Quote
==>$joe = 6.1;

==>echo($joe);
6.1

==>echo($joe == 6.1);
0


==>if($joe == 6.1) { echo("true"); }

==>echo($joe < 6.1);
1


==>if($joe < 6.1) { echo("somethings wrong"); }
somethings wrong


==>echo($joe > 6.1);
0
==>if($joe > 6.1) { echo("somethings wrong"); }

It seems that it is more than 0 though.

Code: [Select]
==>if($Steve == 1.9) {echo("It's bad");}
==>if($Steve >= 1.9) {echo("It's bad");}
==>if($Steve <= 1.9) {echo("It's bad");}
It's bad
==>if($Steve >= 0) {echo("It's good, but terrible.");}
It's good, but terrible.

Badspot

  • Administrator
The problem is systemic to floating point numbers.  Numbers that look nice and neat in base 10 end up being repeating decimals in binary, then they're truncated to fit in a 32 bit float.  Then every time you add two numbers together the result is truncated and you get accumulated error.  Tweaks could be made to improve consistency in torque script for these test cases, but the underlying problem would still exist. 

You should never make a comparison like "if myfloat == 1.0" in any programming language.  If your program requires exacting comparison of 2 numbers you should be using integers.