我写了一个小脚本(我在Lua的一个非常基本的层面)输出一个值表:
-- ProbabilityOfOralExam.lua
-- This script outputs a data file where in the first column are
-- written the numbers that are the possible sum of the digits for
-- the numbers belonging to Range and in the second column is
-- computed how many times that number is repeated in Range.
--
-- $ lua ProbabilityOfOralExam.lua RANGE OUTFILE
-- (OUTFILE = outprob.txt)
--
-- If RANGE is not given, default is 100.
-- If OUTFILE is not given, standard output will be used.
--
-- ATTENTION: ATM DOESN'T WORK IF range IS NOT GIVEN.
dofile("./statistic.lua")
function Main (Range, OutFileName)
Range = Range or 100
local OutHandle = OutFileName and io.open(OutFileName, "w")
or io.stdout
local C, A = Statistic(Range)
for k, v in ipairs(C) do
-- to be improved
OutHandle:write(string.format("%d %d\n", k, v))
end
OutHandle:close()
end
Main(...)
脚本调用的函数如下:
-- statistic.lua
function Statistic (Range)
-- Store in the array `A' the numbers from 1 to Range (as the
-- key/index) and the sum of their digits (as value.)
local A = {}
-- Computes the sum of the digits that Number is made of.
local function SumOfDigits (Number)
-- We treat Number as a string.
Number = tostring(Number)
-- Decompose Number (now a string) in its digits and store
-- them in the array B.
local B = {}
for I = 1, #Number do
B[I] = string.sub(Number, I, I)
end
-- Sum the values in B to get the sum of the digits of Number.
local Sum = 0
for key, value in ipairs(B) do
Sum = Sum + B[key]
end
return Sum
end
for I = 1, Range do
table.insert(A, SumOfDigits(I))
end
-- Find the highest value in A.
local MaxSum = math.max(table.unpack(A))
-- Store in `C' all the numbers from 1 to MaxSum (which are all
-- the possible sums of digits for numbers in Range) and the
-- times they appear.
local C = {}
for I = 1, MaxSum do
C[I] = 0
for key, value in ipairs(A) do
if I == value then
C[I] = C[I] +1
end
end
end
--[[ Turn absolute frequency into relative frequency.
for k, v in ipairs(C) do
C[k] = (C[k] / Range) * 100
end
--]]
return C, A
end
虽然仍然存在一些问题,但如果我在return
之前注释掉函数中的最后三行,它似乎工作正常。但是如果我“启用”它们,我会将这些值四舍五入到它们的第一个数字,而我想要Lua的默认行为(如>=5/6
中所示。)
从终端调用脚本(上述行被注释掉)我得到以下输出
$ lua ProbabilityOfOralExam.lua 500
1 3
2 6
3 10
4 15
5 21
6 25
7 30
8 35
9 40
10 43
11 44
12 43
13 40
14 35
15 30
16 25
17 20
18 15
19 10
20 6
21 3
22 1
这基本上是正确的,但在第二列中我得到一个“绝对频率”,而我想要一个“相对频率”。
如果我“启用”该功能的最后一行,我得到:
$ lua ProbabilityOfOralExam.lua 500
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
10 8
11 8
12 8
13 8
14 7
15 6
16 5
17 4
18 3
19 2
20 1
21 0
22 0
虽然它应该是:
1 0.6 -- = 3/500*100
2 1.2 -- = 6/500*100
3 2.0 -- = 10/500*100
...
为什么?
可以改进函数SumOfDigits
来查看这个问题:Sum of the digits of an integer in lua,但我想尽可能多地挽救我的代码。
答案 0 :(得分:5)
看看你的格式字符串:
OutHandle:write(string.format("%d %d\n", k, v))
您希望将输出打印为浮点%f
而不是整数%d
。
OutHandle:write(string.format("%d %f\n", k, v))
基本上,说明符%d
要求它将值打印为整数。
此文档仅引用C printf。看看C的printf格式说明符,其中大部分都可以在Lua中使用。