2. 参数化圆柱体建模与表面积批量分析
任务说明
本案例将构建一个参数化圆柱体建模与批量分析流程:定义圆柱体半径与高度为可变参数,批量生成多组参数组合对应的圆柱体模型,自动计算每个圆柱体的表面积与体积,最终生成参数-结果对比图表,用于快速评估不同尺寸方案下的几何特性。
实现方案
采用Python标准库math完成圆柱体表面积与体积计算,使用matplotlib绘制对比图表。为体现“参数化建模”概念,代码中通过dataclass定义圆柱体参数模型,批量参数组合以列表形式输入,计算过程与可视化过程分离,便于后续替换为CAD内核(如OpenCASCADE)或仿真脚本。
代码实现
import math
import csv
from dataclasses import dataclass
from itertools import product
import matplotlib.pyplot as plt
@dataclass
class Cylinder:
"""参数化圆柱体模型"""
radius: float
height: float
def surface_area(self) -> float:
"""计算表面积 S = 2πr² + 2πrh"""
return 2 * math.pi * self.radius**2 + 2 * math.pi * self.radius * self.height
def volume(self) -> float:
"""计算体积 V = πr²h"""
return math.pi * self.radius**2 * self.height
def batch_analyze(radii: list[float], heights: list[float]) -> list[dict]:
"""批量生成圆柱体并计算表面积与体积"""
results = []
for r, h in product(radii, heights):
cyl = Cylinder(radius=r, height=h)
results.append({
"radius": r,
"height": h,
"surface_area": round(cyl.surface_area(), 4),
"volume": round(cyl.volume(), 4)
})
return results
def save_csv(results: list[dict], filename: str = "cylinder_results.csv") -> None:
"""保存结果为CSV文件"""
with open(filename, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["radius", "height", "surface_area", "volume"])
writer.writeheader()
writer.writerows(results)
def plot_comparison(results: list[dict]) -> None:
"""生成表面积与体积对比图表"""
labels = [f"r={r['radius']},h={r['height']}" for r in results]
surface = [r["surface_area"] for r in results]
volume = [r["volume"] for r in results]
x = range(len(results))
fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.bar(x, surface, width=0.4, label="表面积", color="#1e88e5", alpha=0.8)
ax1.set_xlabel("参数组合")
ax1.set_ylabel("表面积", color="#1e88e5")
ax1.tick_params(axis="y", labelcolor="#1e88e5")
ax1.set_xticks(list(x))
ax1.set_xticklabels(labels, rotation=45, ha="right", fontsize=8)
ax2 = ax1.twinx()
ax2.plot(x, volume, "o-", color="#d81b60", label="体积", linewidth=2)
ax2.set_ylabel("体积", color="#d81b60")
ax2.tick_params(axis="y", labelcolor="#d81b60")
fig.tight_layout()
plt.title("圆柱体参数-表面积/体积对比")
plt.savefig("cylinder_comparison.png", dpi=150)
plt.close()
if __name__ == "__main__":
# 定义参数范围(可自由调整)
radii = [0.5, 1.0, 1.5]
heights = [2.0, 3.0, 4.0]
# 批量计算
results = batch_analyze(radii, heights)
# 输出到控制台
print(f"{'半径':>6} {'高度':>6} {'表面积':>10} {'体积':>10}")
print("-" * 36)
for item in results:
print(f"{item['radius']:>6.2f} {item['height']:>6.2f} "
f"{item['surface_area']:>10.4f} {item['volume']:>10.4f}")
# 保存CSV与图表
save_csv(results)
plot_comparison(results)
print("\n已生成 cylinder_results.csv 与 cylinder_comparison.png")
运行方式
确保已安装matplotlib(pip install matplotlib),将上述代码保存为cylinder_batch.py,在终端执行:
python cylinder_batch.py
验证方法
程序运行后,控制台将输出9组参数对应的表面积与体积。以第一组参数(r=0.5, h=2.0)为例,手工计算验证:
- 表面积 S = 2π(0.5)² + 2π(0.5)(2.0) = 1.5708 + 6.2832 = 7.8540
- 体积 V = π(0.5)²(2.0) = 1.5708
对照程序输出,第一行应显示0.50 2.00 7.8540 1.5708,与手工计算结果一致。同时检查当前目录下是否生成cylinder_results.csv(包含9行数据)和cylinder_comparison.png(包含柱状图与折线图)。满足以上条件即可判定案例通过。