2.5 Normal Approximation and Confidence Intervals


Index

Example 2.5a: Normal Approximation of Relative Frequencies in a Coin Toss Experiment. A form is created that takes as input the total number of coin tosses and the probability of heads on each trial. An interval is output for which there is an approximately 95% probability that it contains the relative frequency of heads (based on the Normal Approximation to the Binomial Distribution). Also, the approximate worst error in using the normal approximation to the Binomial Distribution, assuming Sqr(npq) >=3, is output to a label. The number and proportion of heads are updated periodically and output during each run of the main procedure until the final results are obtained.

Example 2.5b: Repeated runs of the Coin Toss Experiment Outputting History to a Grid. A form is created that takes as input the total number of tosses and the probability of heads on each toss. During each run of the procedure, the number and the proportion of heads are determined, then output in labels. In another output label is displayed an interval which should contain the the relative frequency 95% of the time (based on a Normal Approximation to the Binomial Distribution). Each time the procedure is run, it is determined whether the relative frequency is actually contained in the interval, and after repeated runs, the overall percentage of time this occurs.

Example 2.5c: Coin Tosses: An Approximate 95% CI for the Probability p of Heads. This form simulates a coin toss experiment and computes an approximate 95% CI for the true probability p of tossing Heads on any trial. The number p is generated as a random number between .1 and .9, and the user inputs the total number of trials per run. Each time the "Compute" Command Button is clicked, the program outputs the relative frequency of Heads, an approximate 95% CI for p, and determines if the actual p in the CI. At any time, the user can reveal or hide the value of p by clicking an option button, or generate a new value of p by clicking a command button. No special consideration of the error in using the Normal Approximation to the Binomial Distribution is made in this program, except to require that the user input for the number of trials be at least 100 to ensure that the approximate worst error is no worse than .03.

Problem 2.5: Repeated runs of the Coin Toss Experiment Calculating CI's and Outputting History to a Grid.Create a form which takes as input the number of tosses of a coin. The program should generate a random number between .1 and .9 for the probability of heads on each trial which at the outset is hidden from the user (but can be revealed by clicking an option button). Ouptut to a label an approximate 95% CI based on a Normal approximation to the Binomial Distribution (not depending on p). Each run of the main procedure should compute and output to labels the relative frequency of heads and whether the true probability p is in the CI. Also, output the results to a grid which keeps a running history of the results since the beginning or the last restart.


Example 2.5a. Normal Approximation of Relative Frequencies.

Event Procedures:

' In (Declarations) section of (General)

' Programmer:   R. Berman 
' Date:         June, 1996 
' Title:        Normal Approximation of Relative Frequencies
' Description:  This form takes as input the total number of coin
'               tosses and the probability of heads on each trial.
'               An interval is output for which there is approximately
'               95% probability that it contains ther relative frequency 
'               of heads. Also, the approximate Worst Error in using the Normal
'               Approximation to the Binomial Distribution, assuming Sqr(npq) >= 3, 
'               is output to a label. The number and proportion of heads are updated         
'               periodically and output during each run of the main procedure until
'               the final results are obtained.
' Version       Microsoft Visual Basic 4.0 

' Require explicit declaration of variables. 
Option Explicit 

' Declare module-level variables as follows: 
' mi_NumberTosses = the total number of tosses in each run 
'                   (integer data type). 
' ms_Probability = the probability of heads on each toss 
'                  (single data type). 
' mb_FirstRunFlag = A flag which is True if this is the first run 
'                   of the main procedure with the present user 
'                   input and False otherwise. 
Dim mi_NumberTosses As Integer 
Dim ms_Probability As Single 
Dim mb_FirstRunFlag As Boolean 

Private Sub CheckApproximation() 

    ' The the theoretical worst error W(n,p) in using Normal 
    ' approximation to the Binomial Distribution Bin(n,p) is 
    ' known to be approximately 
    ' 
    '         |1-2p|/(10*Sqr(npq)) = |1-2p|/(10*StdDev) 
    ' 
    ' provided the Standard Deviation StdDev >= 3. This procedure 
    ' determines if the StdDev is greater than or equal to 3 (so 
    ' that the estimate of W(n,p) is possible) and in that case 
    ' checks to see if W(n,p) =< .01, which we will regard as an 
    ' acceptable level of accuracy. 
     
    ' Define local variables of single data type to store the 
    ' values of the standard deviation of the binomial and the 
    ' approximate worst error estimate. 
    Dim s_StdDevVar As Single
    Dim s_AppxWorstError As Single 
     
    ' Declare 3 variables for the arguments of a message box. 
    ' The first is the actual message, the second is a number 
    ' determining the icon exhibited in the box (we use the 
    ' built-in VB constant vbExclamation which equals 48), and 
    ' the third is the title of the message box. 
    Dim st_Msg As String 
    Dim i_MsgDialog As Integer 
    Dim st_Title As String 
     
    ' If the number of tosses and probability of heads on a 
    ' given toss are such that the Normal approximation cannot 
    ' be determined to be satisfactory, we want to exhibit a 
    ' warning message to this effect. However, we only want to 
    ' exhibit the warning message the first in a sequence of 
    ' runs with the same user input. 
            
    ' First, compute the standard deviation of the binomial 
    ' using the s_StdDev() function and set it to a local 
    ' variable. This is done since it is used more than once and 
    ' it would be inefficient to recalculate each time. We note 
    ' that before this procedure is called, the validity of the 
    ' input is checked so that s_StdDev() will always yield a 
    ' positive value. 
    s_StdDevVar = s_StdDev() 
     
    ' Next compute the approximate worst error according to the 
    ' formula given above. 
    s_AppxWorstError = Abs(1 - 2 * ms_Probability) / (10 * s_StdDevVar) 
         
    ' Define variables for a Message Box to be used if either the 
    ' Standard Deviation < 3 or the approximate worst error > .01. 
    st_Msg = "The Normal approximation may not be accurate " 
    st_Msg = st_Msg & "in this case since " 
    i_MsgDialog = vbExclamation 
    st_Title = "Warning!" 
       
    ' Output in a label either "N/A" (not applicable) or the value 
    ' of the approximate worst error; show a warning message if the 
    ' the standard deviation is less than 3 or the error is > .01. 
    If s_StdDevVar < 3 Then 

        lblWorstError.Caption = "N/A" 
        st_Msg = st_Msg & "the standard deviation of the binomial " 
        st_Msg = st_Msg & "is less than 3." 
        MsgBox st_Msg, i_MsgDialog, st_Title 

    ElseIf s_AppxWorstError > 0.01 Then 

        lblWorstError.Caption = Format$(s_AppxWorstError, "Standard") 
        st_Msg = st_Msg & "the approximate worst error estimate is " 
        st_Msg = st_Msg & "greater than 0.01" 
        MsgBox st_Msg, i_MsgDialog, st_Title 

    Else 

        lblWorstError.Caption = Format$(s_AppxWorstError, "Standard") 

    End If 
     
End Sub 

Private Sub ClearOutput() 

    ' Clear all output labels. 
    lblOutput(0).Caption = ""   ' the number of heads 
    lblOutput(1).Caption = ""   ' the relative freqeuncy 
    lblInterval95.Caption = ""  ' an interval that has 95% 
                                ' probability that the relative 
                                ' frequency is contained in it. 
    lblWorstError.Caption = ""  ' the estimate for the worst error 
                                ' in using the normal approximation 
                                ' to the binomial (or "N/A" if this 
                                ' cannot be determined). 
     
End Sub 

Private Sub Initialize() 
     
    ' Clear output labels of any prior output. 
    ClearOutput 
     
    ' Place default values into text boxes. 
    txtNumberTosses.Text = "100" 
    txtProbability.Text = ".5" 
         
    ' Place default values to two output labels: 
    ' (1) giving an interval for which approximately 95% of the relative 
    '     frequency results should lie, and 
    ' (2) an estimate for the approximate worst error in using the Normal 
    '     approximation to the Binomial Distribution. 
    lblInterval95.Caption = "(0.40,0.60)" 
    lblWorstError.Caption = "0.00" 
             
    ' Set the module-level variable indicating whether this is the
    ' first run of the procedure with the current input to True.
    mb_FirstRunFlag = True
    
