如何重新计算公共指数?

2024-09-30 14:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

为了解释这一点,这基本上是一种将浮点向量数据压缩成具有单个公共无符号指数的8位或16位有符号或无符号整数(其中最常见的是bs16,表示公共指数为11的精度)。在

我不确定这个伪float方法是什么;我只知道要得到结果float,您需要执行以下操作:

float_result = int_value / ( 2.0 ** exponent )

我想做的是通过从给定的浮点数中重新计算指数来匹配这些数据。 (如果处理得当,还可以用其他格式重新计算)

因此,如果我得到的是一个由1140个浮点组成的大组,我如何找到公共指数并将这些浮点转换成这种压缩的bu8bs8bu16或{}(指定)格式?在

编辑:样例

^{pr2}$

编辑2: 我不会确切地称之为“压缩”,因为它实际上是一个提取的尾数,通过共享指数重新计算。在


Tags: 方法编辑value格式符号精度整数result
2条回答

如果有原始值和相应的结果,可以使用log来查找指数。数学有一个日志函数可以使用。您必须将Int_value/float_结果记录到基2。在

例如:

import Math
x = (int_value/float_result)
math.log(x,2)

也许是这样的:

def validExponent(x,e,a,b):
    """checks if x*2.0**e is an integer in range [a,b]"""
    y = x*2.0**e
    return a <= y <= b and y == int(y)

def allValid(xs,e,a,b):
    return all(validExponent(x,e,a,b) for x in xs)

def firstValid(xs,a,b,maxE = 100):
    for e in xrange(1+maxE):
        if allValid(xs,e,a,b):
            return e
    return "None found"

#test:

xs = [x / ( 2. ** 11 ) for x in [-12,14,-5,16,28]]
print xs
print firstValid(xs,-2**15,2**15-1)

输出:

^{pr2}$

当然,您可以编写一个包装器函数,它将接受一个字符串参数,例如'bs16',并自动计算ab

编辑时:

1)如果你有确切的浮动值,以上应该行得通。它引入了任何舍入错误,您可能希望将y == int(y)替换为abs(y-round(y)) < 0.00001(或类似的东西)。在

2)除非原始整数列表中的所有整数均为偶数,否则第一个有效指数将是所需的指数。如果你有1140个值,并且它们在某种意义上是随机的,那么发生这种情况的可能性非常小。在

在进一步编辑时:如果所讨论的浮点不是由该过程生成的,但您希望找到一个允许对给定大小的整数进行(有损)压缩的最佳指数,您可以这样做(未经彻底测试):

import math

def maxExp(x,a,b):
    """returns largest nonnegative integer exponent e with
a <= x*2**e <= b, where a, b are integers with a <= 0 and b > 0
Throws an error if no such e exists"""
    if x == 0.0:
        e = -1
    elif x < 0.0:
        e = -1 if a == 0 else math.floor(math.log(a/float(x),2)) 
    else:
        e = math.floor(math.log(b/float(x),2))
    if e >= 0:
        return int(e)
    else:
        raise ValueError()

def bestExponent(floats,a,b):
    m = min(floats)
    M = max(floats)
    e1 = maxExp(m,a,b)
    e2 = maxExp(M,a,b)
    MSE = []

    for e in range(1+min(e1,e2)):
        MSE.append(sum((x - round(x*2.0**e)/2.0**e)**2 for x in floats)/float(len(floats)))

    minMSE = min(MSE)
    for e,error in enumerate(MSE):
        if error == minMSE:
            return e

要测试它:

>>> import random
>>> xs = [random.uniform(-10,10) for i in xrange(1000)]
>>> bestExponent(xs,-2**15,2**15-1)
11

选择公共指数11似乎是有原因的。在

相关问题 更多 >