在视觉基础中生成具有最大值,最小值和平均值(平均值)的随机数 - 三角形dist

时间:2016-07-18 16:56:39

标签: vba random distribution

我希望看到如何使用3个最小(40)最大值(330)和平均值(100)来创建三角形分布。

这段代码只是给我两个数字之间的随机数,并没有平均值:

 z = =RAND()*(b-a)+a

我怎样才能使它变成三角形。 ?

2 个答案:

答案 0 :(得分:1)

根据@Severin Pappadeux修正

Function trigDist(dMIn As Double, dMax As Double, dMean As Double) As Double

    Dim dFR         As Double
    Dim bProceed    As Boolean

    bProceed = True

    '/ error checks               

    If dMIn >= dMax Then
        MsgBox "max value less than min value."
        bProceed = False
    End If

    If dMean < dMIn Then
        MsgBox "Mean is less than min value."
         bProceed = False
    End If

    If dMean > dMax Then
        MsgBox "Mean is larger than max value."
         bProceed = False
    End If


    If bProceed Then

        dFR = Rnd()

        If dFR < ((dMean - dMIn) / (dMax - dMIn)) Then
            trigDist = Sqr(dFR * (dMean - dMIn) * (dMax - dMIn)) + dMIn
        Else
            trigDist = dMax - Sqr((1 - dFR) * (dMax - dMean) * (dMax - dMIn))
        End If
    Else

       trigDist = 0
    End If

End Function

答案 1 :(得分:1)

显然,@ cyboashu的回答是错误的,因为你有MinMaxMean

所以你开始从输入中恢复A,B,C,使用here中等于(A+B+C)/3的事实。不知道足够的VBA,所以忍受我

A = Min
B = Max
C = 3.0*Mean - A - B

If A >= B Then
    print 'Error, Min is greater than Max'
End If

If C < A Then
    print 'Error, Mean is too small'
End If

If C > B Then
    print 'Error, Mean is too large'
End If

r = Rnd()

If r < ((C - A) / (B - A)) Then
    Res = A + Sqr(r * (B - A) * (C - A))
Else
    Res = B - Sqr((1.0 - r) * (B - A) * (B - C))
End If

return Res