• Welcome to the new Internet Infidels Discussion Board, formerly Talk Freethought.

The Programming Thread

Why use dynamic memory allocation?



Note that there is generally a limit on the size of the stack – which can vary with the operating system (for example OSX currently has a default stack size of 8MB). If a program tries to put too much information on the stack, stack overflow will occur. Stack overflow happens when all the memory in the stack has been allocated, and further allocations begin overflowing into other sections of memory. Stack overflow also occurs in situations where recursion is incorrectly used.


Heap memory
The heap is the diametrical opposite of the stack. The heap is a large pool of memory that can be used dynamically – it is also known as the “free store”. This is memory that is not automatically managed – you have to explicitly allocate (using functions such as malloc), and deallocate (e.g. free) the memory. Failure to free the memory when you are finished with it will result in what is known as a memory leak – memory that is still “being used”, and not available to other processes. Unlike the stack, there are generally no restrictions on the size of the heap (or the variables it creates), other than the physical size of memory in the machine. Variables created on the heap are accessible anywhere in the program.

If you are dealngi with large arrays and declare arrays x[N] it goes on the stack. Stack memory is where local variables and functions operate. You can run out of stack memory with arays.

In the day of 64k memory that was easy to do and swapping both code and data in and out of memory from disk was common.


You can increase the size of an array on the stack int x[N] until the compiler says it is too much.

The example shows how I used OOP. In the 80s I read OOP is ‘the melding of data and the mehods operating on the data’, IOW encapsulation.

On the automated manufacturing systems I designed I had to deal with multiple files. I would pass the file names through the command line parameters main( int argc,char *argv[],char **envp ). T

Using classes ensured the file data could not be inadvertently corrupted by code outside the class. The class contains error checking. I made use of log files. If something did go wrong I’d have a staring point.

As the saying goes 'A gram of prevention is worth a kilogram of cure'.

It would have been impossible using random code. Using structured programming and functions could have worked but it would have been much more complicated and harder to debug. I would debug and test an object and put in a library. Then I’d write the top level code naking use of pretested objects. More work at the start, but a lot less work at the end. Easier maintenance and changes.

You can look at OOP as a form of reductionism.

OOP is more prevalent then you might think, you just don’t see it.

When you click on a folder a window appears. The OS dynamically spawns an object for the graphic window. I don’t know Windows classes. As you drag the window cursor xy is updated as something like window_handle.x widow_handle.y. When the window goes away the object is deallocated.

Same thing in my Scilab tool. When I create a graphics window to plot something I get an object to set parameters.


Code:
const int FILE_ERROR = -1;
const int LIMIT_ERROR = -2;
const int MAX_SIZE = 20;
#define ABORT(){cout<<"CHECK LOG"<<endl;return(-1);}


class LoadFile{

   private:

   int fsize = 0;
   double *array_ptr;;

   void error_log(int i){
        char err_str[3][20] = {"NO EOF",
                          "ARRAY LIMIT",
                          "FILE ERROR"};
     FILE *p = fopen("log.txt","a");
     fprintf(p,"%s\n",err_str[i]);
     fclose(p);
   }

   public:

   int open_file(char *fname){
    int x, i = 0;
    FILE *ptr = fopen(fname,"r");
    if(!ptr){
       error_log(2);
       return(FILE_ERROR);
       }
    while(fscanf(ptr,"%d",&x) == 1){
        fsize += 1;
        if(fsize > MAX_SIZE){
          error_log(0);
          return(FILE_ERROR);
        }
    }
    array_ptr = new double[fsize];
    rewind(ptr);
    for(i = 0;i<fsize;i++){fscanf(ptr,"%d",&x);array_ptr[i] = x;}
    fclose(ptr);
    return(fsize);
   }//open_file()

   int read(int i){
      //prevent over running the array
      if(i >= 0 && i < fsize)return(array_ptr[i]);
      error_log(1);
      return(array_ptr[fsize-1]); //return last entry
    }//read()

