简体   繁体   中英

Octave mod function and integer

I have a problem when I call the mod function. I have a variable M which is a two dimensional vector. When I print M , I see 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) .

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

Therefore you should cast the value to an integer before applying mod , for example:

>> M = int64(M)

now

>> mod(M(2),10)

will give you correct answer, 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. For example is 240.000000000000000000000000000000000001 a multiple of 10 ? 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 . 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. 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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