提升精神浮点数解析器的精度
Boost spirit floating number parser precision
在比较boost::lexical_cast和boost spirit解析时,我注意到了一些奇怪的事情。我正试图将一个字符串解析为float。出于某种原因,精神给出了非常不精确的结果。例如:当使用lexical_cast解析字符串"219721.03839999999"时,我得到了219721.03,这或多或少是可以的。但当我使用spirit(见下面的代码)时,我获得了"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;
}
所以这可能是"float"类型解析器的限制/错误。尝试使用双语法分析器。
#include<iostream>
#include<iomanip>
#include<string>
#include<boost/spirit/include/qi.hpp>
int main()
{
std::cout.precision(20);
//float x=219721.03839999999f;
//std::cout << x*1.0f << std::endl;
//gives 219721.03125
double resultD;
std::string arg="219721.03839999999";
auto itBeg = arg.begin();
auto itEnd = arg.end();
if(!boost::spirit::qi::parse(itBeg, itEnd,boost::spirit::qi::double_,resultD) || itBeg != itEnd)
std::cerr << "Cannot convert from std::string to double" << std::endl;
else
std::cout << "qi::double_:" << resultD << std::endl;
float resultF;
itBeg = arg.begin();
itEnd = arg.end();
if(!boost::spirit::qi::parse(itBeg, itEnd,boost::spirit::qi::float_,resultF) || itBeg != itEnd)
std::cerr << "Cannot convert from std::string to float" << std::endl;
else
std::cout << "qi::float_ :" << resultF << std::endl;
return 0;
}
输出:
qi::双_:219721.03839999999036
qi::float_:219721.109375
相关文章:
- 使用浮点数和双精度数的非常小数字的数学
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 位设置为浮点数或双精度值 c++
- 为什么浮点数的矢量化比双精度更有效?
- 在C++中序列化浮点数/双精度,编译为 WebAssembly
- 为什么编译器接受具有长双精度文本的浮点数的初始化?
- C++ 警告:在一个声明中将截断从双精度初始化为浮点数,但在另一个声明中则不初始化
- 在 OpenCL 内核中实现半精度浮点数据类型
- 如何随机化双精度/浮点数据类型? C++
- 提升多精度浮点数128:标准::exp错误:'no matching function for call'
- 如何提高计算浮点数的精度?
- atof() 返回浮点数而不是双精度
- 如何以最大精度(C++)将uint64_t转换为0到1之间的双精度/浮点数?
- 单个精度浮点数上的第 24 个分数位在哪里?IEEE 754
- 在C++中实现半精度浮点数
- C++双精度/浮点数的内部表示
- 清除单个精度浮点数的位
- 将双精度浮点数舍入到最接近且更大的浮点数
- 如何判断双精度浮点数是否可以安全地存储为单精度浮点数
- 用于高精度浮点数的c++类型