How to calculate formulas like (a + b) ^ 2, sum((a + b) / 2)
using NSExpression
? I am the beginner to NSExpression
.
(a + b) ^
NSExpression
is not a general-purpose mathematical expression evaluator. It's meant to be used with NSPredicate
to describe selection criteria in Core Data queries.
NSExpression is used to represent expressions in NSPredicate. It is not intended for the tasks like yours.
Actually, you can use NSExpression
to calculate the formula value, but this usage is quite limited. To evaluate any mathematical expression you would need to make a string parser using some algorithm i.e. Shunting-yard or just reuse a library like this one.
NSExpression is great for evaluating mathematical expressions. It is NOT only limited to core data queries and you DO NOT need additional third party libraries or write your own parser to evaluate expressions as strings.
To actually answer the question for (a + b) ^ 2 ;)
NSNumber *a = @4;
NSNumber *b = @4;
NSExpression *expression = [NSExpression expressionWithFormat:@"(%@ + %@)**2", a, b];
NSNumber *result = [expression expressionValueWithObject:nil context:nil];
NSLog(@"%@",result);
NSExpression is useful for evaluating math expressions in objective c.
let's see how to find the standard deviation of numbers using NSExpression
NSArray *arrNumbers = @[@3, @6, @3, @8, @4, @12, @9, @11];
NSExpression *expression = [NSExpression expressionForFunction:@"stddev:" arguments:@[[NSExpression expressionForConstantValue:arrNumbers]]];
id value = [expression expressionValueWithObject:nil context:nil];
It's that simple.
Below is list of functions grouped by category.
1)List of statistics methods
average:
sum:
count:
min:
max:
median:
mode:
stddev:
2)Arithmetic functions
add:to:
from:subtract:
multiply:by:
divide:by:
modulus:by:
abs:
sqrt:
log:
ln:
raise:toPower:
exp:
3)Bounding functions
ceiling:
trunc:
4)Random functions
random
random:
5)Binary arithmetic functions
bitwiseAnd:with:
bitwiseOr:with:
bitwiseXor:with:
leftshift:by:
rightshift:by:
onesComplement:
6)Date functions
now
7)String functions
lowercase:
uppercase:
8)No-Op
noindex: