I am using Python in a Jupyter lab enviroment.
If I define this function:
def f(n):
return ((n - 1) + 1/2) / n
when I execute this:
f(3)
the function returns 0.8333333333333334
Instead I'd rather get 5/6
as a result.
I am using Python in a Jupyter lab enviroment.
If I define this function:
def f(n):
return ((n - 1) + 1/2) / n
when I execute this:
f(3)
the function returns 0.8333333333333334
Instead I'd rather get 5/6
as a result.
You should use the fractions
package:
from fractions import Fraction
def f(n):
return Fraction(((n - 1) + Fraction(1, 2)), n)
print(f(3))
will print
5/6
You can use the fractions
module.
from fractions import Fraction
fraction = Fraction(0.8333333333333334).limit_denominator(10)