Question about Functions and Static Variables

jeffnooch

Member
Licensed User
Longtime User
I have this function in an old VBA project...i'm trying to duplicate something similar in B4A...

Questions:
1) how do you create functions in B4A ... I think it is related to the code module...but i'm a little confused...can anyone convert the function below and give me an example of how i'd call it from the main activity? i'm assuming if my code module was called myFunctions then it would be something like myFunctions.RandGauss(myMean, mySd)?
2) how do you assign static variables in B4A...eg in code below it doesn't like the 3 lines with Static <variable> as <datatype>
3) is there an equivalent to Randomize (which in vba essentially initializes the random number generator)


B4X:
Function RandGauss(Mean, Sd) As Double
   'from Numerical Recipes in C, second edition, page 289
   'returns a random number from Gaussian dis with mean and Sd specified
   Static NextRnd As Double
   Static RndWaiting As Boolean
   Static Randomized As Boolean

   Dim fac, rsq, v1, v2, RandStd As Double
   If Not (Randomized) Then
      Randomize
      Randomized = True
   End If

   If Not (RndWaiting) Then
      Do
         v1 = 2# * Rnd() - 1#
         v2 = 2# * Rnd() - 1#
         rsq = v1 * v1 + v2 * v2
      Loop Until rsq <= 1#
      fac = Sqr(-2# * Log(rsq) / rsq) 'natural log
      NextRnd = v1 * fac
      RndWaiting = True
      RandStd = v2 * fac
   Else
      RndWaiting = False
      RandStd = NextRnd
   End If
   'RandStd has mean zero and SD=1.
   RandGauss = (RandStd * Sd) + Mean
End Function

Thanks in advance for your help and clarifications...
 
Last edited:

thedesolatesoul

Expert
Licensed User
Longtime User
1) how do you create functions in B4A ... I think it is related to the code module...but i'm a little confused...can anyone convert the function below and give me an example of how i'd call it from the main activity? i'm assuming if my code module was called myFunctions then it would be something like myFunctions.RandGauss(myMean, mySd)?
A function in B4A is a sub (not code module).
you would just create a sub with a return type.
B4X:
Sub RandGauss(Mean as Double, Std as Double) as Double
     Return Mean*Std
End Sub
2) how do you assign static variables in B4A...eg in code below it doesn't like the 3 lines with Static <variable> as <datatype>
There are no static variables in B4A. You can use global variables instead.

3) is there an equivalent to Randomize (which in vba essentially initializes the random number generator)
There is a function called RndSeed. (Basic4android - Core)
 
Upvote 0
Top