mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
reorganize dir
Signed-off-by: Mia Steinkirch <mia.steinkirch@gmail.com>
This commit is contained in:
parent
1b6f705e7c
commit
a8e71c50db
276 changed files with 23954 additions and 0 deletions
37
ebook_src/bitwise/get_float_rep_bin.py
Executable file
37
ebook_src/bitwise/get_float_rep_bin.py
Executable file
|
@ -0,0 +1,37 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' Given a real number between 0 and 1 (eg: 0.72), this method print the binary
|
||||
representation. If the Number cannot be represented accurately in binary, with at
|
||||
most 32 chars, print error:
|
||||
'''
|
||||
|
||||
def get_float_rep(num):
|
||||
'''
|
||||
>>> get_float_rep(0.72)
|
||||
('Error 2', '.1011100001010001111010111000010')
|
||||
>>> get_float_rep(0.1)
|
||||
('Error 2', '.0001100110011001100110011001100')
|
||||
>>> get_float_rep(0.5)
|
||||
'.1'
|
||||
'''
|
||||
|
||||
if num >= 1 or num <= 0: return 'Error 1'
|
||||
result = '.'
|
||||
while num:
|
||||
if len(result) >= 32: return 'Error 2', result
|
||||
r = num*2
|
||||
if r >= 1:
|
||||
result += '1'
|
||||
num = r - 1
|
||||
else:
|
||||
result += '0'
|
||||
num = r
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue