我正在为MATLAB / Octave中的某些VHDL代码开发一种验证工具。因此,我需要产生“实际”溢出的数据类型:
intmax('int32') + 1 ans = -2147483648 稍后,如果我可以定义变量的位宽会很有帮助,但是现在这并不那么重要。
当我建立一个类似于C的示例时,变量会不断增加直到小于零为止,它永远旋转:
test = int32(2^30); while (test > 0) test = test + int32(1); end 我尝试的另一种方法是自定义的“溢出”例程,每次更改数字后都会调用该例程。这种方法非常缓慢,不可行,并且在所有情况下都无法正常工作。有什么建议么?
回答:
在MATLAB中,一种选择是重载处理
整数数据类型的 算术运算的方法,创建自己的自定义溢出行为,这将导致整数值“环绕”。如文档中所述:
通过将适当命名的方法放在路径上文件夹中的@int*文件夹中,可以为int*定义或重载自己的方法(就像对任何对象一样)。键入help datatypes以获取可以重载的方法的名称。
文档的本页列出了算术运算符的等效方法。二进制加法运算A+B实际上由函数plus(A,B) 。因此,您可以创建一个名为@int32的文件夹(放在
MATLAB路径中的另一个文件夹中), plus.m在其中放置一个函数plus.m ,而不是int32数据类型的内置方法。
这是一个示例,说明如何设计重载plus函数以创建所需的上溢/下溢行为:
function C = plus(A,B) %# NOTE: This code sample is designed to work for scalar values of %# the inputs. If one or more of the inputs is non-scalar, %# the code below will need to be vectorized to accommodate, %# and error checking of the input sizes will be needed. if (A > 0) && (B > (intmax-A)) %# An overflow condition C = builtin('plus',intmin,... B-(intmax-A)-1); %# Wraps around to negative elseif (A < 0) && (B < (intmin-A)) %# An underflow condition C = builtin('plus',intmax,... B-(intmin-A-1)); %# Wraps around to positive else C = builtin('plus',A,B); %# No problems; call the built-in plus.m end end 请注意,我调用了内置的plus方法(使用
BUILTIN函数)来执行int32值的加法,我知道该值不会遇到上溢/下溢问题。如果我改为使用操作A+B执行整数加法,则会导致对重载plus方法的递归调用,这可能导致额外的计算开销,或者(在最坏的情况下,最后一行是C = A+B; )无限递归。
这是一个测试,显示了实际操作中的环绕溢出行为:
>> A = int32(2147483642); %# A value close to INTMAX >> for i = 1:10, A = A+1; disp(A); end 2147483643 2147483644 2147483645 2147483646 2147483647 %# INTMAX -2147483648 %# INTMIN -2147483647 -2147483646 -2147483645 -2147483644
更多&回答...