Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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)

where

(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|improve this question

2 Answers 2

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

share|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|improve this answer

Your Answer

 
discard

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.