自定义函数无法将十进制转换为单精度浮点

时间:2017-09-10 11:19:13

标签: algorithm matlab octave ieee-754

这是一个试图将实数转换为其近似单精度浮点表示的代码,用于教育目的以演示中间结果:

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&lt; d&lt; 1。

问题

我做错了什么?

如何修改代码以正确返回数字的IEEE表示&gt; = 1和d&lt; = 0?

注意:

基于关系的实现d =( - 1)符号 * 2 指数 - 偏差 *(分数+ 1),其中分数= Sum(1/2 ^ n),n = 0,...,22;偏见= 127。

1 个答案:

答案 0 :(得分:1)

已确认here MATLAB使用IEEE 754进行单精度浮点运算。

为什么不让MATLAB处理内部并做这样的事情?:

s = dec2bin(typecast(single(0.085),'uint32'), 32)

给出了:

00111101101011100001010001111011

这符合所需的输出(来自您提到的independent check),也适用于值&gt; 1。

如果您需要数字而不是字符串,则可以将其转换为:

x = s-'0'
相关问题