Generating integers between in a range, excluding zero


  • administrators

    There are a couple of ways to achieve this depending of what you are trying to do.

    Using Maple T.A. only functions you can use three random numbers and a switch statement to achieve this.

    # random integer from -5 to 5 excluding 0
    
    $a=switch(rint(2),rint(5)-5,rint(5)+1);
    

    An alternative using a Maple call and only one random number and an if statement is

    # Create a procedure called gen(). If you want a number random number you just call gen() again.
    # Below we can see the variables a and b are both random numbers.
    $alg=maple("
    randomize():
    
    gen := proc ()
        local roll, r;
        roll := -5+rand(10);
        r := roll();
        if 0 <= r then
            r := r+1
        end if;
        r
    end proc:
    
    a:=gen():
    b:=gen():
    ")
    

    There is a cost to the maple call and a cost to rolling three random numbers. Experiment with your algorithm to find out which is best.


Log in to reply