kastnermario / yaml-cpp

Automatically exported from code.google.com/p/yaml-cpp
MIT License
0 stars 0 forks source link

Operator = loses floating point precision #192

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Floating point precision is lost when storing a double in a Node using operator 
=.  This lost precision can be a significant problem when saving things like 
simulation parameters.

What steps will reproduce the problem?

    YAML::Node node;
    double k = 0.123456789;

    node["k"] = k;   // rounding occurs on assignment
    std::cout.precision(15);
    std::cout << "should be k:" << k << endl;
    std::cout << node << endl;

What is the expected output? What do you see instead?

    I would expect to see:

    should be k:0.123456789
    k: 0.123456789

    but instead see:

    should be k:0.123456789
    k: 0.123457

What version of the product are you using? On what operating system?

    I'm using yaml-cpp-0.5.0 on Ubuntu 12.10

Please provide any additional information below.

The problem appears to be caused by using a stringstream with the default 
precision.  Adding the following line to 
yaml-cpp-0.5.0/include/yaml-cpp/node/convert.h seems to fix this:

#define YAML_DEFINE_CONVERT_STREAMABLE(type)\
    template<>\
    struct convert<type> {\
        static Node encode(const type& rhs) {\
            std::stringstream stream;\
+           stream.precision(std::numeric_limits<type>::digits10);\
            stream << rhs;\
            return Node(stream.str());\
        }\

Original issue reported on code.google.com by km...@case.edu on 11 Feb 2013 at 10:34

GoogleCodeExporter commented 8 years ago
Interesting, thanks for reporting!

Original comment by jbe...@gmail.com on 11 Feb 2013 at 10:47

GoogleCodeExporter commented 8 years ago
Fixed, 
https://code.google.com/p/yaml-cpp/source/detail?r=8fdf371594f502e502288fa8d102f
39dccdf1c5f.

Original comment by jbe...@gmail.com on 13 Apr 2013 at 6:11