   ~LoadFile(void){cout<<"Goodbye"<<endl;}

};//LoadFile
int main(){

    LoadFile f[2]; // create an array of file objects
    char fname[2][20] = {"d1.txt","d2.txt"};
    int i = 0,n[2],n_files = 2;

    // boot initialization
    for(i = 0;i<n_files;i++){
        n[i] = f[i].open_file(fname[i]);
        if(n[i] == FILE_ERROR)ABORT()
        }

   for(i = 0; i<n[0];i++){
     cout<<f[0].read(i)<<endl;
     }
   for(i = 0; i<n[1];i++){
     cout<<f[1].read(i)<<endl;
     }

    // destroy the objects.
    for(i = 0;i<n_files;i++)f[i].~LoadFile();


return 0;
}
 
Last edited:
Simulating random particles.

Particles are represented by objects. Each object tracks position of the particle. I have it reflecting off an x wall.

Particles are initialized from random variables, or can be done individually.

Next step is making it 3D and figuring out how to manage particle collisions.

Number of particles limited only by memory.

Scilab is used ro create the random variables and plot. A free tool.

My goal is add mass and gravity simulating gas particles in a tank.

Code:
const int MAX_SIZE = 10000;
const int Npoints = 100;

class LoadFile{
    public:

    double *v,*angle,*x,*y,*z;

    int open(string fname){
        int i = 0,n = 0;
        ifstream datafile;
        datafile.open(fname);
        datafile >> n;
        v = new double[n];
        angle = new double[n];
        x = new double[n];
        y = new double[n];
        z = new double[n];

        for (i = 0; i < n; i++)
            datafile >> v[i] >> angle[i] >> x[i]>>y[i]>>z[i];
        cout << "Load DONE" << "\n";
        return(n);
    }//open()
};//LoadFile




int save(char *fname,int n, double *x, double *y) {
    int i;
    FILE *ptr = fopen(fname,"w");
    if(!ptr)return(FILE_ERROR);
    fprintf(ptr,"%d\n",n);
    for (i = 0; i < n; i++)fprintf(ptr,"%f    %f\n",x[i],y[i]);
    if(fclose(ptr))return(1);
    cout <<fname<<"  SAVE DONE" << "\n";
    return(0);
}//save()



class Particle{

    public:
    double *x = new double[Npoints];
    double *y = new double[Npoints];


    double  mass = 0, v = 0,ke = 0,
            x0 = 0,y0 = 0, xpos = 0, ypos = 0,
            dt = 0,xlim = 0,ylim = 0,
            distance = 0,angle = 0;
    double kas = 0, kac = 0;
    int count = 0;
     int s = 1;


    void initialize(void){
        for(int i = 0;i<Npoints;i++){x[i] = 0;y[i] = 0;}
        angle = _PI*angle/180.;//degrees to radians
        kas = sin(angle);
        kac = cos(angle);
        x[0] = x0;
        y[0] = y0;
        xpos = x0;
        ypos = y0;
        count = 1;
    }//init()

    void update(void){
        distance = distance + (v*dt);
        if(s)xpos = (kas * distance) + x0;
          else xpos = xlim -(kas * distance);
        ypos = (kac * distance) + y0;
        y[count] = ypos;
        x[count] = xpos;

        if(x[count] >= xlim && s){  //reflection
            y0 = y[count];
            x0 = x[count];
            s = 0;
            distance = 0;
            }
        count++;
    }//update()

};//Particle

