Please help me convert this Javascript to VBA

Tkeller

Board Regular
Joined
Jul 23, 2003
Messages
143
Office Version
  1. 365
Platform
  1. Windows
  2. Mobile
JavaScript:
//*************************************************************************
//*           Returns random numbers from Standard Normal Distribution   **
//*************************************************************************
    double gauss() {
        double fac;
        double r = 99;
        double V1 = 0;
        double V2 = 0;
        while (r >= 1) {
            V1 = 2 * Math.random() - 1;
            V2 = 2 * Math.random() - 1;
            r = Math.pow(V1, 2) + Math.pow(V2, 2);
        }
        fac = Math.sqrt(-2 * Math.log(r) / r);
        return V2 * fac;
    }
 

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
Try the following function . . .

VBA Code:
Public Function gauss() As Double

    Dim fac As Double
    Dim r As Double
    Dim V1 As Double
    Dim V2 As Double
   
    r = 99
    V1 = 0
    V2 = 0
   
    VBA.Randomize
    While (r >= 1)
        V1 = 2 * VBA.Rnd() - 1
        V2 = 2 * VBA.Rnd() - 1
        With WorksheetFunction
            r = .Power(V1, 2) + .Power(V2, 2)
        End With
    Wend
   
    fac = VBA.Sqr(-2 * VBA.Log(r)) / r
   
    gauss = V2 * fac
   
End Function

Actually, the following lines of code . . .

VBA Code:
        With WorksheetFunction
            r = .Power(V1, 2) + .Power(V2, 2)
        End With

. . . can be replaced with . . .

VBA Code:
        r = (V1 ^ 2) + (V2 ^ 2)

Hope this helps!
 
Upvote 0

Forum statistics

Threads
1,214,971
Messages
6,122,521
Members
449,088
Latest member
RandomExceller01

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top