Random Number Generation in ABAP

Random Numbers are used for a variety of purposes in programming, and in this article we will see how to generate a Random Number or Random Number Sequence in ABAP

As always, there are more than one ways to do this in ABAP and I’ll go with my recommended way first. I prefer using CL_ABAP_RANDOM_INT class for generating random numbers.

      o_rand type ref to cl_abap_random_int,
      n type i,
      seed type i.

seed = cl_abap_random=>seed( ).

    seed = seed
    min = 0
    max = 100
    prng = o_rand

n = o_rand->get_next( ).

First, you need to create an object of type CL_ABAP_RANDOM_INT. However, this class does not have a constructor. Instead of having a constructor, it has a method named create which will return the object of type CL_ABAP_RANDOM_INT.

It has three importing parameters named seed, min, and max where the later two are used for the purpose of specifying the range within which the random number has to be generated, seed takes a integer value which the random number generating algorithm will solely depend on for generating random numbers.

Though seed is an optional parameter, passing a seed value is important without which you will end up in the same sequence of random numbers again and again for each execution. So passing a good seed value is important for generating random number. cl_abap_random=>seed( ) method returns a seed value which is the best choice to use.

Once an object is created, you can call get_next( ) method any number of times and get a random number everytime. The sequence of numbers returned by get_next( ) is called as Random Number Sequence. And to reproduce an already generated Random Number Sequence, you have to pass the same seed value and create the object. Consider a quiz application which displayed same questions in random order to different users. Once all the users completed their tests, you wish to see the order of questions in which the user attended the quiz for a particular user. To acheive this, Should we store the entire sequence? No, we need to store only the seed. With the seed, we will be able to generate the whole sequence again.

The other ways to generate random numbers in ABAP is to use the Function Modules QF05_RANDOM_INTEGER or GENERAL_GET_RANDOM_INT. However, they don’t have the ability to get a seed value as input and obviously the random number generating algorithms differ.

comments powered by Disqus