Suppose size of a block is 1X1 and I have to move in steps of 1/16 along both the x and y direction. I want to round 0.53124 to the nearest 1/16 of the size of the block which is 0.5625. And similarly I want to truncate 0.53124 to the nearest 1/16 of the size of the block which is 0.5. Is there an efficient way of doing this? Please let me know.
preguntado el 10 de marzo de 12 a las 16:03
Simplest way in most situations and languages would to be to
- multiplicar por 16
- round to the nearest integer
- dividir por 16.
Since you seem to want punto fijo, I would simply use fixed point (integers in units of 1/16) if possible. But if you really need to mix with floating point operations and round, one way is to parcialidad all your values by a huge number such that the 1/16 place is the last place. Unfortunately with gcc, this approach can have problems on systems like i387 where floating point expressions are evaluated with extra precision, unless you're already using
long double everywhere, so from a practical standpoint, Joachim's answer may be easier to make reliable (although it probably performs much worse).