Created
August 24, 2020 03:02
-
-
Save jfcarr/e839041737e81b720da25f3c3533e4a5 to your computer and use it in GitHub Desktop.
Assertions on doubles with variable precision
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Assertions on doubles are tricky in C, because of the way precision is handled. The default precision | |
used in things like displaying and comparing is 6 decimal places, even though the internal precision value | |
is much higher. This makes things like assertions difficult, if you want to assert on any value other | |
than the default 6 decimal places. Here's a way to do it by converting both values to strings before | |
the assertion. | |
*/ | |
#include <math.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
#include <string.h> | |
void assert_doubles(double compare1, double compare2, int places); | |
int main() | |
{ | |
double hours = 18.0; | |
double minutes = 31.0; | |
double seconds = 27.0; | |
double a = fabs(seconds) / 60.0; | |
double b = (fabs(minutes) + a) / 60.0; | |
double c = fabs(hours) + b; | |
double d = (hours < 0.0 || minutes < 0.0 || seconds < 0) ? -(c) : c; | |
printf("Result is %0.8f\n", d); | |
assert_doubles(d, 18.52416667, 8); | |
return (0); | |
} | |
void assert_doubles(double compare1, double compare2, int places) | |
{ | |
char compare_string1[50]; | |
char compare_string2[50]; | |
sprintf(compare_string1, "%0.*f", places, compare1); | |
sprintf(compare_string2, "%0.*f", places, compare2); | |
assert(strcmp(compare_string1, compare_string2) == 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment