user1337 - 1 year ago 73

Python Question

I'm trying to figure out a clever way to randomly split a numpy integer array into two parts so that the two parts sum to the original array.

**Example:**

`a = np.array([0,1,2,3])`

b, c = rand_split(a)

# Should give something like

# b = [0, 1, 1, 2], c = [0, 0, 1, 1]

EDIT: All entries should be non-negative.

Answer Source

Here's a solution with a list comprehension:

```
b = np.array([np.random.randint(0, n+1) for n in a])
c = a - b
```

This should be faster since it's doing all the work in numpy:

```
b = (np.random.uniform(size=a.shape) * (a + 1)).astype(int)
```