Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the numerator and denominator of a nested fraction using sympy

Tags:

python

sympy

I am trying to extract numerator and denominator of expression using sympy.fraction method. The code is as follows-

from sympy import *
x=symbols('x')
a=1/(1+1/x)
print(fraction(a))

The output that I want is

(x,x+1)

but it is outputting

(1, 1+1/x)

like image 694
Ajinkya Ambatwar Avatar asked Sep 03 '25 06:09

Ajinkya Ambatwar


2 Answers

Ask for simplification of the expression first:

>>> from sympy import *
>>> var('x')
x
>>> a = 1/(1+1/x)
>>> a.simplify()
x/(x + 1)
>>> fraction(a.simplify())
(x, x + 1)
like image 127
Bill Bell Avatar answered Sep 04 '25 19:09

Bill Bell


The docstring of fraction says:

This function will not make any attempt to simplify nested fractions or to do any term rewriting at all.

The rewrite you want is done by together.

print(fraction(together(a)))   #  (x, x + 1)

simplify has the same effect, but it's a heavier tool that tries a lot of various simplification techniques. The output of specific functions like together, cancel, factor, etc is more predictable.