End Sub 

Private Function b_GetInput() As Boolean 

    ' This function gets the user input of the number of 
    ' coin tosses and the probability of heads, and determines 
    ' if the input is valid. If so, it assigns the values to 
    ' the module-level variables mi_NumberTosses and 
    ' ms_Probability and returns a value of True (-1), 
    ' otherwise it returns the value False (0). 
         
    ' Declare 3 variables for the arguments of a message box. 
    ' The first is the actual message, the second is a number 
    ' determining the icon exhibited in the box (we use the 
    ' built-in VB constant vbExclamation which equals 48), 
    ' the third is the title of the message box. 
    Dim st_Msg As String 
    Dim i_MsgDialog As Integer 
    Dim st_Title As String 
     
    ' Check that the number of tosses is a nonnegative integer 
    ' between 0 and 32,767 and the probability is between 
    ' 0 and 1. The Val() function is used to convert its argument 
    ' to a numeric value. 
    If (Val(txtProbability.Text) > 0) _ 
        And (Val(txtProbability.Text) < 1) _ 
        And Int(Val(txtNumberTosses.Text)) = Val(txtNumberTosses.Text) _ 
        And 0 < Val(txtNumberTosses.Text) _ 
        And Val(txtNumberTosses.Text) <= 32767 _ 
        Then 
            ' Get the user input of the number of tosses and the 
            ' probability of heads and assign them to the corresponding 
            ' module-level variables. 
            mi_NumberTosses = Val(txtNumberTosses.Text) 
            ms_Probability = Val(txtProbability.Text) 
            b_GetInput = True 
    Else 
        st_Msg = "The number of tosses should be a positive " 
        st_Msg = st_Msg & "integer no more than 32,767 and " 
        st_Msg = st_Msg & "the input for the probability " 
        st_Msg = st_Msg & "should be between 0 and 1." 
        i_MsgDialog = vbExclamation 
        st_Title = "Change Input" 
        MsgBox st_Msg, i_MsgDialog, st_Title 
        b_GetInput = False 
    End If 

End Function 

Private Sub ComputeRelFreq() 

    ' The role of this function is to run through the trials of a 
    ' Bernoulli experiment for which the total number of trials 
    ' and probability of success on each trial are input by the 
    ' user. The function outputs the number of successes and the 
    ' relative frequency of success in output labels, updating the 
    ' results periodically during the process and at the end. 
    ' This function is called after the user input has been obtained, 
    ' validated, and assigned to the module-level variables 
    ' mi_NumberTosses and ms_Probability, respectively. 
         
    ' Declare two variables of Integer data type to keep track 
    ' of which toss it is and a running total of the number 
    ' of heads. 
    Dim i_Index As Integer, i_Heads As Integer 
     
    ' Declare a variable of Single data type to store the 
    ' proportion of heads after each toss. Note that this
    ' is used so that output can be updated periodically during 
    ' the running of the procedure. 
    Dim s_Proportion As Single 

    ' For each index, determine whether the random number 
    ' generated corresponds to heads, and keep a running 
    ' total of the number of heads. 
    For i_Index = 1 To mi_NumberTosses 
             
        ' If the random number is less than the probability 
        ' then increment the number of heads by 1 
        If Rnd < ms_Probability Then 
            i_Heads = i_Heads + 1 
        End If 
             
        ' Display the current value of the number of heads 
        ' and the proportion of heads every 100 flips and 
        ' when all the flips have been completed. The "Refresh" 
        ' method ensures that the control will be updated at 
        ' that time instead of at the end of the procedure run. 
        If i_Index Mod 100 = 0 Or i_Index = mi_NumberTosses Then 
             
            lblOutput(0).Caption = i_Heads 
            lblOutput(0).Refresh 
             
            ' Calculate the proportion of heads. 
            s_Proportion = i_Heads / i_Index 
             
            ' The Relative Frequency will be formatted as a percentage. 
            lblOutput(1).Caption = Format$(s_Proportion, "Standard") 
            lblOutput(1).Refresh 
         
        End If 
     
    Next i_Index 

End Sub 

Private Function s_LeftEndPt() As Single 
     
    ' Based on the normal approximation to the binomial distribution, 
    ' the left-hand endpoint of an interval for which there is a 95% 
    ' probability that it contains the relative frequency, should be 
    ' roughly 1.96 standard deviations to the left of the probability. 
    s_LeftEndPt = ms_Probability - 1.96 * s_StdDev() / mi_NumberTosses 

End Function 

Private Function s_RightEndPt() 

    ' Based on the normal approximation to the binomial distribution, 
    ' the right-hand endpoint of an interval for which there is a 95% 
    ' probability that it contains the relative frequency, should be 
    ' roughly 1.96 standard deviations to the right of the probability. 
    s_RightEndPt = ms_Probability + 1.96 * s_StdDev() / mi_NumberTosses 
     
End Function 

Function s_StdDev() As Single 

    ' This function returns the standard deviation of the 
    ' binomial distribution. It is called after the module-level 
    ' variables for the total number of tosses and the probability 
    ' of heads on each trial has been validated and assigned to 
    ' corresponding module-level variables. 
    s_StdDev = Sqr(ms_Probability * (1 - ms_Probability) * mi_NumberTosses) 

End Function 

Private Sub cmdCompute_Click() 

    ' Call the appropriate menu click procedure. 
    mnuFileCompute_Click 

End Sub 

Private Sub cmdExit_Click() 
     
    ' Call the appropriate menu click procedure. 
    mnuFileExit_Click 

End Sub 

Private Sub Form_Load() 

    ' Center the form in the screen. 
    Top = (Screen.Height - Height) / 2 
    Left = (Screen.Width - Width) / 2 

    ' Initialize the module-level variables using a procedure 
    Initialize 
       
    ' Seed the random number generator with the present time. 
    Randomize Timer 
     
End Sub 

Private Sub mnuFileCompute_Click() 

    ' This procedure conducts one run of the binomial experiment 
    ' outputting the number of heads, the relative frequency, an 
    ' interval in which the relative frequency should be contained 
    ' with 95% probability, and an estimate of the Worst Error in 
    ' using the Normal Approximation to the Binomial Distribution 
    ' and updates the module-level variable keeping track of whether 
    ' this is the first run with the current user input. 
     
    ' Declare a variable of Single data type to store the relative 
    ' frequency of heads. 
    Dim s_RelFreq As Single 
     
    ' Get the input and, if it is valid, proceed with the 
    ' remainder of the procedure. 
    If b_GetInput() Then 
         
        ' The module-level variable mb_FirstRunFlag is set to True at 
        ' initialization or whenever there is new user input. This 
        ' procedure sets the variable to False and the value stays 
        ' that way until the next change of user input. Because the 
        ' variable is module-level variable, it maintains its value 
        ' between calls. The same result could have been achieved by 
        ' declaring it as a Static variable within this procedure. 
         
        ' The first time the procedure is run (in a sequence of runs), 
        ' check if the Normal Approximation of the Binomial is 
        ' satisfactory and output an estimate of the Worst Error if 
        ' it is possible to determine this. Also, set the Flag for the 
        ' first run to False. 
        If mb_FirstRunFlag Then 

            CheckApproximation 
            mb_FirstRunFlag = False 

        End If 
         
        ' Assign to the appropriate output label a string which gives 
        ' an interval which has a 95% probability of containing the 
        ' Relative Freqency (based on a Normal approximation to the 
        ' Binomial Distribution). This is assigned by means of a 
        ' function st_Interval95(). 
        lblInterval95.Caption = st_Interval95() 
         
        ' Run the binomial experiment and assign the relative freqency 
        ' to the appropriate output label. 
        ComputeRelFreq 
     
    End If 

End Sub 

Private Sub mnuFileDefaults_Click() 

    ' Call a procedure which clears all output labels 
    ' and sets the initial values of the number of 
    ' independent coin tosses, the probability of heads 
    ' on a single toss, the interval for 95% to the relative 
    ' frequencies, an the Worst Error Estimate. 
    Initialize 
      
