Sharedsage_worksheets / ternary.sageOpen in CoCalc
Author: Ken Levasseur
Description: Worksheets related to Applied Discrete Structures
1def b_div_by_3(n):
2    if n%3==2:
3        return (n//3)+1
4    else:
5        return n//3
6
7def b_mod_3(n):
8    if n%3==2:
9        return -1
10    else:
11        return n%3
12
13def tern(n):
14    if n==0:
15        return [0]
16    elif abs(n)==1:
17        return [n]
18    else:
19        return [b_mod_3(n)]+tern(b_div_by_3(n))
20
21def tern_powers(n):
22    t=tern(n)
23    l=len(t)
24    return [[3^(k) for k in range(len(t))],t]
25
26from sage.plot.polygon import Polygon
27
28def visual_tern(n):
29    dat=tern_powers(n)
30    exp=1/2
31    w=2*abs(n)^exp
32    pic=Graphics()
33    nb=0
34    pb=0
35    nbase=[]
36    pbase=[]
37    for k in reversed(range(len(dat[0]))):
38        if dat[1][k]>0:
39            pbase=pbase+[dat[0][k]]
40            s=dat[0][k]^exp.n()
41            pic+=polygon([(w-s,pb),(w+s,pb),(w+s,pb+s),(w-s,pb+s)])
42            pic+=text(str(dat[0][k]),(w,pb+s/2),color='yellow')
43            pb+=s
44        elif dat[1][k]<0:
45            nbase=nbase+[dat[0][k]]
46            s=dat[0][k]^exp.n()
47            pic+=polygon([(-w+s,nb),(-w-s,nb),(-w-s,nb+s),(-w+s,nb+s)])
48            pic+=text(str(dat[0][k]),(-w,nb+s/2),color='yellow')
49            nb+=s
50    if n>0:
51        s=n^exp
52        pic+=polygon([(-w+s,nb),(-w-s,nb),(-w-s,nb+s),(-w+s,nb+s)],color='black')
53        pic+=text(str(n),(-w,nb+s/2),color='red')
54    else:
55        s=(-n)^exp
56        pic+=polygon([(w+s,pb),(w-s,pb),(w-s,pb+s),(w+s,pb+s)],color='black')
57        pic+=text(str(n),(w,pb+s/2),color='red')
58    pic+=line([(-2*w,0),(2*w,0)],color='black')
59    pic+=polygon([(0,0),(w/4,-w/4),(-w/4,-w/4)],color='red')
60    pic+=text(str(n)+" = sum("+str(pbase)+")-sum("+str(nbase)+")",(0,-(abs(n)^exp)))
61    pic.show(axes=False)