本文實例講述了Java使用Math.random()結合蒙特卡洛方法計算pi值。分享給大家供大家參考,具體如下:
一、概述
蒙特·卡羅方法(Monte Carlo method),也稱統(tǒng)計模擬方法,是二十世紀四十年代中期由于科學技術的發(fā)展和電子計算機的發(fā)明,而被提出的一種以概率統(tǒng)計理論為指導的一類非常重要的數(shù)值計算方法。是指使用隨機數(shù)(或更常見的偽隨機數(shù))來解決很多計算問題的方法。與它對應的是確定性算法。
詳細可參考百度百科:https://baike.baidu.com/item/%E8%92%99%E7%89%B9%C2%B7%E5%8D%A1%E7%BD%97%E6%96%B9%E6%B3%95
二、實現(xiàn)代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/** * Monte Carlo algorithm */ import java.math.*; public class PI { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub double xf = 0 .0d; double yf = 0 .0d; int total = 0 ; for ( int i = 0 ;i< 1000000 ;i++){ xf = Math.random(); yf = Math.random(); if (Math.sqrt(xf*xf+yf*yf) < 1 ) total++; } System.out.println( "服務器之家測試結果:" ); System.out.println( 4 *(total/ 1000000.0 )); } } |
運行結果:
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/baidu_22502417/article/details/46439267