Since I missed this on the Internet, here is my own implementation in Pari / GP -
{balanced_ternary(x,maxdigits=20,chars=["y","0","1"])=my(res,st,dez,dig);
dez=floor(log(abs(2*x))/log(3));
res=x/3^dez;
st="";
for(k=0,maxdigits,
if(k==dez+1,st=Str(st,"."));
dig = if(res>1/2
,res--;chars[2+1]
,if(res<-1/2
,res++;chars[2-1]
,chars[2+0]
));
st=Str(st,dig);res*=3
);
return(st);}
Then
balancedternary (1) \\ %1002 = "1.00000000000000000000"
balancedternary (-1) \\ %1003 = "y.00000000000000000000"
balancedternary (1.2) \\ %1004 = "1.1yy11yy11yy11yy11yy1"
balancedternary (-1.2) \\ %1005 = "y.y11yy11yy11yy11yy11y"
balancedternary (27-3) \\ %1006 = "10y0.00000000000000000"
balancedternary (400) \\ %1007 = "1yy0y11.00000000000000"
balancedternary (sqrt(3)) \\ %1008 = "1y.y1yy10y0000yy1100y0"
balancedternary (sqrt(3)/3) \\ %1009 = "1.yy1yy10y0000yy1100y0"
Just q & d, not all "special cases" are marked / encoded.
source
share