Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Actionscript displays different values for modulus of large values?

Using Flash CS4 with Actionscript 3 I type the following:

 trace(Math.pow(97,83) % 205);

Which results in 86. However if I type in Wolfram-Alpha:

 97^83 mod 205

I get 13 which is the right answer. Why is actionscript displaying the wrong value?

Thanks, Y_Y

like image 282
Y_Y Avatar asked Dec 16 '22 00:12

Y_Y


2 Answers

This is due to float point precision of the Number type. Flash only uses 64 bits to represent the result of Math.pow(97,83) of which 53 are used to describe the mantissa portion of the floating point number. With 53 bits, you can only get about 15-16 digits of precision on a number before you need to round it. Since Math.pow(97,83) is a number roughly 164 digits long, Flash keeps an approximation of the form 7.98093813043768e+164

This is not the exact value of Math.pow(97,83) due to the loss of precision and thus will yield bad results when calculating a mod.

Wolfram-Alpha probably uses a specialized library for calculating large numbers without loss of precision. I am not aware of any such libraries for Actionscript 3 but google may help there ;)

like image 170
Godfather Avatar answered Jan 21 '23 12:01

Godfather


Because the result of 97^83 is way too large to be calculated correctly in AS3. See http://en.wikipedia.org/wiki/IEEE_754-2008

like image 40
Creynders Avatar answered Jan 21 '23 12:01

Creynders