2013-12-11 2 views
0

나는이 게임에서 돈을 얻었는지 또는 느슨하게했는지 알아보기 위해 다음 함수에 1000 번 중재하고 싶습니다.확률 주사위 게임 두 개의 오지로 파이썬에서

게임은 당신이 주사위를 던져 돈을 돌려 받거나 돈을 잃어 버리도록 설계되었습니다. 우리가 5 코인으로 시작한다고 가정 해 봅시다.

을 내고, 동전을 산출한다.

을 던지면 동전이 나온다.

을 내면, 0.5 동전이 나온다.

9,8 또는 7을 던지면 아무 것도 산출되지 않습니다. 던지는

6,5,4,3,2 또는 1동전의 당신의 양에서0.5 동전을 공제.

이 내 구현은 지금까지 모습입니다 : 내가 이것을 달성하는 방법에 대한 더 우아한 해결책이 있어야한다는 인식 때문에

def luckCalc(): 

    amount = 5 

    # if 12 then 1/36 chance 

    if random.randrange(1,7) == 6 and random.randrange(1,7) == 6: 
     amount = amount + 1.5 

    # if 11 then 2/36 chance 
    elif (random.randrange(1,7) == 5 and random.randrange(1,7) == 6) or (random.randrange(1,7) == 6 and random.randrange(1,7) == 5): 
     amount = amount + 1 

    # if 10 then 3/36 chance 

    elif (random.randrange(1,7) == 5 and random.randrange(1,7) == 5) or (random.randrange(1,7) == 4 and random.randrange(1,7) == 6) or (random.randrange(1,7) == 6 and random.randrange(1,7) == 4): 
     amount = amount + 0.5 

    # if 9,8,7 
    # 4/36 + 5/36 + 6/36 chance 
    # 1+6, 2+5, 3+4, 4+3, 5+2, 6+1 chance 
    # 2+6, 3+5, 4+4, 5+3, 6+2 chance 
    # 3+6, 4+5, 5+4, 6+3 chance 
    # then no change in amount 

    # if 6,5,4,3,2,1 
    # chances... 
    # then amount -0.5 

return amount 

# Iterate over the dice throwing simulator and calculate total 

total = 0.0 
for a in range(1000): 
    total = total + luckCalc() 

print (total) 

내가, 함수의 끝으로 코딩을 중단했다. 어떤 재미있는 제안이라도,이 몬테카를로는 계속 듣고 있니?

+4

현재 루틴 "다시 롤"각'if' 문에 대해 주사위입니다. 'roll = random.randrange (1,7) + random.rangerange (1,7) '로 시작한 다음 그걸 테스트 해보십시오. luckCalc를 통해 매번 금액을 외부로 추적하지 않고 재설정합니다. 또한 11은 무엇을합니까? – jonrsharpe

+0

글쎄, 당신의 예리한 눈이 논리적 인 구멍을 발견했다. - 11을 더했습니다. – nottinhill

답변

2

random.randrange(1,7)을 호출 할 때마다 난수가 생성됩니다. 당신은 하나의 "회전"을 테스트하고 있기 때문에, 두 번 롤 :

def roll_die(): 
    return random.randrange(1, 7) 

total = roll_die() + roll_die() 

을 그리고 합이 범위에있는 경우 참조 :

>>> from collections import Counter 
>>> counts = Counter(play_turn() for i in xrange(100000)) 
>>> counts 
    Counter({-0.5: 41823, 0: 41545, 0.5: 8361, 1.0: 5521, 1.5: 2750}) 
>>> probabilities = {score: count/100000.0 for score, count in counts.items()} 
>>> probabilities 
    {-0.5: 0.41823, 0: 0.41545, 0.5: 0.08361, 1.0: 0.05521, 1.5: 0.0275} 
: 여기

def play_turn(): 
    total = roll_die() + roll_die() 

    if total == 12: 
     return 1.5 
    elif total == 11: 
     return 1.0 
    elif total == 10: 
     return 0.5 
    elif total <= 6: 
     return -0.5 
    else: # total is 7, 8, or 9 
     return 0 

