这里是一段代码,试图将实数转换为其近似的单精度浮点表示形式,用于演示中间结果的教育目的:
function [IEEE] = myDec2IEEE (d)
% Accepts a decimal number, d.
% Returns 1x32 bit array holding its closest IEEE representation.
s = getSign(d);
[e, f] = getCharacteristic(d);
binaryE = binStr2binArr(dec2bin(e)); % convert to binary integer array.
if numel(binaryE) < 8 % extend to exponent bits number.
binaryE = [zeros(1, 8 - numel(binaryE)), binaryE];
end
binaryF = expandFractionToBinary(f);
IEEE = [s , binaryE, binaryF];
end
function [B] = binStr2binArr (s)
% Accepts a binary character string, s.
% Returns binary integer array, B.
len = numel(s);
B = zeros(1, len);
for i = 1 : len
B(i) = s(i) - '0';
end
end
function [B] = expandFractionToBinary(f)
% Accepts what has remained from the decimal number
% after the calculation of the exponent, i.e its fractional part.
% Returns a 1x23 binary array which is the approximation of the
% fractional part represented as a sum of negative powers of 2,
% (up to the 22 - nd power).
singlePrecision = 22;
B = zeros(1, singlePrecision); % binary string to store fraction of IEEE754.
i = 1; % exponent of 2; (i+1) -index in binary array.
while f != 0 && i <= singlePrecision
ith = 1 / (2^(i));
if ith <= f
f = f - ith;
B(i) = 1; % include coefficient in the sum.
end
i = i + 1;
end
end
function [e, f] = getCharacteristic (d)
% Accepts a number is base10, d.
% Returns the exponent and fraction in d's IEEE754 representation, in base10.
% write d in base-2 scientific notation
% i.e. factor it into number in the range [1, 2] and a power of 2.
bias = 127;
i = 1;
f = 0;
while ~(f >= 1 && f <= 2)
f = d / (2^(-i));
% pause; % if number > 1 the denominator -> 0 and (faster than f -> Inf)
i = i + 1;
end
i = i - 1; % last check is done after incrementation.
e = bias - i;
f = f - 1;
end
function [s] = getSign (d)
% Accepts a number in base10, d.
% Returns the sign bit of its IEEE754 representation.
if d >= 0
s = 0;
else
s = 1;
end
end
输入:
IEEE = myDec2IEEE(0.085)
输出:
Columns 1 through 21:
0 0 1 1 1 1 0 1 1 0 1 0 1 1 1 0 0 0 0 1 0
Columns 22 through 31:
1 0 0 0 1 1 1 1 0 1
但是,它仅适用于以下十进制数:0 < d < 1。
问题
我做错了什么?
应如何修改代码以正确返回数字 >= 1 和 d <= 0 的 IEEE 表示?
备注:
基于关系 d = (-1)sign * 2exponent - bias * (fraction + 1) 的实现,其中 fraction = Sum (1/2^ n), n = 0,...,22;偏差 = 127。
最佳答案
已确认here MATLAB 将 IEEE 754 用于单精度 float 。
因此,为什么不让 MATLAB 处理内部结构并做这样的事情呢?:
s = dec2bin(typecast(single(0.085),'uint32'), 32)
给出:
00111101101011100001010001111011
这匹配所需的输出(来自您提到的 independent check)并且也适用于值 > 1。
如果您需要一个数字而不是字符串结果,您可以像这样转换它:
x = s-'0'
关于algorithm - 自定义函数无法将小数转换为单精度 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140135/