LoginSignup
10
6

More than 5 years have passed since last update.

Python でハートを描く その 2 (SymPy 編)

Last updated at Posted at 2017-04-21

概要

昨晩「Pythonからはじめる数学入門」という書籍を読みながら、Python でハートを描く という記事を書きました。今晩も :bed: の中で読んでいたのですが、第 4 章で紹介されていた SymPy というライブラリに度肝を抜かれました。なんと Python で式の計算ができちゃうのです!鉛筆で紙に方程式を書いて解くのと同じ感覚で、手軽にプログラムできちゃいます。これがあれば昨日の :heart: を描画するコードもシンプルになるのではと :bed: から飛び起きました。

ハートを描く

前回の Python でハートを描く と同様の式を使います。

$x = 16sin^3(t)$
$y = 13cos(t)-5cos(2t)-2cos(3t)-cos(4t)$

この式をそのまま plot_parametric 関数1に渡すことでプロットできます。直感的すぎる! :open_mouth:

from sympy.plotting import plot_parametric
from sympy import Symbol, cos, sin


def draw_heart():
  t = Symbol('t')
  x = 16 * sin(t) ** 3
  y = 13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t)

  p = plot_parametric(x, y, autoscale=True, title='ハート', show=False)
  p[0].line_color = 'pink'
  p.show()


if __name__ == '__main__':
  try:
    draw_heart()
  except KeyboardInterrupt:
    pass

figure_1.png


  1. 書籍内で紹介されていた SymPy のプロット用の関数は plot でしたが、今回はパラメーター表示 (媒介変数表示) で表された関数をプロットする必要があるので plot_parametric を使いました。 

10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6