Float应该有5个前导数字,没有小数

时间:2013-11-08 04:17:10

标签: python floating-point-precision

我需要将用户输入的float转换为没有小数的5位数来计算浮点数的尾数和指数

示例: - 输入:12尾数:12000指数:-3

但我只能在math.frexp(x)找到我无法用于作业的信息。基本上我需要一种方法将用户输入转换为5位数的尾数,但我完全没有想法,也无法弄清楚如何正确转换浮点数,以便它可以在指数的计算中工作。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

我不确定它是否正确,如果您在输入中找到位数,然后将输入乘以所需的10次幂,则为尾数。

答案 1 :(得分:0)

我不太倾向于为您提供您所需要的(帮助您自己学习),但如果您学习以下代码,您可能会得到您所需要的。

def func(user_input):
    user_in = str(user_input)
    if not '.' in user_in: # Make the input as float
        user_in = user_in + '.'
    try:
        float(user_in)
    except:
        return ValueError

    decimal_pos = user_in.find('.')
    no_digits = decimal_pos

    if no_digits == 5:
        exponent = 0
        mantissa = int(user_in[:decimal_pos])
    elif no_digits > 5:
        exponent = 5 - no_digits
        mantissa = int(user_in[:decimal_pos])//(10**(-exponent))
    else:
        if no_digits == 1 and user_in[0] == '0':
            exponent = 5
        else:
            exponent = 5 - no_digits

        if len(user_in) >= decimal_pos+exponent+2:
            mantissa = int(user_in[:decimal_pos+exponent+2].replace('.',''))
        else:
            mantissa = int(user_in.replace('.','')) * (10**(decimal_pos+exponent+1 - len(user_in)))

    if float(user_in) == 0:
        exponent = 0
        mantissa = 0

    return mantissa, exponent

for a in (1.2345, 0.12345, 12, 12345, 123456, 123456.78):
    print a, func(a)

以上

的输出
1.2345 (12345, 4)
0.12345 (12345, 5)
12 (12000, 3)
12345 (12345, 0)
123456 (12345, -1)
123456.78 (12345, -1)