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

Decimal precision truncated when serialize/deserialize std::vector<double> container #417

Closed
zhoupengwei opened this issue Apr 2, 2024 · 2 comments · Fixed by #420
Closed

Comments

@zhoupengwei
Copy link

zhoupengwei commented Apr 2, 2024

Hi author, I found that the std::vector lost precision during the process of deserializing, As the following sample code:

ryml::Tree tree;

  {
    std::vector<double> test_vec{1.23234412342131234,
                                 2.12323123143434237,
                                 3.67847983572591234};
    ryml::NodeRef root = tree.rootref();
    root |= ryml::SEQ;
    root << test_vec;
  }

  {
    ryml::ConstNodeRef root = tree.crootref();
    std::vector<double> test_vec;
    root >> test_vec;
    for (const auto& elem : test_vec) {
      std::cout << "elem " << elem << std::endl;
    }
  }

The program will output:
elem 1.23234
elem 2.12323
elem 3.67848

How can I avoid losing numerical accuracy ?

@biojppm
Copy link
Owner

biojppm commented Apr 3, 2024

TL;DR:
The loss happens only when serializing using the default operator<< in C++11 and C++14.

Use at least C++17 (because it provides std::to_chars()), or do the following:

        ryml::Tree serialized;
        ryml::NodeRef root = serialized.rootref();
        root |= ryml::SEQ;
        for(const double v : test_vec)
            root.append_child() << ryml::fmt::real(v, 17, ryml::FTOA_FLOAT);

For more details, see the linked PR, which adds an example and explanation to the quickstart.

@zhoupengwei
Copy link
Author

@biojppm Thank you for providing detailed examples and great project.

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

Successfully merging a pull request may close this issue.

2 participants