function y=ternary(x,n) %Returns the first n digits of the ternary expansion of x, %where it is assumed that 0<=x<=1 currentbase=3; for j=1:n if x< (1/currentbase) y(j)=0 elseif x<(2/currentbase) y(j)=1 else y(j)=2 end x=x-(y(j)/currentbase); currentbase=currentbase*3; end