I'd like to do some arbitrary-precision math on rational numbers, e.g.:
>>> from fractions import Fraction
>>> Fraction(318483434, 1980410394309430943904903) * Fraction(34913483843843843843, 902490524905498548954894898889923232)
Fraction(5559683113745453573439198431, 893650808144311844544465740142994088494601632782777989203248)
Is there a library which would allow me to do this in a straightforward way?
If you're using boost, you can use boost::rational
in conjunction with boost::multiprecision::cpp_int
(arbitrary-precision integer):
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
typedef boost::rational<cpp_int> fraction_t;
For some reason, the constructor fraction_t("1", "2")
doesn't work, although cpp_int("1")
does, so if you need large int literals, you can use this helper function to not require explicit construction of cpp_int
objects each time you create a fraction:
template <typename A, typename B>
fraction_t fraction(A a, B b)
{
return fraction_t(cpp_int(a), cpp_int(b));
}
cout << fraction(318483434, "1980410394309430943904903") *
fraction("34913483843843843843", "902490524905498548954894898889923232") << endl;
Output:
5559683113745453573439198431/893650808144311844544465740142994088494601632782777989203248
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments