Is there a relatively easy way to use mathematical operators with string variables in Objective C?
For example:
The string "x*x" should return "x^2"
The string "x/x" should return "1"
I'm looking for something that would actually use the variable name "x" without an assigned numerical value and return an answer in terms of "x".
If you put the 'x' value as string then you can evaluate it as :
NSString *string=@"3*3";
NSExpression *expression = [NSExpression expressionWithFormat:string];
float result = [[expression expressionValueWithObject:nil context:nil] floatValue];
NSLog(@"%f", result);
Also,
NSString *string=@"34*(2.56+1.79)-42/1.5";
NSNumber *result=[NSExpression expressionWithFormat:string];
NSLog(@"%@", result);
Change to any datatype float
to int
etc as per your requirement
I've had a look for an Objective C lib doing algebraic manipulation and haven't found much yet.
So your best bet might be to use a C library (Objective C is a superset of ANSI C, after all, and you can mix the the two).
Check out this list of C maths libs:
http://www.mathtools.net/C_C__/Mathematics/
From that list, it seems that Mathomatic might be of use.
Two strategies for using a C library in your Objective C:
Just call the C functions from your Objective C code
Create an Objective C wrapper for the C library and use that (and maybe release it for others to use :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With