Posts

Showing posts from 2009

MySQL: Rank calculation

SELECT ID, @rank := COALESCE( NULL + (@prev := @curr), NULL + (@curr := r.score), NULL + (@counter := @counter+1), IF(@prev = @curr, @rank, @counter) ) AS Rank FROM (SELECT @curr:=null,@prev:=null,@rank:=0,@counter:=0) sel1, Record AS r ORDER BY r.score DESC

Fixed Point

What do you do if you need numbers after the decimal point? Use floats? What is wrong with that is that floats are slow. Really slow. How can we fix that? Fixed point math. The idea behind fixed point math is that we pretend that there is a decimal point. In order to have enough bits, we use a long. That gives us 32 bits. 8 bit precision after the decimal point, 16 bit before. The reason this works is because, if you do all of you math without the decimal point, and then add the decimal point, you get the same result. But, because all we need is precision that is eventually going to be mapped to an integer matrix such as the screen, we don't need to add the decimal point at all. Okay, you might say, but how can we convert a integer to a fixed point? Easy. Just shift foward eight bits, like this: fixed_var = (long) int_var << 8 The next problem is converting floats. Because floats are in IEEE format, shifting will thrash them. To get around this, we must multiply by 256...