2017-10-20 78 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给你计算出圆周率的值