typestar

Float math in WebAssembly

f64 instructions, plus the explicit crossing from integers.

(module
  ;; f64 carries the usual float instructions; convert_i32_s crosses
  ;; over from the integer world.
  (func (export "hypotenuse") (param $a f64) (param $b f64) (result f64)
    (f64.sqrt
      (f64.add
        (f64.mul (local.get $a) (local.get $a))
        (f64.mul (local.get $b) (local.get $b)))))

  (func (export "mean_of_counts") (param $sum i32) (param $n i32)
        (result f64)
    (f64.div
      (f64.convert_i32_s (local.get $sum))
      (f64.convert_i32_s (local.get $n))))

  (func (export "clamp01") (param $x f64) (result f64)
    (f64.min (f64.max (local.get $x) (f64.const 0)) (f64.const 1))))

How it works

  1. f64.sqrt and friends work the stack like the integer ops.
  2. f64.convert_i32_s is the only way an i32 becomes an f64.
  3. f64.min and f64.max nest into a one-expression clamp.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
559
Tokens
132
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 132 seconds.

Type this snippet

Step 3 of 3 in Numbers, step 6 of 28 in Language basics.

← Previous Next →