[Ns-developers] looking for solution for floating point differences

Tom Henderson tomh at tomh.org
Thu Jan 18 22:39:00 PST 2007


Olivier Dalle wrote:
> Hi Tom,
> 
> If the expected result is to round to the nearest integer then maybe you
> could try the C99 lrint(3)/lround(3) functions that should be widely
> available, eg :
> 
> int bpstorate = lrint(log(Bps / 5000) / log(2));
> 
> But I suspect this just translates the problem to half-way values (eg
> rounding some value close to 2.5 may lead to 2 or 3 depending on whether
> the initial FP value is slightly over or under 2.5 ...)

Yes, Sally reported that rounding to nearest int is not the preferred 
behavior.

> 
> On the other hand, if you want to stick to the int cast instead of
> switching to the round semantic, then the fuzzy approach you suggest is
> probably the best, eg something like:
> 
> // Choose Epsilon s.t. any FP in range [(n - Epsilon); n] 
> // will be converted to int value n instead of n-1.
> #define Epsilon 0.00001
> 
> int fuzzy_cast(double f) {
>    int try = (int)f;
>    if ( (f- (float)try) >= (1.0-Epsilon) ) 
>         // Adding a small value such as 2*Epsilon may be risky 
>         // if Epsilon is very small and f is big, while 0.5 should 
>         // work in any case
> 	return (int)(f+0.5); 
>    else
> 	return try;
> }
> 
> and then 
> 
> int bpstorate = fuzzy_cast(log(Bps / 5000) / log(2));
> 
> Regards,
> 
> Olivier.

That works, provided that you avoid the reserved word "try".  So does 
simply adding Epsilon before doing an int cast.

I've asked Sally which she prefers and we'll fix it soon after.

Thanks,
Tom


More information about the Ns-developers mailing list