Hi,
I am having some hard time using numbers. In my code I have this:
float x = 0.0;
float y = some_float_variable_that_changes_every_time*180/M_PI;
float z = abs(x - y);
Serial.println(x);
Serial.println(y);
Serial.println(z);
I am having this in my serial:
0.00
-0.7532
0
If I execute that code above I always get 0 in the last line. It also shows one when this happens:
0.00
-1.2094
1
I assume the function "abs" is for some reason truncating the module of the subtraction. Why?
[codefloat x = 0.0;
float y = some_float_variable_that_changes_every_time*180/M_PI;
float z = abs(x - y);]
It would be best to copy the entire sketch.... With setup() and loop()..
Did you initialize this var: some_float_variable_that_changes_every_time
What about: M_PI
Bits & pieces are useless in answering what you are doing... Obviously the sketch compiled so we are missing lots.
abs() is an integer function. Integer input and an integer result so abs(0.0 - (-0.7532)) is zero.
Use fabs().
Pete
I think this will answer your question about abs()
ABS
Ray
system
December 31, 2014, 1:47pm
5
In C++, "abs" is an "int" function, so "2" is the correct answer.
Please get into the habit of using code tags when posting code.
system
December 31, 2014, 2:52pm
6
AWOL thank you for helping but I think you are wrong.
You're perfectly entitled to your opinion and beliefs, and to express them.
I think that spending three days on a trivial problem that could be solved in 30 seconds of Googling is a total waste of time.
As AWOL said:
AWOL:
In C++, "abs" is an "int" function, so "2" is the correct answer.
(...)
So, try this code:
void setup() {
Serial.begin(115200);
}
void loop() {
Serial.println(fabs(-2.7));
}
The result is what you want? Can you see the differences?
Crossposting when you don't like the answer is also a waste of time - everybody else's time.
Pete
system
December 31, 2014, 3:30pm
9
gilperon:
Also, in the docs of abs function it does not say it works only with int. Any idea?
C++.
cstdlib defines, int abs(int)
cmath defines overloads, double abs(double), float abs(float) and long double abs(long double)
No idea how that relates to the Arduino compiler
I copy pasted your sketch as is, had to change the includes from "..." to <...>
Compiled it with 1.0.6 for Mega2560
I get "2.7" with all the libraries included.
Swapping the libraries about, I don't seem to be able to break it.
el_supremo:
Crossposting when you don't like the answer is also a waste of time - everybody else's time.
Pete
I didn't see the other post .
That's because the other thread has already been merged with this one. It starts with message #5 .
Pete
system
December 31, 2014, 3:42pm
12
Duplicate threads merged and locked.
DO NOT CROSS-POST, IT WASTES TIME.