tags:

views:

56

answers:

2

I introduced myself to the GMP library for high precision arithmetic recently. It seems easy enough to use but in my first program I am running into practical problems. How are expressions to be evaluated. For instance, if I have "1+8*z^2" and z is a mpz_t "large integer" variable, how am I to quickly evaluate this? (I have larger expressions in the program that I am writing.) Currently, I am doing every single operation manually and storing the results in temporary variables like this for the "1+8*z^2" expression:

1) first do mpt_mul(z,z,z) to square z

2) then define an mpz_t variable called "eight" with the value 8.

3) multiply the result from step one by this 8 and store in temp variable.

4) define mpz_t variable called "one" with value 1.

5) add this to the result in step 3 to find final answer.

Is this what I am supposed to be doing? Or is there a better way? It would really help if there was a user's manual for GMP to get people started but there's only the reference manual.

+1  A: 

GMP comes with a C++ class interface which provides a more straightforward way of expressing arithmetic expressions. This interface uses C++ operator overloading to allow you to write:

mpz_class z;
1 + 8 * z**2

This is, of course, assuming you're using C++. If you are using C only, you may need to use the C interface to GMP which does not provide operator overloading.

Greg Hewgill
Yes. I am using pure C.
Dr. Person Person II
In that case, you are taking the correct approach. You may wish to consider moving to C++ if you are going to be doing this sort of thing a lot.
Greg Hewgill
A: 

Turns out that there's an unsupported expression parser distributed with GMP in a "expr" subdirectory. It's not part of GMP proper and is subject to change but it is discussed in a README file in that directory. It isn't guaranteed to do the calculation in the fastest way possible, so buyer beware.

So the user must manually evaluate all expressions when using GMP unless they wish to use this library or make their own expression parser.

Dr. Person Person II