The method for comparing floating-point numbers with 0 equals that of 0.
Check whether the floating point number is 0 in C #. Do not use "=" or "! = "For comparison, is there no way to do this when the value is 0? The following two judgment ideas are shown:
Approximate comparison
Take the discount method and try to convert the direct equal comparison to the comparison form of "> =" and "<=" to achieve the approximate judgment effect.
Const float PRECISION = 0.000001f; float x; if (Math. abs (x) <= PRECISION) {// The floating point x value is 0} else {// The floating point x value is not 0}
Or do not use the Math function.
Const float PRECISION = 0.000001f; float x; if (x <= PRECISION & x> =-PRECISION) {// The floating point x value is 0} else {// The floating point x value is not 0}
Precise judgment
Sometimes, the approximate comparison cannot meet the requirements and must be compared accurately. What should we do? There are still some methods.
In the IEEE754 standard, the single-precision floating point number (4 byte) Representation: 1bit symbol bit (S), 8bit index bit (E, expressed in order code), and 23bit decimal part (tail number M ). Double-precision floating point number (8 byte) Representation: 1bit symbol bit, 11bit index bit (expressed in order), 52bit decimal part (ending number ). So the true value of a normalized Single-precision floating point number x is x = (-1) ^ S) * (1.M) * (2 ^ (E-127); apparently, x cannot always be zero.
For the above description, when the level code E is all 0 and the tail number M is all 0, we can consider that the true value x represents the absolute 0 value in the computer, combined with the symbol bit S, there are two points: positive 0 and negative 0; that is, in addition to the maximum 1bit in 32bit, when the other 31bit is all 0, it is the absolute 0 value in the computer.
Float f = pow (float) 2, (float)-127); int * ptrToInt = (int *) (void *) & f; if (! (* PtrToInt & (0x7fffffff) {// absolute 0 value in the computer}
This Code requires the unsafe flag to be enabled