/* L-17 MCS 572 Fri 30 Sep 2016 : triangularsolve.c */

/* The program generates a random lower triangular system so that
 * the solution is a vector of all ones.  Interestingly, once the
 * dimension gets larger than 800, roundoff error has accumulated
 * so much that we have lost all significant digits. */

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void random_triangular_system
 ( int n, double **L, double *b );
/*
 * Generates an n-dimensional lower triangular
 * system L y = b with random numbers in [0,1],
 * so all components of the solution y
 * are equal to 1. */

void solve_triangular_system
 ( int n, double **L, double *b, double *y );
/*
 * Solves the system L*y = b. */

int main ( int argc, char *argv[] )
{
   int n,v;
   if(argc > 1)
   {
      n = atoi(argv[1]); v = 0;
   }
   else
   {
      printf("Give the dimension : "); scanf("%d",&n);
      v = 1;
   }
   {
      double b[n],y[n];
      int i,j;

      double **L;
      L = (double**) calloc(n,sizeof(double*));
      for(i=0; i<n; i++)
         L[i] = (double*) calloc(n,sizeof(double));

      srand(time(NULL));
      random_triangular_system(n,L,b);
      solve_triangular_system(n,L,b,y);

      if(v > 0)
      {
         for(i=0; i<n; i++) printf("  %.1e",y[i]);
         printf("\n");
      }
      else
         printf("last number : %.16e\n",y[n-1]);
   }

   return 0;
}

void random_triangular_system
 ( int n, double **L, double *b )
{
   int i,j;
   for(i=0; i<n; i++)
   {
      L[i][i] = 1.0;
      for(j=0; j<i; j++)
         L[i][j] = ((double) rand())/RAND_MAX;
      for(j=i+1; j<n; j++)
         L[i][j] = 0.0;
   }
   for(i=0; i<n; i++)
   {
      b[i] = 0.0;
      for(j=0; j<n; j++)
         b[i] = b[i] + L[i][j];
   }
}

void solve_triangular_system
 ( int n, double **L, double *b, double *y )
{
   int i,j;

   for(i=0; i<n; i++)
   {
      y[i] = b[i];
      for(j=0; j<i; j++)
         y[i] = y[i] - L[i][j]*y[j];
   }
}