int main(){

    int Np = 10,Ntot = Np*Npoints, nrand = 0;;
    char fname[20] = {"data.txt"};
    Particle p[Np];
    LoadFile rnd;
    int i = 0,j =0, k = 0,err = 0;
    nrand = rnd.open("rand.txt");
    cout<<"nrand   "<<nrand<<endl;
    if(nrand<Np)cout<<"Not Enough Random Initializers"<<endl;

    double tmax = 10,dt = tmax/Npoints;
    double xlim = 4,ylim = 10000;
    double time = 0;
    double t[Npoints];
    double x[Np] = {0,0}; //starting points
    double y[Np] = {0,1};
    double angle[Np] = {45,-45};
    double v[Np] = {1,1};
    double totalx[Ntot],totaly[Ntot];

    for(i=0;i<Npoints;i++){
        t[i] = time;
        time += dt;
    }//for

  //initialize objects
   for(i=0;i<Np;i++){
        p[i].x0 = rnd.x[i];p[i].y0 = rnd.y[i];
        p[i].v = rnd.v[i];p[i].dt = dt;
        p[i].angle = rnd.angle[i];
        p[i].xlim = xlim;p[i].ylim = ylim;
        p[i].initialize();
    }//for


    //run simulation
    for(i=0;i<Npoints;i++){
        for(j=0;j<Np;j++){
            p[j].update();
                for(k=0;k<j;k++){
                 if((p[k].xpos == p[j].xpos)&&(p[k].ypos == p[j].ypos))
                  cout<<"Colliision"<<endl;
                }//k
        }//j
     }//i

    //concantanate files for scatter plot
    k = 0;
    for(i=0;i<Np;i++){
        for(j=0;j<Npoints;j++){
            totalx[k] = p[i].x[j];
            totaly[k] = p[i].y[j];
            k++;
        }//j
    }//i

    err = save(fname,Ntot, totalx,totaly);
    if(err)cout<<"File Error   "<<err<<endl;

    //for(i = 0;i<100;i++)
    //printf("%f  %f  %f   %f   %f\n",t[i],p[0].x[i], p[0].y[i]);



     //for(i = 0;i<Npoints;i++)
            //printf("%f   %f\n",totalx[i],totaly[i]);
return(0);

}

Scilab script

Plotting
clear
mclose("all")
s1 = "data.txt"
[f1,err] = mopen(s1,"rt")
if(err < 0)then disp("file open error ",err);end;
N = mfscanf(1,f1," %d") //read length of file
y = mfscanf(N,f1,"%f %f ")
mclose("all")
//mprintf("%f %f \n",y) //displays the data on the cosole window

w1 = scf(1)
clf(w1)
scatter(y([1:N],1), y([1:N],2),"filled diamond")
xgrid

Random variables.



n = 10000
m = 1
velocity = grand(n, m, "unf", 1, 2)
angle = grand(n, m, "unf", -90, 90)
x = grand(n, m, "unf", -10, 10)
y = grand(n, m, "unf", -10, 10)
z = grand(n, m, "unf", -10, 10)
mclose("all")
s1 = "rand.txt"
[f1,err] = mopen(s1,"wt")
if(err < 0)then disp("file open error ",err);end;
mfprintf(f1," %d\n",n) //write length of file
mfprintf(f1,"%+3.4f %+3.4f %+3.4f %+3.4f %+3.4f\n",velocity,angle,x,y,z)
mclose("all")

//mprintf("%+3.4f %+3.4f %+3.4f %+3.4f %+3.4f\n",velocity,angle,x,y,z)
 
Well, found a problem. As I increased the numer of points and particles it crashed.

The problem was double totalx[Ntot],totaly[Ntot] defined on the tsack. AS the file size grew it exceed stack memory.

Changed to double *xtot = new dounle[Ntot] *ytot = new dounle[Ntot] putting it on the heap and the problem went away.

To estimate memory

double mem = 0;
mem = ((2*Ntot) + Npoints*2 * Np * double(sizeof(double)))/1e6;
printf("Memory Allocation MB %f\n ",mem);

