Reputation: 3822
I am trying to do a division with floating point. But the problem is I am representing the floating point number in two variables. Qty_int and Qty_deci. Ie, 2.5 is represented as Qty_int = 2, Qty_deci = 5.
My question is how will I divide this kind of numbers with two? ie 2.5/2, where two and five are in different variables. The division must not be expensive and the float data type must not be used. Is there any way to do this??
Upvotes: 0
Views: 174
Reputation: 386621
If Qty_deci is an integer, you can't differentiate between 2.5 and 2.05. You'd need three variables.
2.5 = (2) + (5) * 10^(-1)
2.05 = (2) + (5) * 10^(-2)
^ ^ ^
| | |
Or two different variables with different values than your current values.
2.5 = ( 25) * 10^(-1)
2.05 = (205) * 10^(-2)
^ ^
| |
But that doesn't help anything unless you switch to using base 2 instead of 10.
2.5 = (0x5000) / 2*(15-2)
2.05 = (0x4199) / 2*(15-2)
^ ^
| |
Then, division because possible.
2.5 / 2.0
= ( (0x5000) / 2*(15-2) ) / ( (0x4000) / 2*(15-2) )
= (0x5000) * 2*(15-2) / (0x4000) / 2*(15-2)
= (0x5000) << (15-2) / (0x4000) / 2*(15-2)
= (0x2800) / 2^(15-2)
= 1.25
Note that the above division is an integer division.
You technically don't even need to store the second number. We had a machine with no floating point arithmetic support. We used fixed point arithmentic. It's basically the same as the above, except you never actually store the second number anywhere except in comments.
For example, if we had 16 bit variables and we reserved one for the sign and 2 bits for the integer portion ("B2"),
The equivalent of this would be done by the input function:
int16 qty_B2 = 2.5 * 2**(15-2); // 2.5 B2 = 0x5000
The equivalent of this would be done by your compiler or by hand:
int16 div_B2 = 2.0 * 2**(15-2); // 2.0 B2 = 0x4000
And this is how you do the division:
int32 qty_32_B2 = qty_B2 << 16; // 2.50 B2
int32 qty_32_B4 = qty_32_B2 >> 2; // 2.50 B4
int16 res_B2 = qty_32_B4/div_B2; // 1.25 B4-B2=B2
The equivalent of this would be done by the output function:
printf("%f", res / 2**(15-2));
Note that the above division is an integer division.
Upvotes: 2
Reputation: 346506
Is Qty_deci
a string? If not, how are you going to represent 2.01?
I would advise you strongly against implementing your own custom floating-point format. Reconsider using a native floating-point format (what are your reasons not to use it?), or use a library that implements arbitrary-precision decimal math.
Upvotes: 1