我正在尝试实现一个浮点算术库,但我无法理解减去浮点数的算法。我已经成功地实现了加法,我认为减法只是它的一个特例,但似乎我在某处犯了错误。我在这里添加代码仅供参考,它有很多自我解释的功能,但我不希望有人能 100% 理解它。我想要帮助的是算法。我们遵循与添加浮点数相同的方法,除了当我们添加尾数时,我们将负数(我们减去的数)转换为二进制补码然后添加它们?
这就是我正在做的,但结果不正确。尽管它非常接近......但不一样。有人有什么想法吗?提前致谢!
我很确定我做事的方式是有效的,因为我实现了一个几乎相同的算法来添加浮点数,它就像一个魅力。
_float subFloat(_float f1,_float f2)
{
unsigned char diff;
_float result;
//first see whose exponent is greater
if(f1.float_parts.exponent > f2.float_parts.exponent)
{
diff = f1.float_parts.exponent - f2.float_parts.exponent;
//now shift f2's mantissa by the difference of their exponent to the right
//adding the hidden bit
f2.float_parts.mantissa = ((f2.float_parts.mantissa)>>1) | (0x01<<22);
f2.float_parts.mantissa >>= (int)(diff);//was (diff-1)
//also increase its exponent by the difference shifted
f2.float_parts.exponent = f2.float_parts.exponent + diff;
}
else if(f1.float_parts.exponent < f2.float_parts.exponent)
{
diff = f2.float_parts.exponent - f1.float_parts.exponent;
result = f1;
f1 = f2; //swap them
f2 = result;
//now shift f2's mantissa by the difference of their exponent to the right
//adding the hidden bit
f2.float_parts.mantissa = ((f2.float_parts.mantissa)>>1) | (0x01<<22);
f2.float_parts.mantissa >>= (int)(diff);
//also increase its exponent by the difference shifted
f2.float_parts.exponent = f2.float_parts.exponent + diff;
}
else//if the exponents were equal
f2.float_parts.mantissa = ((f2.float_parts.mantissa)>>1) | (0x01<<22); //bring out the hidden bit
//getting two's complement of f2 mantissa
f2.float_parts.mantissa ^= 0x7FFFFF;
f2.float_parts.mantissa += 0x01;
result.float_parts.exponent = f1.float_parts.exponent;
result.float_parts.mantissa = (f1.float_parts.mantissa +f2.float_parts.mantissa)>>1;
//gotta shift right by overflow bits
//normalization
if(manBitSet(result,1))
result.float_parts.mantissa <<= 1; //hide the hidden bit
else
result.float_parts.exponent +=1;
return result;
}