Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

e/pluginfile.php/2694821/mod_resource/content/O/T2.pdf Flipping a coin Programs

ID: 3914496 • Letter: E

Question

e/pluginfile.php/2694821/mod_resource/content/O/T2.pdf Flipping a coin Programs often need some "randomization" We will consider two ways to easly generate a peeudorandom number Apseudorandom sequence of numbers looks lke a random sequence of numbers but s actualy computed using a deterministic algorthm A seed is used to begin the sequence. The same sequence wil be repeated i& the same seed is used To simulate actual randomness, the truly random sed is chosen For ou puposes, we wont wory about the seed and the output wil be good (random) enough Some applications such cryptographic protocols, need truly random numbers The Hath dlass has a static method that retums a peudorandom double, ca x at Using the output of this static method, we can simulate die rolls, coin fips, etc For example, to simulate the rol of a de we can generate random integers in the range [1,6l using Why does this never generate 77 t we look at what is happening here, Math.randongves a number x in the rangecx1 andso mutiplying this by gives a number in the range x .0 When we cast Pris to an integer, Java simply throws away the decimal part, so we only The Random Class The Rand? class provon menos generang 'anon seoarces (nt gers, haing port numbers, bocleans). Untke the Math class, you will need to create an intance of the Random class (e, create an abject of type Random) to use it The mathods in the class are not staltic If you dig into the Math APl you uil actvaly see hat ath.randon also used the Randon class To smulate the ro of a die (an indeger in the range 11 we would use vuel.andon die new Randon) int die rel-die.ette(6) See the APi for the class to see what other methods the dass provides Code argumant. in your man metod creaeaandon object and use it to generate pseudorandom numbers ( double )1o simuiste a coin ip. The command ine argument (a number between O and 1) will specity the

Explanation / Answer

import java.util.Random; public class Flip { public static void main(String[] args) { double bias = Double.parseDouble(args[0]); int heads = 0, tails = 0; Random random = new Random(); for(int i = 0; i < 100; ++i) { if(random.nextDouble()
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote