Ivan Lim
Ivan Lim

Reputation: 1

Maximum decimal places in C

I've run into a small problem. I'm trying to find whether the reciprocal of a number contains the number in C. However, I can't printf the reciprocal that more than 15 decimal places by using float or double. How can I do to have as much decimal places as possible(like over 100++)?

solution:

char output[10000];
void divide(int a, int b, char *c, int d)
{
    if (d == 10000)
        return;
    int e = a/b;
    int f = (a%b)*10;
    if(d>=1)
        c[d+1] = e + '0';
    divide(f, b, c, d+1);
}

Upvotes: 0

Views: 3563

Answers (1)

Andre Motta
Andre Motta

Reputation: 769

Formatting the printf is not the problem here. It's the data type that is. Floating point numbers in C use IEEE 754 encoding.

This type of encoding uses a sign, a significand, and an exponent.

Because of this encoding, many numbers will have small changes to allow them to be stored. Also, the number of significant digits can change slightly since it is a binary representation, not a decimal one.

Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.
Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.

The smallest positive number you can store in a double is about 2⨯10-308, not counting denormalized numbers, which can be smaller. They have the equivalent of about 15-17 digits of precision, which is sufficient to measure the diameter of the Earth to within the size of a red blood cell, the smallest cell in the human body.

Therefore, you need a big numbers library to deal with your problem.

I suggest HPALIB as it is a simple tool to solve your problem. Please be wary that a number that big will take up a lot of memory.

Upvotes: 4

Related Questions