For any array x[N] mem = sizeof(x)/(sizeof(x[0])

sizeof(x) gives the total size in bytes. sizeof(x[0]) gives the size of the variable in bytes.

When a progan loads you xan watxh the memory usage in the task manager.

10,000 particles with 2000 data ponts takes 300MB and 4 minutes to run.



Looks like there are wys to change memory allocation but it is not straightforward.
 
Last edited:
You are on a space ship being circled by a system that disables your engines and weapons computers by a strange force you have never encountered before.

Fortunately your lap top is unaffected and is running Windows 3,456 with a spread sheet. A magnetic rail gun is working but you have to figure out how fast to launch yourself in a space suit to intercept the orbiting system and attach a bomb.

You have a 60 minute TV show minus the commercials to figure out how to make a bomb and calculate the velocity to launch yourself.

The rail gun is at a 45 degree angle to the xy coordinates. You will launch when the orbiting system crosses (,r) r being the radius of the orbit.

You can't go fast enough to hit it on the first pass and it will take several obits for you to intercept

You have a 10 minute segment ob the show to furiously type on a keyboard writing a macro to calculate velocity while alarms are sounding and a white gas is filling up the ship from battle damage. You are being distracted by a female crew mate wearing a thong.

vp1 your calculated velocity
vp2 orbiting system velocity
r radius of orbit
c orbit circumference
sc distance from (0,r)to intercept point
stot total distance traveled on successive orbits
nlloop number of orbits to intercept at vp1



One down side to using macros is that apparently the only way to use spread sheet math functions is write an equation string to a cell ad read back the result.

The explicit option forces all variables to be defined, prevents typo errors

I used Apache OpenOffice.


Code:
option explicit

Sub Main
Dim Doc As Object
Dim cell as object
Dim Sheet As Object
Doc = ThisComponent
Sheet = Doc.Sheets (0)
Cell = Sheet.getCellByPosition(0,0)
cell.string = "RUNNING"

dim rc,sp1,sp2,ang_deg,c,dt,sc,nloop,vp1,vp2,t,stot,tc,r as double
dim xp1,yp1,yp2,d,sin,cos,ang_rad as double
dim i,miss_flag,n as long
nloop = 1.
t = 0.
r = 100.
ang_deg = 45.  '>0  <90
ang_rad =(ang_deg/360.)*2*pi
c = 2*pi*r
sc = c*ang_deg/360.'distance on first pass
vp2 = 10.
stot = sc+(c*nloop) ' total travel ditance
vp1 =  (r*vp2)/stot
tc = stot/vp2  ' travel time
dt = .001
n = 1000 +  tc/dt
miss_flag = 0

Cell = Sheet.getCellByPosition(4,0)
cell.value = ang_rad
Cell = Sheet.getCellByPosition(4,1)
cell.formula = "=sin($E1)"
sin = cell.value
 Cell = Sheet.getCellByPosition(4,2)
cell.formula = "=cos($E1)"
cos = cell.value


for i = 1 to n

    'update particle distance
    sp1 = t*vp1
    sp2 = t*vp2
    
    ' particles x y coordinates
    yp1 = sin * sp1
    xp1 = cos * sp1
    yp2 = (r^2-xp1^2)^.5
          
    if sp1 > 1.2*r then  'missed
      miss_flag = 1
      exit for
    end if
    
    ' check partcle proximity   
    if  abs(yp1-yp2) < .1 AND t > 0.  then
    'if sp1 >= r then
    exit for
    end if
    
    t = t + dt 
    
next i

Cell = Sheet.getCellByPosition(0,0)
if i >= n OR miss_flag = 1 then
     cell.string = "MISS"
   else
     cell.string = "HIT"
end if


Cell = Sheet.getCellByPosition(0,1)
cell.string = "VP1"
Cell = Sheet.getCellByPosition(1,1)
cell.value = vp1
Cell = Sheet.getCellByPosition(0,2)
cell.string = "VP2"
Cell = Sheet.getCellByPosition(1,2)
cell.value = vp2



Cell = Sheet.getCellByPosition(0,3)
cell.string = "SP1"
Cell = Sheet.getCellByPosition(1,3)
cell.value = sp1
Cell = Sheet.getCellByPosition(0,4)
cell.string = "SP2"
Cell = Sheet.getCellByPosition(1,4)
cell.value = sp2

Cell = Sheet.getCellByPosition(0,5)
cell.string = "Stot"
Cell = Sheet.getCellByPosition(1,5)
cell.value = stot

Cell = Sheet.getCellByPosition(0,6)
cell.string = "xp1"
Cell = Sheet.getCellByPosition(1,6)
cell.value = xp1
Cell = Sheet.getCellByPosition(0,7)
cell.string = "yp1"
Cell = Sheet.getCellByPosition(1,7)
cell.value = yp1
Cell = Sheet.getCellByPosition(0,8)
cell.string = "yp2"
Cell = Sheet.getCellByPosition(1,8)
cell.value = yp2


End Sub

function abs(x as double)

     if x < 0. then
       abs = x * -1.
      else abs = x
     end if
      

end function
 
You are on a space ship being circled by a system that disables your engines and weapons computers by a strange force you have never encountered before.

Fortunately your lap top is unaffected and is running Windows 3,456 with a spread sheet. A magnetic rail gun is working but you have to figure out how fast to launch yourself in a space suit to intercept the orbiting system and attach a bomb.
This strikes me as impossible. A 0,0 intercept doesn't seem possible and the attach a bomb requirement seems to require a 0,0 intercept.
 
It is my fantasy, it only has to make sense to me. As in women in thongs on a saceship under attack.

You start at (0,0) launched by a rail gun, the object is referenced at (0,r) both referenced to time zero at that condition, as in the code. In dynamic systems all positions are referenced to a defined point in space and time relative to an inertial frame.

It is the same in an electrical system althoughwe don't usually think of it that way. A circuit is in three physical dimensions. Electrons move within an inertial frame. When doing mathematical analysis and simulation there is an arbitrary time zero and a set of initial conditions, along with a refebce point (x,y.z) from which to reference voltages. Called ground or power supply common.

An intercept can not occur at (0,0) with an object orbiting in a circle.
 
It is my fantasy, it only has to make sense to me. As in women in thongs on a saceship under attack.

You start at (0,0) launched by a rail gun, the object is referenced at (0,r) both referenced to time zero at that condition, as in the code. In dynamic systems all positions are referenced to a defined point in space and time relative to an inertial frame.

It is the same in an electrical system althoughwe don't usually think of it that way. A circuit is in three physical dimensions. Electrons move within an inertial frame. When doing mathematical analysis and simulation there is an arbitrary time zero and a set of initial conditions, along with a refebce point (x,y.z) from which to reference voltages. Called ground or power supply common.

An intercept can not occur at (0,0) with an object orbiting in a circle.
I meant 0,0 as in zero deviation in speed and course relative to the target. You're going to fly past the target and won't be able to plant your bomb.
 
It is my fantasy, it only has to make sense to me. As in women in thongs on a saceship under attack.

You start at (0,0) launched by a rail gun, the object is referenced at (0,r) both referenced to time zero at that condition, as in the code. In dynamic systems all positions are referenced to a defined point in space and time relative to an inertial frame.

It is the same in an electrical system althoughwe don't usually think of it that way. A circuit is in three physical dimensions. Electrons move within an inertial frame. When doing mathematical analysis and simulation there is an arbitrary time zero and a set of initial conditions, along with a refebce point (x,y.z) from which to reference voltages. Called ground or power supply common.

An intercept can not occur at (0,0) with an object orbiting in a circle.
I meant 0,0 as in zero deviation in speed and course relative to the target. You're going to fly past the target and won't be able to plant your bomb.
Are you taking the text I posted seriously?

The code was posted as a macro for somebody who may want to run it and experiment with.

As it is scifi fantasy the hero launched by a rail gun could hold the bomb out in front of him exploding when it hits the enemy system, dieing in a blaze of glory to save the his ship and the galaxy....
 
It is my fantasy, it only has to make sense to me. As in women in thongs on a saceship under attack.

You start at (0,0) launched by a rail gun, the object is referenced at (0,r) both referenced to time zero at that condition, as in the code. In dynamic systems all positions are referenced to a defined point in space and time relative to an inertial frame.

It is the same in an electrical system althoughwe don't usually think of it that way. A circuit is in three physical dimensions. Electrons move within an inertial frame. When doing mathematical analysis and simulation there is an arbitrary time zero and a set of initial conditions, along with a refebce point (x,y.z) from which to reference voltages. Called ground or power supply common.

An intercept can not occur at (0,0) with an object orbiting in a circle.
I meant 0,0 as in zero deviation in speed and course relative to the target. You're going to fly past the target and won't be able to plant your bomb.
Are you taking the text I posted seriously?

The code was posted as a macro for somebody who may want to run it and experiment with.

As it is scifi fantasy the hero launched by a rail gun could hold the bomb out in front of him exploding when it hits the enemy system, dieing in a blaze of glory to save the his ship and the galaxy....
I thought it was being presented as a puzzle to solve and I'm saying there inherently isn't a solution unless the target is under acceleration, not merely responding to gravity. You can find a path to get the distance to zero but you can't find one that gets both the distance and velocity to zero.
 
The scenarist was a spoof on scifi.

The code posted is a solution to the problem on the Math Quiz thread with a stright line instead of a parabola, incorporating that there is an ifinte number of solutions as you and bomb pointed out.

If you want a problem to solve and code I will post one, just say so. Given the thread I expect that the solution will be in code.

I do this stuff to stay mentally active.
 
The Unix command dump is programmed to take special advantage of the fork() system call. This may be an interesting topic to discuss in this thread.

dump makes backups from a file system to magnetic tape. It examines time-stamps and other information to decide what to backup, but we needn't concern ourselves with that. (Instead of tape, the backup may be to ordinary disk-files, but dump doesn't know the difference; we will refer to the output files as "tape reels.")

