basiswechsel.py 716 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. def euklid(b, Z):
  4. """
  5. Euclids algorithm to change the basis.
  6. Returns
  7. -------
  8. dict
  9. A dictionary mapping the i-th position of the new number to its value,
  10. where higher numbers are more significant.
  11. Examples
  12. --------
  13. >>> euklid(3, 5)
  14. {1: 1, 0: 2}
  15. """
  16. p = 0
  17. while b**p <= Z:
  18. p = p+1
  19. i = p - 1
  20. y = {}
  21. while Z != 0 and i > -5:
  22. y[i] = Z // b**i
  23. R = Z % b**i
  24. Z = R
  25. i = i - 1
  26. return y
  27. if __name__ == "__main__":
  28. r = euklid(16, 15741.233)
  29. print("Result:")
  30. for key in sorted(r.iterkeys(), reverse=True):
  31. print "%s: %s" % (key, r[key])