# 7 Etudes, Op. 2: Musical Math

Example 7-1. Converting metric proportion into time in seconds.

```(define (bpm->seconds bpm)
(/ 60.0 bpm))

(define (rhythm->seconds rhy tempo)
(* rhy 4.0 (bpm->seconds tempo)))
```

Interaction 7-1. Using the rhythm->seconds function.

```cm> (rhythm->seconds 1/4 60)
1.0
cm> (rhythm->seconds 1/2 120)
1.0
cm> (rhythm->seconds 1/8 90)
0.3333333333333333
cm>```

Interaction 7-2. Calculating octaves as powers of 2.

```cm> (expt 2 -2)
.25
cm> (expt 2 -1)
.5
cm> (expt 2 0)
1
cm> (expt 2 1)
2
cm> (expt 2 2)
4
cm>```

Interaction 7-3. Exponentiation.

```cm> (expt 2 0)
1
cm> (expt 2 1)
2
cm> (expt 2 1/2)
1.4142135623730951
cm> (expt 2 1/12)
1.0594630943592953
cm> (expt 2 -3/24)
0.9170040432046712
cm>```

Example 7-2. Scaling Hertz frequency values by equal tempered amounts.

```(define (scale-hz hz mul)
(* hz (expt 2 mul)))
```

Interaction 7-4. Calculating Hertz values with scale-hz.

```cm> (scale-hz 440 1)
880
cm> (scale-hz 440 -2)
110
cm> (scale-hz 440 1/24)
452.8929841231365
cm>```

Example 7-3. Converting MIDI key numbers to Hertz frequency.

```(define lowest-freq 8.175)

(define (keynum->hertz knum)
(* lowest-freq (expt 2 (/ knum 12))))
```

Interaction 7-5. Converting MIDI key numbers to Hertz equivalents.

```cm> (keynum->hertz 60)
261.6255653005986
cm> (keynum->hertz 69)
439.99999999999994
cm>```

Example 7-4. A version of keynum->hertz based on A.

```(define lowest-freq 6.875)

(define (keynum->hertz knum)
(* lowest-freq (expt 2 (/ (+ knum 3) 12))))
```

Interaction 7-6. Converting MIDI key numbers to Hertz equivalents.

```cm> (keynum->hertz 60)
261.6255653005986
cm> (keynum->hertz 69)
440.0
cm>```

Example 7-5. Random selection between a low and high bounds.

```(define (pick-range low high)
(let ((rng (- high low)))
(if (> rng 0)
(+ low (random rng))
0)))
```

Interaction 7-7. Examples of pick-range.

```cm> (pick-range 60 100)
96
cm> (pick-range -1.0 1.0)
-0.697347603174574
cm> (pick-range 440 880)
789
cm>```

Example 7-6. Random selection from a list of values.

```(define (pick-list lst)
(let* ((len (length lst))
(pos (random len)))
(list-ref lst pos)))
```

Interaction 7-8. Examples of pick-list.

```cm> (define aeolian-mode
'(57 59 60 62 64 65 67
69 71 72 74 3 77 79 81))

cm> (pick-list aeolian-mode)
62
cm> (pick-list aeolian-mode)
79
cm> (pick-list aeolian-mode)
71
cm> (pick-list '(1/16 1/8 1/8 1/4))
1/4
cm>```

Example 7-7. Random selection from a list of values.

```(define (chance? prob)
(< (random 1.0) prob))
```

Interaction 7-9. Examples of chance?

```cm> (chance? 0)
#f
cm> (chance? 1)
#t
cm> (chance? .75)
#t
cm> (if (chance? .8) 'retrograde 'prime)