7 years, 4 months ago.

Whats wrong with this code?

include the mbed library with this snippet

double getSTD(int arr[], int size , double avg)
{
    int sum = 0; 
    double temp; // resolves sqrt(int/int error
    double stdDev;
    for (int i = 0; i < size ; i++)
        sum = sum + ((arr[i]-avg)*(arr[i]-avg));
    
    temp = sum/size;
    stdDev = sqrt(temp); 
    return stdDev;
}

this piece of code seems to be stalling my program , any advice? using this in the forloop works , but gives wrong answer :D : sum = sum + pow((arr[i] - avg), 2);

With which data are you calling this function?

posted by Erik - 10 Apr 2013

What MCU is running this code?

posted by Christian Lerche 10 Apr 2013

2 Answers

7 years, 3 months ago.

Hello,

There is at least mixed int and double data types on the calculation which cause truncation errors in the case of using decimal values. I assume following code explains how to fix that:

int result = 0;
double dResult = 0.0;
int xsum = 0;
int a = 0;
double b = 1.0;
double dxsum = 0.0;

// 2^2 = <OK> 4
a = 3;
b = 1.0;
result = ((a-b)*(a-b));
xsum += result;

// 1.5^2 = <WRONG !>2
a = 2;
b = 0.5;
result = ((a-b)*(a-b));
xsum += result;

// 1.5^2 = <OK> 2,25
a = 2;
b = 0.5;
dResult = (((double)a-b)*((double)a-b));
dxsum += dResult;

Consider also to avoid using double data type in embedded because calculation take lot of time.

Br Vesku

P.S [edit] Notice also the variable sum should be double to avoid truncation error caused on every single loop round. If truncation from double to int is done there is need to add extra 0.5 to sum before casting to int.

	int sum = 0;
	double a = 0.42;
	sum += a + a;		// <WRONG> sum = 0 (0.82 ~= 0)
	sum += 0.5 + a + a; // <OK>    sum = 1 (0.82 ~= 1)

Truncation should done after came out of loop and inside loop one should use double to calculate accurate sum. Br Vesku

7 years, 3 months ago.

Thanks for the advice... my problem was the array that i was passing to the function lol. with so many lines of code... it took me a while to figure it out =_=.