Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. **There will be no changes to other Yahoo properties or services, or your Yahoo account.** You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

## Trending News

# 請問Matlab程式問題

請問如何用Matlab

算1+100 用 for指令 和while 指令??

和 如何用蒙地卡羅法算出 pie(指數學的Pie,3.1416)???

謝謝各位

有更簡易的方式算出PI嗎??(但也是要用蒙地卡羅法)

### 1 Answer

- 老師Lv 72 decades agoFavorite Answer
利用 for 計算 1+2+3+,,,+100sum=0;for n=1:100sum=sum+n;endsum------------------利用 while 計算 1+2+3+,,,+100sum=0; n=0;while n<=100sum=sum+n;n=n+1;endsum----------------用蒙地卡羅法算出 pifunction mypi = approxpi(n)% Input: n = number of points to generate% Default is n = 1e6% Larger values of n should perform betterif nargin < 1n = 1e6;end% Generate uniformly distributed points in % [0, 1] x [0, 1]xy = rand(n, 2); % Compute distance from (0.5, 0.5)r = sqrt((xy(:,1)-0.5).^2+(xy(:,2)-0.5).^2); % Count fraction of points within 1/2 unit of (0.5, 0.5)frac = sum(r <= 0.5) / n; % Since square has side 1, circle has radius (1/2) % and should have area of pi*(1/2)^2% frac is approximately pi/4 so pi is approximately 4*fracmypi = 4*frac;參考 http://www.mathworks.com/support/solutions/data/1-... >> approxpi(10)ans = 2.8000>> approxpians = 3.1412