matrix.alc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. include "primitives.alh"
  2. include "random.alh"
  3. Float function v2f(i : Element):
  4. return cast_s2f(cast_v2s(i))!
  5. Element function create_random_matrix(n : Integer):
  6. Element m
  7. Integer i
  8. Integer j
  9. Element t
  10. // Construct the matrix first, with as many rows as there are variables
  11. // Number of columns is 1 higher
  12. i = 0
  13. m = create_node()
  14. while (i < n):
  15. j = 0
  16. t = create_node()
  17. while (j < (n + 1)):
  18. list_append(t, random())
  19. j = j + 1
  20. list_append(m, t)
  21. i = i + 1
  22. return m!
  23. Void function eliminateGaussJordan(m : Element):
  24. Integer i
  25. Integer j
  26. Integer f
  27. Integer g
  28. Boolean searching
  29. Element t
  30. Float divisor
  31. i = 0
  32. j = 0
  33. while (i < read_nr_out(m)):
  34. // Make sure pivot m[i][j] != 0, swapping if necessary
  35. while (v2f(m[i][j]) == 0.0):
  36. // Is zero, so find row which is not zero
  37. f = i + 1
  38. searching = True
  39. while (searching):
  40. if (f >= read_nr_out(m)):
  41. // No longer any rows left, so just increase column counter
  42. searching = False
  43. j = j + 1
  44. else:
  45. if (v2f(m[f][j]) == 0.0):
  46. // Also zero, so continue
  47. f = f + 1
  48. else:
  49. // Found non-zero, so swap row
  50. t = v2f(m[f])
  51. dict_overwrite(m, f, v2f(m[i]))
  52. dict_overwrite(m, i, t)
  53. searching = False
  54. // If we have increased j, we will just start the loop again (possibly), as m[i][j] might be zero again
  55. // Pivot in m[i][j] guaranteed to not be 0
  56. // Now divide complete row by value of m[i][j] to make it equal 1
  57. f = j
  58. divisor = v2f(m[i][j])
  59. while (f < read_nr_out(m[i])):
  60. dict_overwrite(m[i], f, float_division(v2f(m[i][f]), divisor))
  61. f = f + 1
  62. // Eliminate all rows in the j-th column, except the i-th row
  63. f = 0
  64. while (f < read_nr_out(m)):
  65. if (bool_not(f == i)):
  66. g = j
  67. divisor = v2f(m[f][j])
  68. while (g < read_nr_out(m[f])):
  69. dict_overwrite(m[f], g, v2f(m[f][g]) - (divisor * v2f(m[i][g])))
  70. g = g + 1
  71. f = f + 1
  72. // Increase row and column
  73. i = i + 1
  74. j = j + 1
  75. return !