0

I've already completed this pset, but I'd like to improve my understanding of one part of it, so this is a maths question.

I'm using a for loop to calculate hz in relation to octave in the notation used in this pset, i.e. A4:

float keyHz = 27.5; // A0

// How to express this mathematically without a loop?
for (int i = 0; i < octave; i++)
{
    keyHz = keyHz * 2;
}

So starting with a known value of A0 of 27.5hz, A in the 4th octave would be

((((27.5 * 2) * 2) * 2) * 2) // 440hz

Are there other ways there to calculate this without the loop?

2

I used pow from math.h, like 440.0 * pow(2, semitones / 12.0);. semitones in this case would be the number of semitones relative to A4 (one octave being 12 semitones). It's important to have the 12.0 as floating point, since division of two integers is integer again, truncating the result (AKA rounding towards zero). The .0 at the 440 don't matter, as the number would be converted to floating point because pow returns one, so it's a floating point multiplication.

Edit:

As you want to use your approach with given frequencies for octave 0, you can use

keyHz *= 1 << octave;

The << operator shifts by a number of bits, and shifting by one bit essentially is (depending on direction) multiplication or division by two.

7
  • thanks for the pingback. I recognise that this is one approach to the pset, but I took a 0 based approach, where I know the hz of each note at octave 0, and so the hz of octave n is the base hz, multiplied by two for n octaves. So while your answer is one correct approach for the pset, it's not the question i've asked (which is about this particular math problem). As such, I really should downvote your answer.
    – orionrush
    Jul 10 '18 at 13:45
  • 1
    There you go. Bitshift operator << does that on integers.
    – Blauelf
    Jul 10 '18 at 15:09
  • Thanks for filling in this blank - it's not so much that I wanted to do one approach over another, it just that having gone down this particular route, I ran into this gap in my knowledge, and I knew that there was a more succinct solution!
    – orionrush
    Jul 10 '18 at 22:14
  • Just to clarify - this technique only works with division or multiplication by two? So mulplication by an aribitrary int n, isn’t possible with approach?
    – orionrush
    Jul 11 '18 at 0:20
  • 1
    Those are binary numbers, so shifting digits can only cover powers of two. Just like you would multiply/divide by 10 by moving the decimal point.
    – Blauelf
    Jul 11 '18 at 6:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .