今回は今、人気急上昇中であるプログラミング言語の「Python」を使って、
ばねのプログラムを作成しました。
■ プログラム
from tkinter import * from tkinter import messagebox import numpy as np import time, math class Weight: pos = np.array([0.0, 0.0]); vel = np.array([0.0, 0.0]); acc = np.array([0.0, 0.0]); natural = np.array([0.0, 0.0]); d = 0; m = 0; l = 0; k = 0; g = 0; # コンストラクタの定義 def __init__(self, x, y): self.pos = np.array([x, y]); self.vel = np.array([0.0, 0.0]); self.acc = np.array([0.0, 0.0]); self.d = 40; # おもりの大きさ self.m = 5; # おもりの重さ self.l = 50; # ばねの自然長 self.k = 0.1; # ばね定数 self.g = 0.1; # 重力加速度 def display(self, canvas): # おもりの描画 canvas.create_oval(self.pos[0]-10, self.pos[1]-10, self.pos[0]+10, self.pos[1]+10, fill="red", tag="DT") def move(self, w): # 計算 # 自然長での位置を計算 self.natural = self.pos - w.pos; self.natural = self.natural / np.linalg.norm(self.natural); self.natural = self.natural * self.l; self.natural = self.natural + w.pos; self.acc[0] = -1 * self.k * (self.pos[0] - self.natural[0]) / self.m; # 加速度 (x成分) self.acc[1] = -1 * self.k * (self.pos[1] - self.natural[1]) / self.m; # 加速度 (y成分) self.vel = self.vel + self.acc; # 速度 #self.vel = self.vel * 0.99; # 減衰 self.pos = self.pos + self.vel; # 位置 def decay(self): self.vel *= 0.99; # 減衰 def gravity(self): self.vel[1] += self.g; # 重力 def draw(canvas): global n canvas.delete("DT") # ばねの描画 nn = n - 1 for num in range(nn): canvas.create_line(weights[num].pos[0], weights[num].pos[1], weights[num+1].pos[0], weights[num+1].pos[1], fill="blue", tag="DT", width=1) # おもりの描画 for num in range(n): weights[num].display(canvas); # 計算 weights[1].move(weights[0]); weights[1].move(weights[2]); weights[2].move(weights[1]); weights[2].move(weights[3]); weights[3].move(weights[2]); weights[3].move(weights[4]); weights[4].move(weights[3]); weights[4].move(weights[5]); weights[5].move(weights[4]); weights[5].move(weights[6]); weights[6].move(weights[5]); weights[6].move(weights[7]); weights[7].move(weights[6]); weights[7].move(weights[8]); weights[8].move(weights[7]); weights[8].move(weights[9]); weights[9].move(weights[8]); # 減衰、重力 for num in range(n): weights[num].decay(); weights[num].gravity(); #■メイン処理 n = 10; weights = [] # 配列の宣言 # ■複数のインスタンスを生成する weights.append(Weight(250, 2)) # インスタンスを生成し配列に格納する weights.append(Weight(200, 100)) weights.append(Weight(300, 200)) weights.append(Weight(400, 300)) weights.append(Weight(500, 400)) weights.append(Weight(400, 500)) weights.append(Weight(300, 600)) weights.append(Weight(300, 700)) weights.append(Weight(300, 800)) weights.append(Weight(300, 900)) root=Tk(); root.title("ばねの運動") canvas=Canvas(root,width=500, height=500) canvas.pack() while True: while True: draw(canvas); root.update() time.sleep(0.002) if not messagebox.askokcancel("シミュレーション終了", "再開しますか?"):break |
■ 参考サイト