Mark Atwood (fallenpegasus) wrote,
Mark Atwood

C code, for when subtracting two floats, checking for "might as well treat as zero"

/* detecting total precision loss when subtracting two floats */
/* if exponent of the larger of A and B,
minus the exponent of the difference of A and B
is greater than the number of digits of the mantessa,
it's now basically zero, all information lost, that is,
it is smaller than the smallest number representable
by a normalized float with an exponent the same as
the larger of A and B */
int istoosmalldiff_f (float a, float b)
float m_frac, d_frac;
int m_exp, d_exp;
m_frac= frexpf(fmaxf(a, b), &m_exp);
d_frac= frexpf((a - b), &d_exp);
/* my libc doesnt define FLT_MANT_DIG, foo! */
/* just hardwire 24 for floats */
return ((d_exp - m_exp) >= (24-1));

Did I get this right?
Tags: c, code, float, geek, math, programming

  • Razors

    I'm getting ads for I think five different "all metal" "get the best shave of your life" "throw away the plastic" razor startups. They all seem to be…

  • Doing what needs to be done

    On May 1st, one of my co-residents found one of the feral rabbits that live in the area cuddled up against a corner of the house. It was seriously…

  • The CTO of Visa, after listening to me present

    Some years ago, I was asked to travel to the corporate meeting center to present at a presentation-fest to the CxO staff of Visa. Yes, the one with…

  • Post a new comment


    Comments allowed for friends only

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded