51 lines
3.9 KiB
MQL5
51 lines
3.9 KiB
MQL5
//+------------------------------------------------------------------+
|
|
//| pitfalls.mq5 |
|
|
//| Copyright © 2018, Amr Ali |
|
|
//| https://www.mql5.com/en/users/amrali |
|
|
//+------------------------------------------------------------------+
|
|
#property copyright "Copyright © 2018, Amr Ali"
|
|
#property link "https://www.mql5.com/en/users/amrali"
|
|
#property version "4.0"
|
|
#property description "Script to test exact and loose comparisons of doubles."
|
|
|
|
#include <math_utils.mqh>
|
|
//+------------------------------------------------------------------+
|
|
//| |
|
|
//+------------------------------------------------------------------+
|
|
#define PRINT(A) Print(#A + " = ", (A))
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| |
|
|
//+------------------------------------------------------------------+
|
|
void OnStart()
|
|
{
|
|
//--- Examples of where exact comparison of doubles can fail:
|
|
double a = 0.1;
|
|
double b = 0.2;
|
|
double c = a + b;
|
|
|
|
PRINT( (c==0.3) ); // false
|
|
|
|
//---
|
|
double ask = 1.2973;
|
|
double bid = 1.2972;
|
|
double spread = (ask - bid) / 0.0001;
|
|
|
|
PRINT( (spread==1.0) ); // false
|
|
|
|
|
|
//--- Switching to loose comparisons, results become as expected
|
|
PRINT( EQ(c, 0.3) ); // true
|
|
PRINT( EQ(spread, 1.0) ); // true
|
|
|
|
|
|
//PRINT(DoubleToString(c, 16)); // 0.3000000000000001
|
|
//PRINT(DoubleToString(spread, 16)); // 0.9999999999998898
|
|
}
|
|
//+------------------------------------------------------------------+
|
|
|
|
// output:
|
|
// EQ_test EURUSD,M5: (c==0.3) = false
|
|
// EQ_test EURUSD,M5: (spread==1.0) = false
|
|
// EQ_test EURUSD,M5: EQ(c,0.3) = true
|
|
// EQ_test EURUSD,M5: EQ(spread,1.0) = true
|