Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Arrays Methods: Part 2

Math.random()-0.5

Hello!

Would happen to know how Math.random()-0.5 works? Apparently, it distributes positive and negative numbers in an array in an equal manner.

I am not sure how it works and what this equal distribution of negative and positive numbers the instructor is talking about in the lecture video.

Cheers!

8 Answers

Hi orange sky,

That's alright. It's fine to try to get some clarification if it didn't make sense the first time around.

1) Yes, it would be [0, 10). Think of multiplying by a number as a way to scale up or down the range. This new range is now 10 times bigger than the starting range, [0, 1). It can return decimal numbers though. The original range [0, 1] does return floating point numbers from 0 up to but not including 1. Multiplying by 10 just gives you all floating point numbers from 0 up to but not including 10. Whenever in doubt you can always run your expressions in the console and see what you get.

2a) Does Math.randowm() -0.5 return [-0.5, 0.5 ) ? Yes

2b) How about numbers like- 0.5, -0.3, 0.2? It returns numbers like this but in actuality there are more decimal places like 0.49839757683811514

2c) Does Math.randowm() -0.5 *10 returns [-5, 5) ?

No, because of Operator Precedence. Multiplication is done before subtraction and so your expression simplifies to Math.random() - 5 and that will shift your starting range of [0, 1) to the left by 5 and so you get [-5, -4).

To get [-5, 5) you would first want to multiply by 10 to get [0, 10) then subtract by 5 to shift it to the left by 5 to give you [-5, 5). So Math.random() * 10 - 5

2d) And, does it also return decimal numbers like -4.9 or 3.2? Yes, but not in that range and it would be more decimal places returned.

3) These negative and positive number distribution does not come into play when try to sort an array with positive number values like in the example below right? All a code like that does is shuffle the numbers already in the array, right? Yes, it shuffles whatever numbers are in the array whether they be positive, negative, or zero. You could have an array of strings and it would shuffle those around too.

4) Would you happen to know how I can make the console.log return different shuffled or sorted values. My console.log returns the exact range of sorted numbers for each console.

The following code should give you a different ordering of the array each time you run it:

var myArray = [10, 44, 32, 100, 0, 44, 3, 4];

myArray.sort(function( a, b ){
return Math.random()-0.5;
});
console.log(myArray);

It's not going to change any of the numbers in the array. It's simply going to give you a random ordering each time which really isn't any order at all.

I got [100, 0, 44, 44, 10, 32, 3, 4] and [4, 3, 10, 32, 44, 0, 100, 44] 2 of the times that I ran it.

Erik Nemesis
Erik Nemesis
13,356 Points

Simply put, Math.random is returning a number between 0 and 1. Therefore, if you call Math.random() - 0.5 there is a 50% chance you will get a negative number and 50% chance you'll get a positive number.

If you run a for loop and add these results in an array, you will effectively get a full distribution of negative and positive numbers

Hi orange sky,

Is this related to your previous question that you asked about how this relates to sorting an array?

Math.random() returns a number from 0 up to but not including 1. This much I think you understand.

This can be written in interval notation as [0, 1) A bracket indicates that number is included and a parenthesis indicates that it's not included. So the 0 is included in the range but the 1 is not. Think of this range as existing on the number line. It's all the numbers that go from 0(inclusive) to 1(exclusive).

When you do Math.random() - 0.5 you are simply shifting that range to the left by 0.5

If you subtract 0.5 from each of the endpoints of [0, 1) you get a new range [-0.5, 0.5) So on a number line this would be the range of all the numbers from -0.5 up to but not including positive 0.5 This range of positive and negative numbers is centered over zero. So when a random number is returned from this range there's an equal chance it will be positive or negative.

On the other hand, if you look at this range: [-5, 1). This one isn't centered over zero. When returning a random number from this range there is a greater chance the number will be negative because there is much more negative numbers in this range than positive ones.

If you're asking about this in the context of shuffling an array then I think the two key pieces you should understand is the range returned by the Math.random() - 0.5 expression and how the compare function works in the sort method.

