Click here to Skip to main content
15,895,656 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi,

I want to implement a weighted random sampling in Java, something like 'randsample' in matlab. Basically I have to implement
X(i) = randsample([0 1],1,true,[p1 p2]);
,
for n number of times where p1 and p2 are the probabilites of 0 and 1 which keep changing with every iteration(the function selectes either 0 and 1 based on p1 and p2).
Below is the code in Java that I have tried
C#
Object[] population = { 0, 1 };
                double[] weights = { p1, p2 };
                Sampling randsamp = new Sampling(population, weights);
                // randsamp.add(population, weights);
                X[i] = (Integer) randsamp.next();


with this code I am getting random sampling but I am not sure if it is producing 0 and/or 1 based on the weights p1 and p2. also I cannot compare result with matlab since random function generates different number for every iteration.

Can someone tell me if the Java code is working same as Matlab or there is any other function in Java like 'randsample' in Matlab?

Thanks
Posted
Comments
Sergey Alexandrovich Kryukov 15-Oct-13 11:40am    
What do you (and others) mean by "telling the code"? You are supposed to write such code. You can build the function you need based on Java.Util.Random. The rest of it is just some mathematics.
—SA
Member 10305598 15-Oct-13 11:49am    
I built the function based on Random and my question was - is my implementation correct in Java. Since I am new to Java I am reading documents/notes and then trying to implement as I learn.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900