问题描述:

I have a function which encode float number to binary. I split float number by "." and convert both parts to binary. After i concatenate results. Left part I encode by simple convert bin(left_part). Right part I encode by next algorithm:

 while count:

val *= 2

if val >= 1:

val_bin += "1"

else:

val_bin += "0"

val %= 1

count -= 1

return val_bin

I have found this solution on the internet. But I can't found out how to convert back right part to float number in decimal. How i can do it?

I only see the way of full exhaustive search:

Example:

I have "00110011". We move from right to left. In first step we have "1". That means in the step value may be in interval "1.000 to 1.999". In the next step we have another "1". That means that value in the first step was in interval "1.500 to 1.999". In current step we have the next interval "1.001 to 1.999". Next step we have "0". That means in previous step value was in interval 1.000 to 1.499". etc. And after all iterations we will not have a accurate result. Result always will be in the interval. I may be wrong.

网友答案:

Here is a version which uses the built-in int function. It is based on the fact that in any base the decimal part of a decimal expansion is the numerator of a fraction where the denominator is a power of the base. The power in question is easily inferred from the length of the decimal part.

#the following code assumes that '.' appears once

def binToFloat(b):
    parts = b.split('.')
    s,t = parts
    x = 0 if len(s) == 0 else int(s,2)
    y = 0 if len(t) == 0 else int(t,2)
    return x + y/2**len(t)

For example:

>>> binToFloat('1101101.1101')
109.8125

The above code assumed Python 3. In Python 2 you would need to rewrite the final line as

return x + float(y)/2**len(t)
网友答案:

If you have your number in binary as a string and you only want to interpret it as the part to the right of the decimal point, you can use this function:

def binToFloatAfterPoint(b):
    exp = -1
    result = 0
    for digit in b:
        if digit != "0":
            result += math.pow(int(digit)*2,exp)
        exp -= 1
    return result

However, if you have your whole binary number as one string you can directly convert it into a float by specifying how many decimalPlaces you want using this function:

def binToFloat(b,decimalPlaces):
    exp = len(b) - decimalPlaces - 1
    result = 0
    for digit in b:
        if digit != "0":
            result += math.pow(int(digit)*2,exp)
        exp -= 1
    return result

So say you have

b = "1010"

The output of the first function (and the second with decimalPlaces=4) would be: 0.625 At the same time you could call the second function with other values for decimalPlaces which would give you different floats:

binToFloat(b,0) = 10.0
binToFloat(b,1) = 5.0
binToFloat(b,2) = 2.5
binToFloat(b,3) = 1.25
相关阅读:
Top