Sorting between signed and unsigned zeros c++ -
i have able sort negative zeros , zeros assignment doing @ university using c++, tell me why following code produce negative zero? i'm stuck , not sure why works...
cout << "enter number of elements want add vector:\n"; cin >> x; cout << "enter integers: \n" << endl; (int = 0; < x; i++) { cin >> y; y = y - 0.0; cout << y; array.push_back(y); }
if there better way of producing negative 0 when sorting above vector please advise. many thanks!
first of all, there need not negative zeroes in standard c++, assume talking negative 0 ieee-754, (i never encountered exception) c++ implementations base floating point math on.
in case, expression
y = y - 0.0;
will yield -0.0
if either y == -0.0
before assignment or if set rounding mode "round towards -infinity", won't.
to produce double
value -0.0
, can assign desired value:
double d = -0.0;
now d == -0.0
in ieee floating point math.
however,
comparisons shall ignore sign of zero
(ieee 754-1985, 5.7. comparison), -0.0 < 0.0
yield false
, if want sort negative 0 before positive zero, need write own comparator, possibly using std::signbit
.
appendix: relevant standard quote:
when sum of 2 operands opposite signs (or difference of 2 operands signs) zero, sign of sum (or difference) shall + in rounding modes except round toward –infinity, in mode sign shall –.
ieee 754-1985, 6.3 (the sign bit)
Comments
Post a Comment