Matlab:如何在不扩展底层数据类型的情况下执行定点运算?

时间:2013-09-25 10:40:07

标签: matlab fixed-point

谷歌在这个问题上保持沉默。我目前正在Matlab中仅在16位有符号定点上实现数值计算器。但是16位定点上的算术运算会导致数据类型扩展到以下

>> a = int16(1.5 * 4)
a = 6
>> T = numerictype(1, 16, 2)

T = DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 2
>> dis = reinterpretcast(a, T)

dis = 1.5000

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 2
>> c = dis * dis

c = 2.2500

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 32
        FractionLength: 4

我希望变量c保持在WordLength 16,FractionLength 2.是否可以在不扩展基础数据类型的情况下完成16位定点的算术运算?我将承担任何溢出和下溢的风险。任何帮助都会很棒。

编辑:在命令窗口中键入fimath会导致错误。为什么会出现这种错误?

>> F = fimath('OverflowAction','Wrap', 'RoundingMethod', 'Floor', ...
           'ProductWordLength', 16, 'ProductFractionLength', 2);
No public field OverflowAction exists for class embedded.fimath.

Error in fimath (line 72)
  this.(varargin{k}) = varargin{k+1};

1 个答案:

答案 0 :(得分:4)

本地解决方案: 您可以使用fimath对象to specify the precision of the result of a product

F = fimath('OverflowMode','Wrap', 'RoundMode', 'Floor', ...
           'ProductMode', 'SpecifyPrecision', ...
           'ProductWordLength', 16, 'ProductFractionLength', 2);
dis.fimath = F;

然后结果将是:

>> dis*dis
ans =
         2.25

          DataTypeMode: Fixed-point: binary point scaling
            Signedness: Signed
            WordLength: 16
        FractionLength: 2

             RoundMode: floor
          OverflowMode: wrap
           ProductMode: SpecifyPrecision
     ProductWordLength: 16
 ProductFractionLength: 2
               SumMode: FullPrecision
      MaxSumWordLength: 128

全局解决方案:或者,如果您希望将其应用于所有固定点变量,则可以使用

globalfimath('OverflowMode','Wrap', 'RoundMode', 'Floor', ...
             'ProductMode', 'SpecifyPrecision', ...
             'ProductWordLength', 16, 'ProductFractionLength', 2);

注意要限制为16位,您还需要指定求和的精度(使用SumMode的{​​{1}}和SumWordLength属性,否则sum的长度为17:

fimath