2013-09-28 100 views
0

我正在Matlab中實現一個數值方法。但是,我的公式或Matlab出現問題似乎很愚蠢。我想在Matlab中得到1920,但結果如下。 Python解釋器提供了爲什麼兩位翻譯的結果不一樣?

>>> 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

你更可能是傻瓜,而不是Matlab。我猜你對整數除法的理解很差。 – duffymo

+0

Python沒有我暫時忘記名字的類型強制的東西。 'a =(int)(x0_square +(((2 * x0)*(x-x0))/ scale_factor))'沒有任何意義。你想'int((x0_square +(((2 * x0)*(x - x0))/ scale_factor)))'(儘管這可能不是唯一的問題)。 – rlms

+0

但是您使用了多個變量:>>> x0_square = 3200 >>> x0 = 2560 >>> scale_factor = 2048' assignes 3個變量。你的意思是功能還是什麼? – rlms

回答

3

問題是你在Matlab中使用int16。 Python的整數具有無限精度,因此不會溢出。如果您在Python代碼中使用numpy.int16從優你

RuntimeWarning: overflow encountered in short_scalars 

所以這絕對是一個溢出的問題。


使用numpy.int16 S IN 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)))); 
+0

+1 - 第二個數據點告訴我,你知道的不僅僅是數值方法。 – duffymo

1

用手只是做了計算用HP計算器;它證實你應該得到1920.

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

Veedrac已經擊中它的頭 - 溢出。嘗試32位整數。

相關問題