code_arithmetique.py 1.98 KB
 Pierre-antoine Comby committed Feb 04, 2019 1 2 3 4 ``````#!/usr/bin/env python3 import numpy as np `````` Pierre-antoine Comby committed Mar 01, 2019 5 6 ``````N=10 p = 0.2 `````` Pierre-antoine Comby committed Feb 04, 2019 7 ``````P = np.random.rand(N) `````` Pierre-antoine Comby committed Mar 01, 2019 8 9 10 11 ``````X = np.zeros(N,dtype='int') for i in range(N): if P[i] > p: X[i] = 1 `````` Pierre-antoine Comby committed Feb 04, 2019 12 `````` `````` Pierre-antoine Comby committed Mar 01, 2019 13 14 ``````X=[0,1,0,0,1,0,0,0,0,0] print(X) `````` Pierre-antoine Comby committed Feb 04, 2019 15 `````` `````` Pierre-antoine Comby committed Mar 01, 2019 16 ``````def binary(n,m,b=2): `````` Pierre-antoine Comby committed Feb 04, 2019 17 18 19 `````` """ Convertie un nombre décimal en sa version binaire tronqué à m bits. """ `````` Pierre-antoine Comby committed Mar 01, 2019 20 21 22 `````` binaire= np.floor(n*b**m) # on se décale dans les entiers et on floor return binaire,np.binary_repr(int(binaire)) `````` Pierre-antoine Comby committed Feb 04, 2019 23 `````` `````` Pierre-antoine Comby committed Mar 01, 2019 24 ``````def arithm(X,p): `````` Pierre-antoine Comby committed Feb 04, 2019 25 26 27 28 `````` l=[0] h= [1] for x in X: if x == 0: `````` Pierre-antoine Comby committed Mar 01, 2019 29 `````` h.append(l[-1]+p*(h[-1]-l[-1])) `````` Pierre-antoine Comby committed Feb 04, 2019 30 31 `````` l.append(l[-1]) else: `````` Pierre-antoine Comby committed Mar 01, 2019 32 `````` l.append(l[-1]+p*(h[-1]-l[-1])) `````` Pierre-antoine Comby committed Feb 04, 2019 33 34 35 `````` h.append(h[-1]) lmb = (l[-1]+h[-1])/2 `````` Pierre-antoine Comby committed Mar 01, 2019 36 `````` `````` Pierre-antoine Comby committed Feb 04, 2019 37 `````` mu = int(-np.log2(h[-1]-l[-1]))+1 `````` Pierre-antoine Comby committed Mar 01, 2019 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 `````` code = binary(lmb,mu) return code,lmb,mu def arithm_pratique(X,p): l = [0] # borne inférieur h =[1] # borne supérieur f = 0 # follow c =[] # code for k in range(len(X)): print("for loop") if X[k] == 0: l.append(l[-1]) h.append(l[-1]+p*(h[-1]-l[-1])) else: l.append(l[-1]+p*(h[-1]-l[-1])) h.append(h[-1]) print(X[k]) print(l[-3:]) print(h[-3:]) while ((l[-1]>=0 and h[-1]<0.5) or (l[-1]>=0.5 and h[-1]<1) or (l[-1]>= 0.25 and h[-1]<0.75)): print(" loop") if (l[-1]>=0 and h[-1]<0.5): print(" case 1") c += [0]+[1]*f l[-1] *=2 h[-1] *=2 elif (l[-1]>=0.5 and h[-1]<1): print(" case 2") c += [1]+[0]*f l[-1] = 2*l[-1]-1 h[-1] = 2*h[-1]-1 elif (l[-1]>= 0.25 and h[-1]<0.75): print(" case 3") f +=1 l[-1] = 2*l[-1]-0.5 h[-1] = 2*h[-1]-0.5 return c #print(arithm(X,p)) print(arithm_pratique(X,p))``````