0

I've been working on my math parser a bit, and I have come to realize that a bit of code I'm using is unable to handle an exponent that is non-interger. The bit of code I'm using seems to work just fine with an int, but not with a double.

else if ([[token stringValue] isEqualToString: @"^"])
    {
        NSLog(@"^");
        double exponate = [[self popOperand] intValue];
        double base     = [[self popOperand] doubleValue];
        result = base;
        exponate--;
        while (exponate)
        {
            result *= base;
            exponate--;
        }
        [self.operandStack addObject:  [NSNumber numberWithDouble: result]];

    }

' Using Objective-C, how do I make something like 5^5.5 evaluate properly? (6987.71242969)

Joe Million
  • 147
  • 9
  • 2
    Any reason you are not using `pow()` for exponentiation? – Sebastian Aug 06 '13 at 09:39
  • I had never up until this point needed to use it. I'm pretty much self taught. But thanks, another tool I didn't know about added to the toolbox. – Joe Million Aug 06 '13 at 10:05
  • @JoeMillion Also, FYI, the second operand is called the "exponent", not an "exponate". –  Aug 15 '13 at 20:24

2 Answers2

4

Let library code do the work for you:

double exponent = [[self popOperand] doubleValue];
double base = [[self popOperand] doubleValue];

[self.operandStack addObject:@(pow(base, exponent))];
jscs
  • 63,694
  • 13
  • 151
  • 195
2

Josh's answer is right, I just wanted to add something about using floats in conditions:

double exponate = [[self popOperand] intValue];
exponate--;
while (exponate)
{
    result *= base;
    exponate--;
}

This can lead to an infinite loop because of rounding erros while (exponate) might never evaluate to false. If you are using doubles or floats as loop variables, always do something like while (myFloat > 0.0)

Sebastian
  • 7,670
  • 5
  • 38
  • 50