tags:

views:

197

answers:

5

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))
+3  A: 

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.

Calyth
+2  A: 

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.

j_random_hacker
+2  A: 

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).

patros
A: 

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

Greg B
A: 

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

Johan
If the result of 4.5000000 + 0.5 ends up being 4.9999999 then it would be truncated to 4. In my particular case I am not sure that I care but it might matter in some applications and I don't know that I would have thought of it if patros hadn't pointed it out.
Greg B
You are quite right, 4.5 can be a problem.
Johan