我正在寻找 C 或 D 的现有实现,或者在实现有符号和/或无符号整数类型方面的建议浮点语义。
也就是说,一个整数类型在进行算术运算时表现得像浮点类型:溢出产生无穷大(-无穷大对于有符号下溢)而不是回绕或具有未定义的行为,未定义的操作会产生 NaN 等。
从本质上讲,这是一个 float 的版本,其中可呈现数字的分布均匀地落在数字线上,而不是集中在 0 附近。
此外,所有的操作都应该是确定性的;任何给定的二进制补码 32 位架构都应该为相同的计算产生完全相同的结果,而不管其实现如何(而浮点可能并且经常会产生略有不同的结果)。
最后,性能是一个问题,这让我担心潜在的“bignum”(任意精度)解决方案。
另请参阅:定点和饱和算法。
最佳答案
我不知道这方面的任何现有实现。
但我想实现它会是一个问题(在 D 中):
enum CheckedIntState : ubyte
{
ok,
overflow,
underflow,
nan,
}
struct CheckedInt(T)
if (isIntegral!T)
{
private T _value;
private CheckedIntState _state;
// Constructors, getters, conversion helper methods, etc.
// And a bunch of operator overloads that check the
// result on every operation and yield a CheckedInt!T
// with an appropriate state.
// You'll also want to overload opEquals and opCmp and
// make them check the state of the operands so that
// NaNs compare equal and so on.
}
关于c - C 或 D 的具有浮点语义的整数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13544136/