End Sub 

Private Sub mnuFileExit_Click() 

    ' End program 
    End

End Sub 

Private Sub mnuHelpAbout_Click() 

    ' Show the About Box by calling the "ShowAbout" procedure
    ' and passing the arguments consisting of the Caption of the
    ' present form, the programmer, the version number, and the
    ' date.
     ShowAbout Caption, "R. Berman", 1, "June, 1996"

End Sub 

Private Sub txtNumberTosses_Change() 

    ' Call the ClearOutput procedure to clear the
    ' output labels.
    ClearOutput
    
    ' Set the module-level variable indicating whether this is the
    ' first run of the procedure with the current input to True.
    mb_FirstRunFlag = True
     
End Sub 

Private Sub txtProbability_Change() 

    ' Call the ClearOutput procedure to clear the
    ' output labels.
    ClearOutput
    
    ' Set the module-level variable indicating whether this is the
    ' first run of the procedure with the current input to True.
    mb_FirstRunFlag = True

End Sub 

Private Function st_Interval95() As String 
     
    ' This function returns a string which gives an interval in which 
    ' the Relative Frequency should lie with 95% probability. To 
    ' accomplish this, it calls two other functions, s_LeftEndPt() and 
    ' s_RightEndPt() which return the left and right endpoints of the 
    ' interval based on the normal approximation. 
    st_Interval95 = "(" & Format$(s_LeftEndPt(), "Standard") _ 
        & "," & Format$(s_RightEndPt(), "Standard") & ")" 
     
End Function 

  
Object, Property and Settings:

Object          Property        Setting
Form            Name            frmRelFreq0  
                Appearance      0  'Flat 
                BackColor       &H00400000& 
                BorderStyle     3  'Fixed Dialog 
                Caption         "Coin Toss Relative Frequencies" 
                ForeColor       &H80000008& 
                MaxButton       0   'False 
                MinButton       0   'False 
CommandButton   Name            cmdCompute  
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                Caption         "&Compute" 
                Default         -1  'True 
                TabIndex        10 
CommandButton   Name            cmdExit  
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                Caption         "E&xit" 
                TabIndex        11 
TextBox         Name            txtProbability  
                Alignment       2  'Center 
                Appearance      0  'Flat 
                MultiLine       -1  'True 
                TabIndex        3 
TextBox         Name            txtNumberTosses  
                Alignment       2  'Center 
                Appearance      0  'Flat 
                MultiLine       -1  'True 
                TabIndex        1 
Label           Name            lblWorstError  
                Alignment       2  'Center 
                BackStyle       0  'Transparent 
                Caption         "0.00" 
                ForeColor       &H00FFFFFF& 
                TabIndex        13 
Label           Name            Label5  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "Interval with approximately 95% probability 
                                 of containing the relative frequency:" 
                ForeColor       &H0000FFFF& 
                TabIndex        12 
Label           Name            lblInterval95  
                BackStyle       0  'Transparent 
                Caption         "(0.40,0.60)" 
                ForeColor       &H00FFFFFF& 
                TabIndex        9 
Label           Name            Label6  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "Approximate Worst Error in Normal Approximation 
                                 of the Binomial Distribution:" 
                ForeColor       &H0000FFFF& 
                TabIndex        8 
Label           Name            lblOutput  
                Alignment       2  'Center 
                BackColor       &H00000080& 
                BorderStyle     1  'Fixed Single 
                ForeColor       &H00FFFFFF& 
                Index           1 
                TabIndex        7 
Label           Name            lblOutput  
                Alignment       2  'Center 
                BackColor       &H00000080& 
                BorderStyle     1  'Fixed Single 
                ForeColor       &H00FFFFFF& 
                Index           0 
                TabIndex        5 
Label           Name            Label2  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "The probability of heads on a single toss 
                                 of the coin: " 
                ForeColor       &H0000FFFF& 
                TabIndex        2 
Label           Name            Label1  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "The number of independent coin tosses to 
                                 be simulated:" 
                ForeColor       &H0000FFFF& 
                TabIndex        0 
Label           Name            Label3  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "Number of Heads:" 
                ForeColor       &H0000FFFF& 
                TabIndex        4 
Label           Name            Label4  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "Relative Frequency:" 
                ForeColor       &H0000FFFF& 
                TabIndex        6 
Menu            Name            mnuFile  
                Caption         "&File" 
Menu            Name            mnuFileCompute  
                Caption         "&Compute" 
                Shortcut        ^C 
Menu            Name            mnuFileDefaults  
                Caption         "&Defaults" 
                Shortcut        ^D 
Menu            Name            mnuFileSep1  
                Caption         "-" 
Menu            Name            mnuFileExit  
                Caption         "E&xit" 
                Shortcut        ^X 
Menu            Name            mnuHelp  
                Caption         "&Help" 
Menu            Name            mnuHelpAbout  
                Caption         "&About" 
                Shortcut        ^A 


Example 2.5b: Repeated runs of the the coin toss experiment.



Event Procedures:

' In (declarations) section of (General)

' Programmer:   R. Berman 
' Date:         June, 1996 
' Title:        Coin Toss Experiment: Relative Frequencies 
' Description:  This form takes as input the total number of coin 
'               tosses and the probability p of heads on each toss. 
'               During one run of the main procedure, the count of the number 
'               of heads and the proportion of heads are periodically 
'               updated in two output labels; at the completion of the 
'               run, the final results are output in these labels. 
'               Each time the procedure is run, it is determined whether 
'               the relative frequency is contained in a certain interval 
'               centered at the true probability p. The interval is 
'               determined using the Normal approximation to the Binomial 
'               Distribution so that there is a 95% probability that the 
'               relative frequency is in it. The program keeps track of 
'               what percent of the relative frequencies were actually in 
'               the interval. 
' Version       Microsoft Visual Basic 4.0 

' Require explicit declaration of variables. 
Option Explicit 

' Declare module-level variables as follows: 
' mi_NumberTosses = the total number of tosses in each run 
'                   (integer data type). 
' ms_Probability = the probability of heads on each toss 
'                  (single data type). 
' mi_SimulationNumber = a variable which keeps track of the 
'                  number of time the binomial experiment has 
'                  been run (integer data type). 
' mi_NumberInInterval = stores the number of times the relative 
'                       frequency is in the interval (integer 
'                       data type). 
Dim mi_NumberTosses As Integer 
Dim ms_Probability As Single 
Dim mi_SimulationNumber As Integer 
Dim mi_NumberInInterval As Integer 

