mgfraction is an useful C++ library for fraction calculations. mgfraction is
It also implements AutoCancel.
License: BSD-like; see mgfraction.hpp
Simply type make. I tried make with different compilers, and all compilers I tried work perfectly with mgfraction:
It is very easy to use mgfraction in your application. Within the source package, an example file (main.cpp) is equipped. You can check the results of the compiled main.cpp against the reference results:
mg@heavyfuel:~/proj/mgfraction$ ./mgfraction 477495/295245 = 1.61728 131/81 = 1.61728 3872/16038 = 0.241427 176/729 = 0.241427 3/4 = 0.75 -1196126316000/9622346173440 = -0.124307 443325/-3566368 = -0.124307 0/4 = 0 0/1 = 0 4/4 = 1 70/32 = 2.1875 35/16 = 2.1875
There is also a more exact presentation of the calculations that can be done using main.cpp.
template < class T > class mgfraction
{
public:
mgfraction ();
mgfraction (T _n, T _d);
mgfraction (T _i, T _n, T _d);
~mgfraction ();
void add (const mgfraction r);
void sub (const mgfraction r);
void mul (const mgfraction r);
void div (const mgfraction r);
void cancel ();
void expand (T by);
template < class X > X decimal ();
T n;
T d;
bool autocancel;
private:
T gcd (T a, T b);
};
The purpose of these methods should be obvious.
I decided to overload operator+, operator-, operator*, operator/ and operator==. Those operators have been widely used during the creation of main.cpp. Please take a look at it.
Have fun!