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

2 views (last 30 days)
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?

Accepted Answer

David Goodmanson
David Goodmanson on 29 Dec 2021
Edited: David Goodmanson on 29 Dec 2021
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 Comments
David Goodmanson
David Goodmanson on 29 Dec 2021
Edited: David Goodmanson on 29 Dec 2021
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

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!