Float cast reduces value by 1
When casting (float)33554329L the result is 33554328. if the number is then cast back to a long the value stays at 33554328, has any one an explanation for this.
Using VS2005 in C++ [n开发者_如何转开发on managed]
32 bit float has 23 bits for the mantissa which are 8,388,608 distinct values. This means that the accuracy is around 7 significant decimal digits. Your number has 8 decimal significant digits so you see the loss of accuracy in the one last significant digit.
Here's More information on float representation
Double precision are 64 bits and have 52 bit for the mantissa which is 4,503,599,627,370,496 (a 16 digit number) and thus have roughly 15-16 decimal digit accuracy.
A decimal
type is something that potentially allows you to save any number of any length in any accuracy. C# has them but unfortunately they are not a primitive type in C++. You can probably find some 3rd party library that implements them in C++.
Read this:
"What every computer scientist should know about floating point"
http://www.validlab.com/goldberg/paper.pdf
Floats have very low precision for high (3 billion +) numbers.
Float's precision is the best in range 0-1. The further you go from zero, the lesser is the precision. And at around three billion, it is not even precise enough to hold every integer (so it rounds to the closest value it can represent).
Solution: Use double (or decimal representation).
The accuracy of representation of various floating point types varies based on their size. For a 32 bit float you can expect approximately 7 digits of precision. For double's it is approximately 16 digits.
I highly recommend reading up on floating point representations and the various advantages and disadvantages. It'll save you a lot of hassle in the long run, especially when things like comparisons don't work as you expect.
精彩评论