Friday, 29 April 2011

Rounding in KDB

Kdb doesn't have a reserved keyword for rounding rational numbers to the nearest integer; which is rather strange given that it is quite a common computation. One way of doing it is by using casting:

q) "i"$0.1
0
q) "i"$0.9
1

I decided to write function that can be used to do rounding; which is more terse than casting.

.q.round:{floor x+0.5}

q) round 0.1
0
q) round 0.6
1

1 comment:

  1. I think, that this function works wrong with negative numbers.
    q) round -0.5
    0j
    q) round 0.5
    1j

    {$[x < 0; -1; 1] * floor abs[x] + 0.5}

    ReplyDelete