3 - 28 3 - 28
MELSEC-Q
3 LET'S CREATE AND EXECUTE A PROGRAM
REMARK
When single-precision or double-precision values are compared using the equal
sign, there are cases where the result is incorrect.
Example
10 A=0
20 FOR I=1 TO 1000
30 A=A+0.0001
40 NEXT I
50 IFA=0.1 THEN PRINT
60 END
RUN
OK
PRINT A
0.100001
OK
…………………
Since 0.0001 is added 1000
times, A should equal 0.1.
………………
If A is 0.1, EQ! is displayed.
…………………………………………
E Q ! w a s n e v e r d i s p l a y e d .
…………………………………
The value of A is not 0.1.
The reason for this is that single-precision or double-precision values are stored in the
memory in floating point format; thus it is sometimes not possible to hold the exact
values.
( Example is one such case.)
In order to compare whether such values are equal, it should instead be checked if the
absolute value of the difference is smaller than some appropriate tolerance.
10 A=0
20 FOR I=1 TO 10
30 A=A+0.01
40 NEXT I
50 IF ABS(0.1-A)<1E-5 THEN PRINT"EQ!"
60 END
RUN
EQ!
OK
…… When the difference between
0.1 and A is less than 10
-5
,
A is considered equal to 0.1.
………………………………………………… EQ! is displayed.