为什么两个口译员给出的结果彼此不同?

时间:2013-09-28 12:40:18

标签: python matlab

我在Matlab中实现了一个数值方法。但是我的公式出现问题或者Matlab看起来很傻。我想在Matlab中获得1920,但结果如下。 python interpreter给出

>>> x0_square = 3200
>>> x0 = 2560
>>> scale_factor = 2048
>>> x = 2048
>>> a = x0_square +  ( ( (2 * x0) * (x - x0) ) / scale_factor)
>>> print a
1920

但是Matlab给出了

% all variables here is int16. all value are the same as the above.
>> x_square_a = int16(x0_square +  ( ( (2 .* x0) .* (x - x0) ) ./ scale_factor));
>> x_square_a

x_square_a =

   3184

他们为什么会给出不同的结果?如何从Matlab解释器获得1920?另外,我受到限制,除了int16之外,任何变量都不能使用。

2 个答案:

答案 0 :(得分:3)

问题是你在Matlab中使用int16。 Python的整数具有无限的精度,因此不会溢出。如果您在Python代码中自由地使用numpy.int16

RuntimeWarning: overflow encountered in short_scalars

所以这绝对是一个溢出问题。


使用numpy.int16的Python解决方案是先前移动部门:

x0_square = int16(3200)
x0 = int16(2560)
scale_factor = int16(2048)
x = int16(2048)
a = int16(x0_square +  ( ( (int16(2) * x0)  / scale_factor * (x - x0) )))
a
#>>> 1920

这表明matlab代码应该是

x_square_a = int16(x0_square +  ( ( (2 .* x0) ./ scale_factor .* (x - x0) )));

答案 1 :(得分:1)

只需用HP计算器手动计算;它证实你应该得到1920年。

2*2,560*(2,048-2,560) = -1,310,720。最大的16位整数是2^16 = 65,536

Veedrac击中头部 - 溢出。尝试32位整数。