Unidata / UDUNITS-2

API and utility for arithmetic manipulation of units of physical quantities
http://www.unidata.ucar.edu/software/udunits
Other
62 stars 36 forks source link

Unexpected results from ut_compare #121

Open mcflugen opened 7 months ago

mcflugen commented 7 months ago

👋 Hi All!

I'm getting some unexpected results with the ut_compare function. The issue may simply be that I misunderstand what it means for one unit to be greater than or less than another. In any case, here is some code that demonstrates what I'm seeing,

#include <stdio.h>
#include <udunits2.h>

int main() {
    ut_set_error_message_handler((ut_error_message_handler) ut_ignore);
    ut_system *sys = ut_read_xml(NULL);
    ut_encoding enc = UT_UTF8;
    ut_set_error_message_handler((ut_error_message_handler) vprintf);

    char *first_unit, *second_unit;
    int i, cmp;
    char *first_units[5] = {"m", "m", "km", "kg", "g"};
    char *second_units[5] = {"km", "cm", "cm", "cg", "kg"};

    for (i=0; i<5; i++) {
    first_unit = first_units[i];
    second_unit = second_units[i];

    ut_unit *u_first = ut_parse(sys, first_unit, enc);
    ut_unit *u_second = ut_parse(sys, second_unit, enc);

    cmp = ut_compare(u_first, u_second);

    if (cmp < 0) {
        printf("%d) %s is less than %s\n", i + 1, first_unit, second_unit);
    } else if (cmp > 0) {
        printf("%d) %s is greater than %s\n", i + 1, first_unit, second_unit);
    } else {
        printf("%d) %s is equal to %s\n", i + 1, first_unit, second_unit);
    }
    ut_free(u_first);
        ut_free(u_second);
    }

    ut_free_system(sys);
    return 0;
}

Running this gives the following output,

1) m is less than km
2) m is less than cm
3) km is greater than cm
4) kg is less than cg
5) g is greater than kg

The output I would expect would be,

1) m is less than km
2) m is greater than cm
3) km is greater than cm
4) kg is greater than cg
5) g is less than kg

Am I doing something wrong here or not understanding what it means to compare units?

System info: