Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider deffold macro capable of generating fast loop/recur versions? #19

Open
sritchie opened this issue Jan 14, 2022 · 0 comments
Open

Comments

@sritchie
Copy link
Member

For example, here is a version of sicmutils.algebra.fold/kbk-n that generates summation functions that are 3-4x faster than using the fold. We COULD generate both...

(defn- klein-term
  "Takes symbolic variables for

  - `acc`, the accumulating term we're compensating for
  - `delta`, the shared symbol used for deltas

  and generates let-binding entries updating `acc` to `(+ acc delta)` and
  `delta` to the new compensation amount in `(+ acc delta)`."
  [acc delta]
  `[sum# (+ ~acc ~delta)
    ~delta (if (ud/fork
                :clj (>= (Math/abs ~acc)
                         (Math/abs ~delta))
                :cljs (>= (.abs js/Math ~acc)
                          (.abs js/Math ~delta)))
             (+ (- ~acc sum#) ~delta)
             (+ (- ~delta sum#) ~acc))
    ~acc sum#])

(defmacro ^:no-doc kbk-n-sum
  "Given some order `n`, generates a function implementing fast `n`-th order
  Kahan-Babushka-Klein summation.

  See [[kbk-n]] for more detail."
  [n]
  (let [syms   (into [] (repeatedly (inc n) gensym))
        zeros  (map (fn [i] `(~'double ~i)) (repeat 0.0))
        prefix (pop syms)
        final  (peek syms)
        delta  (gensym)]
    `(fn [xs#]
       (loop [i# (long 0)
              ~@(interleave syms zeros)]
         (let [~(with-meta delta {:tag 'double}) (nth xs# i# nil)]
           (if (not ~delta)
             (+ ~@syms)
             (let [~@(mapcat #(klein-term % delta)
                             prefix)]
               (recur (inc i#) ~@prefix (+ ~final ~delta)))))))))
@sritchie sritchie transferred this issue from sicmutils/sicmutils Jan 24, 2023
@sritchie sritchie transferred this issue from another repository Jan 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant