gpt4 book ai didi

c++ - float 限制代码不产生正确的结果

转载 作者:太空狗 更新时间:2023-10-29 20:27:53 25 4
gpt4 key购买 nike

我绞尽脑汁想弄清楚为什么这段代码没有得到正确的结果。我正在寻找浮点正负溢出/下溢水平的十六进制表示。该代码基于此站点和 Wikipedia entry :

7f7f ffff ≈ 3.4028234 × 1038(最大单精度)——来自维基百科条目,对应正溢出

代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>

using namespace std;

int main(void) {

float two = 2;
float twentyThree = 23;
float one27 = 127;
float one49 = 149;


float posOverflow, negOverflow, posUnderflow, negUnderflow;

posOverflow = two - (pow(two, -twentyThree) * pow(two, one27));
negOverflow = -(two - (pow(two, one27) * pow(two, one27)));


negUnderflow = -pow(two, -one49);
posUnderflow = pow(two, -one49);


cout << "Positive overflow occurs when value greater than: " << hex << *(int*)&posOverflow << endl;


cout << "Neg overflow occurs when value less than: " << hex << *(int*)&negOverflow << endl;


cout << "Positive underflow occurs when value greater than: " << hex << *(int*)&posUnderflow << endl;


cout << "Neg overflow occurs when value greater than: " << hex << *(int*)&negUnderflow << endl;

}

输出是:

Positive overflow occurs when value greater than: f3800000 Neg overflow occurs when value less than: 7f800000 Positive underflow occurs when value greater than: 1 Neg overflow occurs when value greater than: 80000001

为了获得 float 的十六进制表示,我使用了一种描述here 的方法:

为什么代码不起作用?我知道它会在正溢出 = 7f7f ffff 时起作用。

最佳答案

您对最高可表示正 float 的表达是错误的。您链接的页面使用 (2-pow(2, -23)) * pow(2, 127),并且您有 2 - (pow(2, -23) * pow( 2, 127))。对于最小的可表示负 float 也是如此。

但是,您的下溢表达式看起来是正确的,它们的十六进制输出也是如此。

请注意,posOverflownegOverflow 只是 +FLT_MAX-FLT_MAX。但请注意,您的 posUnderflownegUnderflow 实际上 小于 FLT_MIN(因为它们是非正规的,并且 FLT_MIN 是最小的正正常 float )。

关于c++ - float 限制代码不产生正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14928764/

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