【发布时间】:2014-05-26 09:58:39
【问题描述】:
我正在使用cpp_dec_float 来获得任意精度,这很好,但我无法弄清楚如何打印所有有效数字。
例如,用这个代码来设置
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;
我收到7.0710678118654752440084436210484903928483593768847403658833986900000000000000000000000000000000000000e-01。我很高兴没有丢失精度,但它不是很保守。
有没有一种方法可以在不损失现有工具的任何精度的情况下删除尾随零?如果不是,如何从结果字符串中删除尾随零?
如果可以使用现有工具来满足我的意图,如何以科学计数法输出cpp_dec_float 而不会丢失精度并将尾随零删除到字符串中?我只能找到stream examples。
更接近
多亏了 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 模拟界面中如此亲切地向我指出,我发现了这些行
if(number_of_digits == 0)
number_of_digits = cpp_dec_float_total_digits10;
这向我建议它应该考虑所有有效数字,由于长度不受限制,基本上输出输入的内容。
我检查了source 中的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() 的第一个参数?
【问题讨论】:
标签: c++ boost trailing multiprecision