iPera
iPera

Reputation: 1073

Strange behavior of the function pow() in Objective-c

I have stupid problem with pow() in my application. Here is the code:

double xf = 0.0153846154;

NSLog(@"%.10f", xf);
if (abs(xf) < (5.0 * pow(10.0, -9.0))) {
    NSLog(@"%.10f", 5.0 * pow(10.0, -9.0));
}

but if I try this one comparation is correct:

if (abs(xf) >= pow(10.0, 10.0)) {
    NSLog(@"%f", pow(10.0, 10.0));
}

and my Log is:

2012-10-13 15:45:24.587 myApp[22941:c07] 0.0153846154
2012-10-13 15:45:28.950 myApp[22941:c07] 0.0000000050

Can someone explains me why is 0.0153846154 < 0.0000000050

Upvotes: 0

Views: 131

Answers (1)

Paul R
Paul R

Reputation: 213049

abs is an integer function so xf gets truncated to 0, so the function result is 0, which then gets cast back to 0.0 for the comparison.

You need to use fabs:

NSLog(@"%.10f", xf);
if (fabs(xf) < (5.0 * pow(10.0, -9.0))) {
    NSLog(@"%.10f", 5.0 * pow(10.0, -9.0));
}

Upvotes: 4

Related Questions