Why does the SQRT function in MATLAB return different answers when I supply numbers that appear to be the same?
4 次查看(过去 30 天)
显示 更早的评论
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)
采纳的回答
MathWorks Support Team
2009-6-27
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;
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!