Dark theme

Data variables


So, how did you do with x?

Here's one solution:

import random

y0 = 50
x0 = 50

if random.random() < 0.5:
    y0 += 1
else:
    y0 -= 1

if random.random() < 0.5:
    x0 += 1
else:
    x0 -= 1

print(y0, x0)

Note that we can't do this:

if random.random() < 0.5:
    y0 += 1
    x0 += 1
else:
    y0 -= 1
    x0 -= 1

...efficient though it would be, as y0 and x0 either increase or decrease symultaneously; there's no option for one to go up while the other goes down.

Note also that if we just want to print string variables, we can put them as a comma separated list in print; this will put spaces between them. This includes anything that automatically casts to a string.


Ok, so that's got us moving y and x once. Copy the code that does this to immediately below itself, so you get a couple of steps (don't re-set the y0 and x0 to 50 though – leave this code at the top so it is only done once).

Make sure you can see that working.


Let's now make a second set of points to represent the position of a second agent. Copy all the code except the import, and place it well below the current code so you can see where it begins and ends. Change the variable names in the copied code to y1 and x1 and check it works

We need to change the variables in this copied code to y1 and x1: if we left them as y0 and x0 we'd be changing the original variables, and we want to compare them.


Lastly, let's add some code to work out the distance between the two sets of coordinates. This is a key element of ABM: agents need to know who is near them so they can decide whether or not to interact with other agents. After all the code (which currently makes two lots of spatial coordinates, and moves them twice each), build code to work out the Euclidian (straight-line) distance between them using Pythagoras' theorem.

To do this, you will need to look up in your notes the operator for raising something to a power, and remember that raising something to 0.5 is the same as the square root. The Pythagorian/Euclidian distance is calculated as the difference in the y-direction between two points, squared, added to the squared difference in the x-direction, all then square rooted. Remember you'll need to assign this to a variable to keep it and then print it, so at some point you'll need something like:

answer = somekindofmaths

Have a go at implementing this yourself.

Once you've done that, given the program is generating random numbers, print all the coordinates and the answer, and check it against a calculator to check it is working (can you think of a way we could make this easier?). Go to the final section to see one potential answer, and some other things we could do to our code.


  1. Agent-based models
  2. Components of a model
  3. Capturing a position in space
  4. Moving y and x
  5. This page
  6. Final ideas <-- next