views:

135

answers:

2

What is the highest number this javascript expression can evaluate to? What is the lowest number? Why?

+(''+Math.random()).substring(2)

Extra credit: How many different values can the expression evaluate to? Can it be every value from the minimum to the maximum, or are some intermediate values not obtainable due to rounding issues?


Response to Daniel's answer (deleted, was 10000000000000000 max, 0 min):

I was playing around in Chrome's console and got this:

    Math.random();

>> 0.00012365682050585747

    '12365682050585747'.length

>> 17

    12365682050585747 > 10000000000000000

>> true

... so 10000000000000000 can't be the max!

+1  A: 

For me the highest number is 1/0 (===Infinity) and the lowest obviously -1/0 (in Chromium browser).

Edit: You can also try parse a number from string to see which evaluates to Infinity.

var a = "1";
while(parseInt(a)!==Infinity) a=a+"0";
alert("Length of the highest number is: " + (a.length-1));

309 for me.

hluk
+3  A: 
KennyTM
Actually, I think it's "Math.random() can return any positive numbers in the interval `[0, 1)` - [0 inclussive, 1 exclussive](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random) "
Peter Ajtai
if it will have 17 significant figures, shouldn't the maximum be 10^17-1? But that would mean it came from a fraction `0.999...` which is equal to 1 -- so it can't be more than 10^17-2, right?
no
Also I'm totally lost on the 324 stuff, do you have a reference for that somewhere?
no
@no: Some numbers will be shown with 16 figures, so that's not always true. 10^17 is just an upper bound, not the tightest one; For where the 324 comes, see http://en.wikipedia.org/wiki/Double_precision_floating-point_format.
KennyTM
Thanks, Kenny, will check it out. Definitely noticed most of the numbers have at most 16 digits, the 17th seems to be used for rounding oddities. BTW I just got `0.999...` (16 nines) like this: `.1+.1+.1+.1+.1+.1+.1+.1+.1+.1` ... so maybe I'm wrong on the second part of my first comment on this answer.
no
`Math.random()` just returned `46789122046902776` in my console, and that is much bigger than `19531249999999998`
Josh Stodola
@Josh: See update.
KennyTM
@Kenny +1 That's more like it. Nice work :)
Josh Stodola
Well, I don't know if it's right but it sure is convincing. I ran some much less clever tests (dividing 1 by 2 through 10000, chopping the `0.`, and then sorting for the largest result) and the highest number I saw was around 7e16... I'm going to go ahead and mark this correct.
no