如何获得提升多精度数字部件?

时间:2013-05-10 11:26:12

标签: c++ boost interop decimal

说我有号码

// bmp = boost::multiprecision
bmp::cpp_dec_float n("123456789.1234567891011121314");

其后端数据为:

[0]  1         unsigned int
[1]  23456789  unsigned int
[2]  12345678  unsigned int
[3]  91011121  unsigned int
[4]  31400000  unsigned int
...  0
[15] 0         unsigned int

这正是我想得到的;不幸的是,我找不到一种方法可以将我的号码的两个部分都作为bmp::int128_t - 例如 - 或者我的号码的基础数据。

也就是说,我喜欢这样的东西:

bmp::int128_t integerPart;
bmp::int128_t floatPart;
n.getParts(integerPart, floatPart);

auto&& data = n.data(); // which is actually private when using `cpp_dec_float`.

无论如何,有人知道如何做我想要实现的目标吗?

为了记录,为了互操作性,我需要将此十进制数表示为C#十进制数。

3 个答案:

答案 0 :(得分:1)

从增强文档中,后端是故意不透明的,因为它可能随时更改而不会发出警告。来自http://www.boost.org/doc/libs/1_55_0/libs/multiprecision/doc/html/boost_multiprecision/ref/cpp_dec_ref.html

的(Class template cpp_dec_float fulfils all of the requirements for a Backend type. Its members and non-member functions are deliberately not documented: these are considered implementation details that are subject to change.

据我所知,你有两个选择。您可以查看您正在使用的后端类的特定版本的源代码,使用number方法从backend访问它,并希望后端永远不会更改(特别是考虑只破坏二进制格式而不是编译的更改。

或者,我建议您使用cpp_dec_float的字符串表示形式并将其自己拆分为两部分,使用stringchar*构造函数为您提供基础整数类型&#39 ;对此感兴趣。

答案 1 :(得分:0)

我不知道你是否正在寻找,试试......

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

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

答案 2 :(得分:-1)

我怀疑你可以使用eval_frexp来获取你正在寻找的值,尽管你仍然需要检查它们是否适合C#Decimal类型。请参阅Boost.Multiprecision后端要求手册: http://www.boost.org/doc/libs/1_53_0/libs/multiprecision/doc/html/boost_multiprecision/ref/backendconc.html

你可以随时进行长手数学和范围检查;如果你没有转移太多数字,这可能足够快。

说了这么多,欢迎你顽皮地做一些事情:

#define private public
#define protected public
#include <boost/multiprecision/cpp_dec_float.hpp>
#undef private
#undef protected

但如果它在将来的版本中中断,你可以保留两个部分。


嘿,谢谢没有评论的downvote。这真的很有帮助。

澄清我上面的评论:

使用eval_frexp:在进一步研究之后,似乎eval_frexp(b, cb, pi)仍然只提供2的幂,而不是Decimal类型所需的10的幂。因此,如果您只想使用公共接口,我怀疑您必须以长格式进行算术运算。

滥用private成员:Boost.Multiprecision类的作者和维护者根据某些指导原则设计了它们;他们显然将未来证明比提供内部结构更重要:

  

类模板cpp_dec_float满足后端类型的所有要求。故意不记录其成员和非成员职能:这些被认为是可能发生变化的实施细节。 (http://www.boost.org/doc/libs/1_53_0/libs/multiprecision/doc/html/boost_multiprecision/ref/cpp_dec_ref.html

我的提案明确标记为“顽皮”,并警告说它可能会在未来的版本中破坏,是将OP的设计需求强加于B.MP的作者之前。

最干净的方法可能是提出对cpp_dec_float类的更改,其中公开了内部结构;鉴于一个引人注目的用例,以及对代码在历史上有多少变化的分析,它甚至可能被接受。

希望这会有所帮助。如果读者仍然遇到问题,请随时关注,但请告诉我哪一部分困扰您,以便我可以尝试改进它。