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

标签 c floating-point int d fixed-point

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

也就是说,一个整数类型在进行算术运算时表现得像浮点类型:溢出产生无穷大(-无穷大对于有符号下溢)而不是回绕或具有未定义的行为,未定义的操作会产生 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/

相关文章:

c - Lua - 数字是 float 还是 double ?

c++ - 为什么我的数字在我的猜数字游戏中计算不正确?

c++ - G++ 浮点精度

c - 如何验证函数 X() 是从函数 Y() 而不是从函数 Z() 调用的?

c - 什么是MinGW的简单解释

c - 下面的表达式的值是多少?我=1; I = (I<<= 1 % 2) (a) 2 (b) 1 (c) 0 (d) 语法错误

c - 在 C 中读/写浮点类型时如何处理字节顺序差异?

java - 如何在 Java 文档中查找 int[].length ?

C++11 枚举类 : plus int failed to compile, 为什么?

c++ - 为什么char * c 可以被赋值为字符串而不需要分配或引用?