Python浮点运算

时间:2013-07-26 10:31:36

标签: python printing floating-point rounding

如何在python中打印简单操作的完整浮点结果?我的代码确实:

if( int(array_Y[counter2]) == int(round(float(elem[0])))):
                if(int(round(float(elem[0]))) == 0):
                    negatiu_verdader += 1
                if(int(round(float(elem[0]))) == 1):
                    positiu_verdader += 1
                counter = counter + 1
            counter2 = counter2 + 1

        error =  float(1.0000- (1.0000 * counter / counter2))

        print "        ERROR!!!!!!!!!!!!!!!!!!!!!!!! :" + ("{0:.15f}".format(round(error,2)))

但错误总是:0.4200000000000000.230000000000000,但我希望错误为:0.43233213213232

1 个答案:

答案 0 :(得分:3)

通过调用round(error, 2)

,您将错误四舍五入到小数点后两位
>>> round(0.43233213213232, 2)
0.43

如果要显示更高的精确度,请不要这样做:

>>> format(round(0.43233213213232, 2), '.15f')
'0.430000000000000'
>>> format(0.43233213213232, '.15f')
'0.432332132132320'

你在代码中做了很多冗余的工作,简化了一下:

elem_rounded = int(round(float(elem[0])))
if int(array_Y[counter2]) == elem_rounded:
    if not elem_rounded:
        negatiu_verdader += 1
    elif elem_rounded == 1:
        positiu_verdader += 1
        counter += 1
        counter2 += 1

    error =  1.0 - (1.0 * counter / counter2)
    print "        ERROR!!!!!!!!!!!!!!!!!!!!!!!! :{0:.15f}".format(error)