Reputation: 1268
I am a newbie with the sympy library, and I am having trouble to calculate the mean after have defined the formula:
import sympy as sp
import numpy as np
sp.init_printing()
mu, N, i, x_i = sp.symbols( 'mu N i x_i' )
mu_form = sp.Eq( mu , (1/N) * sp.Sum( x_i, (i, 1, N) ) )
Now I want to define a list of values for x_i
to actually calculate the mean.. I have attempted in such a way, but it does not seem to work properly:
x_i_val = (1, 1, 3, 3, 2, 2, 2, 2)
mu_val = mu_form.subs( [(x_i, x_i_val), (N, 8)] )
I am not interested in the mean
in particular, I want to understand the way to calculate the result of such a formula, with a summation inside.
I did not have luck in finding a minimal example in the available tutorials and Googling.
Upvotes: 1
Views: 746
Reputation: 91480
The symbol x_i
is not related to the symbol i
. It prints with a subscript, but that is just a printing convention.
A better choice is IndexedBase
. There's a fix from https://github.com/sympy/sympy/pull/8065 that makes this easier, but for now, you can do something like this:
In [13]: x = IndexedBase('x')
In [14]: mu_form = sp.Eq( mu , (1/N) * sp.Sum( x[i], (i, 1, N) ) )
In [15]: mu_form = mu_form.subs(N, 8).doit()
This expands the sum, so that you can substitute the terms:
In [16]: mu_form
Out[16]:
x[1] x[2] x[3] x[4] x[5] x[6] x[7] x[8]
μ = ──── + ──── + ──── + ──── + ──── + ──── + ──── + ────
8 8 8 8 8 8 8 8
In [20]: mu_form = mu_form.subs({x[i]: x_i_val[i - 1] for i in range(1, 9)})
In [21]: mu_form
Out[21]: μ = 2
By the way, it's a lot easier to deal with things if you start your indices at 0 instead of 1, since that's what Python does.
Upvotes: 2