2017-10-20 32 views
0

Cela fonctionne pour la plupart jusqu'à la fin de la boucle for mais je reçois une erreur ne sais pas comment réparer ou si tout est faux.Matlab hit and miss de cercle

Problème:

Le département de mathématiques USF a oublié la valeur de pi et ils veulent que vous calculera pour eux. Supposons que vous avez un quart de cercle à l'intérieur d'un carré avec des côtés de 1x1 unité. Alors le rayon du cercle est 1. La surface d'un cercle est pir2. Si r = 1, la surface est pi et la surface d'un quart de cercle est pi/4. Utilisez une boucle for commençant à 1 et se terminant par une entrée numérique du clavier pour ajouter des points aléatoires dans le carré (utilisez la fonction MATLAB rand() pour obtenir les points). Si un point atterrit à l'intérieur du cercle, c'est un coup, sinon c'est un échec. La surface approximative du cercle (pi) est le (coups)/(total des points) * 4.

Mon 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 

Répondre

0

Tout ce que vous avez besoin de faire est de retirer la boucle while. Je me suis également débarrassé de la variable de ligne puisque vous n'en aviez pas besoin.

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 vous donne la valeur pi calculée