# Generating a random vector with elements in specified range

I would like to generate a random vector in which its elements are between 0 and 1 (including 0 and 1). As far as I know, v = random_matrix(ZZ, 1, 10) is a way to generate a random matrix. How would I restrict the elements to the range I want?

I am trying to build a function with a probability input, and then compare the probability to each of the elements separately in the random vector.

edit retag close merge delete

Sort by ยป oldest newest most voted

This returns such a random vector of a given size. However, note that its elements belong to the semi-open interval $\left[0~1\right)\subset\mathbb{R}$, not the closed interval $\left[0~1\right]\subset\mathbb{R}$ :

sage: def randvect(size=4):return vector([random() for t in range(size)])
sage: randvect(3)
(0.8688082291795581, 0.28209569121849476, 0.3112164215493163)


HTH,

more

@Emmanuel Charpentier: I really need it to be a closed interval though. This is the beginning of a function for a Monte Carlo simulation. I need to know when the input (which is a probability) is less than one.

( 2018-04-26 02:51:16 +0100 )edit
1

Well.. $\Pr\left(X=1|X\in\left[0~1\right]\right)=0$, anyway, unless you are able to state some value $p$ such as $\Pr\left(X=1\right)=p$, in which case, it is trivial to extract your components from a mixture of $\delta(x-1)$ with weight $p$ and the $\mathrm{U}\left[O~1\right)$ (used above) with weight $1-p$. What difference does it do if you are simulating ?

( 2018-04-26 19:04:36 +0100 )edit

And, by the way, what are you simulating ? Shouldn't you specify a bit more the (joint) law of your components ?

( 2018-04-26 19:12:18 +0100 )edit