Private Sub CheckApproximation() 

    ' The the theoretical worst error W(n,p) in using Normal 
    ' Approximation to the Binomial Distribution Bin(n,p) is known to be 
    ' approximately 
    ' 
    '         |1-2p|/[10*Sqr(npq)] = |1-2p|/(10*StdDev) 
    ' 
    ' provided the Standard Deviation StdDev >= 3. This procedure 
    ' determines if the StdDev is greater than or equal to 3 (so 
    ' that the estimate of W(n,p) is possible) and in that case 
    ' checks to see if W(n,p) <= .01, which we will regard 
    ' as an acceptable level of approximation. 
     
    ' Define local variables of single data type to store the 
    ' values of the standard deviation of the binomial and the 
    ' approximate worst error estimate. 
    Dim s_StdDevVar As Single
    Dim s_AppxWorstError As Single 
     
    ' Declare a Boolean variable to be a flag for when the Normal 
    ' Approximation may be inaccurate; that is, it will be set 
    ' to True if the approximation cannot be determined to be 
    ' satisfactory, and False if it can. 
    Dim b_BadApproxFlag As Boolean 
     
    ' If the number of tosses and probability of heads on a 
    ' given toss are such that the Normal Approximation cannot 
    ' be determined to be satisfactory, we want to exhibit a 
    ' warning message to this effect. However, we only want to do
    ' this the first in a sequence of runs under the same conditions.

    ' Declare 3 variables for the arguments of a message box. 
    ' The first is the actual message, the second is a number 
    ' determining the icon exhibited in the box (we use the 
    ' built-in VB constant vbExclamation which equals 48), and 
    ' the third is the title of the message box. 
    Dim st_Msg As String 
    Dim i_MsgDialog As Integer 
    Dim st_Title As String 
            
    ' First, compute the standard deviation of the binomial 
    ' using the s_StdDev() function and set it to a local 
    ' variable. We do this since it is used more than once and 
    ' it would be inefficient to recalculate each time. We note 
    ' that before this procedure is called, the validity of the 
    ' input is checked so that it will always yield a positive 
    ' value. 
    s_StdDevVar = s_StdDev() 
     
    ' Next compute the approximate worst error according to the 
    ' formula given above. 
    s_AppxWorstError = Abs(1 - 2 * ms_Probability) / (10 * s_StdDevVar) 
         
    ' Set the flag for a bad approximation to be True if either 
    ' the standard deviation is less than 3 or the approximate worst 
    ' error is greater than .01. Note that the logical assertion on 
    ' the right of the equal sign is true if either one of the statements 
    ' in parentheses is true. 
    b_BadApproxFlag = (s_StdDevVar < 3) Or (s_AppxWorstError > 0.01) 
     
    ' If the flag is set to True, then the warning message is 
    ' displayed. The precise error message depends on which 
    ' of two situations occur. 
    If b_BadApproxFlag Then 
        st_Msg = "The Normal approximation may not be accurate " 
        st_Msg = st_Msg & "in this case since " 
        If s_StdDevVar < 3 Then 
            st_Msg = st_Msg & "the standard deviation of the binomial " 
            st_Msg = st_Msg & "is less than 3." 
        Else 
            st_Msg = st_Msg & "the approximate worst error estimate is " 
            st_Msg = st_Msg & "greater than 0.01" 
        End If 
        i_MsgDialog = vbExclamation 
        st_Title = "Warning!" 
        MsgBox st_Msg, i_MsgDialog, st_Title 
         
    End If 
  
End Sub 

Private Sub ClearOutput() 

    ' Clear all output labels. 
    lblOutput(0).Caption = ""   ' the number of heads 
    lblOutput(1).Caption = ""   ' the relative freqeuncy 
    lblOutput(2).Caption = ""   ' the number of runs 
    lblOutput(3).Caption = ""   ' the number of times the 
                                ' relative frequency is in 
                                ' the interval of 95% prob. 
    lblOutput(4).Caption = ""   ' the percent of the times 
                                ' that the relative frequency 
                                ' is in the interval. 
    lblInterval95.Caption = ""  ' an interval that has 95% 
                                ' probability that the relative 
                                ' frequency is contained in it. 
     
End Sub 

Private Sub Initialize() 
     
    ' Clear all output labels and set module-level variables 
    ' for counting the number of runs and the number in the 
    ' interval. 
    ClearOutput 
     
    ' Reset the defaults for the number of coin 
    ' tosses and the the probability of heads. 
    txtNumberTosses.Text = "100" 
    txtProbability.Text = ".5" 
    mi_NumberTosses = 100 
    ms_Probability = 0.5 
     
   ' Reset module-level counting variables to 0. 
    mi_SimulationNumber = 0 
    mi_NumberInInterval = 0 

    ' Disable the restart command button and menu option. 
    mnuFileRestart.Enabled = False 
    cmdRestart.Enabled = False 
     
    ' Reset the interval to its initial setting. 
    lblInterval95.Caption = st_Interval95() 
         
End Sub 

Private Function b_GetInput() As Boolean 

    ' This function gets the user input of the number 
    ' of coin tosses and the probability of heads, and 
    ' determines if the input is valid. If so, it assigns 
    ' the values to the module-level variables mi_NumberTosses 
    ' and ms_Probability and returns a value of True (-1), 
    ' otherwise it returns the value False (0). 
         
    ' Declare 3 variables for the arguments of the 
    ' message box. The first is the actual message, 
    ' the second is a number determining the 
    ' icon exhibited in the box (we use the built- 
    ' in VB constant vbExclamation which equals 48), 
    ' the third is the title of the message box. 
    Dim st_Msg As String 
    Dim i_MsgDialog As Integer 
    Dim st_Title As String 
     
    ' Check that the number of tosses is a nonnegative integer 
    ' between 0 and 32,767 and the probability is between 
    ' 0 and 1. The Val() function is used to convert its argument 
    ' to a numeric value 
    If (Val(txtProbability.Text) > 0) _ 
        And (Val(txtProbability.Text) < 1) _ 
        And Int(Val(txtNumberTosses.Text)) = Val(txtNumberTosses.Text) _ 
        And 0 < Val(txtNumberTosses.Text) _ 
        And Val(txtNumberTosses.Text) <= 32767 _ 
        And Int(Val(txtNumberTosses.Text)) = Val(txtNumberTosses.Text) _ 
        Then 
            ' Get the user input of the number of tosses as well as the 
            ' probability of heads and assign them to the corresponding 
            ' module-level variables. 
            mi_NumberTosses = Val(txtNumberTosses.Text) 
            ms_Probability = Val(txtProbability.Text) 
            b_GetInput = True 
    Else 
        st_Msg = "The number of tosses should be a positive " 
        st_Msg = st_Msg & "integer more than 32,767 and " 
        st_Msg = st_Msg & "the input for the probability " 
        st_Msg = st_Msg & "should be between 0 and 1." 
        i_MsgDialog = vbExclamation 
        st_Title = "Change Input" 
        MsgBox st_Msg, i_MsgDialog, st_Title 
        b_GetInput = False 
    End If 

End Function 

Private Function s_ComputeRelFreq() As Single 

    ' The role of this function is to run through a sequence of coin 
    ' tosses (Bernoulli trials) and to return the relative frequency of 
    ' of success. The function is called from the cmdCompute_Click procedure 
    ' after the user input of the total number of trials and the probability 
    ' of heads (success) on each trial has been obtained, validated, and 
    ' assigned to the module-level variables mi_NumberTosses and ms_Probability, 
    ' respectively. 
         
    ' Declare two variables of Integer data type to keep track of which 
    ' toss it is and a running total of the number of heads. 
    Dim i_Index As Integer, i_Heads As Integer 
     
    ' Declare a variable of Single data type to keep track 
    ' of the proportion of heads after each toss. Note that 
    ' this is done here so that output can be updated 
    ' periodically during the running of the procedure. 
    Dim s_Proportion As Single 

    ' For each index, determine whether the random number 
    ' generated corresponds to a heads, and keep a running 
    ' total of the number of heads as well as the proportion 
    ' of heads. 
    For i_Index = 1 To mi_NumberTosses 
             
        ' If random number is less than the probability 
        ' then increment the number of heads by 1 
        If Rnd < ms_Probability Then 
            i_Heads = i_Heads + 1 
        End If 
             
        ' Calculate the proportion of heads. 
        s_Proportion = i_Heads / i_Index 
         
        ' Display the current value of the number of heads 
        ' and the proportion of heads every 100 flips and 
        ' when all the flips have been completed. The "Refresh" 
        ' method updates the control when it is invoked, otherwise 
        ' it would not be updated until the end of the procedure run. 
        If i_Index Mod 100 = 0 Or i_Index = mi_NumberTosses Then 
            lblOutput(0).Caption = i_Heads 
            lblOutput(0).Refresh 
            ' The Relative Frequency will be formatted as a percentage. 
            lblOutput(1).Caption = Format$(s_Proportion, "Percent") 
            lblOutput(1).Refresh 
        End If 
     
    Next i_Index 

    ' Assign the value of the function to be the last proportion 
    ' computed. 
    s_ComputeRelFreq = s_Proportion 
         
End Function 

Private Function s_LeftEndPt() As Single 
     
    ' Based on the normal approximation, the left-hand 
    ' endpoint of the interval should be roughly 1.96 
    ' standard deviations to the left of the probability. 
    s_LeftEndPt = ms_Probability - 1.96 * s_StdDev() _ 
        / mi_NumberTosses 

