Pietro Lazzarotto Pietro Lazzarotto - 1 year ago 88
C++ Question

C++ cout prints " inf " after operations between two big decimal number (long double)

My program takes a vector of long doubles as input (

vector<long double>
) and calculates different solutions using some methods.

Everything works fine untill I try these two numbers: 1.18973e+4932 and 1.18973e+4932.

It outputs the following:

<2: 1.18973e+4932 1.18973e+4932 >

Min: 1.18973e+4932
Max: 1.18973e+4932
Range: 0
Midrange: inf
Median: inf
Mean: inf
Variance: inf
StdVariance : inf

After some researches, I found out that the value is exceeding the space in memory available for its own type.

So the question is: is it possible to handle this inside my code? Or the only solution is to input a smaller number?

Answer Source

Scaling might help depending on what the compiler chooses to do with your code:

$ cat s.cpp
#include <iostream>

int main()
    long double v = 1.18973e+4932L;

    std::cout << "Midrange: " << (v + v) / 2 << '\n';
    std::cout << "Midrange again: " << (v/2 + v/2) << '\n';
    return 0;

$ g++ s.cpp -Wall -O2 -o s

$ ./s
Midrange: inf
Midrange again: 1.18973e+4932

You can also avoid calculating anything when the sample min and max are equal, and just set mean, midrange and median equal to either value, and range, variance and standard deviation to 0.0 without messing around any further.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download