Mark Atwood (fallenpegasus) wrote,
Mark Atwood
fallenpegasus

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
Subscribe
  • Post a new comment

    Error

    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 

  • 8 comments