End Function 

Private Function s_RightEndPt() 

    ' Based on the normal approximation, the right-hand 
    ' endpoint of the interval should be roughly 1.96 
    ' standard deviations to the right of the probability. 
    s_RightEndPt = ms_Probability + 1.96 * s_StdDev() _ 
        / mi_NumberTosses 
     
End Function 

Private Function s_StdDev() As Single 

    ' This function returns the standard deviation of the 
    ' binomial distribution. It is called after the module-level 
    ' variables for the total number of tosses and the probability 
    ' of heads on each trial has been validated and assigned to 
    ' corresponding module-level variables. 
    s_StdDev = Sqr(ms_Probability * (1 - ms_Probability) * mi_NumberTosses) 

End Function 

Private Sub cmdCompute_Click() 

    ' Call the corresponding menu command. 
    mnuFileCompute_Click 

End Sub 

Private Sub cmdExit_Click() 

    ' Call the corresponding menu command. 
    mnuFileExit_Click 

End Sub 

Private Sub cmdRestart_Click() 
     
    ' Call the corresponding menu command. 
    mnuFileRestart_Click 

End Sub 

Private Sub Form_Load() 

    ' Center the form in the screen. 
    Top = (Screen.Height - Height) / 2 
    Left = (Screen.Width - Width) / 2 

    ' Place default values in Text Boxes and clear and initialize labels 
    ' and module-level counter variables. 
    Initialize 
             
    ' Seed the random number generator with the present time. 
    Randomize Timer 
             
End Sub 
  
Private Sub mnuFileCompute_Click() 

    ' This procedure conducts one run of the binomial experiment, 
    ' outputs the relative frequency and determines if it is in 
    ' the interval which should contain it with 95% probability, 
    ' increments module-level variables keeping track of the 
    ' number of runs of the procedure, and updates the module-level 
    ' variable that stores the proportion of times the relavtive 
    ' frequency was contained in the interval. 
     
    ' Declare a variable of Single data type to store the 
    ' relative frequency of heads. 
    Dim s_RelFreq As Single 
     
    ' Get the input and, if it is valid, proceed with the 
    ' remainder of the procedure. 
    If b_GetInput() Then 
         
        ' The variable mi_SimulationNumber is incremented once 
        ' each time the procedure is called. Because it is a 
        ' module-level variable, it maintains its value between 
        ' calls. The same result could have been achieved by 
        ' declaring it as a Static variable within this procedure. 
        ' It should be noted that a variable of Integer data type 
        ' is restricted to be no more than 32,767, so in principal, 
        ' we should check if this limit is achieved. However, there 
        ' is no real concern that a user will run the procedure 
        ' that many times before exiting the program. 
        mi_SimulationNumber = mi_SimulationNumber + 1 
         
        ' Enable the Restart Menu Choice and Command Button 
        mnuFileRestart.Enabled = True 
        cmdRestart.Enabled = True 
         
        ' The first time the procedure is run (in a sequence of 
        ' runs), check if the Normal Approximation of the Binomial 
        ' is satisfactory. If it not possible to determine this, 
        ' or if it is determined it is not, a warning message is 
        ' given. 
        If mi_SimulationNumber = 1 Then 
            CheckApproximation 
        End If 
         
        ' Assign (the string value of) the simulation number to 
        ' the appropriate output label. The function Str$() 
        ' converts the number to a string. 
        lblOutput(2).Caption = Str$(mi_SimulationNumber) 
         
        ' Assign the string which gives an interval which has a 95% 
        ' probability of containing the Relative Freqency (based on 
        ' a Normal approximation to the Binomial Distribution). 
        ' This is assigned by means of a function st_Interval95(). 
        lblInterval95.Caption = st_Interval95() 
         
        ' Run the binomial experiment and assign the return value 
        ' (which is the relative frequency of heads) to a variable. 
        s_RelFreq = s_ComputeRelFreq() 
         
        ' Test whether the Relative Frequency is in the interval, and if 
        ' it is, increment by 1 the variable used for counting the number 
        ' of times this occurs. Note that s_LeftEndPt() and s_RightEndPt() 
        ' are functions which return the left-hand and right-hand endpoint 
        ' of the inverval, respectively. 
        If s_LeftEndPt() < s_RelFreq And s_RelFreq < s_RightEndPt() Then 
             
            ' If the Relative Frequency is in the interval, increment 
            ' the count by 1. 
            mi_NumberInInterval = mi_NumberInInterval + 1 
                     
        End If 
         
        ' Convert the number mi_NumberInInterval to a string and assign 
        ' it to the appropriate output label. 
        lblOutput(3).Caption = Str$(mi_NumberInInterval) 
         
        ' Finally, compute the proportion of times that the Relative 
        ' Frequency has been in the interval and output it using the 
        ' "Percent" format. 
        lblOutput(4).Caption = Format$(mi_NumberInInterval / mi_SimulationNumber, "Percent") 
    Else 
        mnuFileRestart.Enabled = False 
        cmdRestart.Enabled = False 
    End If 
     
End Sub 

Private Sub mnuFileDefaults_Click() 

    ' Call a procedure which clears all output labels 
    ' and sets the initial values of the number of 
    ' independent coin tosses, the probability of heads 
    ' on a single toss, and the interval for 95% to their 
    ' initial values. 
    Initialize 
      
End Sub 

Private Sub mnuFileRestart_Click() 

    ' Clear ouput labels. 
    ClearOutput 
     
    ' Reset module-level counting variables to 0. 
    mi_SimulationNumber = 0 
    mi_NumberInInterval = 0 

    ' Disable the restart command button and menu option. 
    mnuFileRestart.Enabled = False 
    cmdRestart.Enabled = False 
     
    ' Set the focus on the "Compute" Command Button. 
    cmdCompute.SetFocus 
         
End Sub 

Private Sub mnuFileExit_Click() 

    ' End program 
    End

    ' If there is a main form named "frmCoinMain" to which the programs returns,
    ' then the following commands can be used:
    ' Hide 
    ' frmCoinMain.Show 

End Sub 

Private Sub mnuHelpAbout_Click() 

    ' Set the caption property of the About Form 
    ' and various labels which supply information. 
    frmAbout.Caption = "About " & Caption 
    frmAbout!lblTitle.Caption = Caption 
    frmAbout!lblProgrammer.Caption = "Written by R. Berman" 
    frmAbout!lblVersion.Caption = "Version 1" 
    frmAbout!lblDate.Caption = "May, 1996" 
     
    ' Open the About Form. 
    frmAbout.Show 

End Sub 
  
Private Sub mnuHelpConventions_Click() 

    ' The purpose of this procedure is to display in a message 
    ' box containing naming conventions used in the program. It is
    ' identical to the corresponding procedure in Example 2a so it
    ' is not reproduced here.
     
End Sub 

Private Sub mnuHelpInfo_Click() 

    ' Declare 3 variables for the arguments of the message box. 
    ' The first is the actual message, the second is a number 
    ' determining the icon exhibited in the box (we use the 
    ' built-in VB constant vbInformation which equals 48), and 
    ' the third is the title of the message box. 
    Dim st_Msg As String 
    Dim i_MsgDialog As Integer 
    Dim st_Title As String 
     
    ' Assign suitable values and strings to the the variables. 
    st_Msg = "This form takes as input the total number of coin " 
    st_Msg = st_Msg & "tosses and the probability p of heads on each toss. " 
    st_Msg = st_Msg & "During one run of the main procedure, the count of the " 
    st_Msg = st_Msg & "number of heads along with the proportion of heads are " 
    st_Msg = st_Msg & "periodically updated in two output labels; at the completion " 
    st_Msg = st_Msg & "of the run, the final results are output in these labels. " 
    st_Msg = st_Msg & "Each time the procedure is run, it is determined whether " 
    st_Msg = st_Msg & "the relative frequency is contained in a certain interval " 
    st_Msg = st_Msg & "centered at the true probability p. The interval is " 
    st_Msg = st_Msg & "determined using the Normal approximation to the Binomial " 
    st_Msg = st_Msg & "Distribution so that there is a 95% probability that the " 
    st_Msg = st_Msg & "relative frequency is in it. The program keeps track of " 
    st_Msg = st_Msg & "what percent of the relative frequencies were actually in " 
    st_Msg = st_Msg & "the interval." 
     
    i_MsgDialog = vbInformation 
    st_Title = "Information" 
     
    ' Display the message box. 
    MsgBox st_Msg, i_MsgDialog, st_Title 

