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

    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.
    gen := proc ()
        local roll, r;
        roll := -5+rand(10);
        r := roll();
        if 0 <= r then
            r := r+1
        end if;
    end proc:

    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