用python解决潍坊期末概率填空题

题目:

一个点从数轴的原点开始运动,通过投掷骰子决定运动方向:

若出现1,4面之一时,向负方向移动1个单位;

若出现 2,3,5,6面之一时,向正方向移动2个单位,

(1)投掷1次骰子,该点位置的平均值为(        )

(2)投掷6次骰子后,概率大于 \frac{197}{243} 的点的位置存在的最小区间为(        )

答案:1 ,   [3,9]

import random

# 投掷骰子的模拟
def roll_dice():
    return random.randint(1, 6)

# 计算点的位置
def calculate_position(rolls):
    position = 0
    for roll in rolls:
        if roll == 1 or roll == 4:
            position -= 1  # 向负方向移动1个单位
        else:
            position += 2  # 向正方向移动2个单位
    return position

# 模拟多个投掷的结果
def simulate_rolls(num_simulations=100000):
    position_counts = {}
    
    for _ in range(num_simulations):
        rolls = [roll_dice() for _ in range(6)]
        position = calculate_position(rolls)
        
        if position not in position_counts:
            position_counts[position] = 0
        position_counts[position] += 1
    
    return position_counts

# 计算结果的位置区间,使得其概率大于197/243
def find_interval(position_counts, num_simulations):
    sorted_positions = sorted(position_counts.items())
    total_count = num_simulations
    target_prob = 197 / 243
    
    cumulative_prob = 0
    lower_bound = None
    upper_bound = None
    
    for position, count in sorted_positions:
        cumulative_prob += count / total_count
        if cumulative_prob > target_prob:
            upper_bound = position
            break
    
    cumulative_prob = 0
    for position, count in reversed(sorted_positions):
        cumulative_prob += count / total_count
        if cumulative_prob > target_prob:
            lower_bound = position
            break
    
    return lower_bound, upper_bound

# 执行模拟并输出结果
position_counts = simulate_rolls()
lower_bound, upper_bound = find_interval(position_counts, 100000)
print(f"满足条件的最小区间是: [{lower_bound}, {upper_bound}]")

你可能感兴趣的:(python,开发语言)