Dino Paškvan has explained what this range is and why it would shuffle the array here. Dino also linked to one of my answers explaining the compare function. I think that if you can study those 2 answers and put them together then you'll understand how the code in the previous video is shuffling the array.

Let me know if there is something that is still confusing you.

Hello Zoro Roronoa,

I am used to Math.random() returning positive numbers, so if I understand you correctly, when we add -0.5 after Math.random() it can return negative numbers as well.

Can you please show me a small example so that I can visualize what the below means?

If you run a for loop and add these results in an array, you will effectively get a full distribution of negative and positive numbers

thanks!!

Erik Nemesis
Erik Nemesis
13,356 Points

Something like :

var numbers = [];
for (var i = 0; i < 100; i++) {
  numbers.push((Math.random() - 0.5) * 100);
}

Hello Jason and Zoro Roronoa, Sorry Jason but, this concept is totally new, I just didnt get it before. For some reason, I can now visualize what equal distribution really means because of the way you broke it down with a number line and interval notation, . Yes, Dino did explain it, but the concept was new to me and there are still some unconnected dots on my part. Ok, I just need a few more clarifications before I can close the chapter on this topic for good.

1) Math.random () * 10 returns random numbers from [0, 10), right? but it does not return decimals like 4.9, right?

2) Does Math.randowm() -0.5 return [-0.5, 0.5 ) ? How about numbers like- 0.5, -0.3, 0.2? Does Math.randowm() -0.5 *10 returns [-5, 5) ? And, does it also return decimal numbers like -4.9 or 3.2?

3) These negative and positive number distribution does not come into play when try to sort an array with positive number values like in the example below right? All a code like that does is shuffle the numbers already in the array, right?

4) Would you happen to know how I can make the console.log return different shuffled or sorted values. My console.log returns the exact range of sorted numbers for each console.

<!DOCTYPE html>
<head>


</head>

<body>
<script>
var myArray = [10, 44, 32, 100, 0, 44, 3, 4];

myArray.sort(function( a, b ){
return Math.random()-0.5;
console.log(myArray.toString());

});
console.log(myArray.toString());
console.log(myArray.toString());
console.log(myArray.toString());

</script>

</body>
</html>

thanks!!

Hello Jason,

Thank you so much for your detailed explanation. I understand just about everything but I think I need a small code to understand this section (could you please write a small code for me to visualize while rereading this explaination. I actually thought for Math.randowm() -0.5 (multiply by )10, to get the max on the left hand side of the number line, I need multiply -0.5 x 10 = -5, and .5 x 10 = .499999 ) Thanks!!

2c) Does Math.randowm() -0.5 10 returns [-5, 5) ? *No, because of Operator Precedence. Multiplication is done before subtraction and so your expression simplifies to Math.random() - 5 and that will shift your starting range of [0, 1) to the left by 5 and so you get [-5, -4). To get [-5, 5) you would first want to multiply by 10 to get [0, 10) then subtract by 5 to shift it to the left by 5 to give you [-5, 5). So Math.random() * 10 - 5

I think the way you're seeing Math.random() - 0.5 * 10 is that by subtracting 0.5 you get the new range [-0.5, 0.5) and when each number in that range is multiplied by 10 it will be [-5, 5) Is that how you're seeing it?

The problem is that the browser will not do the subtraction first. It does the multiplication first then subtracts that result from whatever Math.random() returned. If you check the link I gave there is a table on that page which shows all the operators from highest to lowest precedence. The browser will evaluate based on that order and not left to right order as you have it written.

What I didn't think about is that you can add parentheses to your expression to change the order of operations.

Like this: (Math.random() - 0.5) * 10 Now the subtraction will be done first and multiplied by 10 second. You would then get the range [-5, 5] as you were expecting.

So this Math.random() * 10 - 5 and (Math.random() - 0.5) * 10 should both give you the range [-5, 5) if I haven't confused myself here.

Does that make more sense? It's all about the order of operations here.

Hello Jason! I am soooo clear on this. Thank you sooo much for breaking it down the way you did!!!

You're welcome. Glad it helped!