Generating a random number

Just a quick bit of help needed for a big project I'm working on. Does anybody know about making a random number that is either '1' or '-1'? I ask because if I just do it in a range like usual, that will also include '0'. I want to randomly make either a '1' or '-1'. Any help would be much appreciated!
pow(-1, rand() %100); (or c++ random here, same idea, less code to xplain)

or you can do it yourself.

if (rand()%2)
value *=-1;

or

int t[] = {-1,1};
value = t[rand()%2];

the last one is the fastest and more easily generalized to various problems, so its probably the best. The first 2 are just for fun.

Last edited on
What is the 'pow' for?
its power
like 2*2*2
is pow(2,3);

-1*-1 = 1
-1*-1*-1 = -1
...
its horribly inefficient even with the % 100 ... its the snarky answer, really, like swapping 2 numbers with xor. Pow doesn't do it with multiplies so the % 100 isn't doing anything except capping rand to a percentage or something easy to observe. Pow runs the series, but its enabled for floating point exponents so it does a bunch of pointless work to come up with the answer.


Last edited on
1
2
3
4
5
6
# include <random>
...
std::mt19937 gen(std::random_device{}());
std::bernoulli_distribution d{0.5};

int const plus_minus = d(gen)? 1: -1;
Topic archived. No new replies allowed.