Piin laskeminen Monte Carlo-menetelmällä

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…).

import java.io.*;

class Monte
{
public static void main(String args[]) throws IOException
{
int sisalla=0, lkm;
double x, y;
BufferedReader lukija = new BufferedReader(new
InputStreamReader(System.in));

System.out.print(”Montako pistettä:”);
lkm = Integer.parseInt(lukija.readLine());

for (int i=0; i < lkm; i++) { x = Math.random(); y = Math.random(); if (Math.sqrt(x*x+y*y) <= 1) { sisalla++; } } System.out.println("Sisällä oli "+sisalla+" pistetta"); System.out.println("Piin likiarvoksi tulee "+sisalla+"/"+lkm+"*4="+((double)sisalla/(double)lkm*4.0)); } } [/java]

Vastaa

Sähköpostiosoitettasi ei julkaista. Pakolliset kentät on merkitty *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close