[英]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))
進行int(0.625*(2**n))
。 但這對我不起作用。
當我的數字大於1
時,會發生問題,因此24.548838022726972
將為我提供392
而不是前四位的12
。 ( 24.548838022726972
= 0b11000.100011001...
)
您可以使用struct.pack()
將浮點數轉換為字節列表,然后從那里提取您感興趣的位。
如果您想要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
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
使用內置函數獲取IEEE 754格式尾數有效位的直接方法是:
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
+尾數,而0b1
0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.