![]() ![]() 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. When you do Math.random() - 0.5 you are simply shifting that range to the left by 0.5 It's all the numbers that go from 0(inclusive) to 1(exclusive). Think of this range as existing on the number line. So the 0 is included in the range but the 1 is not. 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. Math.random() returns a number from 0 up to but not including 1. Is this related to your previous question that you asked about how this relates to sorting an array? The following code should give you a different ordering of the array each time you run it: My console.log returns the exact range of sorted numbers for each console. You could have an array of strings and it would shuffle those around too.Ĥ) Would you happen to know how I can make the console.log return different shuffled or sorted values. ![]() So Math.random() * 10 - 5Ģd) 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.ģ) 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. 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). 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). Whenever in doubt you can always run your expressions in the console and see what you get.Ģa) Does Math.randowm() -0.5 return [-0.5, 0.5 ) ? YesĢb) 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Ģc) Does Math.randowm() -0.5 *10 returns [-5, 5) ? Multiplying by 10 just gives you all floating point numbers from 0 up to but not including 10. It's fine to try to get some clarification if it didn't make sense the first time around.ġ) Yes, it would be does return floating point numbers from 0 up to but not including 1.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |