title: Function Returns #Value Error sometimes
body: <p>This method is based on the following 3 steps algorithm :</p>
  <blockquote>
  <p>1 - generate two uniform numbers on the [-1,1] interval that you will call U1 and U2</p>
  <p>2 - calculate S = U1 ^2 + U2^2</p>
  <p>3 - If  S &lt; 1 the normal number is given by  U1 * square root (-2 ln (S)/S) otherwise go back to step 1 until S &lt; 1.</p>
  </blockquote>
  <p>Program this function in VB and give it the name BoxMuller.</p>
  <p>This is the function I wrote based on above steps I am not sure whether it's correct or not because sometimes it returns #Value error</p>
  <p>I pass following values to the function <code>=BoxMuller(Rand(),Rand())</code></p>
  <pre><code>Function BoxMuller(U1 As Double, U2 As Double) As Double
  Dim S As Double
  
  Do
      U1 = WorksheetFunction.NormInv(U1, 0, 1)
      U2 = WorksheetFunction.NormInv(U2, 0, 1)
      S = U1 * U1 + U2 * U2
      
      If S &lt; 1 Then
          BoxMuller = U1 * Sqr(-2 * Log(S) / S)
          Exit Function
      End If
  
  Loop Until S &lt; 1
  End Function
  </code></pre>
  <p>is the <code>Loop Until S &lt; 1</code> condition right because I think that maybe the real cause of the error.</p>
  <p>Also tried the following :</p>
  <pre><code>Function BoxMuller() As Double
  Dim S As Double
  Dim U1 As Double
  Dim U2 As Double
  Do
  
  U1 = WorksheetFunction.RandBetween(-1, 1)
  U2 = WorksheetFunction.RandBetween(-1, 1)
  
      S = U1 * U1 + U2 * U2
      
      If S &lt; 1 Then
          BoxMuller = U1 * Sqr(-2 * Log(S) / S)
          Exit Function
      End If
  
  Loop
  End Function
  </code></pre>
  <p>And Called <code>=BoxMuller()</code> Still #Value Error</p>