Shaun - 15 days ago 5

Python Question

I have this following double sum, where my c-file (5x4 matrix) is multiplied with two arrays

`g_T_np`

`g_rho_np`

Now, I'm asking myself where I could include another for loop so that every entry within my two arrays are multiplied instead of the whole array.

`g_T = [1,T,T**2,T*sy.log(T),T**2*sy.log(T)]`

g_rho = [1,rho,rho**2,rho*sy.log(rho),rho**2*sy.log(rho)]

g_T_np = np.asarray(g_T)

g_rho_np = np.asarray(g_rho)

c = np.loadtxt("c_file2.txt")

for n in range(5):

for m in range(4):

free = c[n,m]*g_T_np*g_rho_np

f = open('Free_Energy_Values.txt', 'w')

print >> f, 'Free energy:', free

f.close()

Thanks for your help.

EDIT: I'd like to calculate the Free Energy according to this formula.

Answer

Notice, that the outer sum is from 1 to 4, and the inner sum is from 1 to 5. The simplest way to translate a formula into a programming language is to just put the same thing without optimizations.

The straight-forward way:

```
from math import log
import numpy as np
def F(T, rho):
g_T = np.array([1, T, T ** 2, T * log(T), T ** 2 * log(T)])
g_rho = np.array([1, rho, rho ** 2, rho * log(rho), rho ** 2 * log(rho)])
c = np.loadtxt("c_file2.txt")
total_sum = 0
for i in range(4):
for k in range(5):
# we are traversing columns, not rows: notice [k,i], not [i,k]
total_sum += c[k, i] * g_T[i] * g_rho[k]
return total_sum
T = 1 # dummy value
rho = 2 # dummy value
print(F(T, rho))
```

Source (Stackoverflow)

Comments