mardi 7 novembre 2017

Weird behavior with class attribute, __iadd__ (+=) and numpy.random.randn()

I have been modelling a stochastic process with Python and Numpy and witnessing weird behavior with the following code:

import numpy as np

class Example( object ):
    def __init__( self ):
        self.x = 0

    def add_random( self ):
        self.x += np.random.randn(1)
        return self.x

if __name__ == '__main__':
    example = Example()
    state = []
    for x in range(10):
        state.append( example.add_random() )
    print state

This will return an array of 10 identical random numbers as opposed to 10 different random numbers as expected. Eliminating the object.__iadd__ operator and/or replacing np.random.randn(.) with a constant will solve the issue. Anybody has an idea what is the root of this?




Aucun commentaire:

Enregistrer un commentaire