Question

I am working in C to implement pseudo-code that says:

delay = ROUND(64*(floatDelay - intDelay))
where intDelay = (int) floatDelay

The floatDelay will always be positive. Is there an advantage to using the round function from math.h:

#inlcude <math.h>
delay=(int) round(64*(floatDelay-intDelay));

or can I use:

delay=(int)(64*(floatDelay - intDelay) + 0.5))
Was it helpful?

Solution

You should always use the appropriate math libs when dealing with floating point numbers. A float may be only a very close approximation of the actual value, and that can cause weirdness.

For instance, 5f might be approximated to 4.9999999... and if you try to cast directly to int it will be truncated to 4.

To see why in depth, you should look up floating point numbers on wikipedia. But in short instead of storing the number as a straight series of bits like an int, it's stored in two parts. There's a "fraction" and an exponent, where the final value of the float is fraction * (base ^ exponent).

OTHER TIPS

There isn't any advantages that I know of, other than the fact that the cast to int may not be immediately obvious to other programmers that it works like a trunc...

Whereas with the round function, your intentions are clear.

Either is fine, provided as you say floatDelay is positive.

It's possible that one is marginally faster than the other, though it would be hard to tell which without benchmarking, given that round() is quite possibly implemented as a compiler intrinsic. It's even more likely that any speed difference is overwhelmingly unimportant, so use whichever you feel is clearer.

I found "Truncate a decimal value in c++" provided a useful discussion of floating point numbers.

In particular Greg Hewgill provided this link: What Every Computer Scientist Should Know About Floating-Point Arithmetic by David Goldberg

For instance, 5f might be approximated to 4.9999999... and if you try to cast directly to int it will be truncated to 4.

Is this really true?

If you make sure the you add the 0.5 before you truncate to int,
is really 4.9999 a problem.

I mean: 4.9999+0.5=5.4999 -> 5

/Johan

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top