a method that returns equal chance of head or tail

S

strutsng

I need to write a flip method that returns equal chance of head or
tail. Do you think a test for x % 2 is "equal chance"? Well, random
number generator never gets result "equal chance." Is that correct?

Here's my attempts, please advise.

public String flip()
{ Random r = new Random();
int x = r.nextInt();
if (x % 2 == 0)
{ numHeads++;
return "H";
}
numTails++;
return "T";
}

Thanks!!
 
E

E11

Depends on how precisely "equal chance" you want. If you want truly
absolutely equal chance (i.e. out of 1,000,000 invocations, you get
exactly 500,000 heads and 500,000 tails), then you can do this:

int i = 0;
public String flip()
{
i++;
if ((i % 2) == 0)
{
numHeads++;
return "H";
}
else
{
numTails++;
return "T";
}
}

Otherwise, your method using the RNG should do fine. BTW, its better to
use the same instance of Random throughout, i.e.:

Random r = new Random();
public String flip()
{
int x = r.nextInt();

if (x % 2 == 0)
{
numHeads++;
return "H";
}

numTails++;
return "T";
}



Regards,
Edwin
 
J

Jussi Piitulainen

I need to write a flip method that returns equal chance of head or
tail. Do you think a test for x % 2 is "equal chance"? Well, random
number generator never gets result "equal chance." Is that correct?

Here's my attempts, please advise.

public String flip()
{ Random r = new Random();
int x = r.nextInt();
if (x % 2 == 0)

Learn about java.util.Random instead, and for heads and tails use its
nextBoolean() method. As the other guy said, move the generator out of
the method; only initialize it once. Now you are really just sampling
the current time, which is not a random generator at all.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top