I have some simple code using the random number function from picaxes website (slightly adapted)
symbol counter = b7
symbol randword = b5
for counter = 0 to 10
let randword = timer
random randword
write counter, b5
next counter
end
For some reason on picaxe editor version 5 this works perfectly but on picaxe editor 6 all it does is give out 2's, not very random, I have no idea why.
Any help much appreciated
Thanks
Checking the PICAXE BASIC language manual shows a few possible problems with your code:
the timer system variable has to be initialised with the settimer command before you can use it
depending on what preload value you use with settimer, the value of timer may well not have changed in the short time between one loop iteration and the next, which will give you the same result from random
random should be used with a word variable (w0, w1, etc) not a byte variable
What I think the manual entry for random is suggesting you should do, although I agree it isn't exactly clear if you're new to random number generation, is to seed random with timer the first time you call it, then seed it with its own previous value each time after that:
symbol counter = b5
let w3 = timer ; w3 is the word variable consisting of b6 and b7
for counter = 0 to 10
random w3
; ...do something with the value of w3 (but don't change w3 itself)...
next counter
However after saying all this, it is certainly possible that the simulator in one or other version of the PICAXE Programming Editor doesn't simulate the behaviour of timer correctly in all cases. If you can't get the code working on a real PICAXE, take this question to the PICAXE forum where it will be seen by Revolution Education support staff as well as other knowledgeable users.
Related
I was playing around with the lua interpretor and made this little program that generates two numbers and compares them. The program runs until the numbers match. The first number is randomly generated using math.random(), and is set to 1, and 100000. The second value that is generated to compare is between 1 and 100. It also keeps track of how many times the program loops. The program works as intended, but something strange happens when I run it.
The values that come up are always either 1, 31, 62, or 92. I've run the program many times, but it keeps generating these numbers. I have some understanding of how random numbers are generated, but this just seems weird. I'll paste the code in below. If someone can explain what's going on here, I would appreciate it greatly. Thanks!
counter=0;
a=0;
b=1;
while(a~=b)do
a=math.random(1,1000000);
b=math.random(1,100);
counter=counter+1;
if(a==b)then
print(a..", "..b..", and it took "..counter.." times")
end
end
The behaviour of the pseudo-random number generator changed in Lua 5.4. The 5.4 Reference Manual states, under §8.2 – Incompatibilities in the Libraries, that
The pseudo-random number generator used by the function math.random now starts with a somewhat random seed. Moreover, it uses a different algorithm.
If you are curious, that new algorithm is xoshiro256**.
What this means is that programs running in Lua environments prior to 5.4 must explicitly call math.randomseed to seed the pRNG. You want to do this only once in your program.
Without seeding the pRNG, the sequence of numbers produced will be the same each time you run your program. This is because, prior to 5.4, Lua's math.random is implemented using C rand or POSIX random, both of which default to a seed of 1 if not explicitly seeded.
The classic way to seed a pRNG is to use the current time (os.time). This is a simple approach, but has the fault that running this program twice in the same second will have the same result.
local counter = 0
local a = 0
local b = 1
math.randomseed(os.time())
while a ~= b do
a = math.random(1, 1000000)
b = math.random(1, 100)
counter = counter + 1
if a == b then
print(a .. ", " .. b .. ", and it took " .. counter .. " times")
end
end
Documentation links, for comparison:
5.3: math.random math.randomseed
5.4: math.random math.randomseed
What is the typical approach in LUA (before the introduction of integers in 5.3) for dealing with calculated range values in for loops? Mathematical calculations on the start and end values in a numerical for loop put the code at risk of bugs, possibly nasty latent ones as this will only occur on certain values and/or with changes to calculation ordering. Here's a concocted example of a loop not producing the desire output:
a={"a","b","c","d","e"}
maybethree = 3
maybethree = maybethree / 94
maybethree = maybethree * 94
for i = 1,maybethree do print(a[i]) end
This produces the unforuntate output of two items rather than the desired three (tested on 5.1.4 on 64bit x86):
a
b
Programmers unfamiliar with this territory might be further confused by print() output as that prints 3!
The application of a rounding function to the nearest whole number could work here. I understand the approximatation with FP and why this fails, I'm interested in what the typical style/solution is for this in LUA.
Related questions:
Lua for loop does not do all iterations
Lua: converting from float to int
The solution is to avoid this reliance on floating-point math where floating-point precision may become an issue. Or, more realistically, just be aware of when you are using FP and be mindul of the precision issue. This isn’t a Lua problem that requires a Lua-specific solution.
maybethree is a misnomer: it is never three. Your code above is deterministic. It will always print just a and b. Since the maybethree variable is less than three, of course the for loop would not execute 3 times.
The print function is also behaving as defined/expected. Use string.format to show thr FP number in all its glory:
print(string.format("%1.16f", maybethree)) -- 2.9999999999999996
Still need to use calculated values to control your for loop? Then you already mentioned the answer: implement a rounding function.
I am running a Fenuc Karel robot for a class assignment which uses a variation of Pascal however our robot is from 1991-1993 before they added random(). Does anyone know how to get a random number on an old dos implementation of Pascal? Please note because of the age variable names can't be more than 8 characters and numbers can't count past 255
If it is a borland pascal version, you can use asm { … } blocks, which would allow you to get a value from the RTC, which is sufficiently random for many intents and purposes. Given a variable random:
asm {
xor ax, ax;
int 1ah;
mv random, al;
}
This would give you the last 8 bit of the real time clock value.
Apart from that you could look for pseudorandom number generation on old machines, e.g. C64; though you'd have to port the code to pascal.
Update: It appears, Fanuc Karel (I hope this is it) has a GET_TIME routine, though I'm unsure about what that returns.
Now I'm trying to figure out best method for iterating over bits in FPGA. I'm using some variation of fast powering algorithm, a.k.a exponentiation by squaring (more precisely it's doubling and add algorithm for elliptic curve mathematics). To implement it on hardware, I know I must use FSM which does iteration. My problem is how to properly "handle" moving from bit to bit. My first thought was to switch order of bytes, but when my k = 17 is 32bit, I must discard first 27 bits, so it's rather stupid idea. Another concept was with "moving" 0001000 pattern and bitwise & it with number, but it also requires to find first nonzero bit.
TL&DR
Got for example k = 17 (32bits, so: 17x0 10001) and want to iterate 5 times (that means I start iteration on first "real" bit of number) knowing each bit I iterate over.
Language doesn't matter - I need only the algorithm, not solution in specific language. However, if it is easily done in Verilog, I wouldn't mind. :P
A dedicated combinatorial circuit to find the first nonzero bit, shift it to the first position and tell you the shift amount should be fairly light on resources.
In principle, the compiler should be able to find this solution on its own and improve on it:
if none of the top 16 bits are set, set bit 4 of the shift amount, and shift by 16.
if none of the top 8 bits are set, set bit 3 of the shift amount, and shift by 8.
...
The compiler should be able to find further optimizations on this.
Don not code for FPGA but still:
rewrite algorithm to iterate number x from LSB to MSB
then in each iteration bit shift x right by 1 bit
stop if x==0.
this way you have bit-scan inside your main loop and do not need additional cycles for it.
x!=0 is done easily by ORing all its bits together
C++ code example:
DWORD x = ...;
for (; x != 0; x >>= 1)
{
//here is your iteration loop stuff like:
if (DWORD(x & 1) !=0 ) ...;
}
Something like:
always # *
casex(num)
8XXX_XXXX: k = 32;
4XXX_XXXX: k = 31;
2XXX_XXXX: k = 30;
...
Should give you the value of k.
You can have a shift register which can be parallel loaded so you can write a 1 to the kth bit, so you know when your iterations have ended.
If you loop from 0 to 31 and discard the 27 leading zeros...you aren't necessarily wasting cycles. Depends on whether you've surrounded this with a synchronous process, or a asynchronous one.
One gives you a rather small clocked circuit with a 32 clock latency.
The other gives you a giant rats nest of ANDs and ORs which won't run at a very high frequency.
Depends on what you want. Remember though, that even if you do decide to loop over 32 clocks, you can PIPELINE it such that you start a new calculation every clock. It might take you 32 clocks to get an answer, but you CAN do them at high speed.
I am a beginner trying to do some engineering experiments using fortran 77. I am using Force 2.0 compiler and editor. I have the following queries:
How can I generate a random number between a specified range, e.g. if I need to generate a single random number between 3.0 and 10.0, how can I do that?
How can I use the data from a text file to be called in calculations in my program. e.g I have temperature, pressure and humidity values (hourly values for a day, so total 24 values in each text file).
Do I also need to define in the program how many values are there in the text file?
Knuth has released into the public domain sources in both C and FORTRAN for the pseudo-random number generator described in section 3.6 of The Art of Computer Programming.
2nd question:
If your file, for example, looks like:
hour temperature pressure humidity
00 15 101325 60
01 15 101325 60
... 24 of them, for each hour one
this simple program will read it:
implicit none
integer hour, temp, hum
real p
character(80) junkline
open(unit=1, file='name_of_file.dat', status='old')
rewind(1)
read(1,*)junkline
do 10 i=1,24
read(1,*)hour,temp,p,hum
C do something here ...
10 end
close(1)
end
(the indent is a little screwed up, but I don't know how to set it right in this weird environment)
My advice: read up on data types (INTEGER, REAL, CHARACTER), arrays (DIMENSION), input/output (READ, WRITE, OPEN, CLOSE, REWIND), and loops (DO, FOR), and you'll be doing useful stuff in no time.
I never did anything with random numbers, so I cannot help you there, but I think there are some intrinsic functions in fortran for that. I'll check it out, and report tomorrow. As for the 3rd question, I'm not sure what you ment (you don't know how many lines of data you'll be having in a file ? or ?)
You'll want to check your compiler manual for the specific random number generator function, but chances are it generates random numbers between 0 and 1. This is easy to handle - you just scale the interval to be the proper width, then shift it to match the proper starting point: i.e. to map r in [0, 1] to s in [a, b], use s = r*(b-a) + a, where r is the value you got from your random number generator and s is a random value in the range you want.
Idigas's answer covers your second question well - read in data using formatted input, then use them as you would any other variable.
For your third question, you will need to define how many lines there are in the text file only if you want to do something with all of them - if you're looking at reading the line, processing it, then moving on, you can get by without knowing the number of lines ahead of time. However, if you are looking to store all the values in the file (e.g. having arrays of temperature, humidity, and pressure so you can compute vapor pressure statistics), you'll need to set up storage somehow. Typically in FORTRAN 77, this is done by pre-allocating an array of a size larger than you think you'll need, but this can quickly become problematic. Is there any chance of switching to Fortran 90? The updated version has much better facilities for dealing with standardized dynamic memory allocation, not to mention many other advantages. I would strongly recommend using F90 if at all possible - you will make your life much easier.
Another option, depending on the type of processing you're doing, would be to investigate algorithms that use only single passes through data, so you won't need to store everything to compute things like means and standard deviations, for example.
This subroutine generate a random number in fortran 77 between 0 and ifin
where i is the seed; some great number such as 746397923
subroutine rnd001(xi,i,ifin)
integer*4 i,ifin
real*8 xi
i=i*54891
xi=i*2.328306e-10+0.5D00
xi=xi*ifin
return
end
You may modifies in order to take a certain range.