提高属性树PUT / GET DBL_MAX [英] boost property tree put/get DBL_MAX

查看:139
本文介绍了提高属性树PUT / GET DBL_MAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编程ptree中,在某些时候我需要把DBL_MAX中(作为缺省值)。
我看到正确的号码,当我打开生成的XML文件。

I'm programming a ptree and at some point I need to put DBL_MAX in (as a default value). I see the right number when I open the generated xml-file.

但是当我使用ptree.get得到一个异常被抛出数:数据转换为D型失败。

But when I use ptree.get to get the number an exception is thrown:conversion of data to type "d" failed

下面是我的code:

using boost::property_tree::ptree;
ptree pt;

double d=-DBL_MAX;
double d2=-1.797693134862316e+308;
double d3=-1.79769e+308;

cout<<d<<endl;
cout<<d2<<endl;
cout<<d3<<endl;

pt.put<double>("double", d);
write_xml("test.xml", pt);

cout << "totalEndTimeLowerBound: " << pt.get<double>("double")<<endl;
//doesn't work with d and d2, but works with d3

什么可能导致这个错误,我怎么能解决这个问题?

What can cause this error and how can I resolve it?

推荐答案

默认情况下,ptree中存储其值的std ::字符串并使用basic_stringstream与precission它们转换:

By default, ptree stores its values as std::string and convert them using basic_stringstream with precission:

s.precision(std::numeric_limits<double>::digits10+1);

当其转换为DBL_MAX为std :: string,因为它舍入到一个无效的值号码出现此问题。你可以用下面的code一下:

This problem appears when it converts DBL_MAX to std::string because it rounds the number to an invalid value. You can check it with the following code:

  ptree pt;
  pt.put("min", -DBL_MAX);
  pt.put("max", DBL_MAX);
  cout << "Min=" << pt.get<string>("min") << std::endl;
  cout << "Max=" << pt.get<string>("max") << std::endl;

使用Visual Studio,它打印:

Using Visual Studio, it prints:

敏= -1.797693134862316e + 308

Min=-1.797693134862316e+308

最大值= 1.797693134862316e + 308

Max= 1.797693134862316e+308

然而,DBL_MAX被定义为1.7976931348623158e + 308使打印的值超出限制。

However, DBL_MAX is defined as 1.7976931348623158e+308 so the printed value is out of limits.

有几种解决方法,但没有一个是完美的:

There are several workarounds but none is perfect:

  • Use a different default value smaller than DBL_MAX. For example 1.797693134862315e+308.
  • Catch the bad_data exception and assume that it means default.
  • Register a new type with your custom converter. You can see an example here.
  • Reduce the precission of the stored value. You can perform this using the following code:

 namespace boost { namespace property_tree 
 {
   template <typename Ch, typename Traits>
   struct customize_stream<Ch, Traits, double, void>
   {
     static void insert(std::basic_ostream<Ch, Traits>& s, const double& e) {
       s.precision(std::numeric_limits<double>::digits10-1);
       s << e;
     }
     static void extract(std::basic_istream<Ch, Traits>& s, double& e) {
       s >> e;
       if(!s.eof()) {
         s >> std::ws;
        }
     }
   };
 } }


这篇关于提高属性树PUT / GET DBL_MAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