I am self teaching myself python and computational physics via Mark Newmans book Computational Physics the exercise is 2.9 of Computational Physics I have to compute the Madelung constant. .
I have two different solutions worked out I wanted to know which code is correct and is there a way to exclude 0 in my range so I don't have to write two separate for loops. I think my second answer is correct can somebody verify.
My first answer:
M = 0
for i in range(-200,0):
for j in range(-200,0):
for k in range(-200,0):
M += ((-1)**(i+j+k))/((i**2 + j**2 + k**2)**(1/2))
print(M)
for i in range(1,200):
for j in range(1,200):
for k in range(1,200):
M += ((-1)**(i+j+k))/((i**2 + j**2 + k**2)**(1/2))
print(M)
My second answer:
M = 0
i = 0
j = 0
k = 0
for l in range(-200,0):
i = l
j = l
k = l
M += ((-1)**(i+j+k))/((i**2 + j**2 + k**2)**(1/2))
print(M)
for l in range(1,200):
i = l
j = l
k = l
M += ((-1)**(i+j+k))/((i**2 + j**2 + k**2)**(1/2))
print(M)