Skip to content

Randomness and simulation

Python for AP CS Principles Lesson 10 2:02 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
Some programs need chance — games, experiments, models of the real world. 有些程序需要"随机"——游戏、实验、对真实世界的模型。
The random tools live in a module, so you write import random at the top. 随机工具放在一个模块里,所以你在开头写 import random。
Then randint of one and six rolls a die, and every time you run it you may get a different number. 然后 randint(1, 6) 就是掷一个骰子, 每跑一次你都可能得到不同的数字。
One detail matters for the exam: both ends are included, so a one and a six are just as possible as anything between. 有一个细节对考试很要紧:两端都是包含在内的, 所以 1 和 6 跟中间任何一个数一样有可能出现。
Which raises a problem: if the numbers change every run, how do you test the program? 这就带出一个问题: 如果每次跑出来的数字都不一样,你怎么测试这个程序?
The answer is a seed. 答案是"种子"。
A seed sets the random starting point, and with the same seed you get the same numbers every time. 种子设定随机的起点, 用同一个种子,你每次都会得到同样的数字。
Look at the third column — it is identical on every run. 看第三列——它每一次运行都一模一样。
That is not random being broken; it is random being controlled, so results can be repeated. 这不是随机坏掉了;这是随机被"控制"住了, 好让结果可以复现。
Now a simulation: a model of a real process, built out of those random values. 现在来做一个模拟: 用那些随机值搭出来的、对真实过程的模型。
Flip a coin many times, counting heads. 抛很多次硬币,数正面的次数。
At ten flips the answer looks nothing like a fair coin — thirty percent. 抛 10 次的时候,结果看上去完全不像一枚公平的硬币——30%。
Keep going. 继续抛。
At a hundred it is closer, and at a thousand it settles right by the halfway line. 100 次的时候接近了些,1000 次的时候就稳稳落在一半那条线旁边。
That is why a simulation runs many trials: only then does the long-run pattern appear. 这就是模拟要跑很多次的原因: 只有这样,长期的规律才会显现出来。
On the exam the same thing is written with RANDOM in capitals. 在考卷上,同样的东西写作大写的 RANDOM。
RANDOM of a and b gives a whole number from a to b, which is exactly randint — both ends included. RANDOM(a, b) 给出一个从 a 到 b 的整数, 跟 randint 完全一样——两端都包含在内。
Four things to take with you. 带走四点。
One: randint gives a whole number, both ends included. 第一:randint 给出一个整数,两端都包含。
Two: a seed makes a random run repeat exactly. 第二:种子让一次随机运行可以精确复现。
Three: a simulation models a real process with chance. 第三:模拟用随机来给真实过程建模。
Four: run many trials to see the long-run pattern. 第四:多跑几次,才看得见长期的规律。
Now build a simulation in the tasks below. 现在去下面的题里做一个模拟。

Log in or create account

IGCSE, A-Level & AP