gpt4 book ai didi

c - 为什么在通过求和计算 FLT_MAX 时 float 在某个时刻不会增加?

转载 作者:行者123 更新时间:2023-11-30 15:18:34 25 4
gpt4 key购买 nike

我正在尝试使用以下代码从 FLT_MAX 计算 <float.h>:

float increase(float a, float step)
{
float t = a, original = a;
while((t = a + step) > a)
{
a = t;
}

if(original == a)
{
printf(" %lf was not increased with %lf step \n", original, step);
return a;
}
printf(" %lf increased to %lf with %lf step \n", original, a, step);
return increase(a, step / 100.0);
}


void main()
{
printf("FLT_MAX : %f \n", FLT_MAX);

// compute:
increase(0.0, 10.0);
increase(0.0, 100.0);
increase(0.0, 10000.0);
increase(0.0, 100000000.0);
increase(0.0, 10000000000000000.0);
}

它输出:

FLT_MAX : 340282346638528860000000000000000000000.000000
0.000000 increased to 268435456.000000 with 10.000000 step
268435456.000000 was not increased with 0.100000 step
0.000000 increased to 2147483648.000000 with 100.000000 step
2147483648.000000 was not increased with 1.000000 step
0.000000 increased to 274877906944.000000 with 10000.000000 step
274877906944.000000 was not increased with 100.000000 step
0.000000 increased to 2251799813685248.000000 with 100000000.000000 step
2251799813685248.000000 was not increased with 1000000.000000 step
0.000000 increased to 302231454903657290000000.000000 with 10000000272564224.000000 step
302231454903657290000000.000000 was not increased with 100000000376832.000000 step

为什么在那些看起来还有空间的点上它会停止增加?看起来需要一些位操作才能获取 FLT_MAX 或者是否可以通过求和来获取它?谢谢!

最佳答案

原始代码在不同的地方停止,因为float值是对数分布的并且具有有限的精度。 [1000000 到 2000000] 范围内的 float 值大约与 [0.0000001 到 0.0000002] 之间的值一样多。在某些时候,将一个小float添加到一个大float中并不能区分连续的float值。

代码即将运行。

在 while 循环结束时,代码需要

1) 如果出现一些增加,请尝试更大的步骤
2) 如果步数不是太小(缺少),请尝试添加较小的步数,或者
3)返回

此外,步骤更改应该是一个小因子,例如 *2.0 或/2.0,而不是 100.0。添加了无穷大检测

#include <float.h>
#include <stdio.h>

float increase(float a, float step) {
fflush(stdout);
float t = a, original = a;
while ((t = a + step) > a) {
if (1.0f/t == 0.0f) break;
a = t;
}
if (original == a) {
printf(" %lf was not increased with %lf step \n", original, step);
if (step > 1.0) return increase(a, step / 2.0);
return a;
}
printf(" %lf increased to %lf with %lf step \n", original, a, step);
return increase(a, step * 2.0);
}

//void main() {
int main(void) {
printf("FLT_MAX : %f \n", FLT_MAX);

// compute:
increase(0.0, 10.0);
// increase(0.0, 100.0);
// increase(0.0, 10000.0);
// increase(0.0, 100000000.0);
// increase(0.0, 10000000000000000.0);
printf("FLT_MAX : %f \n", FLT_MAX);
return 0;
}

输出

FLT_MAX : 340282346638528859811704183484516925440.000000 
0.000000 increased to 268435456.000000 with 10.000000 step
...
340282346638528859811704183484516925440.000000 was not increased with 0.625000 step
FLT_MAX : 340282346638528859811704183484516925440.000000

关于c - 为什么在通过求和计算 FLT_MAX 时 float 在某个时刻不会增加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31357258/

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