Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I use Math.imul()?

Does it perform better than * expressions? Why?

This article describes it as being useful for projects like Emscripten. Why is that?

Thanks

like image 408
Matthew Avatar asked Jan 10 '14 19:01

Matthew


1 Answers

Short version

Math.imul(a,b) multiplies a and b as though they were 32 bit signed integers. (a*b)|0 does the same, but may give incorrect results for large numbers.

Long version

You would use Math.imul whenever you want to multiply two numbers, and you want the multiplication to act as though the two numbers were 32 bit signed integers. That is, you want integer multiplication modulo 2^32.

Normally, you can get this effect by using a bitwise operator on the result. For instance, (0xffffffff + 1)|0 quite correctly gives you 0. However, this doesn't work for multiplication. (0x7fffffff * 0x7fffffff)|0 gives us 0, when 32 bit multiplication of the two numbers would give us 1. The reason for this failure is precision. The Number type is a IEEE754 double precision floating point number, which has 53 bits of mantissa. When you try to use numbers larger than 2^53, you start losing precision. You can test this by running Math.pow(2,53) == Math.pow(2,53)+1 in your browser.

When you multiply two 32 bit numbers in Javascript and truncate the result using a bitwise operator the intermediate result may be larger than 2^53 and may thus be incorrect, which means that the end result of course will also be incorrect.

like image 162
valderman Avatar answered Oct 08 '22 09:10

valderman