Numpy array values changed without being aksed?

前端 未结 2 1597
谎友^
谎友^ 2021-01-21 16:04

I have 2 vectors, posVec and dirVec who\'s value I woudl like to keep at (0.0,0.0,0.0).

So I set up temporary vectors t_pos & t_dir

2条回答
  •  感动是毒
    2021-01-21 16:12

    This is happening because with

    t_pos = posVec
    t_dir = dirVec
    

    You are not copying the contents of the vectors but you copy their references. So basically t_pos and posVec are pointing to the very same numpy array object.

    What you want to do is:

    t_pos = numpy.copy(posVec)
    t_dir = numpy.copy(dirVec)
    

    EDIT: Differences for copy methods:

      1 import timeit                                                                                                       
      2 import copy  
      3 import numpy as np
      4              
      5 someArr = np.arange(100)
      6              
      7 def copy1(): 
      8     tempArr = someArr.copy()
      9              
     10 def copy2(): 
     11     tempArr = np.copy(someArr)
     12              
     13 def copy3(): 
     14     tempArr = copy.copy(someArr)
     15              
     16 def copy4(): 
     17     tempArr = copy.deepcopy(someArr)
     18              
     19 print ("copy1: " + str(timeit.timeit(lambda: copy1(), number=1000000)))
     20 print ("copy2: " + str(timeit.timeit(lambda: copy2(), number=1000000)))
     21 print ("copy3: " + str(timeit.timeit(lambda: copy3(), number=1000000)))
     22 print ("copy4: " + str(timeit.timeit(lambda: copy4(), number=1000000)))
    

    Prints the following output (in seconds):

    copy1: 0.5677032630010217
    copy2: 1.473885050001627
    copy3: 1.2420436849988619
    copy4: 2.733253653999782
    

    So yes, there are huge differences but only in terms of used computation resources. The results for your example stay exact the same.

    someArr.copy() refers to the object you already have saved in memory, so accessing this is the fastest way and every numpy array holds such a method, so basically you are accessing the method of your already created numpy array.

    np.copy(someArr) calls the copy-method of the numpy library, therefore it is slower, because it (as far as I know) produced some overhead with creating a temporary instance.

    copy.copy(someArr) is the python (non-numpy) way to copy objects generally. I am a bit confused that it performs slightly better than the numpy way...because of its generality (for nearly all objects) it should perform worse...at least I thought that.

    copy.deepcopy(someArr) clearly performs worst but it is important to remember it. Deepcopy not only creates a copy of your object (someArr) but it also creates new, fresh copies of every element in your array. So if you have objects (references) stored in your array, you will face the same problem you did. Therefore deepcopy is used and of course creating not only a copy of your array, but also of every element in it takes the most time.

提交回复
热议问题