B4J Question Random numbers with decimals

kostefar

Active Member
Licensed User
Longtime User
Dear All,

I was playing around to see if I could find a smart way with the Rnd function to generate random numbers deriving from numbers already containing decimals by multiplying the input by 100000000, knowing that it will have a max of 8 decimals, and dividing it afterwards by 100000000.
But because of the limits of integers, this does not work well. Is there any known smart way to do this?

Let me make it clear .. both the input low and high and the output should be with decimals.

I found a post with a function that almost does it, but it does not work on numbers with a value below 1.

https://www.b4x.com/android/forum/threads/long-rnd.44051/#post-268155
 
Last edited:

keirS

Well-Known Member
Licensed User
Longtime User
Something like:

B4X:
Dim JORandom As JavaObject
    JORandom.InitializeStatic("java.lang.Math")
    Dim MinRange As BigDecimal
    Dim MaxRange As BigDecimal
    Dim Random As BigDecimal
    Dim Range As BigDecimal
    Dim Result As BigDecimal
    MinRange.Initialize("0.5")
    MaxRange.Initialize("2.5")
    Range = MaxRange.Subtract(MinRange)
    Random.Initialize(JORandom.RunMethod("random",Null))
    Result = MinRange.Add(Range.Multiply(Random)).Round(8,MinRange.ROUND_HALF_UP)
    Log(Result.ToPlainString)

This uses the BigNumbers library.
 
Upvote 0

kostefar

Active Member
Licensed User
Longtime User
Not sure that I understand. Do you want to randomly choose a number out of a set of specific numbers?

Hi Erel,

No, what I needed was to generate random numbers with up to 8 decimal places.. for instance Rnd(0.00008922,8789321.08082789). But keirS has solved my problem!
 
Upvote 0

kostefar

Active Member
Licensed User
Longtime User
Something like:

B4X:
Dim JORandom As JavaObject
    JORandom.InitializeStatic("java.lang.Math")
    Dim MinRange As BigDecimal
    Dim MaxRange As BigDecimal
    Dim Random As BigDecimal
    Dim Range As BigDecimal
    Dim Result As BigDecimal
    MinRange.Initialize("0.5")
    MaxRange.Initialize("2.5")
    Range = MaxRange.Subtract(MinRange)
    Random.Initialize(JORandom.RunMethod("random",Null))
    Result = MinRange.Add(Range.Multiply(Random)).Round(8,MinRange.ROUND_HALF_UP)
    Log(Result.ToPlainString)

This uses the BigNumbers library.

Amazing, just what I needed. Never heard of the BigNumbers library. Thanks!
 
Upvote 0
Top