Search code examples
pythonmathsympysymbolic-math

How to evaluate numeric math expressions symbolically in sympy?


I am new to sympy and not a python expert. I need to do some calculation symbolically, just like the below example.

Evaluate: C(4, 2) / C(7, 2)

I.e. 2/7

C(4, 2) is an express widely used in our country, it is 4x3/2x1. Maybe you call it Combination. Similarly, C(7, 2) is 7x6/2x1.

1, Although I can write a function to calculate C(x, y), is there an existed wheel to do that in sympy?

2, No matter how I got C(4, 2) and C(7, 2), how can I get the quotient in the format 2/7 rather than a float number that is not symbolical?

3, I need something symbolical in a variable to use in other expressions. How to do that? Just like below:

x = 2/7
y = x * 7

PS: I have already learned below is a symbolical way, but how can I keep pure numeric expressions like the above symbolical?

x = sympy.symol('x')
y = x / 7

Solution

  • There is a function nC which does this:

    In [51]: from sympy.functions.combinatorial.numbers import nC
    
    In [52]: nC(4, 2) / nC(7, 2)
    Out[52]: 2/7