Why does fprintf attach a negative sign to a zero?
Ältere Kommentare anzeigen
Here is some code to set up the demonstration,
load data
fid = fopen('runsim.py','w');
rotation=[0,0,-GantryAngles(1)];
This next line verifies that rotation(3) is exactly equal to zero,
isZero = (rotation(3)==0)
Nevertheless, when I do a formatted file print, the 3rd zero ends up printed to the file with a negative sign attached:
fprintf(fid, "vN_%d.set_rotation(%g, %g, %g, 'deg')\n",1, rotation);
type runsim.py
Why does this happen?
Akzeptierte Antwort
Weitere Antworten (2)
fprintf('%g %g\n', 0, -0)
Negative zero is represented differently than non-negative zero, This is because it is mathematically different:
fprintf('%g %g\n', 1/0, 1/-0)
4 Kommentare
Walter Roberson
am 5 Dez. 2025
-0<0
being true would imply that there is a positive value epsilon such that
-0+epsilon == 0
but there is no such positive value.
Note that there is at least one behavior described in the Arithmetic section on that page where MATLAB differs from IEEE. As stated in the IEEE Compliance section on the sqrt page:
format hex
negativeZero = -0 % note the sign bit
positiveZero = 0
x = sqrt(negativeZero) % matches positiveZero not negativeZero
FYI the hypot, atan2, and power documentation pages also have IEEE Compliance sections. Hypot's involves combinations of NaN and Inf, atan2's involves combinations of +0 and -0, and power's involves some NaN cases.
The error message for a real, negative input
try
realsqrt(-1)
catch ME
ME.message
end
suggests realsqrt actually did a computation but caught the error on the result.
OTOH, with a complex input
try
realsqrt(-1+1i)
catch ME
ME.message
end
it seems like realsqrt does error checking on the input.
John
am 5 Dez. 2025
1 Stimme
I'll add that negative zero is part of the IEEE 754 spec for floating point numbers. This is not MATLAB-specific.
Kategorien
Mehr zu MATLAB Coder finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!