1

Maybe this is an idiot question but I can't figure out the problem.

Running the following code:

    double num = 0.0;
    double den = 0.0;
    std::string line;
    if (std::getline (file,line))
    {
        std::istringstream iss(line);
        while (iss>>valueLine[j++]){} //Read and parse an entire line
        for (int i = 0; i < numberOfUe; i++)
        {
            num = num + (valueLine[i+1]/1000);
            den = den + ((valueLine[i+1]*valueLine[i+1])/1000000);
        }
        [...]

I obtained that ((valueLine[i+1]*valueLine[i+1])/1000000) = -1010 when valueLine[i+1] = 57314. Where is the error? Why I obtained a negative result? What I'm missing?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
rebatoma
  • 734
  • 1
  • 17
  • 32

2 Answers2

4

Note that:

3284894596  = 57314 * 57314

while in my machine for example, INT_MAX is:

2147483647

which means, that you are a victim of overflow ( that's why you did good for posting in Stackoverflow :) ).

In your machine INT_MAX may have another value, but again it is smaller than 57314².

You may also want to take a look here:

maximum value of int


Your move to divide won't do any good, since the multiplication will happen first. You could use unsigned int. On my machine:

#include <limits>
#include <iostream>

int main(){

    std::cout << std::numeric_limits<unsigned int>::max() << std::endl;
    unsigned int a = 57314;
    std::cout << a * a << std::endl;
}

gives:

4294967295
3284894596

PS - You could divide each term with 100, but you will lose some accuracy if you are not careful.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

You are more than likely hitting a overflow. Really large numbers squared together can create a number that cannot be stored in the memory allocated for your valueLine[i+1] so it "overflows" into the negative number.

Things you could try:

  • Using an unsigned long type (e.g., uint64_t) instead of double
  • If you need signed values try using a larger type

Check out and MSDN article relating to type sizes: MSDN

radical7
  • 8,957
  • 3
  • 24
  • 33