fork() is the system call which creates a new process. Here's an example: the two do_something routines will be executed concurrently by two different processes.

Code:
        child = fork();  // create a child process
        if (child == 0) {
                // code executed by child
                do_something_childish();
                exit(STATUS);
        }
        // code executed by parent
        do_something_parental();
        waitpid(child, &status, 0);
        switch (status) {
                // process child's exit status
                . . .
        }

(Does Windows have something similar? Will someone post a similar fragment to compare Windows' method with Unix's?)

fork() is frequently used to start an executable, and multiple fork()'s are needed to start a piped command group, but fancier usage of fork() is relatively uncommon. An exception is the dump program.

dump does a fork() at the beginning of every tape reel. If an error occurs the child will exit with a status code, and the parent repeats the fork(), automatically restarting from a correct check-point. When dump is on its N'th tape reel, there will be at least N+1 dump processes alive, but all but one will be ready to exit as soon as their child exits normally. But wait: There's more.

In the BSD dump the master process for a reel will spawn three children. The master will apportion the work-load among the three processes. Each process will read the file system data to be backed up and write it, along with control information, into a tape write buffer; but the buffered data will only be written to tape when that process has a "baton." The single baton is passed round-robin among the three processes. Inter-process communication is accomplished with pipes and with Unix's kill()/signal() mechanism. This allegedly high-speed dump was developed in the early 1980's or thereabouts.

