 # What's up with the abs() function :D?

Hi, I just noticed that under the abs function the description is as follows :

“Computes the absolute value of a number.abs(x); where x is the number The function returns x if x is greater than or equal to 0 and returns -x if x is less than 0.”

the absolute value should never be negative if I’m not mistaken ?

If x = +2, then abs(x) returns x or +2.

If x = -2, then abs(x) returns -x or -(-2) = +2.

So it does what you want.

1 Like

ahhh now it makes sense, I’m having issues with the decimals disappearing - is that a result of the abs() function ? - or the numbers after the decimal point turning into 0

where prev and array are both float arrays

float difference = array[i]-prev[i];
accDifference[i] = abs(difference);
differenceSum += accDifference[i];

On Spark right now, abs() is a macro so you can have problems if you put certain operations inside the parens–the doc gives the example `abs(a++)` as being something to avoid. I don’t know of a way that abs() could lose precision, though.

If you are having problems, I would make sure that your taking abs() of just a variable: `y = abs(x);` so that nothing bad can happen.

If you want to post some code, we can have a look and try to help.

here’s the code that I’m using atm float difference = array[i]-prev[i];
accDifference[i] = abs(difference);
differenceSum += accDifference[i];

where array and prev are both float arrays

What types are accDifference[] and differenceSum in your code above?

C has a rule for the += operator that the right hand side is always cast into the left hand side’s type before the operation is performed, so if I had guess, that is where your problems is.

accDifference is an array of floats and differencesum is a float - so it shouldn’t be typecasting anything ?

float accDifference;

``````unsigned long Now = millis(); // Used to compare to last punch

// check to see if there is a previous value before calculating differences
if(on == false){
for(int i = 0; i < 3; i++){
prev[i] = array[i];
on = true;
}
}

else if(Now - lastPunch > punch_delay) {

for(int i = 0; i < 3; i++){

float difference = array[i]-prev[i];
accDifference[i] = abs(difference);
differenceSum += accDifference[i];

prev[i] = array[i];

}

filterSignal(accDifference);

}
``````

}

Ok so i fixed it - I’m guessing the abs() function returns an int ?

So I just made another function ``````float absolute(float num){
if(num < 0){
return -num;
}else{
return num;
}
}
``````

works like a charm now

1 Like

Yes, abs() is integer while fabs() is float. While fabs() is standard C, the spark docs do not mention it specifically so I can’t say if it is implemented. Worth a test, though.

1 Like

Is there an emoticon for face palm? Boy did I miss the obvious–sorry!

fabs() is there if you `#include "math.h"`

2 Likes