Silverfrost Forums

Welcome to our forums

Floor hangs with 64 bit values

21 Jul 2019 1:04 #24056

I may be doing something daft, I'm trying to generate a 64 bit random number. The following hangs when floor is called.

  REAL :: r, z
  integer(kind=3):: j

  CALL random_seed()
  CALL RANDOM_NUMBER(r)
  print *, \'Random is \', r
  print *, \'huge is \', Huge(j)
  z = Huge(j) *r
  print *, \'z is \', z

! Next line hangs. j = floor(Huge(j)*r) print *, 'j is ', j

I can make this work for a 32 bit integer by changing to;

  integer(kind=3):: j

What dumbness have I emitted? Also, how should I declare the integer j to avoid the compiler warning if I want a 32 or 64 bit integer?

For example, 32 bit shows;

COMMENT - Specifying the kind of the type INTEGER with a constant is non-portable - 'SELECTED_INT_KIND(9)' would be better

Ryan

21 Jul 2019 6:07 #24059

It looks like overflow is occurring with the argument to floor.

You have to be careful that the argument to floor is not outside the range of the largest default integer or the largest integer of a kind specified as an optional argument:

   j = floor(huge(j)*r, kind(j))

Just because you are multiplying the largest integer (huge(1)) by a value r that is smaller than 1 doesn't mean that overflow won't occur when r is close to 1 (due to floating point rounding).

If you really need 63 bits you could generate two 32 bit values and concatenate them together (using IOR).

Its better not to use RANDOM_NUMBER for this but to use your own random number generator to generate the integers you want. This way you can make your code portable to different compilers and avoid the problems above.

See for examples

http://www.firstpr.com.au/dsp/rand31/p1192-park.pdf https://create.stephan-brumme.com/mersenne-twister/

23 Jul 2019 2:49 #24069

Ryan

I think that there is something here that we need to fix for 64 bits. If you start with integer(4)::j then it looks like floor(z, 4) is missing.

I have made a note of this.

24 Jul 2019 10:21 #24082

This has now been fixed for 64 bit code. It applies to FLOOR and CEILING and the fix will be in the next release of FTN95 and clearwin64.dll.

1 Sep 2019 10:15 #24291

Thank you Paul.

Please login to reply.