I have been trying to implement an assembly routine in MSP430 for division. I already got the code for the division from the Horner Division Algorithm. The problem is that I only got the integer part. How I can get the fractional part from a division? For example: 5/2 = 2.5. How do I get the 0.5 part?
2 Answers
You should get the remainder.
To turn that into a fraction you first need to decide between fixed and floating point; and if fixed, how many fractional bits.
Fixed point is easy : if you decide you want 8 fractional bits, just divide 2^8 * remainder / denominator, and use the size of that operation's remainder to determine rounding.
In your example, that would give
(256 * 1) / 2 = 128 as your fractional part, i.e. 128 / 256 = 0.5
Or for 3 fractional (decimal) digits, just compute 10^3 * remainder / denominator.
For floating point you would use a floating point library; it's far too complex to seriously consider rolling your own.
-
\$\begingroup\$ The result should be with 3 digits for the fractional part and least significant bit of that part should be rounded. So yes it is a fixed point format. \$\endgroup\$– EMPVCommented Nov 12, 2015 at 19:25
-
1\$\begingroup\$ correction: fraction = (2^8 * remainder)/denominator \$\endgroup\$– greggoCommented Nov 12, 2015 at 20:24
-
\$\begingroup\$ How that's going to be represented in a register in the MSP430? \$\endgroup\$– EMPVCommented Nov 12, 2015 at 21:28
-
\$\begingroup\$ That's up to you. \$\endgroup\$– user16324Commented Nov 12, 2015 at 23:08
You can do
q =(num * 2^n)/ denom
as an integer division; the result will have n
extra, fractional, bits. So with n=8,
(5*256)/2 = 640
which is 2.5 * 256 or 2 * 256 + (128/256).