Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 19054

How can I convert a recurring binary number into decimal and vice-versa without approximating it?

$
0
0

I want to convert a number like 10.1(010) (which I'm storing as a triple ('10','1','010')) into decimal, getting 2.6(428571) (or ('2','6','42857')).

I want to get the exact number, repeating decimals and all, not a float that approximates it.

I can easily convert it to a float, by simply reading each item as an integer and multiplying it by the appropriate place value:

bin_to_decimal(('10','1','010')) = 2 + 1 * 2-1+ 2 * 2-1/(23-1) = 2.642857142857143

Which I wrote in python

def read_numeral(self, numeral, base=2) -> float:    if ',' not in numeral: numeral = numeral.replace('r',',r')    integer, finite, period = numeral    offset = len(finite)    n = read_int(integer, base)    if finite: n += read_int(finite, base) * (base ** -offset)    if period: n += read_int(period, base) * base ** -offset / (base**len(period)-1)    return n

I couldn't figure out a way to get the exact decimal representation, though.


Viewing all articles
Browse latest Browse all 19054

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>