0

I am trying to find the lowest energy distribution of charges on a disk The coordinates of the charges are stored in an array Q, this is cloned into array A then one charge is moved. If the move lowers energy it is accepted and A is copied over A with the new position

I print Q before and after these 2 lines:

if Rnew<R:
    A[charge]=(Rnew, thetanew)

where Rnew,R thetanew and charge are all numbers (charge is the charge that is being changed)

Why is Q changing?

whole code for context

import numpy as np
import random
from random import randint
from math import pi, cos, sin, atan2, exp
import matplotlib.pyplot as plt

N=6
R=1
W=0

Q=[] #current charge location
A=[] #potential carge location
array=np.zeros((N,N)) 

for i in range(0,N): #generates N  charges randomly distributed in Q
Q.append((random.uniform(0,R),random.uniform(0,2*pi)))

A=Q #creates duplicate

for i in range(0,N):                                        #Computes the          initial energy, glob W
    for j in range(0,N):
        if i!=j:
            we=0.5*(1/((Q[i][0]**2)+(Q[j][0]**2)-(2*Q[i][0]*Q[j][0]*cos(Q[j][1]-Q[i][1])))**0.5)
            W=W+we

    else:
        break

print W
W=0
we=0
print W

deltaR=0.1
deltatheta=random.uniform(0,2*pi)

charge=randint(0,N-1)
R1=Q[charge][0]

theta1=Q[charge][1]


Rnew=((R1*cos(theta1)+deltaR*cos(deltatheta))**2 +     (R1*sin(theta1)+deltaR*sin(deltatheta))**2)**0.5

thetanew=atan2((R1*sin(theta1)+deltaR*sin(deltatheta)),    (R1*cos(theta1))+deltaR*cos(deltatheta))

print Q
if Rnew<R:
    A[charge]=(Rnew, thetanew)
print Q

for i in range(0,N):                                        #Computes the initial energy, glob W
    for j in range(0,N):
        if i!=j:
            we=0.5*(1/((Q[i][0]**2)+(Q[j][0]**2)-(2*Q[i][0]*Q[j][0]*cos(Q[j][1]-Q[i][1])))**0.5)
            W=W+we

        else:
            break
print W
fistofgod
  • 1
  • 2
  • I think your indentation is wrong (see `for i in range(0,N):` `for j in range(0,N):`) - please [edit your post](http://stackoverflow.com/posts/29490411/edit) to correct it. – GoBusto Apr 07 '15 at 11:26

2 Answers2

0

A=Q won't create a duplicate. It will just make A and Q point to the same item, so a mutation through one variable will result in a mutation in the other (not exactly this - it's just that A and Q are identical and refer to the same memory location).

Try

A=Q[:]

This will actually close Q and you will be able to change the one, without resulting in a change in the other list.

codingEnthusiast
  • 3,800
  • 2
  • 25
  • 37
0

A=Q makes a shallow copy. If you modify the elements in A you will modify them in Q.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218