LoginSignup
4
3

More than 5 years have passed since last update.

PyCall を使って Ruby でハートを描く

Last updated at Posted at 2017-04-24

概要

ハートを描くシリーズ第 3 弾です。今回は第 2 弾の Python でハートを描く その 2 (SymPy 編) の Python コードを、PyCall という Gem を使って Ruby コードに移植してみました。

なお PyCall は現時点 (2017/04/24 23:30) で最新のバージョン 0.1.0.alpha.20170419' をインストールしました。

コード

移植元 (Python)

draw_heart.py
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)

  plot_parametric(x, y,
                  autoscale=True, title='ハート', line_color='pink')


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

移植先 (Ruby)

draw_heart.rb
require 'pycall/import'
include PyCall::Import

pyimport 'sympy'
pyfrom 'sympy', import: %i[cos sin]
pyfrom 'sympy.plotting', import: :plot_parametric

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

  plot_parametric.(x, y, autoscale: true, title: 'ハート', line_color: 'pink')
end

draw_heart

実行結果

figure_1.png

動いたー :heart_eyes:

現状使い方のドキュメントが公式リポジトリの README.md にないので、 コード例 を参考にしながら書きました。意外とすんなり動きました!Ruby で Python のコードがほぼそのままに動くなんて不思議ですね :sparkles:

4
3
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
4
3