By the mid or late 1980's it was recognized that this dump was not as fast as it could be. It didn't take advantage of shared-memory, a feature available by then on the latest kernels. Moreover, dividing the workload among three processes each doing reads and writes was not optimal. A new approach was developed at two companies. The two new dump's were VERY similar, even though there was ZERO contact between the designers.

In the new approach, two processes were spawned to do the grunt work instead of three; one read the disk and prepared the tape buffer, the other wrote the tape. The tape buffer was located in shared memory. Ordinary kernel scheduling would automatically switch control between the processes as appropriate.

Any other interesting examples of fork()?
 
Looks like C++ can do all or most of the OS level functions as in Unix,

This gets the current process ID.

#include "windows.h"
#include "tchar.h"
#include "psapi.h"


int main(){

DWORD x = GetCurrentProcessId();
cout<<x<<endl;
return 0;
}

 
One of Swami's problems got me thinking about random numbers, or more correctly pseudo random numbers. Ilost my copy of Knuth's Semi Numerical Algorithms which has a chapter on random numbers. There can be dante over what random meas. His response was random is whatever yoiu define t to be, anything that meets the definition is then random.

Fr a decimal number I split the number into two random numbers, the fractional and integre parts adding the two. Probably not new.

I tested the fractional part for N = 10,000 multiple times with 10 bins from 0 to 1. At 3 digits the numbers at that granularity were fairly flat. At 4 digits there was a clear bias on the low end that gets worse as the number of digits increase.

When I added the random integer part from 0 - 9 the bias becomes indistinguishable at least for 10 bins granularity. The bias is still there, harder to detect. Doing extensive characterization would take some work, the domain of cryptology. I downloaded a few papers but I don't know the math notation well enough so it will be slow going.

