?

Log in

No account? Create an account
entries friends calendar profile My Website Previous Previous Next Next
C code, for when subtracting two floats, checking for "might as well treat as zero" - Mark Atwood
fallenpegasus
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: , , , , ,
Current Location: Home, Capitol Hill, Seattle WA
Current Mood: geeky
Current Music: Multiplication Rock - Little Twelvetoes

8 comments or Leave a comment
Comments
littleone66 From: littleone66 Date: October 1st, 2007 11:10 pm (UTC) (Link)
I only do theory. :) Sounds right to me.
mauser From: mauser Date: October 2nd, 2007 02:40 am (UTC) (Link)
What are the names for the other parts of the number, aside from Mantissa?

(I recall in scientific notation there was a name for the initial digit and the part after the decimal, but I forget those names as well)
(Deleted comment)
mauser From: mauser Date: October 2nd, 2007 05:32 am (UTC) (Link)
Yanno, with memory and processor speed getting so cheap, someone ought to do a BCD math library that does long division and so forth... :-)
fallenpegasus From: fallenpegasus Date: October 3rd, 2007 11:04 pm (UTC) (Link)
There are a couple of opensource bignum libraries available. GNU has one, and there is a BSD one that's used by OpenSSL. I think they do packed binary format, instead of BCD, but that's an internal detail.
mauser From: mauser Date: October 4th, 2007 02:46 am (UTC) (Link)
Well, the point isn't so much the "bignum" aspect, but that the math would be conducted in Base 10, rather than Base 2.
From: wnoise Date: October 9th, 2007 03:12 am (UTC) (Link)
java.math.BigDecimal. Others exist for other languages.
fallenpegasus From: fallenpegasus Date: October 3rd, 2007 11:04 pm (UTC) (Link)
Except in the standard 80bit format, where it is there, strangely.
fallenpegasus From: fallenpegasus Date: October 3rd, 2007 11:06 pm (UTC) (Link)
The sign and the exponent are the other two parts.

There may be names for the part of the mantessa before and after the point, but I don't recall them. As was pointed out, in most encodings of floating point numbers, the first digit of the mantessa is implicit, because it's always a 1.
8 comments or Leave a comment