简体   繁体   中英

Is it possible to underflow a floating point addition in C++?

I was looking at the Intel Processor manual, volumen 2A, pages 3.266-3.268 and it states that the FADD operation may produce #U (Underflow) exception. The reasoning is that result will be to small to be properly represented in DST.

I wondering if addition underflow is possible on C++ using native datatypes (float, double, long double) or if the language wrapping of the datatype makes the addition operation safe on regards of underflow.

If you add a positive and a negative number that are very close to each other, producing a denormal , then the underflow flag is set (if underflow exception is not masked). Link to intel article denormals and underflow .

Example code (using Microsoft compiler):

    double a,b,c;
    a =  2.2250738585072019e-308;
    b = -2.2250738585072014e-308;
    c = a + b;   /* c is denormal */
    printf("%28.16le %016llx\n", a, a);
    printf("%28.16le %016llx\n", b, b);
    printf("%28.16le %016llx\n", c, c);
    if ( std::fpclassify( c ) == FP_SUBNORMAL ) printf("c is DENORMAL");

To enable (unmask) the underflow exception (Microsoft compiler):

    short fcw; /* floating point control word - 16 bit */
    /* enable underflow exception */
    __asm{
        fnstcw  fcw
        and     fcw,0ffefh
        fldcw   fcw
    }

An underflow condition occurs when the result of the computation is a denormal (subnormal) number. This is formally called gradual underflow (as opposed to producing zero). So by adding almost any two denormal numbers, an underflow will occur as long as the result is also a denormal number. For example:

pow(2.0, -1074.0) + pow(2.0, -1073.0)

All operands here are of type double .

Intel certainly was referring to gradual underflow. However considering abrupt underflow , then it's not possible by using only addition and/or subtraction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM