Friday, 15 April 2011

Objective C if statement possibly not working correctly -



Objective C if statement possibly not working correctly -

i hesitant set because know 99.9% of time user blame error confused one.

i have float named rotation defined in header such:

@property(nonatomic)float rotation;

after rotation has been given value check using if statement

if (fabsf(rotation) == m_pi_2) { nslog(@"execute more code now"); }

now have checked definition of m_pi_2 , came 1.57079632679489661923132169163975144

i noticed wasn't working set nslog before if statement such:

nslog(@"%f == %f", fabs(rotation), m_pi_2);

these results got:

2014-06-26 16:29:40.831 76j284e[82085:60b] 0.000000 == 1.570796 2014-06-26 16:29:40.834 76j284e[82085:60b] 3.141593 == 1.570796 2014-06-26 16:29:44.653 76j284e[82085:60b] 0.000000 == 1.570796 2014-06-26 16:29:44.658 76j284e[82085:60b] 3.141593 == 1.570796 2014-06-26 16:29:47.951 76j284e[82085:60b] 0.000000 == 1.570796 2014-06-26 16:29:47.953 76j284e[82085:60b] 3.141593 == 1.570796 2014-06-26 16:29:54.305 76j284e[82085:60b] 0.000000 == 1.570796 2014-06-26 16:29:54.310 76j284e[82085:60b] 1.570796 == 1.570796 2014-06-26 16:29:54.313 76j284e[82085:60b] 4.712389 == 1.570796 2014-06-26 16:29:54.318 76j284e[82085:60b] 3.141593 == 1.570796

shouldn't few of trigger if statement? doing wrong here, thanks.

edit

i should add together defining rotation m_pi_2 (at times)

your problem m_pi_2 double , rotation float. statement:

float rotation = m_pi_2;

takes double-precision constant m_pi_2, rounds float precision (throwing away 29 bits of mantissa) , assigns rotation.

later on check see if rounded value matches unrounded value. doesn't. 'cause it's been rounded.

try defining m_pi_2 1.570796

nope. 1.570796 still double, , cannot represented float or double, rounding issue still occurs. seek this:

const float m_pi_2 = 1.57079632679489661923132169163975144f;

float rotation = m_pi_2;

if (rotation == m_pi_2) ...

assigning constant float and/or appending 'f' constant trick.

for more details:

http://randomascii.wordpress.com/2012/06/26/doubles-are-not-floats-so-dont-compare-them/

also, when printing floats need print 9 digits of mantissa, otherwise don't know float have. doubles need 17 digits of mantissa. more information:

http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/

objective-c

No comments:

Post a Comment