To crunch it down to 8 bits, that would mean that the valid mantissa bits would range from 0x00 to 0xFF. The algorithm is such that all bit combinations are equally probable. The random number bits are all in the mantissa. The random-number generator is designed so that the exponent is always zero. I don't recall offhand what the exponent ranges for Java are, but it's not important. I'm a little out of practice on floating-point terminology, so I may get some of the terms scrambled, but I think I need to outline what's really happening here and how it shapes the options.Ī floating-point number in binary form consists of 2 components: the exponent and the mantissa. The method with BigInteger suffers from a similar problem that the largest possible result is 2 ⁿ⁻¹. That is about the only way to do it I can find which doesn't have the problem of not exactly reaching 1.0. For any precision write your own Random class or try this. That should give a distribution between 0.0 and 1.0 in steps of approx 0.0000000001. ![]() ((1.0 * Integer.MAX_VALUE - Integer.MIN_VALUE) / ((1.0 * Integer.MIN_VALUE - Integer.MIN_VALUE) / Because of the asymmetrical nature of two's numbers you cannot get the nice distribution between 0.0 and 1.0 you would like. That should give you 2³² different values subject to the usual precision problems you get with doubles. ![]() The 1.0 * bit converts the int to a double you can use a cast instead. Here follows a new version of AJC's formula omitting the − 1 parts.ĭouble myRandom = (1.0 * randomObject.nextInt() - Integer.MIN_VALUE) / (2.0 * Integer.MAX_VALUE + 1.0) What is wrong with using this method of the Random object? So that should work nicely.īut why the -1? That appears unnecessary. So all values in the range of an int can be converted to a double safely, but the larger values in the range of a long mostly cannot be represented as doubles. A double can represent exactly any integer which will fit into the 53 bits' precision available in the IEEE754 format. ![]() Int next = myRandom.nextInt(possibilities) this number is just to prove we can get 1 you can also look at secure Random classes get evenly distributed random numbers. save your Random and reuse it for performance reasons and to You can use BigInteger with many int randoms if you need more possibilities but you will always have to consider the greatest possible value as = 1. This sounds like differential calculus where you need to consider the greatest possible (tends toward 1) value as = one.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |