Skip to content

Instantly share code, notes, and snippets.

@marmakoide
Created October 3, 2023 19:16
Show Gist options
  • Save marmakoide/a5a5ba6be5f1feec3c29f2a645674cc2 to your computer and use it in GitHub Desktop.
Save marmakoide/a5a5ba6be5f1feec3c29f2a645674cc2 to your computer and use it in GitHub Desktop.
Unit simplex in N dimension, as a triangular matrix. 1st vertex is the origin.
import numpy
'''
Unit simplex in N dimension, as a triangular matrix,
only positive coeffs.
1st vertex is the origin, not in the returned matrix
I don't know if this algorithm have been discovered
before. I find it elegant, and I believe it can be
very accurate and stable with arbitrary precision numbers
'''
def get_unit_simplex(N, dtype = float):
S = numpy.zeros((N, N), dtype = dtype)
# Iterative construction
S[0, 0] = 1
for i in range(1, N):
S[i, :i - 1] = S[i - 1, :i - 1]
S[i, i - 1] = S[i - 1, i - 1] / ((i + 1) ** 2)
S[i, i] = 1 - S[i, :].sum()
# Job done
return numpy.sqrt(S)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment