Sub topic 11
Simulating Feedback Loops in Code
Assume you know the difference between a stock, a flow, and a feedback loop. You should also be comfortable with percentages and basic Python. The goal here is to turn a loop into a small simulation, inspect its behavior, and tune its parameters.
The simulation pattern
A simulation repeats the same update rule over several time steps. A time step might represent a turn, lap, day, or combat round.
Each step has three parts:
- Read the current stock.
- Calculate the flow caused by the current state.
- Add the flow to the stock and record the result.
A reinforcing loop uses the current stock to create more growth. For example, a player's income could equal 10% of their current gold.
def reinforcing(turns, rate=0.10, start=10.0):
gold = start
history = [gold]
for _ in range(turns):
gold += rate * gold
history.append(gold)
return history
print(reinforcing(5))The output is:
[10.0, 11.0, 12.1, 13.31, 14.641, 16.1051]The increase becomes larger because the stock becomes larger. This is exponential growth. In a game, the same pattern can model interest on stored resources, stronger units earning more rewards, or a leader gaining better objectives.
Simulating a balancing loop
A balancing loop moves a stock toward a target. The flow depends on the gap between the current value and that target.
def balancing(turns, target=100.0, strength=0.25, start=20.0):
health = start
history = [health]
for _ in range(turns):
health += strength * (target - health)
history.append(health)
return history
print(balancing(5))The correction is large when health is far from 100 and small when health is close to 100. The values approach the target without reaching it immediately.
| Parameter | Meaning | Larger value usually causes |
|---|---|---|
| `turns` | Number of updates | A longer view of the outcome |
| `rate` | Reinforcing growth per step | Faster snowballing |
| `target` | Desired balancing level | A different final level |
| `strength` | Fraction of the gap corrected | Faster recovery or catch-up |
Comparing competing loops
Real mechanics often contain both loop types. The next example gives each player 10% growth, then gives the player behind a catch-up bonus.
def final_gap(rounds, catch_up):
scores = [12.0, 10.0]
for _ in range(rounds):
leader = max(scores)
scores = [
score + 0.10 * score + catch_up * (leader - score)
for score in scores
]
return scores[0] - scores[1]
for catch_up in (0.0, 0.1, 0.3):
print(catch_up, round(final_gap(10, catch_up), 2))With no catch-up, the reinforcing loop widens the gap. A catch-up value of 0.1 offsets that growth. A stronger value may reverse the advantage and make the former leader fall behind.
Exercise
Exercise
In the balancing function, what happens if strength changes from 0.25 to 1.0?
Show answer
Each update corrects the entire gap, so the stock reaches the target in one step and stays there.