How to resolve the algorithm Approximate equality step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Approximate equality step by step in the D programming language

Table of Contents

Problem Statement

Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic.

Create a function which returns true if two floating point numbers are approximately equal.

The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01   may be approximately equal to   100000000000000.011, even though   100.01   is not approximately equal to   100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:

Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Approximate equality step by step in the D programming language

Source code in the d programming language

import std.math;
import std.stdio;

auto approxEquals = (double a, double b, double epsilon) => abs(a - b) < epsilon;

void main() {
    void test(double a, double b) {
        double epsilon = 1e-18;
        writefln("%.18f, %.18f => %s", a, b, a.approxEquals(b, epsilon));
    }

    test(100000000000000.01, 100000000000000.011);
    test(100.01, 100.011);
    test(10000000000000.001 / 10000.0, 1000000000.0000001000);
    test(0.001, 0.0010000001);
    test(0.000000000000000000000101, 0.0);
    test(sqrt(2.0) * sqrt(2.0), 2.0);
    test(-sqrt(2.0) * sqrt(2.0), -2.0);
    test(3.14159265358979323846, 3.14159265358979324);
}


  

You may also check:How to resolve the algorithm Stirling numbers of the second kind step by step in the Julia programming language
You may also check:How to resolve the algorithm Sorting algorithms/Sleep sort step by step in the Groovy programming language
You may also check:How to resolve the algorithm Create a two-dimensional array at runtime step by step in the NetRexx programming language
You may also check:How to resolve the algorithm Playing cards step by step in the Tcl programming language
You may also check:How to resolve the algorithm N'th step by step in the Icon and Unicon programming language