User:Markuman

From Octave
Revision as of 09:27, 22 June 2014 by Markuman (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

random[edit]

how to get equal matlab random numbers in octave - using twister(!) algorithm?

initial situation[edit]

  • ruby and python using twister algo as default
  • force twister algo in matlab and octave
octave[edit]
   octave:1> rand('twister',0)
   octave:2> rand
   ans =    0.844421851525048
python[edit]
   >>> import random
   >>> random.seed(0)
   >>> random.random()
   0.8444218515250481
numpy[edit]
   >>> import numpy
   >>> numpy.random.seed(0)
   >>> numpy.random.random()
   0.5488135039273248
ruby[edit]
   irb(main):001:0> prng = Random.new(0)
   => #<Random:0x00000001d469e8>
   irb(main):002:0> prng.rand()
   => 0.5488135039273248
matlab[edit]
   >> rand('twister',0)
   >> rand
    
   ans =
        
       0.548813503927325


how to get the right seed states in octave?[edit]

   rand('twister',0)
   states=rand('state'); 

seems to be the wrong ones. but they fit to them in python! ;)


   function ret = twister_seed(SEED=0)
   
       ret = uint32(zeros(625,1));
       ret(1) = SEED;
       for N = 1:623
           ## initialize_generator
           # bit-xor (right shift by 30 bits)
           uint64(1812433253)*uint64(bitxor(ret(N),bitshift(ret(N),-30)))+N; # has to be uint64, otherwise in 4th iteration hit maximum of uint32!
           ret(N+1) = uint32(bitand(ans,uint64(intmax('uint32')))); # untempered numbers
       endfor
       ret(end) = 1;   
    
   endfunction


   octave:1> rand('twister',twister_seed) # notice: default seed is 0 in the function
   octave:2> rand
   ans =    0.548813503927325
   octave:3> rand
   ans =    0.715189366372419
   octave:4> rand
   ans =    0.602763376071644

compare to matlab...

   >> rand('twister',0)
   >> rand
   
   ans =
   
      0.548813503927325
   
   >> rand
   
   ans =
   
      0.715189366372419
   
   >> rand
   
   ans =
   
      0.602763376071644

Default Matlab seed is rand('twister',twister_seed(5489))


TODO[edit]

compiling .mex files written by octave for matlab[edit]

Example file

   #include "mex.h"
   
   void
   mexFunction (int nlhs, mxArray *plhs[],
                int nrhs, const mxArray *prhs[])
   {
     mexPrintf ("Hello, World!\n");
   
     mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);
   }

Note: Octave need the file extension .mex. Matlab needs on Linux .mexa64 and on Windows .mexw64 etc.

using gcc or tcc on the same plattform[edit]

Using tcc or gcc

   tcc -I/usr/include/octave-3.8.1/octave/ -lm -shared mexample.c -o mexample.mex
   gcc -I/usr/include/octave-3.8.1/octave/ -lm -shared -fPIC mexample.c -o mexample.mex
   cp mexample.mex mexample.mexa64

This function can now be used on Linux x64 plattform from both, octave and matlab.

  • TODO: crosscompiling