在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)
。