Outrun a wild boar with the power of OCaml (Part 2)

February 25, 2018

This is part 2 of the boar series. (See Part 1)

Let’s observe two facts:

  • At any time, the boar will be running directly towards the farmer’s current position.
  • The boar’s speed is constant throughout its path.

Those facts, plus the initial positions of the farmer and boar are all we need to solve the problem!

Figure 2

The first fact tells us that the vector that describes the boar’s velocity will always be pointing towards the farmer’s current positon. This means that the velocity vector we’re looking for will be in the direction of the difference between the farmer’s position and the boar’s position:

$$v = farmer(t) - boar(t)$$

This vector is directionally correct, but its magnitude needs to be adjusted so that the speed is always constant. To do that, we need to first normalize the vector (scale it so its length is 1):

$$v = \frac{1}{||farmer(t) - boar(t)||} (farmer(t) - boar(t))$$

And then scale that normalized vector by the actual speed (a constant):

$$v = \frac{speed}{||farmer(t) - boar(t)||} (farmer(t) - boar(t))$$

This velocity vector for the boar is the first derivative of the boar’s position. So let’s rewrite the equation like this:

$$boar’(t) = \frac{speed}{|| farmer(t) - boar(t) ||} (farmer(t) - boar(t)) $$

Now we have a single differential equation that models our problem! If we can just solve for \(boar(t)\), we will be able determine the exact path the boar will take for any given speed!

There are ways to solve this problem symbolically, but we’re going to solve it numerically with OCaml.

But first let’s write our the differential equation above in OCaml, using the custom vector operators we created in part 1:

let boarVelocity (boarSpeed: float) (boarPos: Vector2.t) (t: float) =
    (boarSpeed /. (Vector2.norm ((farmerPos t) %- boarPos))) 
      %* (farmerPos t %- boarPos)

This function accepts three parameters: the boar’s speed (a constant), the boar’s current position (a vector), and the current time (a float). It returns a vector.


Kyle MathewsWritten by Brooks Noble, a web developer building complex web apps using functional programming techniques.