Home > Software engineering >  I want to generate a integer from a double
I want to generate a integer from a double

Time:12-03

i was trying to make a function that would generate integers from doubles. I want this function to round based of the decimal at the end of the integer. for example 1.75 would have a 75% chance of rounding up and a 25% chance of rounding down.

here is what i tried so far

public static int fairIntFromDouble(final double number)
{
  Random random = new Random();
  if (random.nextDouble() < number)
  {
    return (int) Math.floor(number);
  } 
  else
  {
    return (int) Math.celi(number);
  }
}

idk why but it seems to always round down

CodePudding user response:

I came up with a simple way of accomplishing what you are asking for. Here is the code, I will explain the logic for this section of code below.

    public static int fairIntFromDouble(final double number) {
    Random random = new Random();
        final double decimal = number - Math.floor(number);
        if (random.nextDouble() < decimal) {
            return (int) Math.ceil(number);
        }
        return (int) Math.floor(number);
    }

So here is what I am doing. First, I am figuring out what exactly the decimal on the number is. After I have that decimal, I am able to use an instance of Random to generate a random double between 0 and 1. Using this decimal I round up if the random number is less than the decimal and down if it is more than or equal to.

The reason why your original function always rounds down is because you are generating a random number between 1 and 0 and then comparing the double you entered as input. This means that if you ever input a double into your funtion with a value more than 1 then you will always be rounding down.

  •  Tags:  
  • java
  • Related