Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

Try using std::expm1

Computes the e (Euler’s number, 2.7182818) raised to the given power
arg, minus 1.0. This function is more accurate than the expression
std::exp(arg)-1.0 if arg is close to zero.

#include <iostream>
#include <cmath>

int main()
{
    std::cout << "expm1(-0.00000000000000000000000000000100000000000000000003) = " << std::expm1(-0.00000000000000000000000000000100000000000000000003) << '\n';
}

Run the example in the below source by changing the arguments to your very small numbers.

Source: https://en.cppreference.com/w/cpp/numeric/math/expm1

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading