16位浮点 c语言,C语言中的16位浮点乘法
我正在開(kāi)發(fā)一個(gè)小項(xiàng)目,我需要浮點(diǎn)乘法和16位浮點(diǎn)數(shù)(半精度)。不幸的是,我遇到了算法的一些問(wèn)題:
示例輸出
1 * 5 = 5
2 * 5 = 10
3 * 5 = 14.5
4 * 5 = 20
5 * 5 = 24.5
100 * 4 = 100
100 * 5 = 482
源代碼
const int bits = 16;
const int exponent_length = 5;
const int fraction_length = 10;
const int bias = pow(2, exponent_length - 1) - 1;
const int exponent_mask = ((1 << 5) - 1) << fraction_length;
const int fraction_mask = (1 << fraction_length) - 1;
const int hidden_bit = (1 << 10); // Was 1 << 11 before update 1
int float_mul(int f1, int f2) {
int res_exp = 0;
int res_frac = 0;
int result = 0;
int exp1 = (f1 & exponent_mask) >> fraction_length;
int exp2 = (f2 & exponent_mask) >> fraction_length;
int frac1 = (f1 & fraction_mask) | hidden_bit;
int frac2 = (f2 & fraction_mask) | hidden_bit;
// Add exponents
res_exp = exp1 + exp2 - bias; // Remove double bias
// Multiply significants
res_frac = frac1 * frac2; // 11 bit * 11 bit → 22 bit!
// Shift 22bit int right to fit into 10 bit
if (highest_bit_pos(res_mant) == 21) {
res_mant >>= 11;
res_exp += 1;
} else {
res_mant >>= 10;
}
res_frac &= ~hidden_bit; // Remove hidden bit
// Construct float
return (res_exp << bits - exponent_length - 1) | res_frac;
}
順便說(shuō)一下:我將浮點(diǎn)數(shù)存儲(chǔ)在整數(shù)中,因?yàn)槲視?huì)嘗試將此代碼移植到某種沒(méi)有浮點(diǎn)操作的匯編程序。
問(wèn)題
為什么代碼僅適用于某些值?我忘記了一些規(guī)范化或類似的嗎?或者它只是偶然起作用?
免責(zé)聲明:我不是CompSci學(xué)生,它是一個(gè)休閑項(xiàng)目;)
更新#1
感謝Eric Postpischil的評(píng)論,我注意到代碼存在一個(gè)問(wèn)題:hidden_bit標(biāo)志被一個(gè)人關(guān)閉(應(yīng)該是1 << 10)。有了這個(gè)改變,我不再獲得小數(shù)位數(shù),但仍有一些計(jì)算結(jié)果(例如3?3=20)。我假設(shè),它是res_frac轉(zhuǎn)變,如答案中所描述的那樣。
更新#2
代碼的第二個(gè)問(wèn)題確實(shí)是res_frac轉(zhuǎn)移。在更新#1之后,當(dāng)?shù)玫絝rac1 * frac2的22位結(jié)果時(shí),我得到了錯(cuò)誤的結(jié)果。我已使用更正的班次語(yǔ)句更新了上面的代碼。感謝所有的評(píng)論和回答! :)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的16位浮点 c语言,C语言中的16位浮点乘法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 土木工程和计算机专硕,第一次发帖 关于
- 下一篇: python树莓派串口通信实例_树莓派通