Can't Determine Value in a "For" loop

 

Hello ,

i have a problem with a for loop and i can't figure out what's wrong , the loop skips some values if you put for example 0.1 or 0.12345 in place of 0.123 the comment appear but like this the comment never appeared .

void price()
{
   for(int i=0; i<=2/_Point;i++)
   {
      if(i*_Point==0.123)
      {
      Comment("price=0.123");
      }
   }
}
 
Doubles are rarely equal. Understand the links in:
          The == operand. - MQL4 programming forum
 
William Roeder:
Doubles are rarely equal. Understand the links in:
          The == operand. - MQL4 programming forum
Thank you very much.
 

To test equality of doubles, you should compare their abs difference to a very small value

if(i*_Point==0.123)

Change the above line to

if(MathAbs(i*_Point-0.123)<0.00000001)

Another choice is to use EQ() function from the Math Utils Library 

https://www.mql5.com/en/code/20822

if(EQ(i*_Point,0.123))
Math Utils
Math Utils
  • www.mql5.com
Sometimes, when comparing two double numbers that assumed to be equal, but reached to via different calculations, the comparison goes wrong. Actually A can differ from B by in very little amount (at the 16th decimal place) due to binary rounding errors, so exact comparisons (==, !=, >, >=, <, <= operators) fail. Real situations of...
 
amrali:

To test equality of doubles, you should compare their abs difference to a very small value

Change the above line to

Another choice is to use EQ() function from the Math Utils Library 

https://www.mql5.com/en/code/20822

Thank you very much for the reply .
 
amrali: To test equality of doubles, you should compare their abs difference to a very small value
if(MathAbs(i*_Point-0.123)<0.00000001)

Not a very small value. That is approaching the problem of doubles not comparing equal. If two prices are less than Point/2 apart, they are by definition equal. If two lot sizes are less than lot step apart they are by definition equal.

 
William Roeder:

Not a very small value. That is approaching the problem of doubles not comparing equal. If two prices are less than Point/2 apart, they are by definition equal. If two lot sizes are less than lot step apart they are by definition equal.

Hi William, the very small value is meant to overcome the implicit binary rounding errors (at the 16th decimal place) due to inherent imprecision in the IEEE floating point format.

If you do explicit rounding in your code, you are free to choose whatever the smallest relevant difference like point or tick. 


double v=0.1+0.2;

Print(v==0.3); //false

Print(MathAbs(v-0.3)<0.00000001); //true

Reason: