Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematically create a positive or negative one using a random number function

Tags:

random

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.

like image 956
Albert Renshaw Avatar asked Jun 13 '11 03:06

Albert Renshaw


People also ask

How do you generate a negative and positive random number in C++?

int randomNum = rand() % 19 + (-9);

How do you generate positive random numbers in Matlab?

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.


2 Answers

Easy. random(0,1) * 2 - 1 will do it.

like image 87
Anomie Avatar answered Sep 28 '22 10:09

Anomie


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); 
like image 20
nithins Avatar answered Sep 28 '22 10:09

nithins