I am implementing a math calculation in Objective-C in which i have used pow(<#double#>, <#double#>) function but it behaves weird.

I am trying to solve below math

  100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12)) 

For same math, result of excel and xcode is different.

 Excel output = 100.01001 (correct)
 NSLog(@"-->%f",100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12)));
 Xcode output = 100.045667 (wrong)

Now as everyone knows 3/12 = 0.25.
When i replace *3/12* with 0.25 in above math than xcode returns true result as below

 Excel output = 100.01001 (correct)
 NSLog(@"-->%f",100 *(0.0548/360*3+powf(1+0.0533, 0.25)/powf(1+0.0548, 0.25)));
 Xcode output = 100.010095 (correct)

Anyone knows why pow function behave weird like this?
Note: I have also used powf but behavior is still same.

有帮助吗?

解决方案

3/12, when you're doing integer math, is zero. In languages like, C, C++, ObjC and Java an expression like x / y containing only integers gives you an integral result, not a floating point one.

I suggest you try 3.0/12.0 instead.

The following C program (identical behaviour in this case to ObjC) shows this in action:

#include <stdio.h>
#include <math.h>
int main (void) {
    // Integer math.

    double d = 100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12));
    printf ("%lf\n", d);

    // Just using zero as the power.

    d = 100 *(0.0548/360*3+powf(1+0.0533, 0)/powf(1+0.0548, 0));
    printf ("%lf\n", d);

    // Using a floating point power.

    d = 100 *(0.0548/360*3+powf(1+0.0533, 3.0/12.0)/powf(1+0.0548, 3.0/12.0));
    printf ("%lf\n", d);

    return 0;
}

The output is (annotated):

100.045667 <= integer math gives wrong answer.
100.045667 <= the same as if you simply used 0 as the power.
100.010095 <= however, floating point power is okay.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top