How do you write -0 in an array on matlab?

조회 수: 7 (최근 30일)
Alfie Sargent
Alfie Sargent 2016년 2월 9일
답변: Walter Roberson 2016년 2월 9일
I have recently been tasked with sorting a variety of numerical values and Nan's using a shell sort function. It works so far but whenever I want to sort -0 it always comes out as 0 in the sorted list. Any ideas?
This is the full question: Give the output of a program run that proves it can generates minus zero as a floating-point object that is not identical to zero.

답변 (2개)

Stephen23
Stephen23 2016년 2월 9일
편집: Stephen23 2016년 2월 9일
Note that according to standard definitions minus zero has the same value as positive zero: "...regarded as equal by the numerical comparison operations". This means they cannot be sorted (which by definition requires a value comparison function to provide the order):
>> -0<0
ans =
0
So sort will not work for you:
>> [out,idx] = sort([0,-0])
out =
0 0
idx =
1 2
If you want to sort them separately you will need to implement your own sort algorithm. The most reliable way to test for minus zero is to use a divide-by-zero and check the Inf sign:
>> 1./[-0,0]
ans =
-Inf Inf
Note that negative zero is not displayed in MATLAB:
>> x = 1*(-0)
x =
0
>> 1/x
ans =
-Inf
Interestingly the sort example above keeps the negative zero in the output:
>> 1./out
ans =
Inf -Inf
  댓글 수: 3
Guillaume
Guillaume 2016년 2월 9일
Sorting NaN (Not a Number!) is an antinomy. By definition, there's no ordering on NaN.
If you come across a program that sorts NaN, then that program is not working properly.
Walter Roberson
Walter Roberson 2016년 2월 9일
The sort routine counts nan, removes them, sorts, adds nan to an end. It does not keep track of which nan (there are many many representations of nan), just slams in standard nan.

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


Walter Roberson
Walter Roberson 2016년 2월 9일
num2hex distinguishes +0 from -0

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by