0

When I run this little program, I get in the output file the same 3 values repeated all over, but if I print the values in each forcycle, I get all different values.

Why does this happen and how do I make it correct?

import random
import math
import numpy as np

def normalizeVector(_x, _y, _z):
    _mag = math.sqrt(_x**2 + _y**2 + _z**2)
    return _x/_mag, _y/_mag, _z/_mag

points2DL = []
pointsV = [0.] * 3
for _i in xrange(0, 10000):
    _x = random.gauss(0, 1)
    _y = random.gauss(0, 1)
    _z = random.gauss(0, 1)
    _nx, _ny, _nz = normalizeVector(_x, _y, _z)
    _radius = 1.
    _sx, _sy, _sz = _radius*_nx, _radius*_ny, _radius*_nz

    pointsV[0] = _sx
    pointsV[1] = _sy
    pointsV[2] = _sz
    points2DL.append(pointsV)

pointsA = np.array(points2DL, dtype=np.float32)
pointsA.tofile('sphere_points.csv', sep=",")
jamylak
  • 128,818
  • 30
  • 231
  • 230
jbssm
  • 6,861
  • 13
  • 54
  • 81
  • can you show what part of the code be cause the error ? – Mazdak Dec 15 '14 at 18:39
  • @Cyber How is this a clone of a question about copying/cloning lists when there is no cloning/copying in the example? – jbssm Dec 15 '14 at 18:40
  • @Kasra I have no idea, this is the full code. – jbssm Dec 15 '14 at 18:41
  • 2
    @jbssm You are modifying `pointsV` every time in the list. So you are actually appending a copy of the same list over and over, which you keep modifying. – Cory Kramer Dec 15 '14 at 18:41
  • @jbssm, it's the lack of `pointsV` cloning that's the problem. – Brian Cain Dec 15 '14 at 18:42
  • 2
    The quick fix would be to move `pointsV = [0.] * 3` down so it is inside the loop. Then each iteration gets a brand new list, with no weird referential entanglement with previous lists. – Kevin Dec 15 '14 at 18:46

0 Answers0