Decimal precision truncated when serialize/deserialize std::vector<double> container
Closed this issue · 2 comments
zhoupengwei commented
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 commented
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 commented
@biojppm Thank you for providing detailed examples and great project.