2017-10-20 82 views
0

它的作用大部分,直到for循環的結束,但我得到一個錯誤不知道如何解決或如果它的一切都錯了。Matlab的命中和漏洞的圓形區域

問題:

的USF數學系已經忘記pi的價值,他們希望你能計算它爲他們。假設在一個正方形中有一個四分之一圓,邊長爲1x1單位。那麼圓的半徑是1.圓的面積是pir2。如果r = 1,則面積爲pi,四分之一圓的面積爲pi/4。使用for循環從1開始並結束於鍵盤的數字輸入,以便在方塊中添加隨機點(使用MATLAB函數rand()獲取點)。如果一個點落在該圈內,那麼這是一個命中,否則它是一個小姐。圓圈(pi)的大致面積是(點數)/(總點數)* 4。

我學嘗試:

clear;clc 
numP=input('Enter the number of points to test: '); 
randNums=[rand(1,numP);rand(1,numP)]' 
row=0; 
hits=0; 
total=0; 
for i=1:numP 
    while i<=numP 
     dist=sqrt((randNums(row+1))^2 + (randNums(row+(numP+1))^2)) 
     if dist <= 1 
      hits=hits+1    
     end 
     total=total+1 
     row=row+1 
    end 
end 
approx=(hits/total)*4 

回答

0

所有你應該要做的是去掉while循環。

我也擺脫了行變量,因爲你不需要它。

clear;clc 
numP=input('Enter the number of points to test: '); 
randNums=[rand(1,numP);rand(1,numP)]; 
hits=0; 
total=0; 
for i=1:numP 

    dist=sqrt((randNums(i))^2 + (randNums(i+numP)^2)); 
    if dist <= 1 
     hits=hits+1; 
    end    
    total=total+1; 

end 
approx=(hits/total)*4 
0
clear; % Clear workspace. 
clc; % Clear command line. 
numP=input('Enter the number of points to test: '); 
pi_c = 0; % Initialize the computed value of pi. 
format long 
count = 0; % Count resets to 0 after every value of m. 
for j = 1:numP 
    x = rand; % Choose a random number 0 and 1. 
    y = rand; % Choose a random number 0 and 1. 
    if (x^2 + y^2 - 1 <= 0) % If the point falls in a circle... 
     count = count + 1; % Increment count. 
    end 
end 
pi_c = 4 * count/numP; % Computed value of pi. 
disp(pi_c) 

pi_c給你計算出圓周率的值