# How does one get Sage to make random choices?

Like say in the middle of a code I compute a function value $f(x)$ and I knwo that $0 \leq f(x) \leq 1$. Now I want to write an if-then-else which will do one option with probability $f(x)$ and the other otion with probability $1-f(x)$. How does one make Sage do this?

Can somoen kindly show a template example to simulate this?

edit retag close merge delete

Sort by » oldest newest most voted

This question looks like homework, so it could be nice to tell us where is the point you are stuck. Here are some hints: if you want to pick a number between 0 and 1 uniformly at random, just use the random() function:

sage: random()
0.49232726718735065


Now, what you have to do is to compare this value to f(x). For this, you have to know that Sage uses the Python programming language, so you can look for tutorials about "if statement" in Python.

Please tell us if you encounter difficulties (and do not hesitate to post your code and where it does not work), so that we can help further.

more

@tmonteil I don't know in what kind of a course can this be a homework :D I am a researcher who recently started using Python and Sage for my research! Back to the question : I don't understand what you are saying. Roughly I would think that one needs to simulate a coin toss where heads come with probability $f(x)$. How is that equivalent to comparing $f(x)$ to a randomly generated number in the interval $[0,1]$ ? (If the two options are $a$ and $b$ then say I want to choose $a$ with a probability $f(x)$ and $b$ with a probability $1-f(x)$ and then I guess you mean that this is equivalent to choosing $a$ if the random number is (greater? or lesser?) then $f(x)$ or else otherwise?) I am not getting you.

Yes, i mean that the following are equivalent:

• to choose a with probability f(x) and b otherwise (hence with probability 1-f(x))
• to pick a random number y in [0,1] and choose a if y<f(x) and b if y>=f(x)

To get convinced, draw a picture of the interval [0,1] cut into two intervals [0,f(x)) and [f(x),1]: the first one has length f(x), the second has length 1-f(x). When you pick a random number y in [0,1] (according to Lebesgue measure), the probability that y belongs to [0,f(x)) is f(x) and the probability that y belongs to [f(x),1] is (1-f(x)) (indeed, on [0,1], the Lebesgue measure is nothing but the length).

If you are happy you can choose @tmonteil answer by clicking on the button "accept" on the left!