Search code examples
c++stlfractions

What is the best way to implement a Fraction type in C++?


I would like to handle rational numbers (possibly negative) in a C++ program, in a clean and effective way because they will be heavily used. And I mean, heavily.

I can code a textbook-style Fraction class that has 2 integer attributes, overloads all common operators, uses a gcd algorithm trick in the constructor, and all this stuff. The usual suspects of any decent C++ course.

However my instinct is that someone, possibly even the STL programmers, has already done this in a much, much better way than I would. Any best practice on this subject ?


Solution

  • Would Boost Rational Numbers fit your needs ?
    http://www.boost.org/doc/libs/1_60_0/libs/rational/rational.html