Why does the SQRT function in MATLAB return different answers when I supply numbers that appear to be the same?

5 views (last 30 days)
I create the following vectors, which appear to be the same:
x = -[1; i]
y = [-1; -i]
When I compare these two vectors:
x == y
it reports that the corresponding elements in the two vectors to be equal. However, when I compute the square root of the two vectors:
sx = sqrt(x)
sy = sqrt(y)
I find that the first element is different.
sx =
0 - 1.0000i
0.7071 - 0.7071i
sy =
0 + 1.0000i
0.7071 - 0.7071i
Both answers are correct, but it seems inconsistent that the following does not hold.
x==y ==> sqrt(x)==sqrt(y)

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
The SQRT function is returning different roots because the first elements of "x" and "y" are not in fact the same. The difference can be observed by using hexadecimal format:
format hex
x,y
which produces:
x =
bff0000000000000 8000000000000000i
8000000000000000 bff0000000000000i
y =
bff0000000000000 0000000000000000i
8000000000000000 bff0000000000000i
The first row of "x" is the hexadecimal representation of "-1-0i", while the first row of "y" represents "-1+0i". Although the "==" incorrectly indicates these two values are identical, situations such as this indicate the difference between these two values.
The following is another situation where the use of +0 and -0 returns different results:
1/0 ==> Inf
1/(-0) ==> -Inf
If you would like to remove all -0 parts of each element of a matrix (real and imaginary), use the following command:
z = z.^1;

More Answers (0)

Products


Release

R14SP1

Community Treasure Hunt

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

Start Hunting!