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

답변 (1개)

Voss
Voss 2024년 4월 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

Rimon
Rimon 2024년 4월 8일
편집: Rimon 2024년 4월 8일
Thank you for this detailed explanation. How can I however overcome this issue?
Voss
Voss 2024년 4월 8일
편집: Voss 2024년 4월 8일

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.

댓글을 달려면 로그인하십시오.

태그

질문:

2024년 4월 1일

편집:

2024년 4월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by