MQL4 Real Types (double, float)

Overview

Real types (floating-point) represent numbers with fractional parts. MQL4 provides two such types:

  • **float**: 4 bytes, minimal positive value 1.175494351e-38, maximum value 3.402823466e+38. C++ analog: float.
  • **double**: 8 bytes, minimal positive value 2.2250738585072014e-308, maximum value 1.7976931348623158e+308. C++ analog: double.
  • double offers twice the precision of float and is generally more convenient. float is useful for memory saving in large arrays.

    Representation

  • Floating-point numbers are represented in memory according to the IEEE 754 standard, independent of platform or OS.
  • Decimal notation: Consists of an integer part, a decimal point (.), and a fractional part (e.g., 12.111, -956.1007, 0.0001, 16).
  • Scientific notation: Uses e to denote powers of 10 (e.g., 1.12123515e-25).
  • Precision and Comparison Issues

  • Real numbers are stored with limited binary precision, which can lead to inexact decimal representations (e.g., 0.3, 0.7). Numbers that are powers of two (e.g., 0.25) are stored exactly.
  • **Direct equality comparison (==) of real numbers is unreliable and should be avoided.**
  • Comparing Real Numbers

    Two methods are recommended for comparing real numbers:

    1. **Epsilon Comparison**: Compare the absolute difference between two numbers against a small tolerance value (epsilon). * DBL_EPSILON (for double): 2.2204460492503131e-016. Condition: 1.0 + DBL_EPSILON != 1.0. * FLT_EPSILON (for float): 1.192092896e-07. Condition: 1.0 + FLT_EPSILON != 1.0. * Example function: EqualDoubles(d1, d2, epsilon).

    2. **Normalized Difference Comparison**: Compare the result of NormalizeDouble(number1 - number2, precision) with zero. * Example function: CompareDoubles(number1, number2).

    Invalid Real Numbers

    Mathematical operations can result in invalid numbers:

  • **Not a Number (NaN)**: e.g., -1.#IND, -1.#QNAN, 1.#SNAN, 1.#QNAN.
  • **Infinity**: Positive (1.#INF) and Negative (-1.#INF).
  • Use MathIsValidNumber() to check if a number is valid.
  • Operations with invalid numbers yield undefined results.
  • Special values include positive/negative zero, greatest/smallest normalized numbers, and specific NaN representations.
  • Constants and Related Functions

  • DBL_EPSILON, FLT_EPSILON
  • DoubleToString()
  • NormalizeDouble()
  • MathIsValidNumber()
  • MathArcsin() (example of function producing invalid numbers)