Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi line math results different than single line

I was having an issue with some floating point math and I've found that if I do my math on one line, I get -0 passed to tan(), and if I do it across two lines, I get 0 passed to tan(). Have a look:

float theta = PI / 2.f;
float p = (PI / 2.f) - theta;
float result = tan(p);

The above, p = -0, result = -4.37...

float theta = PI / 2.f;
float p = PI / 2.f;
p -= theta;
float result = tan(p);

The above, p = 0, result = 0.

Can anyone explain the difference? I assume the -0 is causing that result from tan(), although I can't find anything on google that explains why. Why does the exact same calculation spread across different lines result in a different answer?

Thanks

like image 962
taurous Avatar asked Dec 28 '18 07:12

taurous


2 Answers

It is probably because of the type of PI.

If you use double it will change to float and then the outcome will be as you just represent.

But if PI is float both of this test scenarios are equal.

like image 148
Naor Tedgi Avatar answered Oct 25 '22 05:10

Naor Tedgi


What @Naor says is probably correct. but I'd like to add something.

You probably not getting -4.37xx but -4.37xxxe-xx which is a pretty small negative number.

Since you can always get errors in floating point math. I'd say there is no need to change your code. Both snips are correct.

like image 36
apple apple Avatar answered Oct 25 '22 06:10

apple apple