Skip to content

Floating point equality - revisited #703

Description

@cburlacu

This is related to #185. I know that comparing floats implementation is a delicate subject, but the current behavior can be improved.

Suppose this code (suppose no errors occurs):

    using json = nlohmann::json;
    json j1, j2;
    j1["test_double"] = 3.12345;
    j1["test_string"] = "test string";
    j1["test_array"] = (std::vector<int>){12345, 12346, 2345, 23456, 3456, 4567, 5678, 6789};
    j1["test_float"] = 3.123f;

    j2 = json::parse(j1.dump());

    json::iterator it = j1.begin();
    bool areEqual = true;

    for( ; it != j1.end(); ++it) {
        auto otherVal = j2[it.key()];
        auto thisVal = it.value();
        if(otherVal != thisVal) {
            areEqual = false;
            break;
        }
    }

When the float properties are compared, the result is false which is not what I was expecting.

                case value_t::number_float:
                    return (lhs.m_value.number_float == rhs.m_value.number_float);

this comparison translates to 3.123f as:
lhs = 3.1229999065399201
rhs = 3.122999906539917

Tested both on Ubuntu 17.04 & macOS Sierra with same results.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions