2017-10-20 3 views
0

forループの終わりまではほとんどの部分で動作しますが、修正方法やそのすべてが間違っているかどうかはわかりません。Matlabが打ち切って円の領域を逃した

問題:

USFの数学部門は、PIの値を忘れていると、彼らはあなたが彼らのためにそれを計算します。あなたは1x1単位の側面を持つ正方形の中に四半期円を持っているとします。円の半径は1です。円の面積はpir2です。 r = 1の場合、面積はπであり、四分円の面積はπ/ 4である。 1から始まるforループを使用し、キーボードからの数字入力で終わり、四角形内のランダムな点を追加します(MATLAB関数rand()を使用して点を取得します)。ポイントが円の内側に着くと、ヒットします。それ以外はミスです。円のおおよその面積(pi)は(ヒット)/(合計点)* 4です。

マイattemp:

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はあなたの計算されたPI値を与える

関連する問題