Ratio to binary sequence

Hello all,

how would be the easiest way to convert a ratio to a binary sequence of 0/1 as in: 3/2 = [1,1,1,0,0]?

Many thanks!
Jan

Probably start with asFraction.

Btw the help for this method seems to be incorrect: “an array of denominator and divisor of the nearest and smallest fraction” but the denominator is the divisor. I suppose it should say “an array of the numerator and denominator…”

hjh

Could you be precise? In SuperCollider when you evaluate a ratio like 3/2 it gives a float number such as 1.5 in that case. What you can do is to convert your ratio to an Array, then [2,3].collect{|it,i| i!it}.flat.reverse
or
(3/2).asFraction.reverse.collect{|it,i| i!it}.flat.reverse

thanks @jamshark70 and @Yann_Ics for pointing out and the example, that looks like a totally workable solution for what im after! i just generally wondered whether there could be more direct methods for this kind of conversion to binary sequences.

I’m not sure what you mean by a more direct method – this is already as direct as it gets (apart from one bit of tidying up, below). You could package it into a function, or your own extension method.

The algorithm you’re proposing isn’t one that’s in common use, which leaves it pretty much up to you to package as you like.

I imagine the double-reverse isn’t necessary – (3/2).asFraction.collect{|it,i| i!it}.flat is more straightforward AFAICS.

hjh

:+1:
The double-reverse is necessary in order to get the expected result…
probably there is a more straightforward way to do it.

Oh, I see, because i is 0 first, then 1.

I’d probably have written (1 - i) ! it then.

hjh

thanks again to both! it’ll be neatly wrapped as extension:)