fork download
  1. class Matrix < Array
  2. def initialize(ary)
  3. @d = (ary.size ** 0.5).to_i
  4. super ary
  5. end
  6.  
  7. def +(other)
  8. Matrix.new map.with_index { |m, i| m + other[i] }
  9. end
  10.  
  11. def *(other)
  12. Matrix.new size.times.map { |i|
  13. @d.times.map { |j| self[i / @d * @d + j] * other[i % @d + @d * j] }.reduce :+
  14. }
  15. end
  16.  
  17. def /(scalar)
  18. Matrix.new map { |m| m / scalar }
  19. end
  20.  
  21. def identity
  22. Matrix.new ([1] + [0] * @d) * (@d - 1) + [1]
  23. end
  24.  
  25. def exponential
  26. series = (2..size * 2).map { |i| ([self] * i).reduce(:*) / (1..i).reduce(:*) }
  27. [self, series.reduce(:+), identity].reduce :+
  28. end
  29. end
  30.  
  31. test = Matrix.new [
  32. 0.0, -1.0, 3.0, 0.5,
  33. 1.0, 0.0, 0.45, 0.1,
  34. -3.0, -0.45, 0.0, 0.4,
  35. -0.5, -0.1, -0.4, 0.0
  36. ]
  37.  
  38. test.exponential.each_slice(4) { |row| p row.map { |e| e.round 7 } }
  39.  
Success #stdin #stdout 0.05s 4892KB
stdin
Standard input is empty
stdout
[-0.9276446, -0.2437849, -0.2285533, 0.1667568]
[-0.2809791, 0.7661246, 0.5148905, 0.2626626]
[-0.0150871, 0.5946104, -0.7613132, -0.2580951]
[0.2455577, -0.0077772, -0.3210194, 0.9146516]