n dimensional grid in Python / numpy

前端 未结 5 843
忘掉有多难
忘掉有多难 2021-01-23 06:57

I have an unknown number n of variables that can range from 0 to 1 with some known step s, with the condition that they sum up to 1. I want to create a

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-23 07:54

    Here is a direct method using itertools.combinations:

    >>> import itertools as it
    >>> import numpy as np
    >>> 
    >>> # k is 1/s
    >>> n, k = 3, 3
    >>> 
    >>> combs = np.array((*it.combinations(range(n+k-1), n-1),), int)
    >>> (np.diff(np.c_[np.full((len(combs),), -1), combs, np.full((len(combs),), n+k-1)]) - 1) / k
    array([[0.        , 0.        , 1.        ],
           [0.        , 0.33333333, 0.66666667],
           [0.        , 0.66666667, 0.33333333],
           [0.        , 1.        , 0.        ],
           [0.33333333, 0.        , 0.66666667],
           [0.33333333, 0.33333333, 0.33333333],
           [0.33333333, 0.66666667, 0.        ],
           [0.66666667, 0.        , 0.33333333],
           [0.66666667, 0.33333333, 0.        ],
           [1.        , 0.        , 0.        ]])
    

    If speed is a concern, itertools.combinations can be replaced by a numpy implementation.

提交回复
热议问题