我正在为基本类型编写类,因此代码在多个平台和编译器上在逻辑上是相同的(例如int_least16_t
for int
)。为了娱乐! (我还是个学生。)
我读到了这个:
float [...] 匹配 IEEE-754 binary32 格式如果支持的话。 https://en.cppreference.com/w/cpp/language/types
更糟糕的是:
浮点类型MAY支持特殊值:∞、NaN 或 -0 https://en.cppreference.com/w/cpp/language/types
这意味着浮动MAY未签名...
[编辑:是的,这是不同的事情,但没有:“,但必须支持负数”。哟,如果标准中没有这样的东西,它可能不支持正常的 0...(我没有规范。)see https://stackoverflow.com/questions/72138837/can-floats-not-suport-negative-or-even-0]
我知道这就像__int128 https://stackoverflow.com/questions/16088282/is-there-a-128-bit-integer-in-gcc,而标准只是一个标准,
但仍然...
IEEE-754 是 1985 年的,但有些机器可能很奇怪,
一些旧硬件没有浮动单元。
据我了解, float 是强制性的(不像 int16_t 那样是可选的),
但可以采用任何标准,并且任何一组值都可以吗?
我们唯一拥有的就是一些宏(<cfloat> https://en.cppreference.com/w/cpp/header/cfloat):
-
FLT_MIN
, FLT_MAX
- 即使FLT_MIN = IEEE-754::FLT_MIN
, float 可以是非 IEEE-754。
例如浮动:带有分数的翻转指数...
-
FLT_RADIX
- 基础系统?如果是这样,可以帮忙写出准确的值。但是,float 仍然可以是 3 位或 200 位(大小)...
-
FLT_EPSILON
-(从 1 到下一个)我们可以使用它(带基数)来检查分数大小......
-
FLT_MANT_DIG
- 是“尾数”数字/分数大小吗?
-
FLT_MAX_EXP
- IEEE-754 中用 1... 填充的指数,
但外面可以是随机数吗?
如果 float 就像 IEEE-754(符号、指数、分数),那么就很简单,
但如果 -0 和 NaN 是可选的那么它MAY有所不同。
因为我无法区分它们,所以我无法使用位表示
(以安全的方式)。而如果∞是可选的,float
不再是安全类型。
我看到的唯一出路是将宏添加到编译器中。
我知道这是一个理论上的问题,但我很感兴趣是否有任何可能的检查,或者当我们使用时我们都编写依赖于实现的代码float
关键词?
2022年5月4日编辑:
我想出了这个:
用户例如。代码:
//User eg. code:
int main()
{
float_M a = 1f;
float_M b = 0f;
std::cout << a/b; //should output infinty (IEEE-754)
}
//Code:
class float_M
{
public:
#ifdef __STDC_IEC_559__
float data;
//...
float_M operator/(float_M x){return float_M(data/x.data);}
//...
#else
/*union{
float data;
struct{//For noSign case ("absolutly catastrofic" case)
uint_least8_t sign : 1;
uint_least8_t exponent : 8;
uint_least32_t fraction : 23;
}
}*/ //no noSign case ????
float data;
//...
float_M operator/(float_M x){return divide(this, x);}
//funtion pointer alert!
static /*const (1*) */ float_M (*divide)(float_M a, float_M b) =
/*std::numeric_limits<float>::is_signed ?(*/
std::numeric_limits<float>::has_infinity ?(
std::numeric_limits<float>::has_quiet_NaN ?(
[]{return float_M(a.data/b.data);}
): &_divide_noNaN
): &_divide_noNaN
/*): &_divide_noSign*/
//...
#endif
}
它很丑(有函数指针),但可以防止运行时不必要的跳转。希望c++23有更好的宏。
另外,更多链接:
- 关于浮点运算 https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
- 用户定义的文字 https://en.cppreference.com/w/cpp/language/user_literal
- 无 const 函数指针 (1*) https://stackoverflow.com/questions/15506094/const-function-pointers
跟进:浮点数可以不支持负数吗 https://stackoverflow.com/questions/72138837/can-floats-not-suport-negative-or-even-0