Why rand() returns the same values when I run my program in a script ? [duplicate] - c

This question already has answers here:
Run rand() in C language and loop with Shell Scripts
(3 answers)
srand(time(NULL)) doesn't change seed value quick enough [duplicate]
(6 answers)
Closed 6 years ago.
I have a srand(time(NULL)) at the beginning of the execution, then I am doing
*pos_x = (rand() % HEIGHT);
*pos_y = (rand() % WIDTH);
to generate random numbers.
This works fine when I run my program manually, but when I lunch my program with this script :
#!/bin/bash
i="0"
team_number="0"
while [ $i -lt 30 ]
do
./lemipc `pwd` team_number
i=$[$i+1]
if (( $i % 10 == 0 ))
then
team_number=$[$team_number+1]
fi
echo "create process $i"
usleep 10000
done
I always get the same numbers for all the processes.
I even tried to add a usleep to fix this but it still doesn't work.
I get this for exemple :
97 51
create process 1
97 51
create process 2
97 51
create process 3
97 51
where 97 is pos_x and 51 pos_y.
Have an idea why ?

The time() call has only whole-second precision. If your programs all run the same second, they will all use the same seed.
You must add more entropy. Consider using the return value of getpid() if you have it, or else investigate the platform's random sources.

This is cause usleep is delaying the execution of the next script the amount of microseconds (10000 = 0.01 seconds). time(NULL) returns SECONDS, thus making each time(NULL) returning value the same. Increase the amount of time it's delayed

Related

Why is slice faster than view() when constructing a multidimensional array from a vector?

Consider the following Vector:
numbers = Int32[1,2,3,4,5,6,7,8,9,10]
If I want to create a 2x5 matrix with the result:
1 2 3 4 5
6 7 8 9 10
I can't use reshape(numbers,2,5) or else I'll get:
1 3 5 7 9
2 4 6 8 10
Using slice or view(), you can extract the top row and bottom row, convert them to a matrix row, and then use vcat().
I'm not saying using slice or view() is the only or best way of doing it, perhaps there is a faster way using reshape(), I just haven't figured it out.
numbers = Int32[1,2,3,4,5,6,7,8,9,10]
println("Using Slice:")
#time numbers_slice_matrix_top = permutedims(numbers[1:5])
#time numbers_slice_matrix_bottom = permutedims(numbers[6:10])
#time vcat(numbers_slice_matrix_top,numbers_slice_matrix_bottom)
println("Using view():")
#time numbers_view_matrix_top = permutedims(view(numbers,1:5))
#time numbers_view_matrix_bottom = permutedims(view(numbers,6:10))
#time vcat(numbers_view_matrix_top,numbers_view_matrix_bottom)
Output:
Using Slice:
0.026763 seconds (5.48 k allocations: 329.155 KiB, 99.78% compilation time)
0.000015 seconds (3 allocations: 208 bytes)
0.301833 seconds (177.09 k allocations: 10.976 MiB, 93.30% compilation time)
Using view():
0.103084 seconds (72.25 k allocations: 4.370 MiB, 99.90% compilation time)
0.000011 seconds (2 allocations: 112 bytes)
0.503787 seconds (246.63 k allocations: 14.537 MiB, 99.85% compilation time)
Why is slice faster? In a few rare cases view() was faster, but not by much.
From view() documentation:
For example, if x is an array and v = #view x[1:10], then v acts like
a 10-element array, but its data is actually accessing the first 10
elements of x. Writing to a view, e.g. v[3] = 2, writes directly to
the underlying array x (in this case modifying x[3]).
I don't know enough, but from my understanding, because view() has to convert the Vector to a matrix row (the original Vector) through another array (the view()), it's slower. Using slice we create a copy and don't have to worry about manipulating the original Vector.
Your results actually show that view is faster not slicing. The point is that only the second tests is measuring the time to run the code while in the tests 1 and 3 you are measuring the time to compile the code.
This is a common misunderstanding how to run benchmarks in Julia. The point is that when a Julia function is run for the first time it needs to be compiled to an assembly code. Normally in production codes compile times do not matter because you compile only once for a fraction of a second and then run computations for many minutes, hours or days.
More than that - your code is using a global variable so in such a microbenchmark you are also measuring "how long does it take to resolve a global variable type" which is slow in Julia and not used in a production code.
Here is the correct way to run the benchmark using BenchmarkTools:
julia> #btime vcat(permutedims($numbers[1:5]),permutedims($numbers[6:10]));
202.326 ns (7 allocations: 448 bytes)
julia> #btime vcat(permutedims(view($numbers,1:5)),permutedims(view($numbers,6:10)));
88.736 ns (1 allocation: 96 bytes)
Note the interpolation symbol $ that makes numbers a type stable variable.
reshape(numbers, 5, 2)' can be used also to create the desired 2x5 matrix.

Is there a way to make a printing string literally in C, it has? [duplicate]

