我正在编写一个简单的Lua脚本来计算Redis 2.8中排序集(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
问题是当结果应该是float时,脚本总是返回一个整数.结果是错误的.
$ 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