Multi line math results different than single line

  • A+
Category:Languages

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

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: