多次元球の極座標

df<-5
d<-df-1
np<-10000
points<-matrix(0,np,df)
for(i in 1:np){
thetas<-runif(d)
thetas<-thetas*pi
thetas[1]<-thetas[1]*2
negS<-sign(sin(thetas))*(-1)
negC<-sign(cos(thetas))*(-1)
negS[negS==-1]<-0
negC[negC==-1]<-0

lnsin<-log(abs(sin(thetas)))
lncos<-log(abs(cos(thetas)))

Sm<-matrix(1,d,d)
Sm[upper.tri(Sm)]<-0
Sm<-as.matrix(cbind(Sm,rep(0,d)))

Cm<-diag(d)
Cm<-as.matrix(cbind(rep(0,d),Cm))

xs<-t(lnsin)%*%Sm+t(lncos)%*%Cm

sign<-t(negS)%*%Sm+t(negC)%*%Cm
sign<-(-1)^sign
xs<-exp(xs)*sign
xs<-xs/sqrt(sum(xs^2))
points[i,]<-sample(xs)
}

plot(as.data.frame(points[,1:min(df,4)]),cex=0.1)