Question

How we can generate randomize number between a range in the Float numbers (in delphi xe3) ?

For example, randomize number between [0.10 to 0.90]. I need give results like:

[ 0.20 , 0.32 , 0.10 , 0.50 ]

Thanks for solutions....

Was it helpful?

Solution 2

var
  float : Double;

  float := Random;  // Random float in range: 0 <= float < 1
  float := 0.1 + float*0.8 // 0.1 <= float < 0.9

To initialize the Random number generator, make a single call to Randomizeor set the RandSeed parameter before calling the Random function for the first time.

Not doing so, generates the same sequence every time you run the program. Note however, that this sequence is not guaranteed when recompiling for another compiler version.

OTHER TIPS

Another option is to use RandomRange (returns: AFrom <= r < ATo) as follow:

RandomRange(10, 90 + 1) / 100

or

RandomRange(10, 90 + 1) * 0.01

will return numbers in the range of 0.10 to 0.90 (including 0.90)

Try this:

function RandomRangeF(min, max: single): single;
begin
  result := min + Random * (max - min);
end;

This is a bit cheeky but here goes: Depends how many numbers you want after the floating point. For example, if you want 1 number, you could generate in the 100 - 999 range and then divide by 10. Or 1000 - 9999 and divide by 100.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top