when I am subtracting two same values found out from different equations not giving 0, it is giving imaginary value

조회 수: 2(최근 30일)
BIKRAM KESHARI KHANDAI
BIKRAM KESHARI KHANDAI 2021년 12월 29일
편집: David Goodmanson 2021년 12월 29일
n = 7;
t = 0.6;
tp = 0.05;
tc = 0.05;
x = (n-1)*(tp+tc);
delta = sqrt(t-x)
Ans:- delta = 0.0000e+00 + 1.0537e-08i
Here I am getting some imaginary value , How I can get 0 value?

채택된 답변

David Goodmanson
David Goodmanson 2021년 12월 29일
편집: David Goodmanson 2021년 12월 29일
Hi Bikram,
this is all because of precision issues when dealing with floating point numbers. After running your code,
tminusx = t-x
tminusx = -1.1102e-16
Since double precision numbers have 16 digits, an expression differing from 0 by something on the order of 10^(-16) is generally as good as you can expect.
The answer you are getting looks a lot worse than it really is, because you are taking the square root of t-x. So 10^(-16) becomes 10^(-8), with an additional factor of i since it so happens (50-50 chance) that t-x is negative.
  댓글 수: 4
David Goodmanson
David Goodmanson 2021년 12월 29일
Hi Bikram,
In this case you can get a better answer by scaling things appropriately. Suppose time is in seconds, and you know that t = .6 exactly and tp = tc = .05 exactly. Then t = 600 msec, tp = tc = 50 msec. In terms of milliseconds, all the times are integers, which are stored exactly. The calculation is also in integers, so if you do the same calculation you get delta = 0.
By the calculation being in integers I mean that there are, for example, no divisions of integers with a non-integer result, such as y = 1/3. Now y is a floating point quantity and you get back to the same issues. A well known example is
1/10 + 2/10 -3/10
ans = 5.5511e-17

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

추가 답변(0개)

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by