Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does webassembly have a square root opcode?

Webassembly offers only one of the more advanced floating point operations: the square root.

It doesn't have any of the others typically implemented in CPUs, such as powers and trigonometric functions, and this rationale is explained in the official FAQ:

WebAssembly doesn’t include its own math functions like sin, cos, exp, pow, and so on. WebAssembly’s strategy for such functions is to allow them to be implemented as library routines in WebAssembly itself (note that x86’s sin and cos instructions are slow and imprecise and are generally avoided these days anyway). Users wishing to use faster and less precise math functions on WebAssembly can simply select a math library implementation which does so.

That begs the question if there's something special about square roots that justify to make an exception for it. It's useful for distance calculation, but does that come up that much more often that other kinds of powers or the exponential? Is it particularly fast on CPUs and they wanted to exploit that?

If we make two buckets of functions,

  1. the first being addition, multiplication, division and remainder and
  2. the second being powers, trigonometrics and their inversions

then why did they put square root in the first?

EDIT: I just realized that sqrt is special in that an approximation can be found by shifting the exponent one to the right. The exact result still requires finding the square root of the mantissa though, and that's still an interative process. But maybe this head start makes sqrt nice enough to warrant inclusion in IEEE's required operations as Olsonist noted.

There's also the property that sqrt(x*x)=x for all x for which x*x isn't over- or underflowing, which is unusual for operations that can involve rounding (see this SO answer).

like image 593
John Avatar asked Jan 10 '21 15:01

John


1 Answers

IEEE 754-2008 is a requirement for WebAssembly and sqrt is a requirement for IEEE 754-2008 while sin, cos, ... are not requirements for IEEE 754-2008. They are recommended but not required.

like image 71
Olsonist Avatar answered Nov 16 '22 07:11

Olsonist