简体   繁体   中英

Extract the numerator and denominator of a nested fraction using 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)

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM