In Delphi/Object Pascal, the random function returns a float number that is between 0 and 1 inclusive. If you want to get a random number between two float numbers (single or double), you can use the following concise and efficient function.
Type float = Single; // or Double function RandomFloatRange(const A: float; const B: float): float; {$IFDEF INLINE} inline; {$ENDIF} var C, r: float; begin C := (A + B) * 0.5; r := Abs(B - A); Result := C + r * (random - 0.5); // Result = (A, B] end;
The type definition for float can be set to either 4-byte Single, 8-byte Double or 10-byte Extended. The parameter A and B define the range (order doesn’t matter). The middle is computed and the half-width is obtained. The essence is to use the expression r * (random – 0.5) to get a random number between -0.5r to 0.5r and add this to the middle point you have a coverage of numbers covered in the range. There is no conditional checks if you accidentally put A is bigger than B (order reversed).
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Replace WordPress inbuilt Search Box with Google Customize Search
Next Post: Allow ASP Style Short_Open_Tag in PHP.ini