Nice programing

왜 0.1 + 0.2 == 0.3 in D입니까?

nicepro 2020. 10. 19. 12:46
반응형

왜 0.1 + 0.2 == 0.3 in D입니까?


assert(0.1 + 0.2 != 0.3); // shall be true

언어가 기본 부동 소수점 산술을 사용하는지 확인하는 것이 가장 좋습니다.

C ++

#include <cstdio>

int main()
{
   printf("%d\n", (0.1 + 0.2 != 0.3));
   return 0;
}

산출:

1

http://ideone.com/ErBMd

파이썬

print(0.1 + 0.2 != 0.3)

산출:

True

http://ideone.com/TuKsd

다른 예

D에 대해 이것이 사실이 아닌 이유는 무엇입니까? 이해했듯이 D는 기본 부동 소수점 숫자를 사용합니다. 이것은 버그입니까? 특정 숫자 표현을 사용합니까? 다른 것? 꽤 혼란 스럽습니다.

import std.stdio;

void main()
{
   writeln(0.1 + 0.2 != 0.3);
}

산출:

false

http://ideone.com/mX6zF


최신 정보

LukeH 에게 감사합니다 . 이 설명 부동 소수점 상수 접는의 효과 가이 .

암호:

import std.stdio;

void main()
{
   writeln(0.1 + 0.2 != 0.3); // constant folding is done in real precision

   auto a = 0.1;
   auto b = 0.2;
   writeln(a + b != 0.3);     // standard calculation in double precision
}

산출:

false
true

http://ideone.com/z6ZLk


아마도 (0.3! = 0.3)으로 최적화되었을 것입니다. 분명히 거짓입니다. 최적화 설정을 확인하고 꺼져 있는지 확인한 다음 다시 시도하십시오.


(Flynn's answer is the correct answer. This one addresses the problem more generally.)


You seem to be assuming, OP, that the floating-point inaccuracy in your code is deterministic and predictably wrong (in a way, your approach is the polar opposite of that of people who don't understand floating point yet).

Although (as Ben points out) floating-point inaccuracy is deterministic, from the point of view of your code, if you are not being very deliberate about what's happening to your values at every step, this will not be the case. Any number of factors could lead to 0.1 + 0.2 == 0.3 succeeding, compile-time optimisation being one, tweaked values for those literals being another.

Rely here neither on success nor on failure; do not rely on floating-point equality either way.


According to my interpretation of the D language specification, floating point arithmetic on x86 would use 80 bits of precision internally, instead of only 64 bits.

One would have to check however that that is enough to explain the result you observe.

참고URL : https://stackoverflow.com/questions/6874357/why-0-1-0-2-0-3-in-d

반응형