如何在 python 中获取前 n 位浮点数作为整数
How can I get first n bits of floating point number as integer in python
假设我有 0.625
,因为浮点数是 0b.101
,所以如果我想要它的前两位作为整数,即 0b10
= 2
,我怎样才能在 python 中做到这一点?
我试过将数字取 2 的幂并转换为 int,所以如果我想要 n
位,我会 int(0.625*(2**n))
。但这对我不起作用。
当我的数字大于 1
时会出现问题,因此 24.548838022726972
将给我前四位 392
而不是 12
。 (24.548838022726972
= 0b11000.100011001...
)
您可以使用 struct.pack()
将浮点数转换为字节列表,然后从中提取您感兴趣的位。
While the number is greater than or equal to 1, divide by 2.
Multiply by 2**n
Round or truncate to an integer.
这是测试用例的简化 Java 程序:
public class Test {
public static void main(String[] args) {
double in = 24.548838022726972;
while (in >= 1) {
in /= 2;
System.out.println(in);
}
in *= 16;
System.out.println(in);
System.out.println((int) in);
}
}
输出:
12.274419011363486
6.137209505681743
3.0686047528408715
1.5343023764204358
0.7671511882102179
12.274419011363486
12
如果您想要 n
个最高有效位,一种开始的方法是使用 math.frexp
将您的数字标准化到 [0.5, 1.0)
范围内。然后乘以 2**n
并取整数部分将为您提供所需的结果。
>>> import math
>>> math.frexp(24.54883) # significand and exponent
(0.7671509375, 5)
>>> math.frexp(24.54883)[0] # just the significand
0.7671509375
>>> int(math.frexp(24.54883)[0] * 2**4) # most significant 4 bits
12
您可以使用 math.ldexp
函数来执行第二部分操作,而不是显式计算 2
的幂以进行缩放。
>>> int(math.ldexp(math.frexp(24.54883)[0], 4))
12
使用内置函数获取IEEE 754 format中尾数有效位的一种直接方法是:
In [2]: u=24.54883
In [3]: bin(u.as_integer_ratio()[0])
Out[3]: '0b11000100011001000000000011111011101010001000001001101'
In [4]: u=.625
In [5]: bin(u.as_integer_ratio()[0])
Out[5]: '0b101'
你得到 0b1
+ 尾数没有非重要的 0.
假设我有 0.625
,因为浮点数是 0b.101
,所以如果我想要它的前两位作为整数,即 0b10
= 2
,我怎样才能在 python 中做到这一点?
我试过将数字取 2 的幂并转换为 int,所以如果我想要 n
位,我会 int(0.625*(2**n))
。但这对我不起作用。
当我的数字大于 1
时会出现问题,因此 24.548838022726972
将给我前四位 392
而不是 12
。 (24.548838022726972
= 0b11000.100011001...
)
您可以使用 struct.pack()
将浮点数转换为字节列表,然后从中提取您感兴趣的位。
While the number is greater than or equal to 1, divide by 2.
Multiply by 2**n
Round or truncate to an integer.
这是测试用例的简化 Java 程序:
public class Test {
public static void main(String[] args) {
double in = 24.548838022726972;
while (in >= 1) {
in /= 2;
System.out.println(in);
}
in *= 16;
System.out.println(in);
System.out.println((int) in);
}
}
输出:
12.274419011363486
6.137209505681743
3.0686047528408715
1.5343023764204358
0.7671511882102179
12.274419011363486
12
如果您想要 n
个最高有效位,一种开始的方法是使用 math.frexp
将您的数字标准化到 [0.5, 1.0)
范围内。然后乘以 2**n
并取整数部分将为您提供所需的结果。
>>> import math
>>> math.frexp(24.54883) # significand and exponent
(0.7671509375, 5)
>>> math.frexp(24.54883)[0] # just the significand
0.7671509375
>>> int(math.frexp(24.54883)[0] * 2**4) # most significant 4 bits
12
您可以使用 math.ldexp
函数来执行第二部分操作,而不是显式计算 2
的幂以进行缩放。
>>> int(math.ldexp(math.frexp(24.54883)[0], 4))
12
使用内置函数获取IEEE 754 format中尾数有效位的一种直接方法是:
In [2]: u=24.54883
In [3]: bin(u.as_integer_ratio()[0])
Out[3]: '0b11000100011001000000000011111011101010001000001001101'
In [4]: u=.625
In [5]: bin(u.as_integer_ratio()[0])
Out[5]: '0b101'
你得到 0b1
+ 尾数没有非重要的 0.