RedPen RedPen -4 years ago 66
Python Question

How to compute the following equation correctly?

Using python 2.7 I am trying to compute the following rather difficult set of equations.

enter image description here

I have successfully implemented the first two, but am struggling with the third. Here is my attempt,

def pi_tau( r ):
return (1 - (1 - r)**(t + 1))/(2 - r)

def mean_field( r ):
return 1 - (1 - r)**t

def pi_neighbour( r ):
inside = []
for kappa_dash in range(0, kappa - 1):

Binomial_Coefficient = (math.factorial(kappa - 1)) / (math.factorial(kappa - 1 - kappa_dash)*math.factorial(kappa_dash))

top = ((mean_field( r )*pi_tau( r ))**kappa_dash)*(1 - mean_field( r )*pi_tau( r ))**(kappa - 1 - kappa_dash)

bottom = kappa_dash + 1

fraction = top/bottom
inside.append(kappa_dash)
inside[kappa_dash] = inside[kappa_dash] + fraction*Binomial_Coefficient

return pi_tau*inside


I then try to call this function

# set parameters
r = 0.15
kappa = 2.1
T = 10

ppp_t = []
mmm_f = []
nnn_t = []

for t in range(0, T):
ppp_t.append(pi_tau( r ))
mmm_f.append(mean_field( r ))
nnn_t.append(pi_neighbour( r ))


I get the following error message

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)
<ipython-input-41-9bcf462306f0> in <module>()


6 ppp_t.append(pi_tau( r ))
7 mmm_f.append(mean_field( r ))
----> 8 nnn_t.append(pi_neighbour( r ))

<ipython-input-39-d9acdd7490f9> in pi_neighbour(r)
19 inside[kappa_dash] = inside[kappa_dash] + fraction*Binomial_Coefficient
20
---> 21 return pi_tau*inside

TypeError: can't multiply sequence by non-int of type 'function'


I am looking for any advice on how to implement the third function and improve on my method.

Answer Source

There are several weird things here:

  • you calculate the top, bottom, and bionomial all in the for loop, but don't sum up in that for loop; and
  • you multiply the pi_tau function with a list?

    return pi_tau*inside
    
  • you use range(0, kappa - 1), but the upperbound of range(..) is exclusive

Nevertheless, you make things quite hard. You could use the following approach:

from math import factorial

def pi_neighbour(r):
    sum = 0.0
    for kappa_dash in range(0,kappa):
        bin_coeff = factorial(kappa-1)/(factorial(kappa-1-kappa_dash)*factorial(kappa_dash))      
        top = ((mean_field(r)*pi_tau(r))**kappa_dash)*(1-mean_field(r)*pi_tau(r))**(kappa-1-kappa_dash)
        sum += bin_coeff*top/(kappa_dask+1)
    return pi_tau(r)*sum
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download