Doubles Comparator – MetaTrader 5 Library | MT5 EA Download – MetaTrader 5 Resources
A small class for comparing floating point variables with the required precision in the correct way.
template < type name > class float { public : float() {precision( size (T));} integer compare( constant TX, constant y) { return ((( fab (xy)<minutes))? 0 :((xy>=minimum value))? 1 :- 1 );} blank exact( integer digits) {min = pow ( 10 , -fab (number));} protected : Double minutes; };
Suppose you have two doubles with a value of 1.15.
When you compare them, you expect them to be equal.
But doubles in computers behave strangely.
1.15 can be stored as 1.14999999999.
So the comparison will live up to your expectations.
The correct way to compare floating point variables is to check their subtraction from some minimum value.
FlatingPoint must be initialized with a double or float data type.
The comparator method returns 0 if x = y; 1 if x > y; or -1 if x < y.
Accuracy can vary.
For doubles, the default precision is 8 digits after fp; for floats, the default precision is 4 digits.
FloatingPoint class usage example.
blank start () { float <double> fp; Double a= 1.15 ,b= 1.14999999999 ; for ( integer i = 15 ; i > 5 ; i --) { fp.Precision(i); Integer comparison=fp.Compare(a,b); string resource = (comparison == 0 )? ”= :(Compare == 1 )? ”>” : “<” ; Print format ( "%g %s %g, %d bit precision" ,a,res,b,i); } }
Output:
/**
You don't want this:
1.15 > 1.15 (15 digits of precision)
1.15 > 1.15 (14 bits of precision)
1.15 > 1.15 (13 digits of precision)
1.15 > 1.15 (12-bit precision)
1.15 > 1.15 at 11 digits of precision
You expect this:
1.15 = 1.15 (10 digits of precision)
1.15 = 1.15 at 9 digits of precision
1.15 = 1.15 at 8 digits of precision
1.15 = 1.15 at 7 digits of precision
1.15 = 1.15 at 6 digits of precision
/**/
Attachment download
📎 floatingpoint.mq5 (1.05 KB)
📎 floatingpoint.mqh (1.14 KB)
Source: MQL5 #29615
💡 Featured Recommendations
✍️ Latest by the author
- •
- •
- •
- •
- •
- •
📌 Popular topics
- •
- •
- •
- •
- •
- •
- •
- •
🔗 You May Be Interested In
- •
- •
- •
- •
- •
- •