End Sub 

Private Sub txtNumberTosses_Change() 
  
    ' Call the ClearOutput procedure to clear the 
    ' output labels. 
    ClearOutput 
      
    ' Reset module-level counting variables to 0. 
    mi_SimulationNumber = 0 
    mi_NumberInInterval = 0 

End Sub 

Private Sub txtProbability_Change() 

    ' Call the ClearOutput procedure to clear the 
    ' output labels. 
    ClearOutput 
      
    ' Reset module-level counting variables to 0. 
    mi_SimulationNumber = 0 
    mi_NumberInInterval = 0 
     
End Sub 

Private Function st_Interval95() As String 
     
    ' This function returns a string which gives an 
    ' interval in which the Relative Frequency should lie 
    ' with 95% probability. To accomplish this, it calls 
    ' two other functions, s_LeftEndPt() and s_RightEndPt() 
    ' which return the left and right endpoints of the 
    ' interval based on the normal approximation. 
    st_Interval95 = "(" & Format$(s_LeftEndPt(), "Standard") _ 
        & "," & Format$(s_RightEndPt(), "Standard") & ")" 
     
End Function 
  
Object, Property and Settings:

Object          Property        Setting
Form            Name            frmCoinRelFreq  
                Appearance      0  'Flat 
                BackColor       &H00400000& 
                BorderStyle     3  'Fixed Dialog 
                Caption         "Coin Toss: Relative Frequencies" 
                ControlBox      0   'False 
                ForeColor       &H80000008& 
                MaxButton       0   'False 
                MinButton       0   'False 
CommandButton   Name            cmdCompute  
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                Caption         "&Compute" 
                Default         -1  'True 
                TabIndex        16 
CommandButton   Name            cmdRestart  
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                Caption         "&Restart" 
                TabIndex        17 
CommandButton   Name            cmdExit  
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                Caption         "E&xit" 
                TabIndex        18 
TextBox         Name            txtNumberTosses  
                Alignment       2  'Center 
                Appearance      0  'Flat 
                MultiLine       -1  'True 
                TabIndex        1 
TextBox         Name            txtProbability  
                Alignment       2  'Center 
                Appearance      0  'Flat 
                MultiLine       -1  'True 
                TabIndex        3 
Shape           Name            Shape1  
                BorderColor     &H00FFFFFF& 
                FillColor       &H00FFFFFF& 
Shape           Name            Shape2  
                BorderColor     &H00FFFFFF& 
                FillColor       &H00FFFFFF& 
Label           Name            lblOutput  
                Alignment       2  'Center 
                BackColor       &H00000080& 
                BorderStyle     1  'Fixed Single 
                ForeColor       &H00FFFFFF& 
                Index           2 
                TabIndex        11 
Label           Name            lblOutput  
                Alignment       2  'Center 
                BackColor       &H00000080& 
                BorderStyle     1  'Fixed Single 
                ForeColor       &H00FFFFFF& 
                Index           3 
                TabIndex        13 
Label           Name            lblOutput  
                Alignment       2  'Center 
                BackColor       &H00000080& 
                BorderStyle     1  'Fixed Single 
                ForeColor       &H00FFFFFF& 
                Index           0 
                TabIndex        5 
Label           Name            lblOutput  
                Alignment       2  'Center 
                BackColor       &H00000080& 
                BorderStyle     1  'Fixed Single 
                ForeColor       &H00FFFFFF& 
                Index           1 
                TabIndex        7 
Label           Name            lblOutput  
                Alignment       2  'Center 
                BackColor       &H00000080& 
                BorderStyle     1  'Fixed Single 
                ForeColor       &H00FFFFFF& 
                Index           4 
                TabIndex        15 
Label           Name            Label1  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "The number of independent coin tosses to be simulated:" 
                ForeColor       &H0000FFFF& 
                TabIndex        0 
Label           Name            Label2  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "The probability of heads on a single toss of the coin: " 
                ForeColor       &H0000FFFF& 
                TabIndex        2 
Label           Name            Label3  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "Number of Heads:" 
                ForeColor       &H0000FFFF& 
                TabIndex        4 
Label           Name            Label4  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "Relative Frequency:" 
                ForeColor       &H0000FFFF& 
                TabIndex        6 
Label           Name            Label5  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "The interval that should contain approximately 95% 
                                of relative frequencies:" 
                ForeColor       &H0000FFFF& 
                TabIndex        8 
Label           Name            Label6  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "The number of times this procedure has been run:" 
                ForeColor       &H0000FFFF& 
                TabIndex        10 
Label           Name            Label7  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "The number of times the Relative Frequency 
                                has been in the interval:" 
                ForeColor       &H0000FFFF& 
                TabIndex        12 
Label           Name            Label8  
                Alignment       1  'Right Justify 
                Appearance      0  'Flat 
                BackColor       &H80000005& 
                BackStyle       0  'Transparent 
                Caption         "The percentage of times that the Relative Frequency 
                                was in the interval:" 
                ForeColor       &H0000FFFF& 
                TabIndex        14 
Label           Name            lblInterval95  
                BackStyle       0  'Transparent 
                Caption         "(0.40,0.60)" 
                ForeColor       &H00FFFFFF& 
                TabIndex        9 
Menu            Name            mnuFile  
                Caption         "&File" 
Menu            Name            mnuFileCompute  
                Caption         "&Compute" 
                Shortcut        ^C 
Menu            Name            mnuFileRestart  
                Caption         "&Restart" 
                Shortcut        ^R 
Menu            Name            mnuFileDefaults  
                Caption         "&Defaults" 
                Shortcut        ^D 
Menu            Name            mnuSep1  
                Caption         "-" 
Menu            Name            mnuFileExit  
                Caption         "E&xit" 
                Shortcut        ^X 
Menu            Name            mnuHelp  
                Caption         "&Help" 
Menu            Name            MnuHelpInfo  
                Caption         "&Information" 
                Shortcut        ^I 
Menu            Name            mnuHelpConventions  
                Caption         "Con&ventions" 
                Shortcut        ^V 
Menu            Name            mnuHelpAbout  
                Caption         "&About" 
                Shortcut        ^A 


Example 2.5c: Coin Tosses: An Approximate 95% CI for the Probability p of Heads.

' In (declarations) section of (General)
  
' Programmer:   R. Berman 
' Date:         June, 1996 
' Title:        Coin Tosses: An approximate 95% CI for the the probability p of Heads 
' Description:  This program simulates a coin toss experiment and computes 
'               an approximate 95% Confidence Interval (CI) for the true 
'               probability p of tossing Heads on any trial. The number p 
'               is generated as a random number between .1 and .9 and the 
'               user inputs the total number of trials per run. Each time 
'               the "Compute" Command Button is clicked, the program 
'               outputs the relative frequency of Heads, an approximate 
'               95% CI for p, and determines if the actual p is in the Cl. 
'               The user can reveal or hide the value of p, or generate 
'               a new value of p at any time by clicking the appropriate 
'               option button. In this particular example, we will not be 
'               concerned with the Worst Error in using the Normal 
'               approximation to the Binomial Distribution except for the 
'               following comments. We will require user input for the 
'               number of tosses to be at least 100; this in conjunction 
'               with the fact that p is between .1 and .9 guarantees that 
'               the standard deviation is at least 3, and that with worst 
'               is approximately no worse than .8/30 < .027. 
' Version       Microsoft Visual Basic 4.0 

' Require explicit declaration of variables. 
Option Explicit 

