Created
May 24, 2018 08:30
-
-
Save ronekko/e297ce9dc1e856fc189a229bd2755e90 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Created on Thu May 24 17:00:23 2018 | |
@author: sakurai | |
""" | |
import numpy as np | |
import sympy.geometry as sg | |
# Copied from https://github.com/is0280fp/Side-by-Side-Walking-Model/blob/009779de45ca13efa3ff9fff836ad7aa685d344f/line_math.py#L22 | |
# 点p1と点p2を結ぶ直線上のp1=(x1, y1)から同じ直線上で距離r離れた点を求める | |
def other_p_1(p1, p2, r): | |
center = sg.Point(p1[0], p1[1]) | |
radius = r | |
circle = sg.Circle(center, radius) | |
line = sg.Line(sg.Point(p1[0], p1[1]), sg.Point(p2[0], p2[1])) | |
return np.array(sg.intersection(circle, line), np.float) | |
# Numpy implementation | |
# 点p1と点p2を結ぶ直線上のp1=(x1, y1)から同じ直線上で距離r離れた点を求める | |
def other_p_2(p1, p2, r): | |
v12 = p2 - p1 | |
distance = np.linalg.norm(v12) | |
unit_vector = v12 / distance | |
return np.array([p1 - r * unit_vector, p1 + r * unit_vector]) | |
if __name__ == '__main__': | |
p1 = np.array([0, 0], np.float64) | |
p2 = np.array([2, 2], np.float64) | |
r = 1 | |
center_p_1 = other_p_1(p1, p2, r) | |
center_p_2 = other_p_2(p1, p2, r) | |
np.testing.assert_allclose(center_p_1, center_p_2) | |
# IPython コンソール上で | |
# ``` | |
# timeit other_p_1(p1, p2, r) | |
# ``` | |
# を実行すると `other_p_1(p1, p2, r)` の平均実行時間が計測できます. | |
# ↓は2つの実装の実行時間を比較してみた結果です(numpyのほうが4000倍速い) | |
# timeit other_p_1(p1, p2, r) | |
# 45 ms ± 467 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) | |
# timeit other_p_2(p1, p2, r) | |
# 7.48 µs ± 123 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment