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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!