Skip to content

Instantly share code, notes, and snippets.

@thormagnusson
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thormagnusson/cfad621924864b8c4bc3 to your computer and use it in GitHub Desktop.
Save thormagnusson/cfad621924864b8c4bc3 to your computer and use it in GitHub Desktop.
Recursive Rational Number Algorithm in SuperCollider
// version 1 - didn't work well on numbers such as 1.0666666666667
// a recursive algorithm for finding the Rational Number from a floating point ratio
a = { arg ratio=1, num=1, den=1, oldnum=1;
var max = 1000;
ratio = ratio.value;
num = num+1;
if(num == max, {num = oldnum; oldnum = oldnum+1; den = den+1; });
if(ratio != (num/den), {
if(den >= max, {
"--> No rational number found".postln;
nil
}, {
thisFunction.(ratio,num,den)
})
}, {
"--> The rational number is : ".post; num.asString +/+ den.asString;
});
}
a.(1.2)
b = Tuning.just.ratios[2].round(0.000001)
Tuning.just.ratios.round(0.01).collect({arg ratio; a.(ratio)})
// not good:
a.(1.0666666666667)
// version 2 - using the .asFraction method of SimpleNumber
a = {arg ratio;
var fraction = ratio.asFraction;
(fraction[0].asString +/+ fraction[1].asString)
}
// better
a.(1.0666666666667)
b = Tuning.just.ratios.collect({arg ratio; a.(ratio)})
b.asString.interpret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment