Mathematically create a positive or negative one using a random number function
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.
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);