This question already has answers here:
How to escape the % (percent) sign in C's printf
(13 answers)
Closed 1 year ago.
fprintf(fptr, "#NoEnv SetWorkingDir %A_ScriptDir% CoordMode, Mouse, Window SendMode Input #SingleInstance Force SetTitleMatchMode 2 #WinActivateForce SetControlDelay 1 SetWinDelay 0 SetKeyDelay -1 SetMouseDelay -1 SetBatchLines -1 Loop { Sleep, 10 CoordMode, Pixel, Screen PixelSearch, FoundX, FoundY, 1324, 589, 1324, 589, 0x00786A, 0, RGB If ErrorLevel = 0 { Sleep, 1000 Click, 696, 728 Left, 1 Sleep, 10 Sleep, 300 Click, 775, 726 Left, 1 Sleep, 10 Sleep, 300 Click, 1273, 590 Left, 1 Sleep, 10 Return } else { sleep, 4000 Send {f5} sleep, 3000 Click, 1324, 589, 0 sleep, 10 }} Return")"");
Here is my code, not sure if it would work for what I'm doing, but it believes that the % and other stuff in the quotations are meant to be variables or whatever, how do I make it so it ignores all of that and just prints it?
fprintf stands for File Print Formatted.
In order to print unformatted, consider using fputs
You need to escape the %. You can do this by writing %% instead of %.

Stata: Observation-pairwise calculation

input X group
21 1
62 1
98 1
12 2
87 2
end
Now I try to calculate a measure as follows:
$$ \sum_{g} \left | X_{ig}-X_{jg} \right | $$
,where $i$ or $j$ ($i \neq j$) indexes an observation. g corresponds to the group variable (here, 1 and 2)
How to calculate this number using loops?
Looks like a Gini mean difference, apart from a scaling factor. There are numerous user-written commands already in this territory. There is (unusually) a summary within the Stata manual at [R] inequality.
In addition, this is related to the second L-moment. See the lmoments command from SSC.
You need not calculate this through a double loop over indexes. It collapses to a linear combination of the order statistics.
LATER: See David's 1998 paper which is open-access at
https://doi.org/10.1214/ss/1028905831

apending for loop/recursion / strange error

I have a matlab/octave for loop which gives me an inf error messages along with the incorrect data
I'm trying to get 240,120,60,30,15... every number is divided by two then that number is also divided by two
but the code below gives me the wrong value when the number hits 30 and 5 and a couple of others it doesn't divide by two.
ang=240;
for aa=2:2:10
ang=[ang;ang/aa];
end
240
120
60
30
40
20
10
5
30
15
7.5
3.75
5
2.5
1.25
0.625
24
12
6
3
4
2
1
0.5
3
1.5
0.75
0.375
0.5
0.25
0.125
0.0625
PS: I will be accessing these values from different arrays, that's why I used a for loop so I can access the values using their indexes
In addition to the divide-by-zero error you were starting with (fixed in the edit), the approach you're taking isn't actually doing what you think it is. if you print out each step, you'll see why.
Instead of that approach, I suggest taking more of a "matlab way": avoid the loop by making use of vectorized operations.
orig = 240;
divisor = 2.^(0:5); #% vector of 2 to the power of [0 1 2 3 4 5]
ans = orig./divisor;
output:
ans = [240 120 60 30 15 7.5]
Try the following:
ang=240;
for aa=1:5
% sz=size(ang,1);
% ang=[ang;ang(sz)/2];
ang=[ang;ang(end)/2];
end
You should be getting warning: division by zero if you're running it in Octave. That says pretty much everything.
When you divide by zero, you get Inf. Because of your recursion... you see the problem.
You can simultaneously generalise and vectorise by using logic:
ang=240; %Replace 240 with any positive integer you like
ang=ang*2.^-(0:log2(ang));
ang=ang(1:sum(ang==floor(ang)));
This will work for any positive integer (to make it work for negatives as well, replace log2(ang) with log2(abs(ang))), and will produce the vector down to the point at which it goes odd, at which point the vector ends. It's also faster than jitendra's solution:
octave:26> tic; for i=1:100000 ang=240; ang=ang*2.^-(0:log2(ang)); ang=ang(1:sum(ang==floor(ang))); end; toc;
Elapsed time is 3.308 seconds.
octave:27> tic; for i=1:100000 ang=240; for aa=1:5 ang=[ang;ang(end)/2]; end; end; toc;
Elapsed time is 5.818 seconds.

How to use rand() to generate numbers in a range? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Generate Random numbers uniformly over entire range
How to use rand function to
Could anyone tell me how to use the rand() function in C programming with 1 = min and
7 = max, 1 and 7 included.
Thanks
This will do what you want:
rand() % 7 + 1
Explanation:
rand() returns a random number between 0 and a large number.
% 7 gets the remainder after dividing by 7, which will be an integer from 0 to 6 inclusive.
+ 1 changes the range to 1 to 7 inclusive.
Use the modulo operator. It returns the remainder when dividing. Generate a number in range 0 to 6 by using
rand() % 7. Add 1 to that to generate a number in range 1 to 7.

Resources