我正在开发一个小项目,我需要浮点乘法和16位浮点数(半精度)。不幸的是,我遇到了算法的一些问题:
示例输出
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;
}
顺便说一下:我将浮点数存储在整数中,因为我会尝试将此代码移植到某种没有浮点操作的汇编程序。
问题
为什么代码仅适用于某些值?我忘记了一些规范化或类似的吗?或者它只是偶然起作用?
免责声明:我不是CompSci学生,它是一个休闲项目;)
更新#1
感谢Eric Postpischil的评论,我注意到代码存在一个问题:hidden_bit标志被一个人关闭(应该是1 << 10)。有了这个改变,我不再获得小数位数,但仍有一些计算结果(例如3•3=20)。我假设,它是res_frac转变,如答案中所描述的那样。
更新#2
代码的第二个问题确实是res_frac转移。在更新#1之后,当得到frac1 * frac2的22位结果时,我得到了错误的结果。我已使用更正的班次语句更新了上面的代码。感谢所有的评论和回答! :)