简体   繁体   English

八度Mod功能和整数

[英]Octave mod function and integer

I have a problem when I call the mod function. 调用mod函数时出现问题。 I have a variable M which is a two dimensional vector. 我有一个变量M,它是一个二维向量。 When I print M , I see M = [350,240.00] . 当我打印M ,我看到M = [350,240.00]

Here is the problem : when I type mod(M(1),10) , I obtain 0 which is fine but I get 10 when I type mod(M(2),10) . 这是问题所在:当我键入mod(M(1),10) ,我得到0很好,但是当我键入mod(M(2),10)时得到10

I don't know if anyone has ever encounter this kind of problem or has an idea. 我不知道是否有人遇到过这种问题或想法。

Documentation of the mod function says that it "[...]is written such that the correct modulus is returned for integer types." mod函数的文档说,它“被编写为针对整数类型返回正确的模数”。

Therefore you should cast the value to an integer before applying mod , for example: 因此,应在应用mod之前将值转换为整数,例如:

>> M = int64(M)

now 现在

>> mod(M(2),10)

will give you correct answer, 0. 会给您正确答案,0。

If you are trying to check if a floating point number is a multiple of 10 then you need to choose a precision to work with. 如果要检查浮点数是否为10的倍数,则需要选择要使用的精度。 For example is 240.000000000000000000000000000000000001 a multiple of 10 ? 例如240.00000000000000000000000000000000000110的倍数吗? It probably should be for your case. 这可能应该适合您的情况。 You need to be careful because your computer can't always exactly represent for floating point number in it's decimal format because internally it is stored in binary. 您需要小心,因为您的计算机不能始终以十进制格式精确表示浮点数,因为它在内部以二进制形式存储。 For example 0.1 looks pretty precise in decimal, if I do something like 0:0.1:100 then you'd expect a few numbers in that series to be perfectly divisible by 10 . 例如, 0.1十进制看起来非常精确,如果我做类似0:0.1:100那么您希望该系列中的一些数字可以被10整除。 However 0.1 in binary is 0.0001100110011001100... which is requires at all and it will at some tiny precision get truncated by your computer. 但是,二进制文件中的0.10.0001100110011001100...这是绝对需要的,它将以某种微小的精度被计算机截断。 Now when you start adding them all up those tiny truncation errors compound and can result in you storing something like 10.00000000000000000008989883 instead of a perfect 10. So that's why you need to choose a minimum precision you're will to work with and ignore any errors below that. 现在,当您开始将所有这些微小的截断错误复合在一起时,它们可能会导致您存储类似于10.00000000000000000008989883之类的东西,而不是完美的10。因此,这就是为什么您需要选择一个最低精度的原因,您将使用它并忽略下面的任何错误那。

I suggest you round off to some precision and then check the multiple from there eg 我建议您四舍五入到一定的精度,然后从那里检查倍​​数,例如

p = 1e8 %//Check to 8 decimal points
mod(floor(M(2)*p), 10*p)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM