|
|
View previous topic :: View next topic |
Author |
Message |
Guest
|
32 bit integer divsion to float |
Posted: Fri Oct 20, 2006 2:51 am |
|
|
Hi,
I need to divide a 32 bit int by a larger 32 bit int. i want the resulting answer stored as a float. it will always be less than 1. Im not sure how to achieve this. I have read on the forum you need to typecast an int to force float division but this is not an option as my 32 bit number will be too large to be stored as a float.
Any help greatly appreciated!
Thanks!
Karl |
|
|
Ttelmah Guest
|
|
Posted: Fri Oct 20, 2006 3:23 am |
|
|
You need to perform the division using floats, or the fractional component will be lost.
For instance:
float_val=int1/int2;
This performs an integer division, so the result, though converted to a float, will already have lost the fractional part. Instead:
float_val=(float)int1/int2;
This changes 'int1', into a float data type, _before_ division. Hence floating point division is used, and the fractional part will be preserved. Downside, is that the arithmetic will take longer.
Best Wishes |
|
|
Karl Guest
|
|
Posted: Fri Oct 20, 2006 4:49 am |
|
|
Hi Ttelmah,
Thanks for your quick reply.
But if my int is a 32 bit int, can this be converted into a 32 bit float? Wont the value be too large to be represented by a float data type?
Thanks,
Karl |
|
|
jma_1
Joined: 08 Feb 2005 Posts: 147 Location: Wisconsin
|
|
Posted: Fri Oct 20, 2006 10:50 am |
|
|
You can readily determine this yourself. Data types have constants associated with it (min, max, radix, etc). Look in 'float.h' -> DBL_MAX. Compare 2^32 with the value from float.h. Alternatively, write a quick test. Place your largest possible int32 value you are interested in, perform your calculation, display the results.
Cheers,
JMA |
|
|
Ttelmah Guest
|
|
Posted: Fri Oct 20, 2006 2:51 pm |
|
|
Any 32bit integer can convert to a float, _but_ you will only have 24bits of accuracy in the result. A 32bit integer, can hold a value up to 4294967295, and still have a resolution of '1'. With a 32bit float, only the first 6.5 digits will be resolved (the values will step in effectively 512 count steps at this size).
Best Wishes |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|