tungprime
tungprime

Reputation: 61

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!

Upvotes: 4

Views: 4401

Answers (2)

mbomb007
mbomb007

Reputation: 4271

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.

Upvotes: 5

Leonardus Chen
Leonardus Chen

Reputation: 1254

Since everyone keeps suggesting to use fractions.Fraction for some reason, I'm going to put this in here:

** FLOATS ARE RATIONAL **

As a matter of fact, the class numbers.Rational provides a default for the numerator/denominator of floats. You can use float.as_integer_ratio() to get the exact numerator/denominator representation.

Now of course, the reason for this is the limited precision of floats requires all irrationals are truncated to rationals. So if it is exact computations you are after, then yes, go with fractions.Fraction.

Upvotes: -1

Related Questions