在MATLAB代碼與matlab mod()相比,c中的fmod()如何工作?
Longitude = mod(-1789.8916,360);
下返回值10.108325
但在C代碼
Longitude = fmod(-1789.8916,360);
返回值-349.8916
我想相同的C代碼值
在MATLAB代碼與matlab mod()相比,c中的fmod()如何工作?
Longitude = mod(-1789.8916,360);
下返回值10.108325
但在C代碼
Longitude = fmod(-1789.8916,360);
返回值-349.8916
我想相同的C代碼值
該matlab mod
函數總是返回一個正值,但C函數(至少從C11)將返回一個負值,如果第一個參數爲負值。 (在之前的C標準中,針對否定論證的確切行爲取決於實現)。
因此,如果第一個參數是負數且結果大於零,您可以通過在答案中減去360(在本例中)來轉換matlab版本。
mod
函數總是返回一個在MATLAB中的正值,從C11 fmod
返回一個負值,如果第一個參數是負值。
您可以使用此功能來模仿MATLAB的fmod
行爲
function m = fmod(a, b)
% Where the mod function returns a value in region [0, b), this
% function returns a value in the region [-b, b), with a negative
% value only when a is negative.
if a == 0
m = 0;
else
m = mod(a, b) + (b*(sign(a) - 1)/2);
end
end
說明:
sign(a)
是1
當a
爲正,或-1
當a
爲負。分別爲0
或-1
。
如果a
爲負數,則會導致b
從結果中減去,得到期望的結果範圍[-b, b)
。