Questions on the SI language - page 11

 
TheXpert:

pointer to a piece of data of size 4 or 8 bytes.

The size depends on the platform because of the alignment. If you use something like pragma pack 1, the size will be the same (1 byte probably)

I also sometimes look in VS C++, compile in asm listing mode and then look at it, a lot becomes clear. Yes, it sounds scary, but asm is the absolute truth in the last resort. And the language isn't difficult to understand. It's hard to write it correctly))

 
Это рекурсия просто. Быстрая сортировка как раз таки и применяет рекурсивный вызов функции. О принципах, преимуществах и недостатках ее использования можете почитать в интернете. И да, это применительно к любому ЯП. В кратце скажу, что главное требование рекурсии - это то, что бы последующий вызов рекурсии приближал алгоритм к завершению. Ну и главный недостаток это требование к оперативной памяти при большое обработке данных, так как каждый вызов такой рекурсии будет блокировать память.... Простой пример с рекурсией на том же си и нахождению факториала в 2 вариациях. 
1) Рекурсия внутри 1 функции:

long long Factorial(int n){
        if(n == 1) return 1;
        return n * Factorial(n-1); // Здесь выполнил требование приближение рекурсии к завершению(то есть n стремится к 1(где исполнится условие выше))
}

2) Рекурсия между несколькими функциями:

int Fun2(int); // Прототип.
int Fun1(int i){
        if(i == -5){return i;}
        return i + Fun2(i-1);
}

int Fun2(int i){
        if(i == -5){return i;}
        return i + Fun1(i-1);
}
 
Gleb Krel:

Yes, thank you... as they say, I knew but forgot as I'm not a programmer and rarely do it :)

 

I want to port this source code to MQL, but I'm not sure if I can handle std::deque.

#include <deque>

class net
{   std::deque<float*> w;    // весовые коэффициенты (== это образцам)
    const unsigned     n;    // количество входов сети
    
    float activation(float v) const
    {   return v>n?n:v<0?0:v;
    }
public:
    net(unsigned numInputs):n(numInputs){}
    ~net(void)
    {   for(unsigned i(0); i<w.size();) delete [] w[i++];
    }
    unsigned learnImage(const float* const image)
    {   w.push_back( (float*)memcpy( new float[n],image, sizeof(float)*n) );
        return w.size();
    }
    unsigned recognizeImage(const float* const image) const
    {   float*  axons( (float*)memset(new float[w.size()],0,sizeof(float)*w.size()) );
        float   sum1(.0), sum2(.0), e(0.95 f/w.size());
        unsigned i,j;

        for(i=0; i < w.size(); ++i)    // цикл инициализации сети
        {   for(j=0; j < n; ++j)
                axons[i] += image[j]*w[i][j];
            sum1 += axons[i] = activation(0.5 f*(axons[i]+float(n) ) );
        }
                
        while( sum2 != sum1 )        // цикл пока выходы сети изменяются
        {   sum1 = 0.0 f * ( sum2 = sum1 );
            for(i=0; i < w.size(); ++i)
                sum1 += axons[i] = activation( axons[i]-e*(sum2-axons[i]) );
        }
        for(i=w.size(); i!=-1 u && !axons[i--];);    // поиск активного аксона сети 
        delete [] axons;
        return i;
    }


};



int _tmain(int argc, _TCHAR* argv[])
{  // входы можно сделать и целочисленными, роли играть не будет
    float a1[4][15] = {{1.,1.,1.,  1.,-1.,-1.,  1.,-1.,-1.,  1.,-1.,-1.,  1.,1.,1.},// символ С
                        {1.,1.,1.,  1.,-1.,-1.,  1.,1.,-1.,   1.,-1.,-1.,  1.,1.,1.}, // Символ E
                        {1.,1.,1.,  1.,-1.,1.,   1.,-1.,1.,   1.,-1.,1.,   1.,1.,1.}, // Символ О
                        {1.,1.,1.,  1.,-1.,1.,   1.,-1.,1.,   1.,-1.,1.,   1.,1.,1.}  // искаженный
                      };

    net n(15);
    n.learnImage( a1[0] );
    n.learnImage( a1[1] );    
    n.learnImage( a1[2] );
    return n.recognizeImage( a1[3] );
}


taken from here:https://habr.com/ru/sandbox/43916/

SZZY: googled and did not find any other Hamming source code, links to other sources are welcome (not the Hopfield network!!! - google always gives them together)

 
Igor Makanu:

I want to port this source code to MQL, but I'm not sure if I can handle std::deque.

it's a bidirectional list. the above code only has push_back so chances are you can replace it with a vector.

if not, you can make a simple implementation of deque via array with a reserve from the beginning and end. in STL it is somehow implemented that way.

 
Andrei Trukhanovich:

this is a bidirectional list. in the above code there is only push_back so there is a chance that it can be replaced by a vector.

