In my program I call "granularity" the "minimum step" for a number. For example, if granularity == 4
then I only work with numbers "0, 4, 8, 12 etc" (so normal integer
has granularity == 1
).
I need a function to round an integer number to a certain granularity. So for example, if granularity == 3
, I want this map:
// I don't use negative number so don't care about negative results
0 -> 0
1 -> 0
2 -> 3
3 -> 3
4 -> 3
5 -> 6
6 -> 6
7 -> 6
8 -> 9
and so on
This is my implementation:
#include <iostream>
#include <stdint.h>
using namespace std;
typedef int64_t myDecimal;
myDecimal Round(myDecimal val, myDecimal granularity)
{
myDecimal rest = val % granularity;
myDecimal candidat = val / granularity;
if (2 * rest < granularity) {
return candidat * granularity;
} else {
return (candidat + 1) * granularity;
}
}
int main()
{
for (int i = -10; i < 10; i++){
std::cout << "i = " << i << " " << Round(i, 3) << std::endl;
}
return 0;
}
How can you further improve it for better latency as I'm using this in HFT trading?