The Sound of Maths 1 – Prime Numbers

Have you ever wondered what the first 500 prime numbers sound like? (Of course you have). Well, wonder no longer, as with the help of Python, it’s easy to find out!

The is no known pattern to the primes, a fact which has tantalized mathematicians since ancient times, since there are nonetheless hints of pattern – a kind of ordered chaos is you will. For example, in the sound clip above, can you hear how the higher notes (representing prime numbers) frequently come in pairs? These are known as twin primes.

What else do you notice when you listen to the track?

The track was made using Jython Music which is a completely free, open source project that makes exploring sound with Python easy and fun. You can also make music in your browser with Jython Music.

There is also a great book availabe that explores computer science through making music using Jython Music.

For those curious to try it themselves, download Jython Music (or use this link to an online version), open a new file, paste in the code below and hit play. Of course you can experiment by changing some of the values to see what happens. For example you can easily speed up/slow down the piece by adjusting the tempo value.

from music import *


def isprime(n):
    """Check if integer n is a prime."""
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
    # 2 is the only even prime number
    if n == 2:
        return True
    # all other even numbers are not primes
    if not n & 1:
        return False
    # range starts with 3 and only needs to go up the squareroot of n
    # for all odd numbers
    for x in range(3, int(n ** 0.5) + 1, 2):
        if n % x == 0:
            return False
    return True


# create lists of pitches and durations
pitches1 = []
durations1 = []
for n in range(500):
    if isprime(n):
        pitches1.append(67)
        durations1.append(0.1)
    else:
        pitches1.append(60)
        durations1.append(0.1)

# create an empty phrase, and construct piece using pitch/rhythm data
piece = Phrase()
piece.addNoteList(pitches1, durations1)

# set the instrument and tempo for the piece
piece.setInstrument(35)
piece.setTempo(60)

# play it
Play.midi(piece)

Have fun!

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *