gpt4 book ai didi

c++ - 任意算术类型比较 : does anyone know an implementation?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:46:49 24 4
gpt4 key购买 nike

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

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类型特征来实现,根据提供给比较函数的模板参数自动选择合适的算法。然而,这非常复杂,而且有很多地方可能会出现错误,所以我认为自己发明所有东西并不值得。有谁知道正确实现上述内容的库?

最佳答案

您可能想在 http://gmplib.org/ 查看 GNU 的 MP Bignum 库.从他们的页面:

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.

关于c++ - 任意算术类型比较 : does anyone know an implementation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6724977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com