使用浮点任意精度 C++ 改造现有代码图书馆,有成功的机会吗?
假设我有这样的代码片段:
typedef double My_fp_t;
My_fp_t my_fun( My_fp_t input )
{
// some fp computation, it uses operator+, operator- and so on for type My_fp_t
}
My_fp_t input = 0.;
My_fp_t output = my_fun( input );
是否可以使用浮点任意精度 C++ 库改造我现有的代码?
我想简单地添加 #include
,将我的 typedef double My_fp_t;
更改为 typedef random_double_t My_fp_t;
并让运算符重载C++ 的工作...
我的主要问题是实际上我的代码没有 typedef
:-( 所以也许我的计划注定要假设
我的代码有 typedef,我还会遇到什么其他问题?
Let say I have a snippet of code like this:
typedef double My_fp_t;
My_fp_t my_fun( My_fp_t input )
{
// some fp computation, it uses operator+, operator- and so on for type My_fp_t
}
My_fp_t input = 0.;
My_fp_t output = my_fun( input );
Is it possible to retrofit my existing code with a floating point arbitrary precision C++ library?
I would like to simple add #include <cpp_arbitrary_precision_fp>
, change my typedef double My_fp_t;
into typedef arbitrary_double_t My_fp_t;
and let the operator overloading of C++ doing its job...
My main problem is that actually my code do NOT have the typedef
:-( and so maybe my plan is doomed to failure.
Assuming that my code had the typedef, what other problems would I face?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能很难。我在我的博士论文代码中使用了模板方法来处理不同的数字类型。您可能想看一下它以了解我遇到的问题。
问题是,如果您对数字所做的只是使用标准算术运算符,那就没问题。但是,一旦您使用平方根或其他非运算符函数,您就需要创建辅助对象来检测对象的类型(在编译时,因为在运行时执行此操作太慢;请参阅 boost 元编程库以获取帮助)然后调用正确的函数并将其作为正确的类型返回。这一切都是完全可行的,但可能需要比您想象的更长的时间,并且会大大增加代码的复杂性。
根据我的经验,(我使用的是 GMP,它一定是 C++ 可用的最快的任意精度库)在我引入的所有努力和复杂性之后,我发现 GMP 对于我正在进行的各种计算来说太慢了;所以它在学术上很有趣,但实际上毫无用处。在开始之前,请先进行一些速度测试,看看如果您使用任意精度算术,您的库是否仍然可用。
This might be tough. I used a template approach in my PhD thesis code do deal with different numerical types. You might want to take a look at it to see the problems I encountered.
The thing is you are fine if all you do with your numbers is use the standard arithmetic operators. However, as soon as you use a square root or some other non operator function you need to create helper objects to detect your object's type (at compile time as it is too slow to do this at run time; see the boost metaprogramming library for help on that) and then call the correct function and return it as the correct type. It is all totally doable, but is likely to take longer than you think and will add considerably to the complexity of your code.
In my experience, (I was using GMP which must be the fastest arbitrary precision library available for C++) after all of the effort and complexity I had introduced, I found that GMP was just too slow for the sorts of computation that I was doing; so it was academically interesting, but practically useless. Before you start on this do some speed tests to see whether your library will still be usable if you use arbitrary precision arithmetic.
如果库定义了一个正确重载您使用的运算符的类型,我没有看到任何问题......
If the library defines a type that correctly overloads the operators you use, I don't see any problem...