0

A simplified version of my code, generates two objects with random states which their state are uniformly picked from a circle. The problem is checking the state of the objects return the same random point. What is the problem?

import numpy as np
def uniform_spherical_sample(dim=2,size=1):
    """returns a sample of size `size` uniformly from a hypersphere with dimension `dim`"""
    a=np.random.multivariate_normal(mean=np.zeros(dim),cov=np.identity(dim),size=size)
    normed_a=a/np.linalg.norm(a,axis=1)[...,None]
    return normed_a
class a:
    def __init__(self,state=uniform_spherical_sample()):
        a.state=state
obj=a()
obj2=a()
print obj.state
print obj2.state

The output is always the same values for both objects. I have to emphasise that running the function twice gives different values.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Cupitor
  • 11,007
  • 19
  • 65
  • 91
  • 1
    Your problem is with calling `uniform_spherical_sample()` *at function definition time*. It is not executed on each call to `__init__`. – Martijn Pieters Jun 01 '14 at 15:17
  • Why the title of that question is so complex?? Thanks anyways. – Cupitor Jun 01 '14 at 15:20
  • 1
    Usually, people fall into this trap (thinking defaults are re-evaluated on each call) when using mutable arguments, such as `{}` or `[]`. But the underlying reasons are the same here. – Martijn Pieters Jun 01 '14 at 15:21

0 Answers0