我在用着cpp_dec_float http://www.boost.org/doc/libs/1_55_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/cpp_dec_float.html对于任意精度,这很棒,但我无法弄清楚如何打印所有有效数字。
例如,使用此代码进行设置
using boost::multiprecision::cpp_dec_float;
typedef boost::multiprecision::number<cpp_dec_float<100>> mp_type;
mp_type test_num("7.0710678118654752440084436210484903928483593768847403658833986900e-01");
如果我只是打印
std::cout << std::scientific << test_num << std::endl;
结果是7.071068e-01
,这样就可以了。
如果我选择分手
std::cout << std::setprecision(std::numeric_limits<mp_type>::digits) << std::scientific << test_num << std::endl;
I get 7.0710678118654752440084436210484903928483593768847403658833986900000000000000000000000000000000000000e-01
。我很高兴没有失去精度,但它在空间上不是很保守。
有没有办法使用现有工具删除尾随零而不损失任何精度?如果不是,如何从结果字符串中删除尾随零?
如果现有的工具能够满足我的意图,如何才能cpp_dec_float
以科学记数法输出,而不会丢失精度并将尾随零删除到字符串中?我只能找到流示例 http://www.cplusplus.com/reference/ios/scientific/.
Closer
感谢mockinterface,我更接近了。
我已将代码更改为:
using boost::multiprecision::cpp_dec_float;
typedef boost::multiprecision::number<cpp_dec_float<0>> mp_type;
mp_type test_num("7.0710678118654752440084436210484903928483593768847403658833986900e-01");
std::cout << test_num.str(0, std::ios_base::scientific) << std::endl;
具有潜在的无限长度;但是,这是打印的:
7.0710678118654752440084436210484903928480e-01
这很接近但看起来很奇怪。在里面source http://code.woboq.org/boost/boost/boost/multiprecision/cpp_dec_float.hpp.htmlmockinterface 如此慷慨地向我指出,我发现了这些行
if(number_of_digits == 0)
number_of_digits = cpp_dec_float_total_digits10;
这对我来说意味着它应该考虑所有有效数字,基本上输出输入的内容,因为长度不受限制。
我检查了source http://code.woboq.org/boost/boost/boost/multiprecision/cpp_dec_float.hpp.html#_ZN5boost14multiprecision8backends13cpp_dec_float28cpp_dec_float_total_digits10E for cpp_dec_float_total_digits10
,我无法确定它到底是什么;不过,我确实找到了似乎定义它的代码部分。
private:
static const boost::int32_t cpp_dec_float_elem_digits10 = 8L;
static const boost::int32_t cpp_dec_float_elem_mask = 100000000L;
BOOST_STATIC_ASSERT(0 == cpp_dec_float_max_exp10 % cpp_dec_float_elem_digits10);
// There are three guard limbs.
// 1) The first limb has 'play' from 1...8 decimal digits.
// 2) The last limb also has 'play' from 1...8 decimal digits.
// 3) One limb can get lost when justifying after multiply,
// as only half of the triangle is multiplied and a carry
// from below is missing.
static const boost::int32_t cpp_dec_float_elem_number_request = static_cast<boost::int32_t>((cpp_dec_float_digits10 / cpp_dec_float_elem_digits10) + (((cpp_dec_float_digits10 % cpp_dec_float_elem_digits10) != 0) ? 1 : 0));
// The number of elements needed (with a minimum of two) plus three added guard limbs.
static const boost::int32_t cpp_dec_float_elem_number = static_cast<boost::int32_t>(((cpp_dec_float_elem_number_request < 2L) ? 2L : cpp_dec_float_elem_number_request) + 3L);
public:
static const boost::int32_t cpp_dec_float_total_digits10 = static_cast<boost::int32_t>(cpp_dec_float_elem_number * cpp_dec_float_elem_digits10);
能否确定有效位数并将其用作第一个参数boost::multiprecision::cpp_dec_float::str()
?