"Exact" determines whether a floating point number is equal to 0

Source: Internet
Author: User

Someone on the Forum asked, "accurately determine whether a floating point number is equal to 0. Do not use the same if (data <1e-10) method .". In fact, we understand how floating point numbers are stored in computers, and the answer to this question is clear.

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 )))
{
// The absolute 0 value in the computer
}

For a 32-bit floating-point number in a computer, the absolute value range of the technique is about (1e-38 )~ (1e + 38), that is, 2 ^ (-127 )~ 1.111111b * (2 ^ 128): the absolute value of a floating point number is smaller than 2 ^ (-127). There is no absolute 0 in a floating point number, so we can only take an approximate value.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.