Estimate Pi

Example 1


(module
  (import "js" "rand" (func $rand (result f32)))
  (func $calcPi (export "calcPi") (param $count f32) (result f32)
    (local $x f32)
    (local $y f32)
    (local $inside f32)
    (local $i f32)
    (set_local $inside (f32.const 0))
    (set_local $i (f32.const 0))

    (block $b0
      (loop $l0
        
        (set_local $x (f32.sub (f32.mul (call $rand) (f32.const 2)) (f32.const 1)))
        (set_local $y (f32.sub (f32.mul (call $rand) (f32.const 2)) (f32.const 1)))

        (f32.add (f32.mul (get_local $x) (get_local $x)) (f32.mul (get_local $y) (get_local $y)))
        (f32.const 1)
        f32.lt
        if $i0
          (set_local $inside (f32.add (f32.const 1) (get_local $inside)))
        end

        (set_local $i  (f32.add (f32.const 1) (get_local $i)))
        
        (get_local $count)
        (get_local $i)
        f32.eq
        br_if 1

        br 0
      )
    )

    (f32.mul (f32.const 4) (f32.div (get_local $inside) (get_local $i)))
  )
)

Example 2

Last updated

Was this helpful?