Number of bits (field in general) required to store decimal number
I am trying to write program as
if I give any decimal number as input n, it should give output x = log2n i.e log n/log2 Quote:
So Is there is any better way or algorithm to implement in program. Guide me please. |
Code:
int bits= (int) floor (ln (num) / ln (2)); |
yes.
Thank you for introducing new library function floor().But in my case I need to use ceil() as to round up value. Actually I thought that this formula(log n/log 2) fails after certain number. But I will stick with this. |
Code:
int bits= (int) floor (ln (num) / ln (2)) + 1; Quote:
|
You are right, it is ceil what you need, my bad.
Code:
int bits= (int) ceil (ln (num) / ln (2)); Code:
for (ntmp= num, ndigits= 0; ntmp>0; ntmp /= 2) ++ndigits; |
Quote:
Quote:
|
Thank you for pointing out my faults.
Anyways, let's try something to encode positive integers with bitvectors. Well, every positive integer can be written in binary, and the first binary digit is always 'one'. Let's store every bits, except for the first one: Code:
1 - [] |
A few comments here:
(1) There are several well-known floating point number formats. All of them store an exponent and a mantissa. The actual number of "digits" represented internally is reflected in the mantissa, which is then raised to the power of the exponent. Probably the most-common format is the Extended floating-point type of the now-ubiquitous Intel® microprocessors. (2) Each time you see a floating-point number, it has been converted to a printable (decimal) representation ... which, as it happens, is not exactly equal to its float-binary (internal) representation. Thus, "5.12" might be displayed as "5.1" or "5." and in any case it probably is not exactly-equal to "5.1200000...". (3) Determination of "how many digits of the answer are significant" is really a basic engineering question, and would be even if you were using a slide-rule. Functions such as ln() are, after a certain point, just estimations. There's a certain, predictable amount of numeric error, and the subsequent series of operations that you perform will increase (never "decrease") that accumulated error. (4) "Truly-decimal" floating point packages do exist ... which represent the numbers in question as individual digits and perform math exactly the way that you'd do it by hand. But these are typically used for accounting, not engineering applications, and I would not expect any of them to include transcendantal functions. |
All times are GMT -5. The time now is 01:55 PM. |