Last active
August 29, 2015 14:04
-
-
Save thormagnusson/cfad621924864b8c4bc3 to your computer and use it in GitHub Desktop.
Recursive Rational Number Algorithm in SuperCollider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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