Simulating VB Randomize and Rnd

Coding + IDE + Code-Editor + Syntax + User-Functions + Anything else

Simulating VB Randomize and Rnd

Postby blatman » Wed Aug 15, 2012 10:46 pm

I have a project that I wish to port to Q7B but it relies on the VB Randomize and Rnd pseudo-number generator method.
The project uses a number between -32768 and 32767 as an argument for Randomize() and this is used to seed the Rnd therefore giving a repeatable sequence for Rnd between 0 and 1. Looking at the Q7B Randomize and Random methods they appear to work differently with Randomize using the system time only - no argument is allowed. However it looks like qsrand and qrand may do what VB does - indications are that the same qsrand argument used as a seed for qrand will produce a repeatable sequence and qrand can be set for 0-1 range.
Question is - is it possible to access these two methods from Q7B - my knowledge of C++ is sketchy - in fact I don't even have the pencil!
Cheers,
Blane
blatman
 
Posts: 51
Joined: Mon Jul 16, 2012 12:33 pm
Location: UK

Re: Simulating VB Randomize and Rnd

Postby berndnoetscher » Thu Aug 16, 2012 8:52 am

Hi

This is a solution:
Code: Select all
Event Init()
  Randomize()

  MsgBox(RND(65536) - 32768)

End Event
berndnoetscher
Site Admin
 
Posts: 344
Joined: Thu Mar 25, 2010 9:57 am

Re: Simulating VB Randomize and Rnd

Postby blatman » Thu Aug 16, 2012 8:59 pm

Hi Bernd,

thanks for the response - it didn't quite work but put me on the right track. MSDN suggests that using a negative argument for RND will produce a repeatable sequence so I tried the following and it seems to work well.

Dim xx1 as Integer
Dim xx2 as Integer
Dim xx3 as Integer
Dim choice as Short 'choice between -32768 and 32767 using InputBox

Randomize() ' Done once

RND(- 65536 - choice) ' will always produce negative argument to give repeatable sequence.
' In VB choice had to be used with Randomize as the seed for RND
xx1 = 100 * RND()
Pause(500) ' avoid possible issues with Randomize and System time being sampled within 1 ms
xx2 = 100 * RND()
Pause(500)
xx3 = 100 * RND()

Result using choice = -32768 gave -
xx1 - 58
xx2 - 2
xx3 - 77

This was always the same sequence if the same choice was used - which is the requirement.
Not sure why randomize() didn't upset things because it uses the system time as the seed which varies but hey - it works!

All seems to be a bit reversed to VB where I had to use choice as the argument for Randomize rather than RND

Cheers.
blatman
 
Posts: 51
Joined: Mon Jul 16, 2012 12:33 pm
Location: UK


Return to Questions & Answers

Who is online

Users browsing this forum: No registered users and 0 guests

cron