PDA

View Full Version : Remainder (Modulus, Modulo)



PICn-It
- 11th January 2010, 22:40
Can someone give me a hand understanding how to use the remainder (Modulus) operator properly.

For instance I'm trying to divide 480 by 148. On my calculator I get 3.24.

When I try to use // in something like this I get 36 instead of 24:


Num_1 var WORD
Num_2 var WORD
Int_part var WORD
Fract_part var WORD

Num_1 = 480 : Num_2 = 148
Int_part = Num_1 / Num_2
Fract_part = Num_1 // Num_2

the variable Fract_part doesn't have the 24 I was expecting, it contains 36 ...?

(BTW; I'm trying to work around floating point math on a 16F micro)

ScaleRobotics
- 12th January 2010, 00:58
Do you remember way back when, the teacher wouldn't let you use a calculator, and you were allowed to stop with a fraction, instead of having to solve for x decimal points? I do, but I am old. Anyway, the remainder is just that, a remainder. If you want a decimal, you will have to do some more work.

148 goes into 480 3 times, but there are 36 left over.

Jerson
- 12th January 2010, 01:08
The answers are correct. Surprised? Here's how it works

480/148 = 3 in integer math.
= 3.24 in fractional math

480 mod 148 = 36 how?
480 - (148*3) = 36

Then you might ask, what is the 0.24 and 36.

When you multiply 0.24 by the divisor 148, you get the fraction that remains 36.

If you want to do fixed place math, multiply the upper number by 100 and you will get a result that has the additional 2 digits and you put the decimal after dividing by 100.

eg : 480 / 148 now becomes (480*100)/148
result will be 324. This is actually 100 times greater because we multiplied by 100. So, while printing the value, you print 324/100, ".", 324 mod 100 to get the proper value of 3.24

You might find more ports out here explaining flxed point math - search

PICn-It
- 12th January 2010, 02:16
The answers are correct. Surprised? Here's how it works

480/148 = 3 in integer math.
= 3.24 in fractional math

480 mod 148 = 36 how?
480 - (148*3) = 36

Then you might ask, what is the 0.24 and 36.

When you multiply 0.24 by the divisor 148, you get the fraction that remains 36.

If you want to do fixed place math, multiply the upper number by 100 and you will get a result that has the additional 2 digits and you put the decimal after dividing by 100.

eg : 480 / 148 now becomes (480*100)/148
result will be 324. This is actually 100 times greater because we multiplied by 100. So, while printing the value, you print 324/100, ".", 324 mod 100 to get the proper value of 3.24

You might find more ports out here explaining flxed point math - search

Ahhh that makes some sense, thank you.