' Declare module-level variables as follows: 
' mi_NumberTosses = the total number of tosses in each run 
'                   (integer data type). 
' ms_Probability = the probability of heads on each toss 
'                  (single data type). 
Dim mi_NumberTosses As Integer 
Dim ms_Probability As Single 
  
Private Function b_InInterval95(s_CenterPoint As Single) As Boolean 

        ' This function determines if the the true probability is 
        ' contained in the interval consisting of the center point plus 
        ' or minus 1/sqr(mi_NumberTosses). The function returns True or 
        ' False accordingly. 
        b_InInterval95 = (ms_Probability > _ 
            s_CenterPoint - 1 / Sqr(mi_NumberTosses)) And _ 
            (ms_Probability < s_CenterPoint + 1 / Sqr(mi_NumberTosses)) 

End Function 

Private Sub ClearOutput() 
     
    ' Clear output labels. 
    lblOutput(0).Caption = "" 
    lblOutput(1).Caption = "" 
    lblInterval95.Caption = "" 
       
End Sub 

Private Sub Initialize() 

    ' Select a random number between .1 and .9 for the probability 
    ' of Heads and assign it to the ms_Probability variable. 
    mnuFileNewProbability_Click 
     
    ' Set the number of tosses to 100. 
    txtNumberTosses.Text = "100" 
    mi_NumberTosses = 100 
     
End Sub 

Private Sub cmdCompute_Click() 

    ' Call the corresponding menu click procedure. 
    mnuFileCompute_Click 
     
End Sub 

Private Sub cmdExit_Click() 

    ' Call the corresponding menu click procedure. 
    mnuFileExit_Click 
     
End Sub 

Private Sub cmdNewProbability_Click() 

    ' Call the corresponding menu click procedure. 
    mnuFileNewProbability_Click 

End Sub 
     
Private Sub Form_Load() 

    ' Center the form in the screen. 
    Top = (Screen.Height - Height) / 2 
    Left = (Screen.Width - Width) / 2 

    ' The program will use random numbers in various ways. 
    ' This is a convenient point to seed the random number 
    ' generator with the present time (to avoid the use of the 
    ' same sequence of random numbers each time the program 
    ' is run). 
    Randomize Timer 
     
    ' Call the Sub procedure that sets the Text Box for the number 
    ' of tosses (as well as the corresponding form-level variable) 
    ' to "100", and selects a random number between .1 and .9 for 
    ' the probability of heads on a given toss. 
    Initialize 

End Sub 

Private Function st_Interval95(s_CenterPoint As Single) As String 
     
    ' This function returns a string which consists of an interval centered 
    ' at the center point (passed as an argument in the procedure) having 
    ' length equal to twice the reciprocal to the square root of the number of 
    ' tosses. This will give an approximate 95% CI for the probability p in 
    ' case the center point is the relative frequncy of heads. 
    st_Interval95 = "(" & _ 
        Format$(s_CenterPoint - 1 / Sqr(mi_NumberTosses), "Standard") & "," & _ 
        Format$(s_CenterPoint + 1 / Sqr(mi_NumberTosses), "Standard") & ")" 
     
End Function 

Private Sub mnuFileCompute_Click() 

   ' Declare an index variable for each toss in one run of 
   ' this procedure. 
    Dim i_Index As Integer 

    ' Declare a variable of integer data type to count the 
    ' number of heads in one run of the procedure. 
    Dim i_TotalHeads As Integer 

    ' Declare a variable to store the relative frequency 
    ' of heads. 
    Dim s_RelFreq As Single 
     
    ' Recall that the following module-level variables have been defined: 
    ' 
    ' mi_NumberTosses = the total number of tosses in each run 
    '                   (integer data type). 
    ' ms_Probability = the probability of heads on each toss 
    '                  (single data type). 
     
    ' Get the user input for the total number of tosses in each run 
    ' and proceed with the calculations provided it an integer that 
    ' is at least 100 and no more that 32,767. 
    If b_GetInput() Then 
     
        ' Use a For-Next Loop which increments through the number 
        ' of tosses of the coin. Each time, determine if a Heads 
        ' comes up and keep track of the total number of heads. 
        For i_Index = 1 To mi_NumberTosses 
         
            ' If the random number is less than the probability input 
            ' the user, then the flip is regarded as Heads and and the 
            ' counter for the number of heads is incremented. 
            If Rnd < ms_Probability Then 
                i_TotalHeads = i_TotalHeads + 1 
            End If 
         
        Next i_Index 
         
        ' Compute the relative frequncy of heads and output it to the 
        ' appropriate label. 
        s_RelFreq = i_TotalHeads / mi_NumberTosses 
        lblOutput(0).Caption = Format$(s_RelFreq, "Standard") 
         
        ' Compute the 95% CI and assign it to the appropriate label. 
        ' Note that the function st_Interval95() takes as input the 
        ' center point of the interval (the relative frequency), and 
        ' returns a string which gives an interval whose endpoints 
        ' consist of the center point plus or minus 1/sqr(mi_NumberTosses). 
        lblInterval95.Caption = st_Interval95(s_RelFreq) 
         
        ' Assign "In" or "Out" to to appropriate output label according 
        ' to whetner the function b_InInterval95() is true or false. 
        If b_InInterval95(s_RelFreq) Then 
            lblOutput(1).Caption = "In" 
        Else 
            lblOutput(1).Caption = "Out" 
        End If 

    End If 

End Sub 

Private Sub mnuFileExit_Click() 

    ' Return to Main Form 
    Hide 
    frmCoinMain.Show 
     
End Sub 

Private Sub mnuFileNewProbability_Click() 

    ' Generate a random number between .1 and .9 and assign 
    ' it to the module-level variable for the probability. 
    ms_Probability = 0.8 * Rnd + 0.1 
     
    ' Output this to the appropriate label. Note that by default 
    ' this will not be visible unless the option button labeled 
    ' "Reveal" is clicked by the user. 
    lblProbability.Caption = Format$(ms_Probability, "Standard") 

End Sub 

Private Sub mnuFileRestart_Click() 

    ' Clear the output labels. 
    ClearOutput 
     
    ' Reinitialize the number of coin tosses to 100 and generate a new 
    ' probability as a random number between .1 and .9. 
    Initialize 
         
    ' Set the focus on the "Compute" Command Button. 
     cmdCompute.SetFocus 
         
End Sub 

Private Sub mnuHelpAbout_Click() 
 
    ' Show the About Box by calling the "ShowAbout" procedure 
    ' and passing the arguments consisting of the Caption of the 
    ' present form, the programmer, the version number, and the 
    ' date. 
     ShowAbout Caption, "R. Berman", 1, "June, 1996" 
     
End Sub 
  
Private Function b_GetInput() As Boolean 

    ' This function is set up so that it gets the user input 
    ' of the number of tosses, and returns a value of True (-1) 
    ' if the the input is an integer greater than or equal to 100 
    ' (so that the standard deviation is at least 3) and False (0) 
    ' otherwise. 
             
    ' Declare 3 variables for the arguments of the message box. 
    ' The first is the actual message, the second is a number 
    ' determining the icon exhibited in the box (we use the 
    ' built-in VB constant vbExclamation which equals 48), the 
    ' third is the title of the message box. 
    Dim st_Msg As String 
    Dim i_MsgDialog As Integer 
    Dim st_Title As String 
     
    ' Check that the number of tosses is an integer that is at least 100. 
    If IsNumeric(txtNumberTosses.Text) And _ 
        Int(Val(txtNumberTosses.Text)) = Val(txtNumberTosses.Text) And _ 
        Val(txtNumberTosses.Text) >= 100 _ 
        And Val(txtNumberTosses.Text) <= 32767 _ 
        Then 

        ' Get the user input of the number of tosses to the corresponding 
        ' module-level variable. 
        mi_NumberTosses = Val(txtNumberTosses.Text) 
        b_GetInput = True 

    Else 

        st_Msg = "The number of tosses should be an integer between 100 and " 
        st_Msg = st_Msg & "32,767. The lower limit of 100 ensures that the " 
        st_Msg = st_Msg & "normal approximation is at least roughly accurate " 
        st_Msg = st_Msg & "for extreme values of p near .1 or .9." 
        i_MsgDialog = vbExclamation 
        st_Title = "Change Input" 
        MsgBox st_Msg, i_MsgDialog, st_Title 
        b_GetInput = False 

    End If 

