Formation I.S.N.

Logarithme

Exercice : logarithme entier

Écrire une fonction python récursive :

Entrée Un réel \( x \in \left[1; +\infty\right[ \).
Sortie L'unique entier j tel que \( 2^j \leqslant x < 2^{j+1}\).
  • un code

from math import floor, log

def partieEntiereLog2(x, j = 0, p = 1) :
	if p >  x :
		return j-1
	else :
		return partieEntiereLog2(x, j+1 , p*2 )
		
		
# boucle de test de notre fonction :	
for x in (1, 1.2, 1.9, 2, 2.3, 3, 5, 6.9, 12.3) :
	print("Avec notre fonction récursive : {}.".format( partieEntiereLog2(x) )) 
	print("Avec les fonctions python : {}.".format( floor(log(x,2) ))) 
	print()