Source code for Mes_fctions_generales





  
    
[docs] def pxs_round(x, ndigits = 0): """ Fr : Description en français En : pxs_round() function works like the high school students' calculators. It is analogous to the python round() function, except that Round() don't use the round to even convention. For example: Round(0.125, 2) = 0.13 while round(0.125, 2) = 0.12 Round a number x to a given precision in decimal digits. The return value is an integer if ndigits is omitted or None or 0 or negative. Otherwise the return value is a floating point number. Version 1 : ------- 13/02/25 Vérification ------ Auteur : Jean-Luc Durand Vérificateurs : Joachim, Delphine, Ronan Paramètres ---------- x : float (to be rounded) ndigits : int positive, null or negative Valeur (numérique ou symbolique) de la puissance, 1 par défaut Retour ------ float retourne l'arrondi sous forme de float Fonction utilisée par --------------------- d????? à préciser """ #Début de la fonction import math # math.isclose() if ndigits == None: ndigits = 0 a = abs(x)*10**ndigits f = int(a) b = abs(x)*10**(ndigits+1) g = int(b) Delta = g - f*10 if ndigits <= 1: if Delta >= 5: result = (f + 1)/(10**ndigits) else: result = f/(10**ndigits) else : if Delta >= 5 or math.isclose(Delta, 5, rel_tol = 3*10**-11): result = (f + 1)/(10**ndigits) else: result = f/(10**ndigits) if ndigits <= 0 or type(x) == int: result = int(result) if x < 0: result = -result return result
# # ############################################################################################################# # # #### Début des essais ######## # # ############################################################################################################# # dig = 12 # ok from dig = 0 to dig = 5 # n = 100000 # ok for n = 100000 # i_err = list() # x_err = list() # for i in range(0, n): # a = 10*i + 5 # x = a/(10**(dig + 1)) # r = pxs_round(x, dig) # target = (a + 5)/(10**(dig + 1)) # expected rounding # if r != target: # i_err.append(i) # x_err.append(x) # print("x = ", x, '\n') # print("Approximation de ",x," est : ", r, '\n') # print("Number of errors: " + str(len(i_err)), '\n') # print("Error rate: " + str(100*len(i_err)/n) + ' %', '\n') # # pxsl_pow(3,2) retourne l'écriture latex de 3^{2} # x = 24.999992 # dig = 2 # A = pxs_round(x, dig) # print(f"{x} arrondi à {dig} chiffres après la virgule est : {A}", '\n') # y = 0.49999999 # digy = 7 # B = pxs_round(y, digy) # print(f"{y} arrondi à {digy} chiffres après la virgule est : {B}", '\n') # z = 0.429 # digz = 1 # C = pxs_round(z, digz) # print(f"{z} arrondi à {digz} chiffres après la virgule est : {C}", '\n') # # ############################################################################################################# # # #### Fin des essais ######## # # #############################################################################################################