If I am in a coding language where I can create a random number for a given range (i.e. 0 to 50, or -30 to 751, etc.) How can I mathematically create a +1 or -1 (not a +1, 0, or -1) using only math and the random function.. no if statements.
int randomNum = rand() % 19 + (-9);
Use the rand , randn , and randi functions to create sequences of pseudorandom numbers, and the randperm function to create a vector of randomly permuted integers. Use the rng function to control the repeatability of your results.
Easy. random(0,1) * 2 - 1
will do it.
You could just get a random number and divide by the absolute value of itself. Something like the following in C#:
Random r = new Random(); int iNum; int result; iNum = r.Next(-30, 50); //put whatever range you want in here from negative to positive result = iNum / (int)Math.Abs(iNum);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With