Python 3 で数学を。

Python 3 とライブラリで数学の問題を解いていきます。統計学や機械学習はときどき。

数値シミュレーション。自由落下。Free fall (Pyton 3, matplotlib, SciPy: scipy.constants, g, Seaborn: set())

使用するライブラリ

matplotlib

SciPy

Seaborn

Python 3 コード

free_fall1.py

#!/usr/bin/env python3


"""(docstring)
"""


import matplotlib.pyplot as plt
from scipy.constants import g
import seaborn as sns


def free_fall1(velocity, altitude, delta_time):
    """(docstring)
    """
    # (scipy.constants の g: 代入して使用しないほうがよいかもしれないが、そもそも g に値を代入できてしまう)。
    GRAVITATIONAL_ACCELERATION = g
    time = 0.0

    time_list = [time]
    altitude_list = [altitude]

    print('time: {}, altitude: {}, velocity: {}'.format(time, altitude, velocity))
    while altitude >= 0:
        time += delta_time
        velocity += GRAVITATIONAL_ACCELERATION * delta_time
        altitude -= velocity * delta_time
        print('time: {}, altitude: {}, velocity: {}'.format(time, altitude, velocity))

        time_list.append(time)
        altitude_list.append(altitude)

    sns.set()
    plt.plot(time_list, altitude_list)
    plt.title('Free fall')
    plt.show()


if __name__ == '__main__':
    free_fall1(0, 100, 0.01)
    free_fall1(-100, 100, 0.01)

出力

$ python3 free_fall1.py

スクリーンショット:

f:id:my_notes:20180610142612p:plain

f:id:my_notes:20180610142633p:plain

ターミナル:

time: 0.0, altitude: 100, velocity: 0
time: 0.01, altitude: 99.999019335, velocity: 0.0980665
time: 0.02, altitude: 99.997058005, velocity: 0.196133
time: 0.03, altitude: 99.99411601, velocity: 0.2941995
time: 0.04, altitude: 99.99019335, velocity: 0.392266
time: 0.05, altitude: 99.985290025, velocity: 0.4903325
time: 0.060000000000000005, altitude: 99.979406035, velocity: 0.588399
# (長いので略)
time: 0.0, altitude: 100, velocity: -100
time: 0.01, altitude: 100.999019335, velocity: -99.9019335
time: 0.02, altitude: 101.997058005, velocity: -99.803867
time: 0.03, altitude: 102.99411601, velocity: -99.7058005
time: 0.04, altitude: 103.99019335, velocity: -99.607734
time: 0.05, altitude: 104.985290025, velocity: -99.50966749999999
time: 0.060000000000000005, altitude: 105.979406035, velocity: -99.41160099999999
# (長いので略)

参考文献

Pythonによる数値計算とシミュレーション

Pythonによる数値計算とシミュレーション

Cによる数値計算とシミュレーション

Cによる数値計算とシミュレーション