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.



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

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




1 Answer

  • 老師
    Lv 7
    2 decades ago
    Favorite 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;參考  >> approxpi(10)ans =    2.8000>> approxpians =    3.1412

Still have questions? Get your answers by asking now.