matrix.alc 2.1 KB

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