GMP arithmetic operations
As we know GMP is the most popular tool for handling large intergers... I have two questions regarding GMP:
- How are internal calculations done in GMP library? Suppose one integer of two bytes, and another of three bytes, what are the operations performed internally on those raw bits!??
- How is performance speed higher for GMP than other general libraries!?
Thanks in advance. For me to know these about these things is much im开发者_如何学Goportant for my project.
This page (http://gmplib.org/manual/Algorithms.html) describes the algorithms GMP uses for its operations.
Also, the GMP library is open source so you can download and look for yourself.
GMP uses native integer arithmetic in order to perform all multi-precision arithmetic operations. Floating-point arithmetic is too messy to be fully trusted, that's why GNU MPFR relies on GMP to do multi-precision floating-point operations. The reason is IEEE floating-point standards 754/854/etc. are way too cumbersome, never have been fully implemented, and implementations vary wildly from platform to platform.
All GMP integer and rational functions rely on
mpn_...
functions, which are low-level operations on natural numbers.mpz_...
functions for instance use sign-magnitude representation and handle sign and then usempn_...
functions for magnitude ops. The fundamental GMP numeric type is themp_limb_t
type, defined ingmp.h
, on which all GMP operations are done, is either aunsigned int
,unsigned long int
,unsigned long long int
, depending on the platform. On virtually all platforms, the example provided, integers with 2 and 3 bytes, will fit anunsigned int
type and so GMP will use the native integer operations on a single shot to do most basic arithmetic. When the numbers you compute with are larger than a limb, GMP will allocate more than one limb to do multi-precision calculations and handle the carries appropriately (see for example this book). See this GMP manual entry to see how the library operates separately on limbs.This is the reason why GMP is widely used, it's both accurate and fast, while widely portable. The GMP's
mpn/
directory contains specific per-processor implementations for the basic arithmetic operations, highly optimized code for each of the most used processors: x86, ARMs, CRAYs, IA64, mips, powerpcs, sparcs, etc. Each fundamental operation is implemented in the best possible way in machine code, and the Autotools (Autoconf and Automake) provided with GMP will know which one to link to higher level functions for the specific target you compile GMP. Note that you can also tune GMP to your machine before compiling so it may use the best algorithms for the many different integer sizes you may compute with (see here).
精彩评论