pnsrp's blog

By pnsrp, 12 years ago, In English

hi anybody can help me, in the second iteration, i'm getting this value, -2.77556e-17 instead of zero, sorry for disturbing you guys, i'm really lost. Pls help me. My code is like this. I'm coding an neutron which learns and  gate.
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
    int i, j;
    double dataIn[4][3];
    freopen( "input.txt", "r", stdin);
    for( i=0; i<4; i++ ){
        for( j=0; j<3; j++ ){
            cin >> dataIn[i][j];
        }
    }
    double weight[2] = { 0.3, -0.1 };
    double error[4];
    double threshold = 0.2;
    int output;
    double alpha = 0.1;
    int epoch = 0;
    int t = 2; //debugging: trying running just two iterations
    while(t--){
        for( i=0; i<4; i++ ){
            double sum = (dataIn[i][0] * weight[0]) + (dataIn[i][1] * weight[1]) - threshold;
            cout << dataIn[i][0] * weight[0] << " " << dataIn[i][1] * weight[1] << " " << threshold << endl;
            cout << sum << endl;
            sum >= 0 ? output = 1 : output = 0;
            cout << output << endl;
            if( output != dataIn[i][2] ){
                error[i] = dataIn[i][2] - output;
                weight[0] = weight[0] + (alpha*error[i]*dataIn[i][0]);
                weight[1] = weight[1] + (alpha*error[i]*dataIn[i][1]);
            }
            else error[i] = 0;
        //    cout << weight[0] << " " << weight[1] << endl;

        }
        cout << endl;
        epoch++;
        if( error[0] == 0 && error[1] == 0 && error[2] == 0 && error[3] == 0 ) break;
        else continue;
    }
    cout << epoch << endl;
    return 0;
}

  • Vote: I like it
  • +8
  • Vote: I do not like it

| Write comment?
12 years ago, # |
  Vote: I like it 0 Vote: I do not like it
Do not compare float numbers with "==", use next construction:
const double eps = 1e-9;
double num1, num2;
if ( fabs( num1 - num2) < eps) // do smth
else // do smth