Skip to content

Instantly share code, notes, and snippets.

@going-digital
Last active June 2, 2021 11:55
Show Gist options
  • Save going-digital/1215a1f4ef4035b8086c81407c050af4 to your computer and use it in GitHub Desktop.
Save going-digital/1215a1f4ef4035b8086c81407c050af4 to your computer and use it in GitHub Desktop.
log2(x) in WebAssembly
;; Calculate log2(x) = ln(x)/ln(2) natively in WebAssembly.
;; Compiles to 75 bytes of WebAssembly code
(module
(export "log2" (func $log2))
(func $log2 (param $x f32) (result f32)
(local $x2 f32)
(f32.add
;; Extract exponent of $x
(f32.convert_s/i32
(i32.sub
(i32.shr_u
(i32.reinterpret/f32
(get_local $x)
)
(i32.const 23)
)
(i32.const 127)
)
)
(f32.mul
(f32.mul
(f32.add
(f32.mul
(f32.add
(f32.mul
;; Calculate ((x-1) / (x+1))^2
(tee_local $x2
(f32.mul
(tee_local $x
;; Calculate (x-1) / (x+1), remembering that mantissa has 1 subtracted already
(f32.div
(tee_local $x
(f32.mul
;; Extract mantissa of $x
(f32.convert_u/i32
(i32.and
(i32.reinterpret/f32
(get_local $x)
)
(i32.const 0x7FFFFF)
)
)
(f32.const 1.1920928955078125e-07) ;; = 1 / 0x800000
)
)
(f32.add
(get_local $x)
(f32.convert_u/i32 (i32.const 2))
)
)
)
(get_local $x)
)
)
(f32.const 0.2) ;; 3rd term
)
(f32.const 0.3333333333333333) ;; 2nd term
)
(get_local $x2)
)
(f32.convert_u/i32 (i32.const 1)) ;; 1st term
)
(f32.const 2.885390043258667) ;; 2/ln(2)
)
(get_local $x)
)
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment