An example of using approximate number comparison in Julia
The algorithm of approximate equality is considered (≈) in the Julia programming language, which allows you to correctly compare floating-point numbers.
Introduction
When working with floating-point numbers in programming, it is often difficult to compare values due to the limited precision of the representation of these numbers in computer memory.
For example, the result of the calculation 0.1 + 0.2 maybe not exactly equal 0.3. To correctly check whether two such numbers are close to each other, special approximate equality methods are used.
In the Julia language, the function is responsible for this. ≈ (or isapprox()), which allows you to compare values taking into account possible rounding errors. This mechanism is widely used in scientific computing, testing, data processing and other areas where high accuracy of comparisons is required.
This example demonstrates how the operator works. ≈ on different sets of pairs of numbers.
Applying approximate equality
Let's create a list of pairs of values that we will compare.
testvalues = [
    # Примеры с очень большими числами:
    [100000000000000.01,        100000000000000.011], # различаются последним десятичным знаком
    
    # Числа среднего порядка:
    [100.01,                    100.011],             # отличаются больше, чем допустимая погрешность
    
    # Операции деления, где результат может быть неточным из-за представления float:
    [10000000000000.001 / 10000.0, 
     1000000000.0000001000],                          # должно быть равно 1000000000000.001 / 10000 = 100000000.0000001
    
    # Очень маленькие положительные числа:
    [0.001,                     0.0010000001],        # разница в миллионных долях
    
    # Очень маленькое число и ноль:
    [0.000000000000000000000101, 0.0],                # почти равно нулю?
    # Математически равные выражения:
    [sqrt(2) * sqrt(2),         2.0],                 # sqrt(2)^2 = 2, но что получится в результате округлений?
    
    # С отрицательными числами:
    [-sqrt(2) * sqrt(2),       -2.0],                 # аналогично для отрицательного случая
    # Число π записанное разным количеством знаков:
    [3.14159265358979323846,    3.14159265358979324] # различаются на один знак после запятой
]
Comparing numbers
Each pair from the list testvalues it is sequentially taken and stored in variables (x, y).
Next, the information is output:
- the value is displayed x, supplemented on the right with spaces up to the length of 21;
- then the "≈" symbol is displayed;
- value y, supplemented on the left with spaces up to the length of 22;
- after the colon, the result of applying the operator is displayed. ≈: true or false.
- this way we can immediately see which pairs are considered approximately equal.
# Проходимся циклом по всем парам (x, y) из массива
for (x, y) in testvalues
    # Выводим результат сравнения x ≈ y вместе со значениями
    println(
        rpad(x, 21),                      # дополняем x пробелами справа до ширины 21
        " ≈ ",                            # операция приближенного равенства
        lpad(y, 22),                      # дополняем y пробелами слева до ширины 22
        ": ",                             # разделитель перед логическим результатом
        x ≈ y                             # вызываем функцию ≈(x, y) -> Bool
    )
end
Operator ≈. How does it work?
Operator ≈ in Julia, by default, it is equivalent to calling a function isapprox(x, y) using the following formula:
Where:
- (absolute tolerance): minimum absolute error;
- (relative tolerance): relative error.
By default, the parameters are defined as follows:
- atol = 0
- rtol = sqrt(eps()) ≈ 1.49e−8
Detailed information on the function can also be obtained in the documentation.
Conclusion
In this example, we examined the use of the approximate equality mechanism in the Julia programming language.
We used the operator ≈ to analyze the differences between real numbers in the context of machine arithmetic inaccuracies.
Thanks to this functionality, you can test calculations, make secure comparisons of floating-point numbers, and work with data that requires tolerance for small errors.
Knowledge of the operator's work ≈ It is useful for programmers working in the fields of mathematics, physical modeling and data analysis.
The example was developed using materials from Rosetta Code