SnakingPrabhu
SnakingPrabhu

Reputation: 166

Find the exponential value using NSExpression?

I am trying to calculate exponential values using NSExpression like below:

NSNumber *number1 = [NSNumber numberWithInteger:2];        
NSNumber *number2 = [NSNumber numberWithInteger:4];

NSArray *arrNum=[NSArray arrayWithObjects:number1,number2,nil];
NSExpression *arrayExpression = [NSExpression expressionForConstantValue: arrNum];

NSArray *arrExp=[NSArray arrayWithObject:arrayExpression]; 

NSExpression* expression =[NSExpression expressionForFunction:@"raise:toPower:" arguments:arrExp];

NSLog(@"powerExp:%@",expression);

int  resultSum = [[expression expressionValueWithObject:nil context: nil] intValue];

NSLog(@"resultnum:%f",resultSum);

I got the error:

-[__NSArrayI doubleValue]: unrecognized selector sent to instance 0x7439e60 2012-10-22 16:04:04.034 operator[3958:c07] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI doubleValue]: unrecognized selector sent to instance 0x7439e60'

Upvotes: 1

Views: 676

Answers (2)

Martin R
Martin R

Reputation: 540025

NSNumber *number1 = [NSNumber numberWithInteger:2];
NSNumber *number2 = [NSNumber numberWithInteger:4];

NSExpression *expr1 = [NSExpression expressionForConstantValue:number1];
NSExpression *expr2 = [NSExpression expressionForConstantValue:number2];

NSArray *exprArgs = [NSArray arrayWithObjects:expr1, expr2, nil];

NSExpression *expression = [NSExpression expressionForFunction:@"raise:toPower:" arguments:exprArgs];
NSLog(@"powerExp:%@",expression);

int resultSum = [[expression expressionValueWithObject:nil context: nil] intValue];
NSLog(@"resultnum:%d",resultSum);

Output:

powerExp:2 ** 4
resultnum:16

Upvotes: 1

Rob Napier
Rob Napier

Reputation: 299595

expressionForConstantValue: takes an NSNumber. You passed it an NSArray of NSNumber.

The exp: function takes a single number (n) and returns e^n. Is that what you're trying to do? Or did you mean to use raise:toPower:, which takes two values?

Upvotes: 0

Related Questions