10 라운드의 결과입니다

0

코드에 몇 가지 사항이 있습니다. 첫째, 6-1 건의 경우 실제로 금액에서 0.5을 뺀 것이 아닙니다. 둘째, 초기 루프마다 5에서 6.5 사이에 추가하는 각 루프를 전달하지 않으므로 합계가 꽤 무의미합니다.

보다 효과적인 총 금액마다 통과하는 것입니다 :

def luckCalc(amount): 

과 다음 루프 :

total = 5.0 
for a in range(1000): 
    total = luckCalc(total) 

내가이 글을 쓰는되면서 바로 게시 블렌더의 대답은, 귀하의 주요 기능을 단순화하는 좋은 방법입니다.

+0

외부 반복에 의해 합계가 제대로 계산됩니다. luckCalc 함수의 코드 끝 부분에 의사 코드를 추가하고 주석 처리했습니다. 예를 들어 1000을 동전의 시작 금액으로 전달합니다.이 금액은 제가 제공 한 사양과 다릅니다. – nottinhill

+0

게임에 대한 오해를 추측합니다. 당신이 작성한대로 매 라운드마다 얇은 공기에서 5 개의 새로운 동전을 추가하고 있습니다. 나는 당신이 단순히 5 개의 동전으로 시작하여 1000 라운드 후에 얼마나 많은 돈을 벌고 싶은지를 생각했다. – user3058428

0

필자의 결과 테이블을 배열 (또는 사전으로 설정하는 것이 좋지만 모든 결과가 소수의 가능한 정수 중 하나 였기 때문에 내 목적에 더 잘 맞았습니다.), 각 주사위 롤의 인덱스가 결과 변경 값. 아래를 참조하십시오.

import random 

def luckCalc(coins=5): 

    diceroll = random.randint(1,6)+random.randint(1,6) #roll them bones 

    #here's that table I was talking about.... 
    results_table = ['index 0 is blank',"you can't roll a one on two dice",-.5,-.5,-.5,-.5,-.5,0,0,0,.5,1,1.5] 

    coins += results_table[diceroll] #changes your coins value based on your roll (as an index of results_table) 

    if results_table[diceroll] > 0: #change the string if your result was + or - 
    result = "gained {}".format(results_table[diceroll]) 
    else: 
    result = "lost {}".format(results_table[diceroll]*-1) 

    print("You {} coins, putting you at {}".format(result,coins)) #report back to the user 
    return coins #this is how you save your output 


#CONSTANTS GO HERE -- YOU CAN CHANGE THESE TO CHANGE YOUR PROGRAM 
STARTING_COINS = 5 
HOW_MANY_ITERATIONS = 1000 

#this way we don't modify a constant 
coins = STARTING_COINS 

#do it how many times? 
for _ in range(HOW_MANY_ITERATIONS): #oh yeah that many times 
    coins = luckCalc(coins) #runs the function and saves the result back to coins 

#report to the user your final result. 
print("After {} rolls, your final total is {}".format(HOW_MANY_ITERATIONS,coins)) 
2

할 수 있습니다 실제로 롤 (하!) 당신은 하나의 함수로하고있는 모든 :

from random import randrange 

def play_game(rolls=1000, amount=5, n=6): 
    """Play game 'rolls' times, starting with 'amount' on 'n'-sided dice.""" 
    for i in range(rolls): 
     roll = randrange(1, n+1) + randrange(1, n+1) 
     if roll == 12: 
      amount += 1.5 
     elif roll == 11: 
      amount += 1 
     elif roll == 10: 
      amount += 0.5 
     elif roll < 7: 
      amount -= 0.5 
    return amount 
+0

나는 다재다능 함을 위해 당신의 답변을 많이 좋아합니다. 제 질문에 대한 귀하의 빠른 의견도 먼저였습니다. 그러나 Blender는 훌륭한 일을 설명했습니다. – nottinhill

관련 문제