任意算术类型的比较:有人知道实现吗?

发布于 2024-11-24 23:28:37 字数 538 浏览 1 评论 0原文

在编写几个数学实用程序时,我遇到需要实现可以在任意两种基本算术类型之间进行比较的通用实用程序。当我开始编码时,很明显这个操作并不像看起来那么简单,因为我需要正确处理极端情况,特别是当类型具有不同的精度时,即类型之间转换期间的舍入策略变得很重要。考虑:

float a1 = 4.8f;
int a2 = 4;
assert(a2 != (int) a1); //fails erroneously since we truncated a1

float b1 = 40000000.0f; //can represent only 40000000 and 40000004 accurately
long b2 = 40000002;
assert(b1 != (float) b2); //fails erroneously since we now truncated b2

上述可以使用 c++0x 类型特征来实现,以根据提供给比较函数的模板参数自动选择适当的算法。然而,这是相当复杂的,并且有很多地方可能会出现错误,所以我认为自己发明所有东西并不值得。有谁知道正确实现上述内容的库?

While writing several math utilities I bumped into need to implement generic utility that can perform comparisons between any two fundamental arithmetic types. As I began coding, it became clear that this operation is not as straightforward as it seems, since I need correct handling of corner cases, especially when the types have different precision, i.e. rounding strategy during conversion between types becomes important. Consider:

float a1 = 4.8f;
int a2 = 4;
assert(a2 != (int) a1); //fails erroneously since we truncated a1

float b1 = 40000000.0f; //can represent only 40000000 and 40000004 accurately
long b2 = 40000002;
assert(b1 != (float) b2); //fails erroneously since we now truncated b2

The above can be implemented using c++0x type traits to automatically select the appropriate algorithm according to the template arguments supplied to the comparison function. However, this is quite complex and there's quite a lot of places where bugs can creep, so I don't think inventing everything myself is worthwhile. Does anyone know a library that implements the above correctly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦冥 2024-12-01 23:28:37

您可能需要查看 GNU 的 MP Bignum 库,网址为 http://gmplib.org/。从他们的页面:

GMP 是一个用于任意精度算术的免费库,运行于
有符号整数、有理数和浮点数。那里
除了隐含的精度之外,对精度没有实际限制
运行 GMP 的机器中的可用内存。 GMP拥有一套丰富的
函数,并且函数有一个常规的接口。

GMP 经过精心设计,以尽可能快地实现,无论是小型企业还是小型企业
操作数和巨大的操作数。速度是通过使用实现的
全字作为基本算术类型,通过使用快速算法,
针对最常见的内部循环的高度优化的汇编代码
很多 CPU,并且普遍强调速度。

You may want to look into GNU's MP Bignum library at http://gmplib.org/. From their page:

GMP is a free library for arbitrary precision arithmetic, operating on
signed integers, rational numbers, and floating point numbers. There
is no practical limit to the precision except the ones implied by the
available memory in the machine GMP runs on. GMP has a rich set of
functions, and the functions have a regular interface.

GMP is carefully designed to be as fast as possible, both for small
operands and for huge operands. The speed is achieved by using
fullwords as the basic arithmetic type, by using fast algorithms, with
highly optimised assembly code for the most common inner loops for a
lot of CPUs, and by a general emphasis on speed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文