An obvious behavior, simple mean code

uuuuuuuuuuuuuuu
Last edited on
I'm guessing overflow. Haven't calculated the total value you're saving, but it might be going beyond what a float can keep.

Try using an (long) integer for sum and returning (float)sum/(1024*2048).
I think a float keeps up to 3ishE+38 so of course no overflow.

What do you mean with
its start to add 16


Check ptr is initialized correctly. And use code tags.
Use double instead of float and it will work.
1
2
3
4
5
6
7
8
double findAvg(double* ptr,int step)
{
double sum=0;
for (int r=0;r<1024;r++)
for(int c=0;c<2048;c++)
sum+=ptr[r*step+c];
return sum/(1024*2048);
}
Last edited on
Thanks!
Looks like a rounding error in this giant sum.

When the total so far reaches a certain point it is much larger than the individual values being added on.
The added on value need to be be adjusted to the same floating point exponent as the sum so far.
This means moving the digits down and some fall of the end, giving an inaccurate representation.

Using doubles will help fix this because they have much more digits and so will not lose accuracy so quickly.

Ziv Mhabary, please don't remove your first post. If you are not allowed to ask for questions, don't ask!

Here is the post in case someone is interested
Hello,
I have the next code which calculate mean of an matrix.
all the values in the matrix are 17. from some reason, after some iterations, its start to add 16 to the sum parmeters. Any idea way?

The code:
float findAvg(float* ptr,int step){
float sum=0;
for (int r=0;r<1024;r++)
for(int c=0;c<2048;c++)
sum+=ptr[r*step+c];
return sum/(1024*2048);
}

Thanks!
Last edited on
OP

Hello,
I have the next code which calculate mean of an matrix.
all the values in the matrix are 17. from some reason, after some iterations, its start to add 16 to the sum parmeters. Any idea way?

The code:
float findAvg(float* ptr,int step){
float sum=0;
for (int r=0;r<1024;r++)
for(int c=0;c<2048;c++)
sum+=ptr[r*step+c];
return sum/(1024*2048);
}

Thanks!
Topic archived. No new replies allowed.