Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to generate a random number that falls in the range 50 to 100 and -50 to -100 I am now using the following formula to achieve this:

(50 + (rand() % 50)) * ((rand() % 2) * 2 - 1)


(50 + (rand() % 50)) gives me a random number in the range 50 to 100 and 
((rand() % 2) * 2 - 1) gives me +/- 1

I used two random generation calls, but Is it possible using just 1 random function call ? Are there any other better alternatives to the above formula ?

share|cite|improve this question

Assuming rand() gives a random on $(0,1)$, you can use x=rand(), if x < 0.5, y=100x-100, else y=100x

share|cite|improve this answer

I assume you want a integer random number in $[-100,-50] \cup [50,100]$. I also assume that the function rand() gives a random integer in the range $[0,\text{RANDMAX}]$, where $\text{RANDMAX}$ is a large integer constant.

Get a random number in the interval [0,101] i.e. a = rand()%102
If (a<=50) return a-100
Else return a-1
share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.