Skip to content

Faster Math.RandG using the ratio of uniforms method.

Rika requested to merge runewalsh/source:randg into main

Implement Math.RandG using this cool method from Numerical Recipes — The Art of Scientific Computing — 3rd Edition:

Ratio-of-Uniforms

Demo: RandG.pas.

My results:

                       RandG trunk                              RandG new
                            ###                                    ###
                          #######                                #######
                         #########                              #########
                         #########                              #########
                        ###########                            ###########
                       #############                          #############
                      ###############                        ###############
                     #################                      #################
                    ###################                    ###################
                   #####################                  #####################
                 #########################              #########################
              ###############################        ###############################
Out of range: 88614 / 100000000 (0.1%).              89220 / 100000000 (0.1%).

Took (x64/SSE):  5.6 s                                  2.3 s 
Took (i386/FPU): 8.4 s                                  5.9 s

With SSE, polar method is more than 2× slower, which means it will remain slower even without discarding the second output. And though with FPU, it is less than 2× slower so could be faster by not discarding the second value, keeping the state is impossible because of RandSeed, so is not even an option.

Edited by Rika

Merge request reports