我正在编写一个简单的Lua脚本,从Redis 2.8中的Sorted Set (http://redis.io/commands/#sorted_set)计算中位数。以下是脚本:
local cnt = redis.call("ZCARD", KEYS[1])
if cnt > 0 then
if cnt%2 > 0 then
local mid = math.floor(cnt/2)
return redis.call("ZRANGE", KEYS[1], mid, mid)
else
local mid = math.floor(cnt/2)
local vals = redis.call("ZRANGE", KEYS[1], mid-1, mid)
return (tonumber(vals[1]) + tonumber(vals[2]))/2.0
end
else
return nil
end
问题在于这个脚本总是返回一个整数,而实际上应该返回一个浮点数。结果是错误的。
$ redis-cli zrange floats 0 100
1) "1.1"
2) "2.1"
3) "3.1"
4) "3.4975"
5) "42.63"
6) "4.1"
$ redis-cli EVAL "$(cat median.lua)" 1 floats
(integer) 3
正确的结果应该是 (3.1 + 3.4975)/2.0 == 3.298