Skip to content

Commit f31c9c5

Browse files
committed
math扩展模块新增randNorm方法生成满足正态分布的随机数方法(Box-Muller)
1 parent df58290 commit f31c9c5

File tree

1 file changed

+33
-15
lines changed

1 file changed

+33
-15
lines changed

mathExtend.lua

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
local MATH={} for k,v in next,math do MATH[k]=v end
22

3-
local floor,ceil=math.floor,math.ceil
4-
local rnd=math.random
5-
local exp=math.exp
6-
73
MATH.tau=2*math.pi
84
MATH.phi=(1+math.sqrt(5))/2
95
MATH.inf=1/0
106
MATH.nan=0/0
117

8+
local floor,ceil=math.floor,math.ceil
9+
local sin,cos=math.sin,math.cos
10+
local rnd=math.random
11+
local exp,log=math.exp,math.log
12+
local tau=MATH.tau
13+
1214
--- Check if a number is NaN
1315
--- @param n number
1416
--- @return boolean
@@ -59,8 +61,8 @@ function MATH.rand(a,b)
5961
end
6062

6163
--- Get a random integer with specified frequency list
62-
---@param fList number[] positive numbers
63-
---@return integer
64+
--- @param fList number[] positive numbers
65+
--- @return integer
6466
function MATH.randFreq(fList)
6567
local sum=TABLE.sum(fList)
6668
for i=1,#fList do sum=sum+fList[i] end
@@ -73,6 +75,22 @@ function MATH.randFreq(fList)
7375
error("Frequency list should be a simple positive number list")
7476
end
7577

78+
--- Get a random numbers in gaussian distribution (Box-Muller algorithm + stream buffer)
79+
--- @return number
80+
local randNormBF
81+
function MATH.randNorm()
82+
if randNormBF then
83+
local res=randNormBF
84+
randNormBF=nil
85+
return res
86+
else
87+
local r=rnd()*tau
88+
local d=(-2*log(1-rnd()*tau))^.5
89+
randNormBF=sin(r)*d
90+
return cos(r)*d
91+
end
92+
end
93+
7694
--- Restrict a number in a range
7795
--- @param v number
7896
--- @param low number
@@ -142,12 +160,12 @@ end
142160

143161
--- Check if a point is in a polygon
144162
---
145-
--- By Pedro Gimeno,donated to the public domain
146-
---@param x number
147-
---@param y number
148-
---@param poly number[] {x1,y1,x2,y2,...}
149-
---@param evenOddRule boolean
150-
---@return boolean
163+
--- By Pedro Gimeno, donated to the public domain
164+
--- @param x number
165+
--- @param y number
166+
--- @param poly number[] {x1,y1,x2,y2,...}
167+
--- @param evenOddRule boolean
168+
--- @return boolean
151169
function MATH.pointInPolygon(x,y,poly,evenOddRule)
152170
local x1,y1,x2,y2
153171
local len=#poly
@@ -174,9 +192,9 @@ function MATH.pointInPolygon(x,y,poly,evenOddRule)
174192
end
175193

176194
--- Get the greatest common divisor of two positive integers
177-
---@param a number
178-
---@param b number
179-
---@return number
195+
--- @param a number
196+
--- @param b number
197+
--- @return number
180198
function MATH.gcd(a,b)
181199
repeat
182200
a=a%b

0 commit comments

Comments
 (0)