c++ (unsigned)(long((double)(8) / (double)log(2.0)) == 2?
as the title says I am getting something very irrational.
I have a program in C++ and what Im trying to do is figure out what my new height is for a binomial queue.
To do this I'm using the algorithm up in the title:
(unsigned)(long((double)(8) / (double)log(2.0))
it actually looks like:
// int count = # of nodes within my vector.
(unsigned)(long开发者_JAVA技巧((double)(count) / (double)log(2.0))
and it does print out a double 3.00000, but when i try to type cast it into an "unsigned int" it gives me a 2.
Why is it giving me this answer? Help?
Casting to integer introduces quantization (truncation) error of as much as 1.0.
Anyway, you need to make sure to round up when computing the required depth of your tree.
BTW, there are much better ways of calculating log base 2 than ratio of logarithms. For example, gcc's __builtin_clz
would be very helpful, the MSVC equivalent is _BitScanReverse
.
The problem is, that conversion from floating-point to integer numbers doesn't automatically do the rounding. The decimal part is simply chopped of, the number is truncated. Even if the double was 2.95834..
it will be 2
after the truncation. Use ceil
and floor
from the standard library to fix that.
This:
(unsigned)(long(log((double)(8)) / (double)log(2.0)))
returns 3, for reason obvious.
And
(unsigned)(log((double)(8) / (double)log(2.0)));
returns 2.
Reasons? I guess roundoff error. The internal error caused by the cmath library leads to a result like 2.99......., then it is cast to a int of 2.
And for the truly interested (bored?), here's an excellent article on this by David Goldberg of PARC:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Sounds like the classic floating-point "rounding" issue:
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
http://docs.python.org/tutorial/floatingpoint.html
Try pick an acceptable tolerance (one that's "close enough" for your application) and add that to the result before you truncate it back to a long.
first, you miss a ')'. second, we know, to describe a number by binary in computer.and some float number we can't convert it to binary, we just express the float with binary approach.that mean the float is single-precision floating point.so "long((double)(8) / (double)log(2.0))" result my be is 2.999999.
精彩评论