Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect floating point parsing #4285

Open
2 tasks done
riasat opened this issue Feb 3, 2024 · 2 comments
Open
2 tasks done

Incorrect floating point parsing #4285

riasat opened this issue Feb 3, 2024 · 2 comments

Comments

@riasat
Copy link

riasat commented Feb 3, 2024

Description

I have a sample json file which has an array of array of array of float weights.
{"input_size": 3, "layer_sizes": [2, 2], "weights": [[[0.50, 0.50, 0.50], [0.30, 0.30, 0.30]],[[0.40, 0.40, 0.40], [0.20, 0.20, 0.20]]]}
When I parse json the some of the floating points value show with less precision such as 0.30 is parsed as 0.299999999999

Reproduction steps

` std::ifstream file(fileName);
nlohmann::json data = nlohmann::json::parse(file);

    int inputSize = data["input_size"];
    std::vector<int> layerSizes = data["layer_sizes"];
    auto weights = data["weights"];`

Expected vs. actual results

expected is to have .30 instead of parsing floating point as .29999999999.

Minimal code example

`       std::ifstream file(fileName);
        nlohmann::json data = nlohmann::json::parse(file);

        int inputSize = data["input_size"];
        std::vector<int> layerSizes = data["layer_sizes"];
        auto weights = data["weights"];`
json file:
`{"input_size": 3, "layer_sizes": [2, 2], "weights": [[[0.50, 0.50, 0.50], [0.30, 0.30, 0.30]],[[0.40, 0.40, 0.40], [0.20, 0.20, 0.20]]]}`

Error messages

No response

Compiler and operating system

VS2017

Library version

3.11.3

Validation

@riasat
Copy link
Author

riasat commented Feb 3, 2024

image

@nlohmann
Copy link
Owner

nlohmann commented Feb 3, 2024

The number 0.3 cannot be exactly represented as double, see https://float.exposed/0x3fd3333333333333. This is independent of this library, C++, or your operating system. See https://json.nlohmann.me/features/types/number_handling for more information.

@nlohmann nlohmann removed the kind: bug label Feb 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants