给我一段模拟计算的python代码
- User
给我一段模拟计算的python代码
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
给我一段模拟计算的python代码
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import random
import math
import matplotlib.pyplot as plt # 可视化 (可选)
def monte_carlo_pi(n):
"""
使用蒙特卡罗方法估算圆周率 pi。
Args:
n: 随机点的数量。
Returns:
估计的 pi 值。
"""
inside_circle = 0
for _ in range(n):
x = random.random() # 生成 0 到 1 之间的随机 x 坐标
y = random.random() # 生成 0 到 1 之间的随机 y 坐标
# 检查点是否在半径为 1 的圆内 (圆心在 (0, 0) 坐标为 x**2 + y**2 <= 1)
if x**2 + y**2 <= 1:
inside_circle += 1
# (inside_circle / n) 约等于 圆面积/正方形面积 = pi*r^2 / (2r)^2 = pi/4
# 所以 pi 约等于 4 * (inside_circle / n)
pi_estimate = 4 * (inside_circle / n)
return pi_estimate
def simulate_dice_rolls(num_rolls, num_dice=2):
"""
模拟掷骰子。
Args:
num_rolls: 模拟的掷骰子的次数。
num_dice: 骰子的数量 (默认为 2)。
Returns:
一个字典,键是骰子的总和,值是该总和出现的次数。
"""
results = {}
for _ in range(num_rolls):
roll_sum = 0
for _ in range(num_dice):
roll = random.randint(1, 6) # 模拟单个骰子的滚动 (1 到 6)
roll_sum += roll
if roll_sum in results:
results[roll_sum] += 1
else:
results[roll_sum] = 1
return results
def random_walk_2d(num_steps):
"""
模拟二维随机游走。
Args:
num_steps: 游走的步数。
Returns:
一个元组,包含所有 X 坐标和所有 Y 坐标的列表。
"""
x = 0
y = 0
x_coords = [x]
y_coords = [y]
for _ in range(num_steps):
# 从四个方向中随机选择一个
direction = random.choice(["up", "down", "left", "right"])
if direction == "up":
y += 1
elif direction == "down":
y -= 1
elif direction == "left":
x -= 1
elif direction == "right":
x += 1
x_coords.append(x)
y_coords.append(y)
return x_coords, y_coords
if __name__ == "__main__":
# 蒙特卡罗 π 模拟
num_points = 100000
pi_approx = monte_carlo_pi(num_points)
print(f"蒙特卡罗模拟的 π 值 ({num_points} 个点): {pi_approx}")
print(f"标准 math.pi: {math.pi}")
# 掷骰子模拟
num_rolls = 1000
dice_results = simulate_dice_rolls(num_rolls)
print(f"\n掷骰子模拟 ({num_rolls} 次):")
for roll_sum, count in sorted(dice_results.items()):
print(f"总和 {roll_sum}: {count} 次")
# 随机游走模拟
num_steps = 100
x_coords, y_coords = random_walk_2d(num_steps)
# 可视化随机游走 (需要 matplotlib)
try:
plt.plot(x_coords, y_coords)
plt.xlabel("X 坐标")
plt.ylabel("Y 坐标")
plt.title("二维随机游走")
plt.grid(True)
plt.show()
except ImportError:
print("\n二维随机游走结果:")
print(f"X 坐标: {x_coords}")
print(f"Y 坐标: {y_coords}")
print("\n注意: 要可视化随机游走,需要安装 matplotlib (`pip install matplotlib`)")
代码解释:
monte_carlo_pi(n): 使用蒙特卡罗方法估算 π:
n 个随机点(x 和 y 坐标在 0 和 1 之间)。simulate_dice_rolls(num_rolls, num_dice=2): 模拟掷骰子:
num_dice 个骰子 num_rolls 次。random_walk_2d(num_steps): 模拟二维随机游走:
num_steps 步。if __name__ == "__main__"::
if __name__ == "__main__": 块中,调用了上面定义的函数并打印结果。 还包括了可选的随机游走可视化部分,需要安装 matplotlib 库。如何运行代码:
.py 文件,例如 simulation.py。python simulation.py。matplotlib 库。 运行 pip install matplotlib (通常在命令行或终端中)。要点:
random 模块的随机数生成。 增加 num_points、num_rolls、num_steps 可以提高模拟的精度。matplotlib 库用于创建图形和可视化数据。 随机游走的可视化可以帮助你直观地了解随机过程的行为。random_walk_2d 函数以包含不同的移动概率或障碍物。 你可以使用其他概率分布来改变骰子滚动模拟。希望这个解释对你有所帮助!