Why fprintf('%​3.1f',roun​d(-eps)) prints -0.0?

8 ビュー (過去 30 日間)
Sandor Toth
Sandor Toth 2017 年 1 月 17 日
コメント済み: James Tursa 2017 年 1 月 17 日
I found some very strange behaviour of the round function in Matlab R2016b (at least for me). I would expect that the round function returns 0 for -eps, but surprisingly the command:
num2hex(round(-eps))
Returns:
8000000000000000
Instead of
num2hex(0) == 0000000000000000
This causes fprintf() to print -0.0. Is this a bug or I just miss something?
  1 件のコメント
James Tursa
James Tursa 2017 年 1 月 17 日
Side Note: This seems to be consistent among the related functions ceil and fix as well. E.g.,
>> num2hex(round(-eps))
ans =
8000000000000000
>> num2hex(ceil(-eps))
ans =
8000000000000000
>> num2hex(fix(-eps))
ans =
8000000000000000

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2017 年 1 月 17 日
編集済み: Stephen23 2017 年 1 月 17 日
You are missing the fact that MATLAB has two zeros: positive zero and negative zero, which have different HEX values. This is a result of the IEEE 754 floating point standard that MATLAB implements, which uses one bit to indicate the number sign: a corollary of this is that even a zero can be positive or negative.
It is not possible to use < to directly test if zero is negative (by definition negative zero is equal to positive zero, so this makes sense):
>> (-0)<0
ans =
0
but here is one simple trick that will test for negative zero:
>> (1/-0)<0
ans =
1
Which relies on this behavior:
>> 1/-0
ans =
-Inf
>> 1/round(-eps) % your question
ans =
-Inf
Neat huh!
You can find more interesting information on negative zeros here:

その他の回答 (1 件)

Adam
Adam 2017 年 1 月 17 日
編集済み: Adam 2017 年 1 月 17 日

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by