-1

Working on a project, trying to find a way to generate a random decimal between 0 and 1, inclusive. Making a multi-threaded project that will increase and decrease an (int) number.

So far I have declared a private int number, initialized to 0 and also a random generator.

The way I am hoping to get this to work is to get a random decimal between 0 and 1 (I.E. 0.564184) and add it to number.

The way the program is designed is to check if number is less than 1, if it is then add a random decimal to it, re run the check until it is above 1 or the next number will make it above 1

I saw an example on Java random number between 0 and 0.06 But when i attached it in and modified it to this :

 while(number < max)
          {         
            double increase = random.nextInt(2);
            increase = increase / 10.0;
            number = (int) (number + increase);
            System.out.println(number);
          }

The program continuously runs just printing out 0's. I do believe this is due to the cast to int when adding the number before printing.

I have the threads working when I just use
number = number - random.nextInt(1) + 1; System.out.println(number);

Now I am stuck, looking different guides, I thought while I am looking I should ask for assistance. Thanks ahead of time.

Community
  • 1
  • 1
NWcis
  • 59
  • 1
  • 10
  • Can't you just make the variable "number" into a double instead of an integer? – Michael Mar 30 '16 at 02:01
  • What does this have to do with multithreading? –  Mar 30 '16 at 02:01
  • 2
    There's no integer value between `0` and `1`. – Elliott Frisch Mar 30 '16 at 02:01
  • Random decimal between 0 to 1 **stored in int** can only be 0 or 1 (if inclusive). int cannot store non-integer value. – Ian Mar 30 '16 at 02:02
  • I wish, that way I know how to do it. However, the requirement is a private int field. The code is self running, using an executor to run two different threads at once 15 times each. If you need, I can post the code for said executors. Now, that has me thinking (and I will test it after I post this) casting the number to a double instead of casting the number to an int? – NWcis Mar 30 '16 at 02:05

2 Answers2

2

If I understand your question, you could simply use Random.nextDouble() which returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. Something like,

while(number < max)
{         
    number += random.nextDouble(); // <-- will round up for 0.5+
    System.out.println(number);
}

If you want half-up and half to stay the same it would be more efficient to do

while (number < max)
{
    number += random.nextBoolean() ? 1 : 0;
    System.out.println(number);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Ints can't hold a decimal value. Changing the variable to a Float or Double will fix your issue.

AussieGuy
  • 21
  • 2