'C++ - dealing with infinitesimal numbers

I need to find some way to deal with infinitesimial double values. For example:

exp(-0.00000000000000000000000000000100000000000000000003)= 0.99999999999999999999999999999899999999999999999997

But exp function produce result = 1.000000000000000000000000000000

So my first thought was to make my own exp function. Unfortunately I am getting same output.


double my_exp(double x)
{
    bool minus = x < 0;
    x = abs(x);
    double exp = (double)1 + x;
    double temp = x;
    for (int i = 2; i < 100000; i++)
    {
        temp *= x / (double)i;
        exp = exp + temp;
    }
    return minus ? exp : (double)1 / exp;
}

I found that issue is when such small numbers like 1.00000000000000000003e-030 doesn't work well when we try to subtract it, neither both if we subtracting or adding such a small number the result always is equal to 1.

Have U any idea how to manage with this?



Solution 1:[1]

I think the best way of dealing with such small numbers is to use existing libraries. You could try GMP starting with their example to calculate billions of digits of pi. Another library, MPFR which is based on GMP, seems to be a good choice. I don't know when to choose one over the other.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1