To stimulate Swami's problem I'd need a random sequence of numbers 1-100 without duplicated numbers.


Code:
//C++ GNU gcc

#include <iostream>
#include "math.h"
#include "stdlib.h"
#include "stdio.h"
#include<iomanip>
using namespace std;

const int FOREVER = 1;

class RandNum{
    public:
    int N = 0;
    double *fr1,*fr2;
    int *ir;
    int sc,offset,sci,scd;

    void init_array(void){
        for (int i = 0;i <N;i++){
            fr1[i] = 0.;
            fr2[i] = 0.;
            ir[i] = 0;
        }
        cout<<"Init Done"<<endl;
    }

    int  save(void){
        FILE *ptr = fopen("data.txt","w");
        if(!ptr)return(1);
        fprintf(ptr,"%d\n",N);
        for(int i = 0;i < N;i++)
        fprintf(ptr,"%10.6f   %10.6f  %10d\n",fr1[i],fr2[i],ir[i]);
        fclose(ptr);
        cout<<"Save Done"<<endl;
    return(0);
    }//save()


    void rand_int_array(void){
        //array random ints
        int i;
        cout << "Rand Int Array" << endl;
        unsigned seed = unsigned (time(NULL));
        srand(seed);
        for (i = 0; i < N; i++)ir[i] = (rand()%sc) + offset;
    }//rand_int_array())

    int rand_int(void){
        //random int
        cout << "Rand Int" << endl;
        unsigned seed = unsigned (time(NULL));
        srand(seed);
        return((rand() % sc) + offset);
    }//rand_int())

    void rand_int_seq(void){
        //one occurrence of each number 1-hi
        cout<<"Rand Int Seq"<<endl;
        int flag = 0, j = 0,i = 0, x = 0,  cnt = 0;
        unsigned seed = unsigned (time(NULL));
        srand(seed);
        for(i = 0; i < N; i++){
         cnt = 0;
         ir[i] = 0;

         while(FOREVER){
            if(cnt++ == 20000){cout<<"Runaway Loop"<<endl;return;}
            x = int(rand()%N) + 1;
            if(i == 0)break;
            flag = 0;
            for(j = 0;j < N;j++)if(ir[j] == x)flag = 1;
            if(!flag)break;
        }//while

        ir[i] = x;
    }//i
    }//rand_int__seq()

  void rand_float_array(void) {
        cout << "Flooat Array" << "\n";
        double rfrac;
        int rint;
        unsigned seed = unsigned (time(NULL));
        srand(seed);
        for (int i = 0; i < N; i++) {
            rint = rand() % sci;
            rfrac = double(rand() % scd);
            fr1[i] = (rfrac / double(scd)) + rint;
        }
    }//rand_float_array()

    double rand_float(void) {
        cout << "Rand Float" << "\n";
        double rfrac;
        int rint;
        unsigned seed = unsigned (time(NULL));
        srand(seed);
        rint = rand() % sci;
        rfrac = double(rand() % scd);
        return((rfrac / double(scd)) + rint);
    }//rand_float()


};//class RandNum


