Listening to my off-by-one error

:: Pi, Sonic-Pi

I was just writing an example for a Sonic Pi demonstration, and thought I’d show looping. But I got it wrong; and when I heard the results, it was totally obvious. This struck me as an example of where visualising code as sound can be a powerful learning tool.

To demonstrate loops, I thought I’d bounce between two notes, with an interval which got less by one each time round the loop, and so I wrote this…

# Welcome to Sonic Pi v2.0
use_synth :beep
use_bpm 120
an_octave = 12
interval = an_octave
loop do
  play 60
  sleep 1
  play 60 - interval
  sleep 1
  if (interval >= 0) then
    interval -= 1

The loop test checks for interval >= 0 before decrementing the interval. So when I ran it, this was the result.

Something’s wrong: instead of ending with the second tone the same pitch as the first, it’s higher—a classic ‛off-by-one’ error, of the sort which has been the cause of many computing woes, including security breaches. And it’s an easy fix to change the test to interval > 0 , but the immediacy of the way in which the sound highlighted the problem was very surprising. (And I wished I’d had such a guide in the innumerable times I’ve been caught out by such errors in the past :-)