为什么我的变量在循环中不增加?

时间:2018-10-19 01:28:08

标签: loops increment montecarlo pi maple

我正在为蒙特卡罗估算pi编写代码。我想计算四分之一圈内与外圈之间的点数。但是,我的totalPointsInside在循环中没有增加。如果在循环后调用totalPointsInside,我仍然得到它等于0。如何解决此问题?

isInsideCircle := (x_2, y_2) ->evalb(distanceFromOrigin(x_2, y_2) < 1);

totalPointsInside := 0;

i:=1;

n:=5;

for i to n do

x_2 := Gen();

y_2 := Gen();

distanceFromOrigin(x_2, y_2);

isInsideCircle(x_2, y_2); #this was added to test my code

if isInsideCircle(x_2, y_2)=true then

totalPointsInside := totalPointsInside +1;

i = i+1;

end if;

end do;

1 个答案:

答案 0 :(得分:2)

您缺少distanceFromOriginGen的定义。

restart;
randomize():

distanceFromOrigin := (a,b) -> sqrt(a^2+b^2):
isInsideCircle := (a,b) -> evalb(distanceFromOrigin(a,b) < 1):

Gen := rand(0.0 .. 1.0):

f :=proc(n)
  local totalPointsInside,i,x_2,y_2;
  totalPointsInside := 0;
  for i from 1 to n do
    x_2 := Gen();
    y_2 := Gen();
    if isInsideCircle(x_2, y_2)=true then
      totalPointsInside := totalPointsInside +1;
    end if;
  end do:
  return evalf(4*totalPointsInside/n);
end proc:

f(5000);
                      3.155200000