Re: Calculate the precision of a floating point number (ie: the number of decimal places)
- From: user923005 <dcorbit@xxxxxxxxx>
- Date: Tue, 30 Oct 2007 13:29:28 -0700
On Oct 30, 7:21 am, Lori <steve.lori...@xxxxxxxxx> wrote:
Hi all
I'm trying to write a reliable and efficient library function that
will calculate the precision of an input number (floating point).
Please excuse my lame mathematics skills! Here is my first attempt at
a function:
int dec_places(double d)
{
int places = 0;
while (!feq(d - (int)(d + 0.5), 0.0)) // where feq returns
true if inputs differ by less than epsilon 0.0000005
{
d *= 10;
++places;
}
return places;
}
The problem I have with the above solution is that it is possible to
get caught in an infinite loop.
One solution would be to have a max iterations, and break out of the
loop if this is reached (thereby causing an error condition, and the
caller must process the return value as an invalid response), but this
is not ideal.
I have searched for answers on the web and in newsgroups to no avail.
Does anyone know of a better algorithm? Perhaps there is an open
source solution available that I am not aware of?
Sure,
return DBL_EPSILON; /* for double */
return FLT_EPSILON; /* for float */
return LDBL_EPSILON; /* for long double */
If you are bound and determined to compute it yourself, look at
paranoia.c which computes this value from first principles.
.
- References:
- Prev by Date: Re: Binary search trees
- Next by Date: Re: A Trend Towards Lower Software Maintenance Budgets?
- Previous by thread: Re: Calculate the precision of a floating point number (ie: the number of decimal places)
- Next by thread: Re: Calculate the precision of a floating point number (ie: the number of decimal places)
- Index(es):