0

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Mario Stefanutti
  • 232
  • 4
  • 22
  • 1
    Does this answer your question? [How to convert a decimal number into fraction?](https://stackoverflow.com/questions/23344185/how-to-convert-a-decimal-number-into-fraction) – Tomerikoo Aug 27 '20 at 13:29
  • 1
    It might be worth understanding that ``1/2`` (and similar) is not a fraction as in *the type*, but a fraction as in *the operation*. It literally means evaluating "divide 1 by 2". – MisterMiyagi Aug 27 '20 at 13:34
  • When you say you would "rather get ``5/6`` as a result", what do you assume is (or desire as) the type of ``5/6``? Naively, ``5/6`` *is* 0.8333333333333334 in Python. – MisterMiyagi Aug 27 '20 at 13:37
  • I was thinking to something similar to this: https://www.wolframalpha.com/input/?i=%28%28n+-+1%29+%2B+1%2F2%29+%2F+n+with+n+%3D+3 – Mario Stefanutti Aug 27 '20 at 14:14
  • 1
    You might be looking for symbolic computation, e.g. as provided by ``sympy``. – MisterMiyagi Aug 27 '20 at 14:19
  • sympy is actually what I used at the end. Thanks – Mario Stefanutti Aug 28 '20 at 11:08

2 Answers2

1

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
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • You might get a massive fraction from time to time, so you can use the method .limit_denominator() to avoid this – en_lorithai Aug 27 '20 at 13:33
  • @en_lorithai Since I don't use float division it would only generate a massive denominator if `n` is massive too, which is expected. – Selcuk Aug 27 '20 at 13:35
  • Float division is default in python 3 which more and more people are using. should be mentioned. – en_lorithai Aug 27 '20 at 13:39
  • @en_lorithai There are no divisions in my answer. – Selcuk Aug 27 '20 at 13:40
  • Thanks @Selcuk I also found this other way: from sympy import symbols, sympify n = symbols('n') f = sympify("((n - 1) + 1/2) / n") print(f.subs(n, 3)) – Mario Stefanutti Aug 27 '20 at 14:10
0

You can use the fractions module.

from fractions import Fraction 

fraction = Fraction(0.8333333333333334).limit_denominator(10)
gmdev
  • 2,725
  • 2
  • 13
  • 28