왜 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
파이썬
print(0.1 + 0.2 != 0.3)
산출:
True
다른 예
- 자바 : http://ideone.com/EPO6X
- C # : http://ideone.com/s14tV
D에 대해 이것이 사실이 아닌 이유는 무엇입니까? 이해했듯이 D는 기본 부동 소수점 숫자를 사용합니다. 이것은 버그입니까? 특정 숫자 표현을 사용합니까? 다른 것? 꽤 혼란 스럽습니다.
디
import std.stdio;
void main()
{
writeln(0.1 + 0.2 != 0.3);
}
산출:
false
최신 정보
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
아마도 (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
'Nice programing' 카테고리의 다른 글
MultipleActiveResultSets = 참 또는 다중 연결? (0) | 2020.10.19 |
---|---|
MongoDB 스키마 설계-작은 문서가 많거나 큰 문서가 적습니까? (0) | 2020.10.19 |
OpenCV / Python에서 카메라 매개 변수 설정 (0) | 2020.10.19 |
Homebrew를 사용하여 OS X에서 OpenSSL 업데이트 (0) | 2020.10.19 |
재귀 적으로 Git LFS 트랙 폴더 (0) | 2020.10.19 |