If not, you can make a simple implementation of deque through array with start and end redundancy.

I googled std::deque and it is as you write, but... I don't know how to use it, and just replace it with a vector... In general, the example is a tutorial, I would not want to mess up and be sure it's the way it's supposed to work wrong ))))

ZS: There's also an example in F# - but I think it's too much ;)

 
Igor Makanu:

I want to port this source code to MQL, but I'm not sure if I can handle std::Alert( n.recognizeImage( a1_3 ) );

taken from here:https://habr.com/ru/sandbox/43916/

HZZ: googled, that I did not find on the fly other Hamming network sources, links to other sources are also welcome (it is not net Hopfield!!! - google always gives them together)

Igor, I do not think it is reasonable to write a deque, a vector will suffice in the vast majority of cases. I rewrote your example using a vector from the thread about stl:

#include <myincl/1_mystd.mqh>

template <typename T>
void fill_vector_from_array(vector_fund<T> &dest, const T &src[]) {
   dest.clear();
   for (int i = 0;  i < ArraySize(src);  ++ i)
      dest.push_back(src[i]);
}
template <typename T>
void fill_vector(vector_fund<T> &dest, T val) {
   for (uint i = 0;  i < dest.size();  ++ i)
      dest.a[i] = val;
}

class net
{   vector_ref<vector_fund<float>> w;    // весовые коэффициенты (== это образцам)
    const uint n;                        // количество входов сети
    
    float activation(float v) const {
        return v>n?n:v<0?0:v;
    }
public:
    net(unsigned numInputs):n(numInputs){}
    unsigned learnImage(const float &image[]) {
        vector_fund<float> tmp;
        fill_vector_from_array(tmp, image);
        w.push_back(tmp);
        return w.size();
    }
    unsigned recognizeImage(const float &image[]) const {   
        vector_fund<float> axons(this.w.size());
        fill_vector<float>(axons, 0);
    
        float   sum1=.0, sum2=.0, e=0.95 f/w.size();
        unsigned i,j;
        vector_fund<float> image_vec;
        fill_vector_from_array(image_vec, image);
        
        for(i=0; i < w.size(); ++i) {   // цикл инициализации сети
            for(j=0; j < n; ++j)
                axons.a[i] += image_vec.a[j]*w.a[i].a[j];
            sum1 += axons.a[i] = activation(0.5 f*(axons.a[i]+float(n) ) );
        }
                
        while( sum2 != sum1 ) {       // цикл пока выходы сети изменяются
            sum1 = 0.0 f * ( sum2 = sum1 );
            for(i=0; i < w.size(); ++i)
                sum1 += axons.a[i] = activation( axons.a[i]-e*(sum2-axons.a[i]) );
        }
        for(i=w.size()-1; i!=(uint)-1 && !axons.a[i--];);    // поиск активного аксона сети 
        return i;
    }


};

unsigned fn() {
   // создал несколько массивов, отказывается мкл передавать многомерные массивы.
   float a1_0[15] = {1.,1.,1.,  1.,-1.,-1.,  1.,-1.,-1.,  1.,-1.,-1.,  1.,1.,1.}; // символ С
   float a1_1[15] = {1.,1.,1.,  1.,-1.,-1.,  1.,1.,-1.,   1.,-1.,-1.,  1.,1.,1.}; // Символ E
   float a1_2[15] = {1.,1.,1.,  1.,-1.,1.,   1.,-1.,1.,   1.,-1.,1.,   1.,1.,1.}; // Символ О
   float a1_3[15] = {1.,1.,1.,  1.,-1.,1.,   1.,-1.,1.,   1.,-1.,1.,   1.,1.,1.}; // искаженный

    net n(15);
    n.learnImage( a1_0 );
    n.learnImage( a1_1 );    
    n.learnImage( a1_2 );

    return n.recognizeImage( a1_3 );
}

void OnStart()
{
   Alert( fn() );
}

I don't want to screw up and be sure it should work improperly ))))

To check this, I've tested the source code and µl code

    Alert( n.recognizeImage( a1_0 ) );
    Alert( n.recognizeImage( a1_1 ) );
    Alert( n.recognizeImage( a1_2 ) );
    Alert( n.recognizeImage( a1_3 ) );

in both cases got: 1 1 0 4294967295

HH: by the way, there seemed to be a mistake in the source - going outside the array boundaries (the comrade forgot to add -1)

for(i=w.size()-1; i!=-1 u && !axons[i--];);    // поиск активного аксона сети 
 
Vict:

Igor, I don't think it's reasonable to write a deque, a vector is enough in the vast majority of cases. I rewrote your example using vector from the thread about stl:

To check it, I've run on pluses source and µl code like

in both cases got: 1 1 0 4294967295

HH: by the way, in the source code seemed to be an error - overrun array (comrade forgot to add -1)

О! That was so fast! Thanks HUMAN!!!

Reason: