Logarithm of a 0<X<1

Hey there Arduino folks!
I'm trying to make some calculation in my sketch, (frequency to midi Note), it's an easy one, you can find the formula anywhere which is:
midiNote = round(12*log2(440/440))+69;

There's no logarithm of base 2 in Arduino, but you can easily write it:
float log2 (float x) {
return (log(x) / log(2));
}

This calculation works fine in Processing but not in Arduino, for any argument between 0 and 1 (which has to result a negative number) it just gaves me and infinite (or something similar, it's been a couple days since I last checked that).

What am I might be doing wrong??

Thanx!

Have you tried making log(2) a constant, and use that throughout your program?

const float LOG2 = 0.30102999566398119521373889472449;

Note: you may have to crop some decimal places there!

And then:

float log2 (float x) {
return (log(x) / LOG2);
}

That will not only make your program a lot faster (because log(2) doesn't ever need to be calculated), but it will ease the burden on the Arduino.

round(12*log2(440/440))+69;

That will only ever produce the value 69. If you try, for example,

round(12*log2(220/440))+69;

The value of 220/440 is zero because it is an integer division. You should use this:

round(12*log2(frequency/440.))+69;

which forces the division to be done with floating point.

Pete

Natural log is the area under the curve 1/x from 1 to the number whose log you are trying to find. Always from 1. There is no natural log for less than 1.

There is no natural log for less than 1.

There certainly is. The log (natural or not) of a number is defined for any real number above zero. Numbers between zero and one have a negative log.

Pete

el_supremo; THAT was certainly THE POINT! :sweat_smile:
Thanx so much! (now it works nice!)

el_supremo:

There is no natural log for less than 1.

There certainly is. The log (natural or not) of a number is defined for any real number above zero. Numbers between zero and one have a negative log.

Pete

I don't remember doing that but I guess you could integrate left-wise, it's just a matter of ordering the limits. It's been a while since I did the math.