bdf_pi(n) calcule le nombre π avec n chiffres significatifs (et donc n - 1 décimales). Pour l’afficher sur plusieurs lignes, utiliser demo(0) pour l’écran graphique, demo(1) pour la console en grande police, demo(1, 0) pour la console en petite police.
from kandinsky import draw_string def bdf_new(d0, nd): bdf = bytes((d0,)) + bytes(nd - 1) return bdf def bdf_add(bdf1, bdf2): c = 0 bdfr = b'' for i in range(len(bdf1) - 1, -1, -1): v = bdf1[i] + bdf2[i] + c if i: c = v >= 10 if c: v -= 10 bdfr = bytes((v,)) + bdfr return bdfr def bdf_sub(bdf1, bdf2): c = 0 bdfr = b'' for i in range(len(bdf1) - 1, -1, -1): v = bdf1[i] - bdf2[i] - c if i: c = v < 0 if c: v += 10 bdfr = bytes((v,)) + bdfr return bdfr def bdf_times(bdf, k): c = 0 bdfr = b'' for i in range(len(bdf) - 1, -1, -1): v = k*bdf[i] + c if i: c = v // 10 if c: v -= 10 * c bdfr = bytes((v,)) + bdfr return bdfr def bdf_div(bdf, k): c = 0 bdfr = b'' for i in range(len(bdf)): x = 10*c + bdf[i] c = x % k bdfr += bytes((x // k,)) return bdfr def bdf_ataninv(d, n): bdf0 = bdf_new(0, n) bdf1 = bdf_new(1, n) k1 = d k2 = 1 d2 = d ** 2 bdfr = bdf0 bdfd = bdf_div(bdf1, k1) while bdfd != bdf0: if k2 % 4 == 3: bdfr = bdf_sub(bdfr, bdfd) else: bdfr = bdf_add(bdfr, bdfd) k1 *= d2 k2 += 2 bdfd = bdf_div(bdf1, k1 * k2) return bdfr def bdf_pi(n): return bdf_times(bdf_sub(bdf_times(bdf_ataninv(5, n), 4), bdf_ataninv(239, n)), 4) def print_bdf(bdf, l): s = str(bdf[0]) + '.' for d in bdf[1:]: if len(s) == l: print(s) s = '' s += str(d) if len(s): print(s) def draw_bdf(bdf, l): y = -3 s = str(bdf[0]) + '.' for d in bdf[1:]: if len(s) == l: draw_string(s, 0, y) s = '' y += 14 s += str(d) if len(s): draw_string(s, 0, y) def demo(shell=True, big=True): if shell: bdfpi = bdf_pi(big and 359 or 687) print_bdf(bdfpi, big and 30 or 43) else: bdfpi = bdf_pi(511) draw_bdf(bdfpi, 32) # shell in big font demo(1, 1) # graphic (big font) #demo(0) # shell in small font #demo(1, 0)