Reputation: 317
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".
Upvotes: 5
Views: 408
Reputation: 387
You can see GiNaC library (www.ginac.de). It is opensource math library. You can simplify algebraic expressions with this library. And also you can compile it on OSX and link it into your Xcode project like a static C++ library. 1. You need to download Ginac, CLN and Pkg-Config (http://www.freedesktop.org/wiki/Software/pkg-config/). 2. Unpack and compile Pkg-Config in your /usr/local directory 3. Unpack and compile CLN 4. Unpack and compile Ginac
Then go to you Project settings in Xcode chose your target and put your headers files path to the Header Search Path in Build Settings. Then go to Build Phases - Link Binary With Libraries click "+" and chose Add Other, then choose your compiled library file libginac.a Thats all i think. Dont forget to include your ginac.h file into your class header file.
#include <ginac.h>
Upvotes: 0
Reputation: 17014
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 :)
Upvotes: 1
Reputation: 46543
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
Upvotes: 1