Randomness and simulation · Aleatoriedad y simulación
What we'll do
- Some programs need chance, like games or experiments.
- Python can make random numbers for us.
- We will also build a tiny simulation (a model of something real).
Qué haremos
- Algunos programas necesitan azar, como juegos o experimentos.
- Python puede generar números aleatorios por nosotros.
- También construiremos una pequeña simulación (un modelo de algo real).
Import random
- The random tools live in a module named
random. - Write
import randomat the top of your program. - Then you can use its functions, like
random.randint.
Importar random
- Las herramientas aleatorias viven en un módulo llamado
random. - Escribe
import randomal principio de tu programa. - Luego puedes usar sus funciones, como
random.randint.
import random
number = random.randint(1, 6)
print(number)
random.randint(a, b)
random.randint(a, b)gives a whole number fromatob.- Both ends are included:
randint(1, 6)can be1,6, or anything between. - Run it again and you may get a different number.
random.randint(a, b)
random.randint(a, b)devuelve un número entero entreayb.- Ambos extremos están incluidos:
randint(1, 6)puede ser1,6o cualquier número intermedio. - Si lo ejecutas de nuevo, es posible que obtengas un número diferente.
import random
for i in range(3):
print(random.randint(1, 6))
Same numbers with a seed
- A seed sets the random start point.
- With the same seed, you get the same numbers every time.
- This is useful for testing, so results can be repeated.
Números iguales con semilla
- Una semilla establece el punto de inicio aleatorio.
- Con la misma semilla, obtienes los mismos números cada vez.
- Esto es útil para probar código, para que los resultados sean reproducibles.
import random
random.seed(42)
print(random.randint(1, 6))
print(random.randint(1, 6))
A tiny simulation
- A simulation models a real process with code.
- Here we model flipping a coin many times and counting heads.
- Running many trials helps us see the long-run pattern.
Una pequeña simulación
- Una simulación modela un proceso real mediante código.
- Aquí modelamos lanzar una moneda muchas veces y contar las caras.
- Ejecutar muchas pruebas nos ayuda a observar el patrón a largo plazo.
import random
random.seed(1)
heads = 0
for i in range(10):
flip = random.randint(0, 1) # 0 = tails, 1 = heads
if flip == 1:
heads = heads + 1
print(heads)
In AP CSP pseudocode
- The exam writes random numbers with
RANDOM. RANDOM(a, b)gives a whole number fromatob, the same idea asrandom.randint(a, b).
En pseudocódigo AP CSP
- El examen escribe números aleatorios usando
RANDOM. RANDOM(a, b)devuelve un número entero entreayb, la misma idea querandom.randint(a, b).
roll ← RANDOM(1, 6)
DISPLAY(roll)
Common mistakes
- A simulation uses random values to model chance.
- Run it many times to see the overall pattern.
Errores comunes
- Una simulación usa valores aleatorios para modelar el azar.
- Ejecútalo muchas veces para ver el patrón general.
Now you try
- Some tasks check a property (like "the roll is between 1 and 6").
- Some tasks use a seed so the output is the same every time.
- Press Check answer to test your code.
Ahora tú prueba
- Algunas tareas verifican una propiedad (como "el lanzamiento está entre 1 y 6").
- Algunas tareas usan una semilla para que la salida sea la misma cada vez.
- Presiona Check answer para probar tu código.
Write roll_die() (no parameters) that returns · retornos a random whole number from 1 to 6 using random.randint. Remember import random. · Escribe roll_die() (sin parámetros) que devuelva un número entero aleatorio entre 1 y 6 usando random.randint. Recuerda import random.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write roll_two() that rolls two dice (each 1 to 6) and returns · retornos their total. The total is always between 2 and 12. · Escribe roll_two() que lance dos dados (cada uno del 1 al 6) y devuelva su suma. La suma siempre estará entre 2 y 12.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Copy this exactly: set random.seed(7), then flip a coin 20 times with random.randint(0, 1) (1 means heads), count the heads, and print the count. With this seed the answer is always the same. · Copia esto exactamente: establece random.seed(7), luego lanza una moneda 20 veces con random.randint(0, 1) (1 significa cara), cuenta las caras y haz print del recuento. Con esta semilla la respuesta siempre es la misma.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.