1

My program takes a vector of long doubles as input (vector<long double>) and calculates different solutions using some methods.

Everything works fine until 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?

phuclv
  • 37,963
  • 15
  • 156
  • 475
L4ZZA
  • 83
  • 12
  • How about this: http://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout – Marco Nov 30 '16 at 16:19
  • 5
    [mcve]'s make solutions way easier, and more reliable. – Topological Sort Nov 30 '16 at 16:21
  • 1
    Please post your code. – Jarvis Nov 30 '16 at 16:24
  • 1
    First, there is no guarantee that `long double` is larger than `double`. Second, whether you use `double` or `long double`, there are a finite number of them whereas there are uncountably many real numbers. So, some will not be representable in the chosen format. – Sinan Ünür Nov 30 '16 at 16:25

1 Answers1

1

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.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • Your post was helpful but it covered only one test case. Now I found another case in which that happen and I can't understand why. `<2: 1.18973e+4932 1.18973e+4932 > Min: 5.94865e+4931 Max: 1.18973e+4932 Range: 5.94865e+4931 Midrange: 8.92298e+4931 Median: 2.97433e+4931 Mean: inf Variance: inf Std_deviation : inf `. here the second number is the first devided by 2 and since they're not equal the calculations are executed and the result overflows. How would you solve it? – L4ZZA Jan 04 '17 at 13:10