Piin laskeminen Monte Carlo-menetelmällä

Bookmark and Share

Tähän lienee jossain myös javalla ratkaisu, mutta 9-luokan taulukkolaskentakurssin innoittamana tein ohjelman javalle, joka laskee piin likiarvon Monte Carlo-menetelmällä. Menetelmällä on mielenkiintoista laskea piin likiarvoa myös taulukkolaskentaohjelmallakin (se on siis melko haastavaa...).

JAVA:
  1. import java.io.*;
  2.  
  3. class Monte
  4. {
  5.     public static void main(String args[]) throws IOException
  6.     {
  7.         int sisalla=0, lkm;
  8.         double x, y;
  9.         BufferedReader lukija =  new BufferedReader(new
  10.                InputStreamReader(System.in));
  11.                
  12.         System.out.print("Montako pistettä:");
  13.         lkm = Integer.parseInt(lukija.readLine());
  14.        
  15.         for (int i=0; i <lkm; i++)
  16.         {
  17.             x = Math.random();
  18.             y = Math.random();
  19.            
  20.             if (Math.sqrt(x*x+y*y) <= 1)
  21.             {
  22.                 sisalla++;
  23.             }
  24.         }
  25.        
  26.         System.out.println("Sisällä oli "+sisalla+" pistetta");
  27.        
  28.         System.out.println("Piin likiarvoksi tulee "+sisalla+"/"+lkm+"*4="+((double)sisalla/(double)lkm*4.0));
  29.        
  30.     }
  31. }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>