Reputation: 121
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)
Upvotes: 4
Views: 5295
Reputation: 19047
The as_numer_denom
method will recursively find the numerator and denominator of a rational expression:
>>> a.as_numer_denom()
(x, x + 1)
The functions fraction
, numer
and denom
just give you the literal numerator and denominator of an expression without doing denesting.
Upvotes: 3
Reputation:
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.
Upvotes: 3
Reputation: 21643
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)
Upvotes: 5