Subtraction Should Show Zero But Shows Small Error
조회 수: 2 (최근 30일)
이전 댓글 표시
I have two variables that were obtained with theoretically mathematically equivalent but not identical equations.
Ex:
A = equation
B = 10^(20)*equation/10^(20)
When I compare A to B via subtraction, some odd things occur. The variables (doubles) show the same 16 digits but are not 0 when subtracted. For example:
A = 0.568542494923802
B = 0.568542494923802
0.568542494923802 - 0.568542494923802 = 0
A-B = 1.1102e-16
What's going on here exactly? My code uses A and B later and acts as if there's no difference. I tried to look into machine epsilon (which I think is related to the issue), but I'm not understanding.
댓글 수: 0
답변 (1개)
Walter Roberson
2024년 2월 3일
What is going on here is that MATLAB represents double precision numbers in IEEE 754 Double Precision format. That format involves a sign bit, several bits of base 2 exponent, and a number of bits of base 2 mantissa. Numbers are represented as
sign * 2^(exponent) * mantissa
where mantissa is an integer in the range 2^52 to 2^53-1
Notice that this is all binary. Multiplying by 10^20 involves a change of exponent and change of mantissa, not just a change of internal exponent.
When you multiply by 10^20, round-off occurs. When you divide again by 10^20, round-off occurs. The two round-offs do not exactly cancel.
The default display of numbers with "format long" is one digit short of displaying all of the digits needed to recreate a number exactly. You need to display the numbers using something like
fprintf('%.999g\n', A)
to see all of the digits.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!