Matlab 掷两个骰子
我被要求模拟10000掷骰子的总数(A部分) 我的问题是Matlab 掷两个骰子,matlab,Matlab,我被要求模拟10000掷骰子的总数(A部分) 我的问题是for循环中的变量i不断重置为玩游戏的次数,而不是增加。(因此,如果我的i=2掷骰子5次(游戏结束),我希望i变成7,但我的i会回到3) A部分的代码 firstwins=0; wins=0; lost=0; for i=1:10000 reset =0; %reset roll =1; %number of rolls in a game chck=zeros(12); %array of zeros
for
循环中的变量i
不断重置为玩游戏的次数,而不是增加。(因此,如果我的i=2
掷骰子5次(游戏结束),我希望i
变成7
,但我的i
会回到3
)
A部分的代码
firstwins=0;
wins=0;
lost=0;
for i=1:10000
reset =0; %reset
roll =1; %number of rolls in a game
chck=zeros(12); %array of zeros
while reset==0 %game is not over yet
a=randi(6); %roll a die
b=randi(6); %roll a die
c=a+b; %two die tossed
if roll==1 %if this is the first roll of the game
if c==7 || c==11 %if the sum equals 7 or 11
wins=wins+1; %player wins so increment win
firstwins=firstwins+1; %#of times won by rolling only once
reset=1; %reset
elseif c==2 || c==3 || c==12 %if the sum is either 2,3, or 12
lost=lost+1; %player loses
reset=1; %reset
else %if the sum is neither 2,3,7,11, nor 12
roll=roll+1; %increment #of times die was tossed in a game
chck(c)=1; %store the sum
end;
else %if this is a reroll
if c==7 %if the rerolled sum == 7
lost=lost+1; %player loses
reset=1; %reset
elseif chck(c)==1 %if initial outcome occurred
wins=wins+1; %player wins
reset=1; %reset
else %neither 7 or the initial outcome
roll=roll+1; %increment the number of rolls in one game
end;
end;
end;
end;
prob=firstwins/10000;
有人能为C部分提供指导吗?解决A部分的MATLAB方法:
t = 10000;
winners = [7 11];
rolls = randi(6, 1, t) + randi(6, 1, t);
numWinners = sum( ismember(rolls, winners) );
numWinners/t
总的来说,你的模拟看起来很好,只是你的骰子滚动永远不会改变!当您执行
roll=roll+1
或重置游戏时,您需要增加i
,以便从骰子中获得一个新的总和!你的外循环应该在一个不同的变量上,比如(sim_num=1:t)另一个问题:如果我在写一个模拟器,我不会做这个c(I)
之类的事情,因为你事先不知道你需要多少转鼓!我将使用一些变量current_dice_sum
,而不是c(i)
,在适当的点(即游戏重置或新掷骰),我将执行current_dice_sum=sum(randi([16],2,1])
我还将(a)、(b)和(c)分离为不同的代码位。(b)和(c)都可以使用你的模拟器,但是(b)在开始特定的初始滚动时有点不同。(a) 不需要完整的模拟器。你可以用你的'a=randi([16],2,t);c=和(a,1);`再多一点就可以给你(a)。(或者你可能已经这样做了!)所以,如果我要为a、b和c编写一个完整的模拟器,我需要为每个for循环迭代生成一个randi,对吗?在更改为a=randi([16],2,t)之前,我就是这样编写代码的;c=总和(a,1);此外,我不确定t=10000是否意味着掷骰子10000次或玩10000次游戏。有什么建议吗?