具有C或D的浮点语义的整数类型

Cor*_*Xii 9 c floating-point int d fixed-point

我正在寻找CD的现有实现,或者实现具有浮点语义的实现,有符号和/或无符号整数类型的建议.

也就是说,这表现为浮点类型整型运算做什么时候:溢出产生无穷大(-infinity的签署下溢),而不是缠绕或具有不确定的行为,不确定的操作产生的NaN

本质上是一个浮点版本,其中可呈现数字的分布均匀地落在数字线上,而不是在0附近聚合.

此外,所有操作都应该是确定性的 ; 任何给定的二进制补码32位架构应该为相同的计算产生完全相同的结果,无论其实现如何(而浮点可能,并且通常会产生稍微不同的结果).

最后,性能是一个问题,让我担心潜在的"bignum"(任意精度)解决方案.

另请参见:定点饱和算术.

小智 3

我不知道有任何现有的实现。

但我想实现它会是一个问题(在 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.
}
Run Code Online (Sandbox Code Playgroud)