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

Antworten (1)

Voss
Voss am 1 Apr. 2024
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 Kommentare

Rimon
Rimon am 8 Apr. 2024
Bearbeitet: Rimon am 8 Apr. 2024
Thank you for this detailed explanation. How can I however overcome this issue?
Voss
Voss am 8 Apr. 2024
Bearbeitet: Voss am 8 Apr. 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.

Melden Sie sich an, um zu kommentieren.

Gefragt:

am 1 Apr. 2024

Bearbeitet:

am 8 Apr. 2024

Community Treasure Hunt

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

Start Hunting!

Translated by