Search code examples
pythonnumpympmath

Summation of a function in Python


I'm new to Python programming. Coming from a MATLAB background. I'm looking something similar to symsum function from MATLAB in Python.

I have my array,

a = np.linspace([0,3.14])

I want to sum

sin(2*i*a) where i ranges from 1 to 20

and then plot the results between a and y

I tried the following

y = nsum(lambda i: np.sin(2*i*a), [0,20])

I'm stuck at this point.

Edit. The MATLAB equivalent would be

a = linspace(0,pi) syms i y=double(symsum(sin(2*i*a),i,0,20)


Solution

  • edit

    Looks like symsum is part of a symbolics package (in MATLAB and Octave). sympy is the Python symbolics package. Its integration with numpy is looser.

    ===

    Here's a guess as to what you are trying to do:

    A range of a values:

    In [180]: a = np.linspace(0, np.pi, 100)                                                     
    

    Outer product with (0,1,2,3,4) (uses broadcasting)

    In [181]: x = np.arange(5)[:,None]*a          
    

    Sum the sin values, and plot:

    In [182]: y = np.sin(2*x).sum(axis=0)                                                        
    In [184]: plt.plot(a,y)                                                                      
    

    sum of 5 sins