pythonfractions

Rational numbers in Python


I need to compute a recursive sequence of numbers. In the formula, I need to compute B(r) where B(x) is a polynomial with rational coefficients (i.e fractions) and r is a rational number. My code is

def B(x):
    return x**2-x+1/6

However, when I plug r in, I get a floating number, not a rational number. This is expected.

I have several polynomials like this and my formula involves addition/subtraction with these numbers. How can I return the final result as a rational number?

Thanks!


Solution

  • As stated in the comments, the fractions module is really helpful.

    from fractions import Fraction
    def B(x):
        x = Fraction(x)
        return x**2-x + Fraction(1,6)
    

    Try It Online

    Basically, x**2-x doesn't have division, it doesn't need to be a Fraction. Because 1/6 would become a floating point number, use Fraction('1/6') or Fraction(1,6). Math with a Fraction input will return a Fraction. Putting x = Fraction(x) at the top allows for fractional inputs.