Wednesday 14 December 2011

c program of Least Square method for curve fitting.


Implementation of Least-square method for curve fitting.

#include<stdio.h>
#include<conio.h>
#include<math.h>
 main()
{
  float x[10],y[10],a[10][10];
  int i,j,k,n,itr;
  printf("\n ENTER THE SIZE OF MATRIX n:");
  scanf("%d",&n);
  printf("\n ENTER MATRIX ELEMENTS AND RHS:\n");
  for(i=1;i<=n;i++)
  {
    for(j=1;j<=n+1;j++)
    scanf("%f",&a[i][j]);
  }
  for(i=1;i<=n;i++)
  {
    x[i]=0.0;
    y[j]=0.0;
  }
  itr=0.0;
  top:
  itr=itr+1;
  for(i=1;i<=n;i++)
  {
    x[i]=a[i][n+1];
    for(j=1;j<=n;j++)
    {
      if(i==j)
      continue;
     else
     x[i]=x[i]-a[i][j]*x[j];
    }
    x[i]=x[i]/a[i][j];
  }
  for(k=1;k<=n;k++)
  if(fabs(x[k]-y[k])>0.0001)
  {
    printf("\n ITERATION=%d}",itr);
    for(i=1;i<=n;i++)
    {
      y[i]=x[i];
      printf("\n x(%d)=%f",i,x[i]);
    }
    goto top;
    }
    else
    continue;
    return;

    }

3 comments:

  1. how can i plot y=mx+c best fit curve in c programming???

    ReplyDelete
  2. I guess you are not a Computer Science major. You have three major problems with your code:

    1. Boundary Checking
    Your arrays only have ten entries in each array. However, if I enter the number of items as 10, your program will abort when j=10. This is because your indices can only be in the range 0 to 9.

    You are also wasting an entry because you are not using any of the elements indexed by zero (i.e. x[0], y[0], a[0][0..9] & a[0..9][0].

    Also, you are not checking the user's input to ensure that they have not exceeded the array items.

    2. Variable itr is declared as an integer, yet you initialize it to a floating pointing value. Setting itr = 0.0 is a type violation.

    3. "goto top;" REALLY? The goto command is to be used under very specific circumstances; This program does NOT qualify. An unchecked goto often results in a stack overflow or an endless loop. Either will cause a program abort.

    ReplyDelete