Search code examples
pythonsumsympyfactorial

Take the Sigma of a factorial with unknown variable (using sympy?)


Good day,

I am trying to write a function for the following equation:

Eurlang B

Where B and N are given and I am solving for A.

I was reading up and it seemed like sympy was the way to go so I started to declare the known variables, but when it came to the sigma notation with the factorial, I had no idea of how to approach it since A is an unknown.

Here is what I came up with:

from sympy import Eq, var, solve
from math import *

A = var('A')
channels = raw_input("Enter the number of channels: ")
#GOS = raw_input("Enter GOS: ")

Sigma = A
for i in range(0,channels+1):
  Sigma += (A**i / factorial(i))

# equation = Eq((A**channels / factorial(channels)) / Sigma) 
# print solve(equation)

which gives me the error TypeError: cannot concatenate 'str' and 'int' objects

This makes sense to me, but my lack of knowledge with sympy makes me unable to figure out how to fix it.

EDIT: Looking around a bit more, I edited my code to this:

  from sympy import *

  A = symbols('A')
  channels = raw_input("Enter the number of channels: ")
  GOS = raw_input("Enter GOS: ")

  Sigma = summation(A**i / factorial(i), (i, 0,channels))
  print Sigma



  # equation = Eq((A**channels / factorial(channels)) / Sigma) 

Now I get NameError: name 'i' is not defined

Thanks in advance.


Solution

  • First of all, the error ( name 'i' not defined) is because you havent defined it. so you need to give an initial value for i.

    secondly, I have tried to make your program run. got an error free solution with this code:

    from sympy import *
    
    A = symbols('A')
    channels = raw_input("Enter the number of channels: ")
    GOS = raw_input("Enter GOS: ")
    
    # note that I convert the string 'channel' to an int
    # convert to float if channel could also be a floating number
    channels = int(channels) 
    Sigma = A
    for i in range(0,channels+1):
        Sigma += (A**i / factorial(i))
    print Sigma
    

    The result,

    inputs: channels = 3, GOS = 1

    output: A**3/6 + A**2/2 + 2*A + 1

    EDIT: Out of interest I started looking further into your problem (also because I could realize this question would not stop just by a datatype issue). The Solve function has 2 inputs, the equation and the symbol to calculate. it solves the equation == 0. so the variable B has to be subtracted from the equation. (I supposed the input GOS is the B variable in the function)

    equation = (A**channels / factorial(channels)) / Sigma
    print(solve(equation-int(GOS), A))
    

    running the code with the lines above (add them under the code) gave these outputs:

    A**3/6 + A**2/2 + 2*A + 1
    [-2 - sqrt(2), -2 + sqrt(2)]
    

    I must notice that if the GOS does not intersect the function it gives large results with additional parameter I (capital i, might indicate imaginary i). I hoped this helped solving your problem.