bobthesnob
bobthesnob

Reputation: 83

How to create an array with predetermined norm and mean?

I want to create an random array with a "norm" of 1 and "mean" of 0. I can use numpy.random.normal() to get the "mean" I want, but how can I create an array such that numpy.linalg.norm(array) returns the number that I want?

Upvotes: 1

Views: 674

Answers (1)

mkrieger1
mkrieger1

Reputation: 23148

Using numpy.random.normal with the size argument will give you an array with values that are drawn from a distribution with a mean of 0. The mean value of the array will not be 0, however (it is more likely to be close to 0, the larger the array is).

But you can easily fix that by subtracting the mean of the array.

Once you have this, you can change the norm of the array to 1 by dividing by its norm. This will not change the mean, because it is 0.

def create(n):
     x = numpy.random.normal(size=n)
     x -= x.mean()
     return x / numpy.linalg.norm(x)

Example

>>> a = create(10)
>>> a
array([-0.48299539,  0.06017975,  0.23788747, -0.31949065,  0.56126426,
       -0.33117035,  0.40908645,  0.01169836, -0.1008337 , -0.0456262 ])
>>> a.mean()
-1.3183898417423733e-17  # not exactly 0 due to floating-point math
>>> numpy.linalg.norm(a)
1.0

Notice how for n=2 there are exactly 2 arrays satisfying these conditions: Those that contain both the positive and the negative square root of 1/2:

>>> for _ in range(5):
...     print(create(2))
...
[-0.70710678  0.70710678]
[-0.70710678  0.70710678]
[-0.70710678  0.70710678]
[-0.70710678  0.70710678]
[ 0.70710678 -0.70710678]

Upvotes: 2

Related Questions