【问题标题】:Converting boost::multiprecision real number to integral ones将 boost::multiprecision 实数转换为整数
【发布时间】:2013-10-09 00:43:48
【问题描述】:

我正在尝试将 boost::multiprecision::cpp_dec_float_x 转换为 boost::multiprecision::uintx_t。所以基本上是一个 boost bigreal 到一个 boost bigint,关于这种转换所需的内存不会有损。 考虑以下几点:

boost::multiprecision::cpp_dec_float_100 myreal(100); /* bigreal */
boost::multiprecision::uint256_t myint; /* bigint */

设计内存分配

我想进行从第一个到最后一个的转换。考虑到我一直在计算所需的位数。从 256 位整数开始,我需要一个能够存储 0 到 2^256-1 的浮点数。我需要多少位数?正是256*log_10(2) ~= 77。所以一个 100 位的浮点数就绰绰有余了。因此,如果我保持我的实数低于 2^256,我可以将其转换为 256 位整数。

考虑到convert_to<> 只能与内置类型一起使用并且static_cast<> 引发错误(考虑到boost documentation 没有提到这样的上下文,这是可以预期的),我该如何进行转换?谢谢你

不关心数据丢失

我不关心数据丢失。出于我的目的,我将存储(在 bigreal 变量中)一个整数(没有小数部分)。所以我没事!

【问题讨论】:

  • "我正在尝试将 boost::multiprecision::uintx_t 转换为 boost::multiprecision::cpp_dec_float_x" - 你没有把它们混在一起吗?
  • 是的...谢谢你注意到...
  • 我换了地方....

标签: c++ boost g++ decimal bigdecimal


【解决方案1】:

不知道是不是你要找的,试试……

cpp_dec_float_100 myreal(100);
cpp_dec_float_100 int_part = myreal.backend().extract_integer_part();

类型仍然是 cpp_dec_float_100,但只包含整数部分。 我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-14
    • 2021-12-03
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 2018-02-03
    • 2013-12-04
    • 1970-01-01
    相关资源
    最近更新 更多