Function
SetEmpId()
As
String
Dim
ref
Randomize
ref
=
Int((
99999
-
10000)
*
Rnd
+
10000)
SetEmpId
ref
End
Function
This function’s purpose is to assign a unique five-digit number to each new employee. To generate a random integer between two given integers where ending_number = 99999 and beginning_number = 10000,the following formula is used:
=Int((ending_number - beginning_number) * Rnd + beginning_number)
2、按概率生成随机整数
如果要随机生成5个数,并控制它们出现的概率.
数字 概率
1 10%
2 10%
3 10%
4 20%
5 50%
那就生成0-1的随机数
0-- 0.1 1
0.1 -- 0.2 2
0.2 -- 0.3 3
0.3 -- 0.5 4
0.5 -- 1.0 5
3、按概率生成随机浮点数
如果要控制1个数落在某个区间的概率,比如要求在sngBegin和sngEnd之间生成一个随机数,这个随机数落在sngPB和sngPE之间的概率是P%。有两种方法,以第二种方法为好。
先说第一种方法,要点是:
(1)由于sngPB和sngPE将整个区间分成3部分,所以先分别计算随机数落在3部分的概率。落在sngPB和sngPE之间的概率是P%,这是已知的。余下的两个区间的总和概率是(1-p%),分到各个区间的概率按它们的长度分成。
(2)然后根据3个概率得到一个区间划分,落在第一个区间的,就在sngPB和sngPE之间生成一个随机数;落在第二个区间的,就是[sngBegin,sngPB]里生成随机数;落在第3个区间的,就在[sngPE,sngEnd]之间生数。
'create a random number between sngBegin and sngEnd
'with a probability of bytP to lie within sngPB and sngPE
Public
Function
GetRndNumP(
sngBegin
As
Single
,
sngEnd
sngPB
sngPE
bytP
Byte)
Single
Dim
bytP1
Byte
bytP2
Byte
Debug
.
Assert(
sngPB
>=
sngBegin)
And(
sngPE
sngPB)
sngEnd
sngPE)
'计算其他区间的概率
bytP1
=((
-
sngBegin)
/((
-(
sngPB)))
*(
100
bytP)
'[sngBegin,sngPB]
bytP2
=
bytP
'[sngPE,sngEnd]
'依据概率投射到相应区间
Select
Case
GetRandomNum(
1
100)
Case
To
bytP
GetRndNumP
=
GetRandomNum(
sngPE)
Case(
+
1)
To(
+
bytP1)
sngPB)
bytP1)
To
100
sngEnd)
End
Select
Function
Public
GetRandomNum(
sngBegin
Single
sngEnd
Single)
Single
GetRandomNum
=(
sngEnd
-
sngBegin)
+
sngBegin
Function