n dimensional grid in Python / numpy

前端 未结 5 805
忘掉有多难
忘掉有多难 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:52

    This method will also work for an arbitrary sum (total):

    import numpy as np
    import itertools as it
    import scipy.special
    
    n = 3
    s = 1/3.
    total = 1.00
    
    interval = int(total/s)
    n_combs = scipy.special.comb(n+interval-1, interval, exact=True)
    counts = np.zeros((n_combs, n), dtype=int)
    
    def count_elements(elements, n):
        count = np.zeros(n, dtype=int)
        for elem in elements:
            count[elem] += 1
        return count
    
    for i, comb in enumerate(it.combinations_with_replacement(range(n), interval)):
        counts[i] = count_elements(comb, n)
    
    ratios = counts*s
    print(ratios)
    

提交回复
热议问题