如何用vb产生均值为100,方差为20 的正态随机数
如何产生均值为100,方差为20 的正态随机数 --------------------编程问答-------------------- 均值和方差是什么? --------------------编程问答-------------------- 我觉得要限定一个范围吧 --------------------编程问答-------------------- 难题均值和方差的概念已经还给老师了......
(即便没还给老师,也是个大难题!!!) --------------------编程问答-------------------- 需对均值与方差限定一范围:
Option Explicit--------------------编程问答-------------------- 对楼上代码有点疑问:这样不是正态分布吧? --------------------编程问答-------------------- LZ要的是正态随机数,可把获得的Sum()数组按小到大重排序. --------------------编程问答-------------------- 均值就是所有样本数的平均数,就是把所有样本数都加起来再除以样本个数 。
Dim i As Integer
Dim Sum() As Single
Dim fc() As Single
Private Sub Command1_Click()
Timer1.Enabled = True
End Sub
Private Sub Form_Load()
Timer1.Interval = 5
End Sub
Private Sub Timer1_Timer()
Cls
Dim fch As Single
Dim sumh As Single
ReDim Sum(1 To 20)
ReDim fc(1 To 20)
Randomize
For i = 1 To 20
Sum(i) = 80 + Rnd * 40
fc(i) = (Sum(i) - 100) ^ 2
fch = fch + fc(i)
sumh = sumh + Sum(i)
Next
Print "方差:" & fch / 100
Print "均值:" & sumh / 20
If (Abs(sumh / 20) - 100) < 0.1 Then
If Abs(fch / 100 - 20) < 0.2 Then
'Print (Abs(sumh / 20) - 100)
For i = 1 To 20
Print Sum(i), fc(i)
Next
Timer1.Enabled = False
End If
End If
End Sub
方差就是把每个样本数减去它们的平均数再平方,把这些平方加起来的和再除以样本个数。
方差表示样本统计数据的离散程度
前给出的代码的方差有错误,正态随机数,可把获得的Sum()数组按小到大重排序,且补上大到小部分现修改代码如下:
Option Explicit
Dim i As Integer
Dim Sum() As Single
Dim SumPx() As Single
Dim fc() As Single
Dim n As Integer
Dim Px As Single
Private Sub Command1_Click()
n = InputBox("输入样本个数=", , n)
Timer1.Enabled = True
End Sub
Private Sub px_Click()
Dim sR As String
Dim j As Integer
ReDim SumPx(1 To n)
For j = 1 To n
SumPx(j) = Sum(j)
Next j
Dim k As Integer
Dim Temp As Single
For j = 1 To n
For k = 1 To n
If (SumPx(j) <= SumPx(k)) Then
Temp = SumPx(k)
SumPx(k) = SumPx(j)
SumPx(j) = Temp
End If
Next k
Next j
Dim i As Long
sR = ""
For i = 1 To n
Print SumPx(i)
Next i
Command2_Click
End Sub
Private Sub Command2_Click()
ReDim Sum(1 To 2 * n - 1)
For i = 1 To n
Sum(i) = SumPx(i)
Next
For i = n + 1 To 2 * n - 1
Sum(i) = SumPx(2 * n - i)
Next
Picture1.Cls
For i = 1 To 2 * n - 1
Picture1.Line (i * 100 + 95, Sum(i) * -70 + 9995)-(i * 100 + 105, Sum(i) * -70 + 10005), vbYellow, BF
Next
End Sub
Private Sub Form_Load()
Timer1.Interval = 5
Timer1.Enabled = False
Picture1.BackColor = vbBlack
Picture1.AutoRedraw = True
End Sub
Private Sub Timer1_Timer()
Cls
Dim fch As Single
Dim sumh As Single
ReDim Sum(1 To n)
ReDim fc(1 To n)
Randomize
For i = 1 To n
Sum(i) = 90 + Rnd * n
fc(i) = (Sum(i) - 100) ^ 2
fch = fch + fc(i)
sumh = sumh + Sum(i)
Next
Print "方差:" & fch / n
Print "均值:" & sumh / n
If (Abs(sumh / n) - 100) < 1 Then
If Abs(fch / n - n) < 1.5 Then
For i = 1 To n
Print Sum(i), fc(i)
Next
px_Click
Timer1.Enabled = False
End If
End If
End Sub
上述代码获得的是仿正态分布的随机数。
补充:VB , 基础类