Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Clojureで多次元配列

 Clojureで多次元配列

ClojureでJavaの配列を利用して数値計算を扱う。

ichisemasashi

December 23, 2020
Tweet

Other Decks in Programming

Transcript

  1. ClojureͰJavaͷ഑ྻΛར༻͢Δ ഑ྻͷཁૉʹσʔλΛઃఆ user=> (aset ^ints my-array 0 0 (int 100))

    100 user=> (aget ^ints my-array 0 0) 100 user=> (pprint my-array) [[100, 0], [0, 0]] nil
  2. ࣮૷ྫɿΨ΢ε-βΠσϧ๏ʹΑΔ࿈ཱ1࣍ํఔࣜͷղ๏ Ψ΢ε-βΠσϧ๏ͷ֓ཁ 5x + y + z = 10 x

    + 4y + z = 12 2x + y + 3z = 13 } x = (10 − y − z)/5 y = (12 − x − z)/4 z = (13 − 2x − y)/3 }
  3. ࣮૷ྫɿΨ΢ε-βΠσϧ๏ʹΑΔ࿈ཱ1࣍ํఔࣜͷղ๏ Ψ΢ε-βΠσϧ๏ͷ֓ཁ 5x + y + z = 10 x

    + 4y + z = 12 2x + y + 3z = 13 } x = (10 − y − z)/5 y = (12 − x − z)/4 z = (13 − 2x − y)/3 } x y z ॳظ஋ 1 1 1 1८໨ 1.600 2.350 2.483 2८໨ 1.033 2.121 2.938 3८໨ 0.988 2.019 3.002 4८໨ 0.996 2.001 3.002 5८໨ 0.999 1.999 3.001
  4. ࣮૷ྫɿΨ΢ε-βΠσϧ๏ʹΑΔ࿈ཱ1࣍ํఔࣜͷղ๏ Ψ΢ε-βΠσϧ๏ͷ࣮૷ (def an-eq (make-array Double/TYPE 3 4)) (def N

    (alength an-eq)) (defn set-eq [arr n x y z w] (aset ^doubles arr n 0 (double x)) (aset ^doubles arr n 1 (double y)) (aset ^doubles arr n 2 (double z)) (aset ^doubles arr n 3 (double w))) (set-eq an-eq 0 5 1 1 10) (set-eq an-eq 1 1 4 1 12) (set-eq an-eq 2 2 1 3 13) (pprint an-eq)
  5. ࣮૷ྫɿΨ΢ε-βΠσϧ๏ʹΑΔ࿈ཱ1࣍ํఔࣜͷղ๏ Ψ΢ε-βΠσϧ๏ͷ࣮૷(ଓ) (def res-arr (make-array Double/TYPE 3)) (dotimes [i N]

    (aset ^doubles res-arr i (double 1))) (pprint res-arr) (def tmp-arr (make-array Double/TYPE 3)) (pprint tmp-arr) (defn eq-elm [x y] (aget ^doubles an-eq x y)) (defn res-elm [x] (aget ^doubles res-arr x)) (defn tmp-elm [x] (aget ^doubles tmp-arr x))
  6. ࣮૷ྫɿΨ΢ε-βΠσϧ๏ʹΑΔ࿈ཱ1࣍ํఔࣜͷղ๏ Ψ΢ε-βΠσϧ๏ͷ࣮૷(ଓ) (def MAX_LOOP 30) (def EPS (double 0.0001)) (def

    q (atom (double 1.0))) (def ll (atom 0)) (defn display-result [] (dotimes [i N] (let [res (res-elm i)] (println (format "x%d = %9.6f" i res)))))
  7. ࣮૷ྫɿΨ΢ε-βΠσϧ๏ʹΑΔ࿈ཱ1࣍ํఔࣜͷղ๏ Ψ΢ε-βΠσϧ๏ͷ࣮૷(ଓ) (defn computing [] (let [s (atom (double 0.0))]

    (dotimes [i N] (reset! s (double 0.0)) (dotimes [j N] (if (not= i j) (reset! s (+ @s (* (eq-elm i j) (res-elm j)))))) (aset ^doubles tmp-arr i (/ (- (eq-elm i N) @s) (eq-elm i i))) (reset! q (+ @q (Math/abs (- (res-elm i) (tmp-elm i))))) (aset ^double res-arr i (tmp-elm i)))))
  8. ࣮૷ྫɿΨ΢ε-βΠσϧ๏ʹΑΔ࿈ཱ1࣍ํఔࣜͷղ๏ Ψ΢ε-βΠσϧ๏ͷ࣮૷(ଓ) (while (and (< EPS @q) (>= MAX_LOOP @ll))

    (do (swap! ll inc) (reset! q (double 0.0)) (computing))) (if (>= @ll MAX_LOOP) (println "ऩଋͤͣɻ") (display-result))