Azzera filtri
Azzera filtri

Subtraction Should Show Zero But Shows Small Error

2 visualizzazioni (ultimi 30 giorni)
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.

Risposte (1)

Walter Roberson
Walter Roberson il 3 Feb 2024
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.

Prodotti


Release

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by