End Function 

Private Sub mnuHelpInfo_Click() 

    ' This procedure displays a message box which gives basic information 
    ' about the program. 
     
    ' Declare 3 variables for the arguments of the message box. 
    ' The first is the actual message, the second is a number 
    ' determining the icon exhibited in the box (we use the 
    ' built-in VB constant vbInformation which equals 48), the 
    ' third is the title of the message box. 
    Dim st_Msg As String 
    Dim i_MsgDialog As Integer 
    Dim st_Title As String 
     
    ' Define the variables which serve as the arguments of the 
    ' message box. 
    st_Msg = "This program simulates a coin toss experiment and computes " 
    st_Msg = st_Msg & "an approximate 95% Confidence Interval (CI) for the true " 
    st_Msg = st_Msg & "probability p of tossing Heads on any trial. The number p " 
    st_Msg = st_Msg & "is generated as a random number between .1 and .9 and the " 
    st_Msg = st_Msg & "user inputs the total number of trials per run. Each time " 
    st_Msg = st_Msg & "the ""Compute"" Command Button is clicked, the program " 
    st_Msg = st_Msg & "outputs the relative frequency of Heads, an approximate " 
    st_Msg = st_Msg & "95% CI for p, and determines if the actual p is in the Cl. " 
    st_Msg = st_Msg & "The user can reveal or hide the value of p, or generate " 
    st_Msg = st_Msg & "a new value of p at any time by clicking the appropriate " 
    st_Msg = st_Msg & "option button. The program requires the user input of the " 
    st_Msg = st_Msg & "number of tosses to be at least 100 which ensures that " 
    st_Msg = st_Msg & "the worst error in using the Normal approximation to the " 
    st_Msg = st_Msg & "binomial distribution is approximately no worse than .03." 
    i_MsgDialog = vbInformation 
    st_Title = "Information" 
     
    ' Display the message box. 
    MsgBox st_Msg, i_MsgDialog, st_Title 

End Sub 

Private Sub optHide_Click() 

    ' Hide the value of p by making the ForeColor of the output label 
    ' to the same as he BackColor. 
    lblProbability.ForeColor = &H80& 
     
End Sub 

Private Sub optReveal_Click() 

    ' Reveal the value of p by making the ForeColor of the output label 
    ' different from the BackColor. 
    lblProbability.ForeColor = &HFFFFFF 

End Sub 

Private Sub txtNumberTosses_Change() 

    ' If the user changes the number of tosses, then clear outcome 
    ' labels corresponding to the relative frequency, the 95% CI, 
    ' the label telling whether p is in our out of the CI, but leave 
    ' the underlying probability p unchanged. 
    lblOutput(0).Caption = "" 
    lblOutput(1).Caption = "" 
    lblInterval95.Caption = "" 
     
End Sub 


Object, Property and Settings:

Object          Property                Setting
Form            Name                    frmConf0  
                Appearance              0  'Flat 
                BackColor               &H00400000& 
                BorderStyle             1  'Fixed Single 
                Caption                 "Approximate CI's" 
                ControlBox              0   'False 
                ForeColor               &H80000008& 
                MaxButton               0   'False 
                MinButton               0   'False 
Frame           Name                    fraProbability  
                BackColor               &H00C0C0C0& 
                Caption                 "Probability &p of Heads" 
                ForeColor               &H00000000& 
                TabIndex                13 
OptionButton    Name                    optReveal  
                Caption                 "Re&veal" 
                TabIndex                14 
OptionButton    Name                    optHide  
                Caption                 "&Hide" 
                TabIndex                8 
                Value                   -1  'True 
TextBox         Name                    txtNumberTosses  
                Alignment               2  'Center 
                Appearance              0  'Flat 
                MultiLine               -1  'True 
                TabIndex                1 
Label           Name                    Label1  
                Alignment               1  'Right Justify 
                Appearance              0  'Flat 
                BackColor               &H00FFFFFF& 
                BackStyle               0  'Transparent 
                Caption                 "Number of tosses:" 
                ForeColor               &H0000FFFF& 
                TabIndex                0 
Label           Name                    Label2  
                Alignment               1  'Right Justify 
                Appearance              0  'Flat 
                BackColor               &H80000005& 
                BackStyle               0  'Transparent 
                Caption                 "Relative Frequency:" 
                ForeColor               &H0000FFFF& 
                TabIndex                2 
Label           Name                    Label3  
                Alignment               1  'Right Justify 
                Appearance              0  'Flat 
                BackColor               &H80000005& 
                BackStyle               0  'Transparent 
                Caption                 "95% Confidence Interval: (CI):" 
                ForeColor               &H0000FFFF& 
                TabIndex                4 
Label           Name                    Label4  
                Alignment               1  'Right Justify 
                Appearance              0  'Flat 
                BackColor               &H80000005& 
                BackStyle               0  'Transparent 
                Caption                 "p is in or out of the CI:" 
                ForeColor               &H0000FFFF& 
                TabIndex                6 
Label           Name                    lblProbability  
                Alignment               2  'Center 
                BackColor               &H00000080& 
                BorderStyle             1  'Fixed Single 
                ForeColor               &H00000080& 
                TabIndex                9 
Label           Name                    lblInterval95  
                BackStyle               0  'Transparent 
                ForeColor               &H00FFFFFF& 
                TabIndex                5 
Label           Name                    lblOutput  
                Alignment               2  'Center 
                Appearance              0  'Flat 
                BackColor               &H80000005& 
                BackStyle               0  'Transparent 
                BorderStyle             1  'Fixed Single 
                ForeColor               &H00FFFFFF& 
                Index                   1 
                TabIndex                7 
Label           Name                    lblOutput  
                Alignment               2  'Center 
                BackColor               &H00000080& 
                BorderStyle             1  'Fixed Single 
                ForeColor               &H00FFFFFF& 
                Index                   0 
                TabIndex                3 
CommandButton   Name                    cmdNewProbability  
                Caption                 "&New Probability" 
                TabIndex                10 
CommandButton   Name                    cmdCompute  
                Appearance              0  'Flat 
                BackColor               &H80000005& 
                Caption                 "&Compute" 
                Default                 -1  'True 
                TabIndex                11 
CommandButton   Name                    cmdExit  
                Appearance              0  'Flat 
                BackColor               &H80000005& 
                Caption                 "E&xit" 
                TabIndex                12 
Menu            Name                    mnuFile  
                Caption                 "&File" 
Menu            Name                    mnuFileCompute          
                Caption                 "&Compute" 
                Shortcut                ^C 
Menu            Name                    mnuFileNewProbability  
                Caption                 "&New Probability" 
                Shortcut                ^N 
Menu            Name                    mnuFileRestart  
                Caption                 "&Restart" 
                Shortcut                ^R 
Menu            Name                    mnuFileSep1  
                Caption                 "-" 
Menu            Name                    mnuFileExit  
                Caption                 "E&xit" 
                Shortcut                ^X 
Menu            Name                    mnuHelp  
                Caption                 "&Help" 
Menu            Name                    mnuHelpInfo  
                Caption                 "&Information" 
                Shortcut                ^I 
Menu            Name                    mnuHelpAbout  
                Caption                 "&About" 
                Shortcut                ^A 

Problem 2.5: Create a form which takes as input the number of tosses of a coin. The program should generate a random number between .1 and .9 for the probability of heads on each trial which at the outset is hidden from the user (but can be revealed by clicking an option button). Ouptut to a label an approximate 95% CI based on a Normal approximation to the Binomial Distribution (not depending on p). Each run of the main procedure should compute and output to labels the relative frequency of heads and whether the true probability p is in the CI. Also, output the results to a grid which keeps a running history of the results since the beginning or the last restart.

If you are more ambitious, you may want to try to create the following form which also keeps track of the percentage of time that the true probability was in the CI.