Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that do addition or subtraction randomly

I wonder if there is a function that can do addition or subtraction operator randomly:

x +- y
like image 684
Math Avatar asked Jan 10 '23 00:01

Math


1 Answers

The question boils down to getting -1 or 1 in random fashion. You can get it using sample:

x + sample(c(-1,1),size=1)*y

or runif:

x + sign(runif(n=1,min=-1,max=1))*y

If x and y are vectors, you can generate sequence of numbers -1 and 1 of the same length as the length of x, as @BondedDust suggested:

x + sample(c(-1,1),size=length(x),replace=T)*y
like image 157
Marat Talipov Avatar answered Jan 20 '23 18:01

Marat Talipov