LearnFrenzy
Sign in Take a free test

Floating Point Issues · Floating Point Programs · Question 1

Compare two doubles with a relative tolerance in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write approx_equal() that treats two doubles as equal when they differ by a tiny relative amount, and test it on tricky pairs.

Solution
main.c
#include <math.h>
#include <stdbool.h>
#include <stdio.h>

bool approx_equal(double a, double b, double rel, double abs_tol) {
    double diff = fabs(a - b);
    if (diff <= abs_tol)                         /* handles values near zero */
        return true;
    return diff <= rel * fmax(fabs(a), fabs(b)); /* scales with the numbers */
}

int main(void) {
    printf("0.1+0.2 vs 0.3: %d\n", approx_equal(0.1 + 0.2, 0.3, 1e-9, 1e-12));
    printf("1e-20 vs 0: %d\n", approx_equal(1e-20, 0.0, 1e-9, 1e-12));
    printf("1000000.1 vs 1000000.2: %d\n", approx_equal(1000000.1, 1000000.2, 1e-9, 1e-12));
    return 0;
}

Output Verified by compiling and running

0.1+0.2 vs 0.3: 1
1e-20 vs 0: 1
1000000.1 vs 1000000.2: 0

A relative tolerance alone fails near zero (any difference is huge relative to 0), and an absolute one alone fails for large numbers. Using both covers the whole range.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links