He isn't following a tutorial actually, if he needed help he would just shoot a dm over discord asking me or someone. After looking at that, I directed him to mdn. He is still proud of doing that all on himself though.
Because of how modulo works - let's say random() returns number in range 0-15, You want a random number in range 0-9 - so you will call random() % 10 -> But there is a problem because every randomly generated number above 9 will fall into range 0-5. So now you have random number generator that will generate 0-9 with the same probability (if number < 10) and additionally will generate 0-5 with higher probability (number > 9). So now you have a RNG that produces non-uniform distribution which, generally, you don't want.
For tutorials and such, using random() % 10 is okay, because the difference in distribution is negligible (random() returns 0-231 - 1, the remainder is 7 so last 3 numbers would be skewed -> you would have to generate gigabytes of data to notice this), but for real-world applications that depend on secure and uniform RNG (most notably all encryption n stuff) you have to use one of many RNG implementations that will usually also provide functions like generateRandom(bottom, top) that will not have the bias I described above.
will return number in range 0-4,294,967,295 (unsigned int, 4 bytes=232). Then let's say you want random numbers between 0-999 -> logically you would call random() % 1000. But there is a problem -> The remainder of 232 - 1 after division by 1000 is 295 -> so if we assume that random() has perfectly uniform distribution (each number will occur with same probability) and we do % 1000 on the result we will get numbers 0-295 with slightly higher probability than the rest because of the remainder. Or more
Coming along super late (just found this subreddit and checked the top posts of all time), but I don't understand your claim. What's wrong with this approach, assuming that random() generates a float approximately uniformly distributed in [0, 1) (like Math.random() in JS does)?
//range is inclusive: [lower, upper]
generateRandomIntInRange(lower, upper) {
n = upper - lower + 1; //number of possible values in target range
randFloat = random() * n; //random float in [0, n)
randInt = floor(randFloat); //random integer in [0, n-1]
result = randInt + lower; //shift [0, n-1] to [lower, upper]
return result;
}
Let's say, to keep the math easier, that there are exactly 264 possible values returned by random(). And that you want to return either 1, 2, or 3. So, 3 different values.
Divide 264 / 3 and you do not get a whole number (because 2^64 % 3 is nonzero).
Therefore, 1, 2, 3 must have unequal odds because you have an extra value that you need to pick goes into one of them.
Alternatively, you say "if we're so unlucky as to get that extra value, we'll just re-roll". But that does involve calling rand again. Possibly an infinite number of times.
It is much better, but still shouldn't be thought in this form. That method not only gives slightly uneven probability but also uses the least significant bits to the random number - the ones with the poorer random properties.Most of the time it didn't matter, but, IMHO, the proper way should be taught and used as default. Then the number of cases where someone who needs or "needs" better rng uses an overpowered generator and then %2 will decrease. And if someone really needs that slight improvement in runtime, it should an informed decision.
The proper way is a bit more complicated*) (so, the proper way to teach, if the lecture isn't about making the generator, is: "use the fraking library") but as a fast and dirty version, even division instead of modulo would be a bit better.
*)libraries do something like this: generator gen gives number from the set {0,1,2...N-1}, we want in the interval {0,1...M-1} r = floor(N/M); L = r*M //( so L is the largest number not greater than N, that is divisible by M). do { g = gen(); }while (g >= L) return (floor(g/r)) (floors aren't required if int is used).
Edit: since on the original pic the real number generator is set, just rescaling is OK.
It's like StackOverflow meme - best way to get the proper way to do things is by posting the wrong way to do it. People can't resist correcting you, but helping people is lame, apparently.
Helping doesn't give that many people something to bother with it. If someone is making something so bad that you feel the urge to correct them, so no one is going to do the same shit
That fear will always be there. At least in my experience. When I became more skilled I changed jobs or took on new projects with new people. I’m constantly around people that are better than me. Which is great in a way, but code review still sucks with the ever increasing demand for quality
Big Brain Bret discovered the true and holy meaning of DRY: window["Return a random integer from 1 to 10, inclusive. Very efficient, don't touch"] = function(){...}
The real big brain move is that the name is also wrong, because it's named getrandomnumberbetween1and10 but also returns 1 and 10 so it's not actually doing what it says. It'd be less misleading to name the thing something useless like number and not set bad expectations at that point.
I had to code a text based sim thing and it has like 4 diferent rand implementations because each time i wasnt sure if it was generating up to or including the said numbers. Probably something to fix if I ever decide to rework it.
Never use Math.ceil() with the value of Math.random() because it has a very small chance of returning 0.0, and if that ever happens, your program may have an unexpected result.
I don't know why this is getting downvoted, multiplying it by 10, truncating and adding 1 makes a more legible approach imo if you want to adjust the range from [0-9] to [1-10]
(int)(math.Random() * 10) + 1
seems more intuitive because you can adjust the ranges as you please
Well, it isn’t exactly the same. If random returns 0.0, then the ceil method return zero. Adding 1 to the floor avoids this problem. Note that random returns 0.0 <= x < 1.0, so adding one to floor will avoid returning 11 as well.
Kinda reminds me of one of my friends back in school. We were all fairly new to coding and only like a week into the school year, writig simple programs like hello world, or basic addition/subtraction calculators. Our task one day was to write a program that would give you the sum of two integers, and i saw a pretty helpless look in the face of my friend. He then called the teacher over for help, because his program was not compiling. I looked over to his screen, because i wanted to see what he had so far and his entire code was just "int=3". This shit was so funny, it's still a running gag a decade later when i talk to my friends from back in the days.
Why waste time and money on a 3 year degree when get same junior job with a 10 week bootcamp.
First 10 weeks of a compute science degree likly is a maths course, and yeah it does not like math but knowing that decimals can be multipled up is 1 step, then taking that awareness to google (stackoverflow) how to do it.
Google 👍 its great if you know what you want to search
111
u/ReconPorpoise Mar 11 '21
Where did they get this idea? I've never seen random taught without floor(random % x) + 1.
167
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Mar 10 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
56
u/tomasek1a Mar 11 '21
So far I've learned more coding from this sub than actual guides.
I fear the day anybody looks at my code.
985
u/Duckslikebreads Mar 11 '21
Ive only just found this sub and its already upset me
601
u/root54 Mar 11 '21
First of all, what the actual fuck is that method name.
176
u/[deleted] Mar 11 '21
return Math.floor(Math.random() * 10);
7
u/kittencantfly Mar 11 '21
Good try. At least, it works.
5
u/kaikalii Mar 11 '21
There must be a better way
4
u/ixBerry Mar 11 '21
That is how the Marsenne twister works internally! /s
1
u/lordheart Mar 14 '21
You should ask him for a
3
u/cashewbiscuit Mar 11 '21
Your friend should Google the term cyclomatic complexity
1
u/Tomekske Mar 11 '21
Can I checkout the function for Random integers between 1 and 1000?
1
u/dvidsilva Mar 11 '21
Such a waste of code, I would change it to this for more efficiency:
You don't need the elses if you're using return.
2
u/[deleted] Mar 11 '21
Well, at least it works.
2
u/redditanomalyy Mar 11 '21
I’m a new coder, only starting learning about a year ago in my IT degree. But what the absolute fuck is that trash
2
u/Kraftdamus02 Mar 11 '21
multiplication exists
this guy: "imma pretend i didn't see that"
2
u/ghencke Mar 11 '21
This is obviously bad code cause he should use a switch statement instead! /s
1
u/Wolfinsk Mar 11 '21
Tell alex i said hi
1
u/Boxit379 Mar 11 '21
I don't even know what to say anymore.. This hurts my soul.
1
u/x2manypips Mar 11 '21
Lol who wrote this
1
u/Cyber_Encephalon Mar 11 '21
Violence is rarely the answer, but in this case, I'll allow it.
Punch him.
1
u/AndStanleyWasHappy Mar 11 '21
imagine if range was 0.01-0.99 lol
1
u/SashayTwo Mar 11 '21
This sub makes me sick
1
u/yourwebdevguy Mar 11 '21
That's cute
1
u/[deleted] Mar 11 '21
For the love of god someone tell them about floors
1
u/Mr_Sky_Wanker Mar 11 '21
I wonder how many percents of this sub posts are fakes
1
u/sevelboen Mar 11 '21
I hate your friend
1
u/ultimo_2002 Mar 11 '21
This is what my life looks like
1
u/[deleted] Mar 11 '21
Oh god no
1
u/[deleted] Mar 11 '21
Clearly a beginner, so points for creativity.
1
u/Wolfplay013 Mar 11 '21
if it's else if 4 or more times. It belongs in this subreddit. It just has to.
1
u/World24Traveller Mar 11 '21
This is why programmers should not be called engineers
1
u/chimphead73 Mar 11 '21
I'm very new to programming and I'm going to have a stroke
1
u/devdave97 Mar 11 '21
Please tell him to use stack overflow
1
u/__Zuki__ evil Mar 11 '21
YandereDev, it's you?
1
u/Serylt Mar 11 '21
What confuses me: Why did he not think about multiplying the numbers by 10 simply and search for a way to cut away the numbers after the dot?
1
u/homiej420 Mar 11 '21
Gross
1
u/aNeoOnReddit Mar 11 '21
easiest solution, return number * 10
1
u/weaboomemelord69 Mar 11 '21
This is... horrible
1
u/ILoveHatsuneMiku Mar 11 '21
Kinda reminds me of one of my friends back in school. We were all fairly new to coding and only like a week into the school year, writig simple programs like hello world, or basic addition/subtraction calculators. Our task one day was to write a program that would give you the sum of two integers, and i saw a pretty helpless look in the face of my friend. He then called the teacher over for help, because his program was not compiling. I looked over to his screen, because i wanted to see what he had so far and his entire code was just "int=3". This shit was so funny, it's still a running gag a decade later when i talk to my friends from back in the days.
1
u/Random_---_Guy Mar 11 '21
Please... tell me that your friend is better now and that this was a past story from when he/she started programming XD
1
u/deadmazebot Mar 11 '21
Why waste time and money on a 3 year degree when get same junior job with a 10 week bootcamp.
First 10 weeks of a compute science degree likly is a maths course, and yeah it does not like math but knowing that decimals can be multipled up is 1 step, then taking that awareness to google (stackoverflow) how to do it.
Google 👍 its great if you know what you want to search
1
u/Liviequestrian Mar 11 '21
But...why?
1
u/NickyPL Mar 11 '21
Pain and suffering...
1
u/Random_---_Guy Mar 11 '21
Wait... isn't this just gonna return 1 assuming that the lowest value of number is 0.1??
...so not only is it unnecessarily long, but it also doesn't work... I can see why this is in r/badcode XD
1
u/troll123456789098765 Mar 15 '21
Are they unfamiliar with the concept of multiplication?
1
u/Pizar_III Apr 28 '21
function yes() { Var number = math.random(); Var yes = number * 10; Return yes; }
1
u/throwawaydontask24 Oct 05 '22
I love how even if they didn't know of the parameters you can set, they literally could've times the result by ten and rounded it or something
1
u/NovaStorm93 Oct 05 '22
my man has never heard of floor(math.random()*10)
0
u/nati9931 Mar 11 '21
Multiply by 10 and floor()
-3
u/vwoxy Mar 11 '21
I like that the C# solution to this is just
new Random().Next(1, 11)