为什么我的变量在我的循环中没有递增?
Why is my variable not incrementing in my loop?
我正在为 Monte Carlo 的圆周率估计编写代码。我想计算四分之一圆内部与外部的点数。但是,我的 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;
您缺少 distanceFromOrigin
和 Gen
的定义。
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
我正在为 Monte Carlo 的圆周率估计编写代码。我想计算四分之一圆内部与外部的点数。但是,我的 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;
您缺少 distanceFromOrigin
和 Gen
的定义。
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