|
| 1 | +''' chapter 42, Algorithm: Converting Positive Decimal Fractions Into Binary Fractions |
| 2 | +''' |
| 3 | + |
| 4 | +def dec_frac2bin_frac(dec_frac: float, num_bin_digits: int = 10) -> str: |
| 5 | + ''' Given a positive fractional float as input, |
| 6 | + returns its base-2 equivalent as a string. |
| 7 | + A second argument is the number of digits |
| 8 | + in the binary fraction. The default is 10 |
| 9 | + digits. |
| 10 | + -------- |
| 11 | + examples |
| 12 | + -------- |
| 13 | + >>>dec_frac2bin_frac(.75) |
| 14 | + '0.1100000000' |
| 15 | + >>>dec_frac2bin_frac(.1, 20) |
| 16 | + '0.00011001100110011001' |
| 17 | + ''' |
| 18 | + # garbage filters |
| 19 | + assert isinstance(dec_frac, float), \ |
| 20 | + "dec_frac must be a positive fraction." |
| 21 | + # if dec_frac is a positive fraction, |
| 22 | + # the subtraction below yields zero. |
| 23 | + # we assert dec_frac must be a positive fraction |
| 24 | + # so we coerce that zero to a bool (False), |
| 25 | + # and negate it to True. |
| 26 | + # Other differences evaluate as False. |
| 27 | + assert not dec_frac - (dec_frac % 1), \ |
| 28 | + "dec_frac must be a positive fraction." |
| 29 | + |
| 30 | + # implementation of algorithm |
| 31 | + # initialization |
| 32 | + running_sum, bin_frac = 0, '0.' |
| 33 | + |
| 34 | + # iterate through the positions of |
| 35 | + # the binary fraction. for each position, |
| 36 | + # calculate its base-10 value, then test |
| 37 | + # whether or not it contributes to the value |
| 38 | + # of the decimal fraction. |
| 39 | + for position in range(1, num_bin_digits+1): |
| 40 | + pos_value = 2**-(position) |
| 41 | + if (running_sum + pos_value) > dec_frac: |
| 42 | + # pos_value does NOT contribute |
| 43 | + # to decimal fraction |
| 44 | + bin_frac = bin_frac + '0' |
| 45 | + else: |
| 46 | + # pos_value contributes |
| 47 | + # to decimal fraction |
| 48 | + bin_frac = bin_frac + '1' |
| 49 | + # update running_sum |
| 50 | + running_sum = running_sum + pos_value |
| 51 | + |
| 52 | + return bin_frac |
0 commit comments