Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can C store a 1001 bit number in double data type?

Tags:

c

double

This is the code to calculate 1000th power of 2.

#include <stdio.h>

int main() {
    double multiply = 1;
    int i;
    for(i = 1; i <= 1000; i++) {
        multiply *= 2;
    }
    printf("%lf\n", multiply);
    return 0;
}

And the output on my system, as well as ideone

10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

which is exactly the right answer:

irb(main):001:0> 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376 == 2 ** 1000
=> true
like image 732
user1527166 Avatar asked Dec 07 '22 10:12

user1527166


1 Answers

According to IEEE 754, floats etc. are stored in a 2-power format: sign, mantissa and exponent for base 2.

So 2^1000 is, simply spoken, stored with a mantissa of exactly 1 and an exponent of 1000.

If you would add 2, the value isn't correct any longer.

like image 168
glglgl Avatar answered Jan 14 '23 04:01

glglgl