【发布时间】:2013-06-30 14:26:42
【问题描述】:
比较 boost::lexical_cast 和 boost 精神解析时,我注意到一些奇怪的东西。 我正在尝试将字符串解析为浮点数。由于某种原因,精神给出了非常不精确的结果。例如:当使用 lexical_cast 解析字符串“219721.03839999999”时,我得到 219721.03,这或多或少是可以的。但是当我使用精神(见下面的代码)时,我得到“219721.11”,这远非正常。知道为什么会这样吗?
template<>
inline float LexicalCastWithTag(const std::string& arg)
{
float result = 0;
if(arg.empty())
{
throw BadLexicalCast("Cannot convert from to std::string to float");
}
auto itBeg = arg.begin();
auto itEnd = arg.end();
if(!boost::spirit::qi::parse(itBeg, itEnd, boost::spirit::qi::float_, result) || itBeg != itEnd)
{
throw BadLexicalCast("Cannot convert from to std::string to float");
}
return result;
}
【问题讨论】:
-
更具体地说,lexical_cast 为您提供正确的
219721.03125,这是最接近219721.03839999999的有效float,而qi::float_为您提供219721.109375,这确实没有看起来是对的。 -
数字的整数部分几乎使容量饱和。在 qi::float_type::parse() 中计算结果的方式是,在“添加”每个小数复合时发生的“小”错误。事实上,这看起来像是一个错误,因为更智能的算法没有这种次优行为。
-
我们如何将这个问题传达给精神维护者?
-
我刚刚在spirit-general添加了我的 0.019999999552965164 美元
-
正如刚刚在 [spirit-general] 邮件列表中宣布的,看起来这个错误已在下一个 boost 版本中得到修复:boost.2283326.n4.nabble.com/Symbol-table-tp4668838p4668842.html /cc @G.Civardi
标签: c++ boost-spirit lexical-cast