जावा गणित यादृच्छिक ()

जावा गणित रैंडम () विधि एक मान लौटाती है जो 0.0 से अधिक या बराबर और 1.0 से कम है।

random()विधि का सिंटैक्स है:

 Math.random()

नोट : random()विधि एक स्थिर विधि है। इसलिए, हम क्लास नाम का उपयोग करके सीधे विधि को कॉल कर सकते हैं Math

यादृच्छिक () पैरामीटर

Math.random()विधि कोई पैरामीटर नहीं लेता है।

यादृच्छिक () वापसी मान

  • 0.0 और 1.0 के बीच छद्म मान लौटाता है

नोट : लौटाए गए मान वास्तव में यादृच्छिक नहीं हैं। इसके बजाय मूल्यों को एक निश्चित कम्प्यूटेशनल प्रक्रिया द्वारा उत्पन्न किया जाता है, जो यादृच्छिकता की कुछ स्थिति को संतुष्ट करता है। इसलिए छद्म आयामी मूल्य कहा जाता है।

उदाहरण 1: जावा गणित। आयामी ()

 class Main ( public static void main(String() args) ( // Math.random() // first random value System.out.println(Math.random()); // 0.45950063688194265 // second random value System.out.println(Math.random()); // 0.3388581014886102 // third random value System.out.println(Math.random()); // 0.8002849308960158 ) )

उपरोक्त उदाहरण में, हम देख सकते हैं कि यादृच्छिक () पद्धति तीन अलग-अलग मान लौटाती है।

उदाहरण 2: 10 और 20 के बीच यादृच्छिक संख्या उत्पन्न करें

 class Main ( public static void main(String() args) ( int upperBound = 20; int lowerBound = 10; // upperBound 20 will also be included int range = (upperBound - lowerBound) + 1; System.out.println("Random Numbers between 10 and 20:"); for (int i = 0; i < 10; i ++) ( // generate random number // (int) convert double value to int // Math.round() generate value between 0.0 and 1.0 int random = (int)(Math.random() * range) + lowerBound; System.out.print(random + ", "); ) ) )

आउटपुट

 10 और 20: 15, 13, 11, 17, 20, 11, 17, 20, 14, 14, के बीच रैंडम नंबर

उदाहरण 3: रैंडम एरे तत्वों तक पहुँच

 class Main ( public static void main(String() args) ( // create an array int() array = (34, 12, 44, 9, 67, 77, 98, 111); int lowerBound = 0; int upperBound = array.length; // array.length will excluded int range = upperBound - lowerBound; System.out.println("Random Array Elements:"); // access 5 random array elements for (int i = 0; i <= 5; i ++) ( // get random array index int random = (int)(Math.random() * range) + lowerBound; System.out.print(array(random) + ", "); ) ) )

आउटपुट

 यादृच्छिक ऐरे तत्व: 67, 34, 77, 34, 12, 77,

अनुशंसित ट्यूटोरियल

  • गणित। घेरना ()
  • गणित। Pow ()
  • गणित। वर्ग ()

दिलचस्प लेख...