I think your style is okay, and the algorithm seems nice and short. Int error_t = eliminate_column(matrix, row, size) Int pivot = select_pivot_column(matrix, row, size) For example, I would write the following snippet before thinking of how I'd implement the pieces: error_t triangularize(double * matrix, int size) In fact, I highly recommend the reversed process. You must understand what that purpose is, give it a name and make it into a function. Return solve_triangular_form(matrix, size, solution) That is better to be reflected in the code: int gauss(double * matrix, int size, double * solution) Gauss is logically divided into 2 algorithms: first, calculate the upper triangular form of a matrix, second, solve the triangular form. Identifying functions not just increase readability, but makes the code reusable and unit-testable. You need to test matrix(i, i) and (matrix(i, x) - counter) at line 38 at each iteration.ĭon't be shy of functions. Later on, while calculating solutions a division by 0 still may occur. The solvability is decided by looking at just one (or two) values. To summarize, a correct implementation must have pivot selection. Same will happen when dividing a pretty large number by a pretty small one.Įven if such division doesn't yield Inf, dividing large by small amplifies errors. Note that a mere presence of 0 at the main diagonal doesn't mean that the system is unsolvable.Īlong the same line, division by 0 is not the only way to end up with Inf. The elimination loop blindly divides by matrix((x - 1), (x - 1)) which very well could be 0. Is there anything I can do to make this code better? Sol = (matrix(i, x) - counter) / matrix(i, i) Matrix(j, k) -= matrix(i, k) * matrix(j, i) / matrix(i, i) Int gauss(double *matrix, int x, double *sol) ĭouble *mat = malloc((x + 1) * x * sizeof(double)), *sol = (malloc(x * sizeof(double))) ![]() ![]() I used indent -kr -i8 -l1000 -lc1000 for styling and I used preprocessor for simplifying the matrix math but some pieces make no sense as as matrix(x, -2): #include ![]() I used linear matrix because I simply don't know how to declare multidimensional array with malloc and I don't know how to pass it as a parameter to function. I was wondering what I can do to make the code shorter (keeping the good style), with better performance and with better memory consumption. Sol= matrix/matrix įor(int j=x-1 j>i j-) counter+= matrix *sol Int gauss(double* matrix, int x, double* sol) ĭouble *mat = malloc((x+1)*x*sizeof(double)), *sol =(malloc(x*sizeof(double))) a pointer to the matrix of coefficients.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |