python作业5
代码:
import random
import matplotlib.pyplot as plt
import numpy as np
def is_inside_heart(x, y):return (x ** 2 + y ** 2 - 1) ** 3 - x ** 2 * y ** 3 <= 0
def monte_carlo_heart(num_samples):points_inside = []points_outside = []for _ in range(num_samples):x = random.uniform(-1.5, 1.5) # x ∈ [-1.5, 1.5]y = random.uniform(-1.5, 1.5) # y ∈ [-1.5, 1.5]if is_inside_heart(x, y):points_inside.append((x, y))else:points_outside.append((x, y))plt.figure(figsize=(8, 8))plt.scatter(*zip(*points_inside), color='red', s=1, label='Inside Heart')plt.scatter(*zip(*points_outside), color='lightgray', s=1, label='Outside')plt.title("Monte Carlo Heart Shape")plt.legend()plt.show()
monte_carlo_heart(50000)
运行截图: