mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-23 08:51:31 -04:00
bitwise scripts fixed
This commit is contained in:
parent
01703751f1
commit
91825867f6
25 changed files with 96 additions and 335 deletions
37
src/bitwise/get_float_rep_bin.py
Executable file
37
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