Weird results while coding using an m-file

Hi,
When using the following code, I expect A = B. The difference (Differ) is however not zero. Any clue?
Thanks
clear all, clc
Vs = 10;
R = 10;
L = 10e-3;
C = 400e-6;
A = (R/(2*L))^2
B = 1/(L*C)
%B = 2.5000e+05
Differ = A-B

Réponses (1)

This is an effect of floating-point arithmetic.
Note that Differ == eps(A), which means that A and B are as close as they can be without being exactly equal.
Vs = 10;
R = 10;
L = 10e-3;
C = 400e-6;
A = (R/(2*L))^2
A = 250000
B = 1/(L*C)
B = 2.5000e+05
Differ = A-B
Differ = 2.9104e-11
eps(A)
ans = 2.9104e-11
eps(A) == Differ
ans = logical
1

2 commentaires

Rimon
Rimon le 8 Avr 2024
Modifié(e) : Rimon le 8 Avr 2024
Thank you for this detailed explanation. How can I however overcome this issue?
Voss
Voss le 8 Avr 2024
Modifié(e) : Voss le 8 Avr 2024

Don't expect Differ to be exactly zero.

When comparing two floating point numbers, don't check for exact equality, use a small tolerance, e.g., abs(A-B) <= 10*eps(A)

or ismembertol

Or use the Symbolic Math Toolbox, e.g. vpa.

Connectez-vous pour commenter.

Question posée :

le 1 Avr 2024

Modifié(e) :

le 8 Avr 2024

Community Treasure Hunt

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

Start Hunting!

Translated by