int main() {

    RandNum rn;
    double yf;
    int N = 10000,yi;
    double* fr1 = new double[N];
    double *fr2 = new double[N];

    int* ir = new int[N];
    rn.N = N;
    rn.fr1 = fr1;rn.fr2 = fr2;rn.ir = ir;
    rn.sc = 10;rn.offset = 0;
    rn.sci = 100;rn.scd = 100000;
    rn.init_array();
    rn.rand_int_seq();
    rn.rand_int_array();
    rn.rand_float_array();
    yf = rn.rand_float();
    cout<<"Rand Float  "<<yf<<endl;
    yi = rn.rand_int();


    cout<<"Rand Int  "<<yi<<endl;
    if(rn.save())cout<<"FILE ERROR"<<endl;;

    int i,j,x[10];
    for(i=0;i<10;i++)x[i] = 0;
    for(i=0;i<10;i++){
        for(j=0;j<N;j++){
            if(fr1[j] > 0.  && fr1[j] <= 10.) x[0] += 1;
            if(fr1[j] > 10. && fr1[j] <= 20.) x[1] += 1;
            if(fr1[j] > 20. && fr1[j] <= 30.) x[2] += 1;
            if(fr1[j] > 30. && fr1[j] <= 40.) x[3] += 1;
            if(fr1[j] > 40. && fr1[j] <= 50.) x[4] += 1;
            if(fr1[j] > 50. && fr1[j] <= 60.) x[5] += 1;
            if(fr1[j] > 60. && fr1[j] <= 70.) x[6] += 1;
            if(fr1[j] > 70. && fr1[j] <= 80.) x[7] += 1;
            if(fr1[j] > 80. && fr1[j] <= 90.) x[8] += 1;
            if(fr1[j] > 90. && fr1[j] < 100.) x[9] += 1;
        }//j
    }//i
    for(i=0;i<10;i++)cout<<x[i]<<endl;
    return(0);
}//main()
 
About random number generators:

This is using a "compute shader" in Unity - that involves doing regular computing on a GPU that can have 1000+ cores.

C:
float random (float2 pt, float seed) {
    const float a = 12.9898;
    const float b = 78.233;
    const float c = 43758.543123;
    return frac(sin(dot(pt, float2(a, b)) + seed) * c );
}

float2's are a kind of vector with an x and a y. "frac" returns the fractional/decimal part of a float. "dot" is a vector dot product. The consts are meant to not have any common factors.
 
"To stimulate Swami's problem I'd need a random sequence of numbers 1-100 without duplicated numbers."
This is just the shuffling problem we looked at earlier.

There are many excellent PRNGs, notably the "Mersenne Twister" and Marsaglia's "KISS". (Each of these has public-domain source code.) Berkeley's random() from the early 1980's is excellent (especially if you take advantage of its huge seeding capability), as are -- one would hope -- the PRNG's provided in any 21st=century rand() library.

All the generators I've looked at work with integers, so excreationist's floating point generator is interesting. I suppose such a generator might feature speed; but not if it calls sin().

If you're ever stuck on a desert island with no PRNG in your library, the simple Fibonacci series (1, 1, 2,, 3, 5, 8, 13, etc.) works well enough for many purposes! Presumably you'll run it automatically modulo 232. Do DISCARD the (at least) 5 lowest-order bits. Skip the first 50 terms or so to avoid the stretch of small numbers at the beginning.
 
Yes.

And the puzzle you posted is just a very simple problem in statiscal sampling with and without replacement.

I am doodling to stay active, and somebody lurking reading the code may get an idea from it. I am surprised when somebody actually reads code I post.

Setting up statistical models for systems I designed to assess statistical variations and impacts was routine.
 
All the generators I've looked at work with integers, so excreationist's floating point generator is interesting. I suppose such a generator might feature speed; but not if it calls sin().
In the example it was calling random() and sin() millions of times per frame (3 color channels per pixel) and still got good framerates.... (since GPUs can have thousands of cores). Apparently some GPUs can do sin() in a single clock cycle:
 
Last edited:
All the generators I've looked at work with integers, so excreationist's floating point generator is interesting. I suppose such a generator might feature speed; but not if it calls sin().
In the example it was calling random() and sin() millions of times per frame (3 color channels per pixel) and still got good framerates.... (since GPUs can have thousands of cores). Apparently some GPUs can do sin() in a single clock cycle:

Thanks for the correction. I had a premonition I was making a fool of myself when I wrote what I did. Computers are somewhat faster than when I first programmed them 58 years ago.

BTW, what portion of humanity's total computation budget is spent mining bitcoins?
 
All the generators I've looked at work with integers, so excreationist's floating point generator is interesting. I suppose such a generator might feature speed; but not if it calls sin().
In the example it was calling random() and sin() millions of times per frame (3 color channels per pixel) and still got good framerates.... (since GPUs can have thousands of cores). Apparently some GPUs can do sin() in a single clock cycle:
If they can sin that fast they're certainly going to hell.
 
Back
Top Bottom