# Re: [R] mixture normal distributions

From: Martin Maechler <maechler_at_stat.math.ethz.ch>
Date: Sat 11 Feb 2006 - 08:20:11 EST

>> Dear R helper,
>> I mange to transform uniform sequences to mixture
>> normal distributions using the following cods:

you forgot to mention the important fact that you are working with package "nor1mix" (of which I am the maintainer which you could have seen from library(help = nor1mix) or packageDescription("nor1mix")

>> > K<-50000
>> > prime<-c(29) , where 29 is prim number
>> > UN<-seq(1:K)%*%t(sqrt(prime))
>> > U1<-UN-as.integer(UN)
>> > e<-norMix(mu=c(-0.825,0.275), sig2 = c(0.773,0.773),
>> w = c(0.25,0.75), name = NULL, long.name = FALSE)
>> > U<-matrix(qnorMix(e,U1),K,1),

This looks like you want to generate pseudo-random values from the mixture distribution.

However by the slowest most possible way: qnorMix() is really slow because it calls uniroot() for each value.

rnorMix() will generate random values distributed according to the normal mixture very very efficiently (particularly compared to using qnorMix()).

But indeed, you have detected a bug in qnorMix() (that happens pretty rarely). Indeed your example also shows that the algorithm can be much improved in some cases.

The next verion of nor1mix should contain a more "robust" qnorMix() function.

>> But somtimes if i use ,e.g, 23 or 11 instead of 29 it
>> will give me the following error.
>>
>> > K<-30000
>> > prime<-c(23)
>> > UN<-seq(1:K)%*%t(sqrt(prime))
>> > U1<-UN-as.integer(UN)
>> > e<-norMix(mu=c(-0.825,0.275), sig2 = c(0.773,0.773),
>> w = c(0.25,0.75), name = NULL, long.name = FALSE)
>> > U<-matrix(qnorMix(e,U1),K,1)
>> Error in uniroot(function(l) pnorMix(obj, l) - pp[i],
>> interval = rq) :
>> f() values at end points not of opposite sign
>>
>>
>> I am seeking help how to avoid this error.
>>