gpt4 book ai didi

c - 避免 float 的不准确性

转载 作者:太空狗 更新时间:2023-10-29 15:19:08 25 4
gpt4 key购买 nike

我完全理解与浮点相关的问题,但我看到了一个我无法解释的非常有趣的行为。

float x = 1028.25478;
long int y = 102825478;
float z = y/(float)100000.0;
printf("x = %f ", x);
printf("z = %f",z);

输出是:

x = 1028.254761 z = 1028.254780

现在,当我将 float 分配给变量 x 时,如果 float 无法表示该特定随机值 (1028.25478)。为什么在变量 z 的情况下不一样?

附言我正在使用 pellesC IDE 来测试代码(C11 编译器)。

最佳答案

我很确定这里发生的是后一个浮点变量被省略,而是保存在 double 寄存器中;然后按原样作为参数传递给 printf。然后编译器将相信在默认参数提升后以 double 传递此数字是安全的。

我设法使用 GCC 7.2.0 生成了一个类似的结果,并使用了这些开关:

-Wall -Werror -ffast-math -m32 -funsafe-math-optimizations -fexcess-precision=fast -O3

输出是

x = 1028.254761 z = 1028.254800

那里的数字略有不同^。

description for -fexcess-precision=fast说:

-fexcess-precision=style

This option allows further control over excess precision on machines where floating-point operations occur in a format with more precision or range than the IEEE standard and interchange floating-point types. By default, -fexcess-precision=fast is in effect; this means that operations may be carried out in a wider precision than the types specified in the source if that would result in faster code, and it is unpredictable when rounding to the types specified in the source code takes place. When compiling C, if -fexcess-precision=standard is specified then excess precision follows the rules specified in ISO C99; in particular, both casts and assignments cause values to be rounded to their semantic types (whereas -ffloat-store only affects assignments). This option [-fexcess-precision=standard] is enabled by default for C if a strict conformance option such as -std=c99 is used. -ffast-math enables -fexcess-precision=fast by default regardless of whether a strict conformance option is used.

此行为不符合 C11

关于c - 避免 float 的不准确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927737/

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