gpt4 book ai didi

c - C中下溢和nan有什么区别?

转载 作者:行者123 更新时间:2023-12-03 15:48:03 25 4
gpt4 key购买 nike

目前我正在学习浮点异常。我正在写一个带有函数的循环。在该函数中,计算出的值等于 0.5 .随着循环的进行,输入值除以 10 .
循环:

 for(i = 0; i < e; i++)
{
xf /= 10.0; // force increasingly smaller values for x
float_testk (xf, i);
}
功能:
void float_testk(float x, int i)
{
float result;

feclearexcept(FE_ALL_EXCEPT); // clear all pending exceptions

result = (1 - cosf(x)) / (x * x);

if(fetestexcept(FE_UNDERFLOW) != 0)
fprintf(stderr,"Underflow occurred in double_testk!\n");
if(fetestexcept(FE_OVERFLOW) != 0)
fprintf(stderr,"Overflow occurred in double_testk!\n");
if(fetestexcept(FE_INVALID) != 0)
fprintf(stderr,"Invalid exception occurred in double_testk!\n");

printf("Iteration %3d, float result for x=%.8f : %f\n",i,x,result);
}
前几次迭代的输出大约是 0.5后来它变成 0由于CC。过了一会儿,这是程序的输出:
Iteration  18, float result for x=0.00000000 : 0.000000
Underflow occurred in double_testk!
Iteration 19, float result for x=0.00000000 : 0.000000
Underflow occurred in double_testk!
Iteration 20, float result for x=0.00000000 : 0.000000
Underflow occurred in double_testk!
Iteration 21, float result for x=0.00000000 : 0.000000
Underflow occurred in double_testk!
Invalid exception occurred in double_testk!
Iteration 22, float result for x=0.00000000 : -nan
Underflow occurred in double_testk!
Invalid exception occurred in double_testk!
我想知道从下溢过渡到 NaN 时会发生什么情况.因为下溢意味着数字太小,无法存储在内存中。
但是如果数量已经太少了, NaN的目标是什么? ?

最佳答案

Because underflow means that the number is too small to be stored in the memory.


不完全的;在浮点中,下溢意味着结果低于可以全精度表示数字的范围。结果可能仍然相当准确。
只要 x至少为 2−75, x * x产生非零结果。可能在浮点域的次正规部分,精度在下降,但实数结果 xx大到可以四舍五入到 2−149 或更大。那么,对于这些小 x , (1 - cosf(x)) / (x * x)计算为零除以非零值,因此结果为零。
x小于 2−75,则 x * x产生零,因为 x 的实数结果• x太小了,在浮点运算中,它被四舍五入为零。然后 (1 - cosf(x)) / (x * x)计算为零除以零,因此结果是 NaN。这就是您的迭代 22 中发生的情况。
(2−149 是 IEEE-754 binary32 中可表示的最小正值,您的 C 实现可能将其用于 float 。在 2−150 和 2−150 之间的实数结果将向上取整为 2−149。较低的结果将向下取整到 0。假设舍入模式是舍入到最近,并列到偶数。)

关于c - C中下溢和nan有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64032082/

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