2つの直線が交わる座標を求める関数を作ってみました。
引数で渡す直線の方程式オブジェクトには、
y軸に平行な場合y、
x軸に平行な場合x、
それ以外の場合はy=mx+nの形式でmとnの値を格納してください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# 2つの直線が交わる座標を求める def calcIntersection(line1, line2): if "y" in line1: # line1がy軸に平行な直線の場合 y = line1["y"] if "x" in line2: # line2がx軸に平行な直線の場合 x = line2["x"] else: x = (y - line2["n"]) / line2["m"] elif "x" in line1: # line1がx軸に平行な直線の場合 x = line1["x"] if "y" in line2: # line2がy軸に平行な直線の場合 y = line2["y"] else: y = line2["m"] * x + line2["n"] elif "y" in line2: # line2がy軸に平行な直線の場合 y = line2["y"] x = (y - line1["n"]) / line1["m"] elif "x" in line2: # line2がx軸に平行な直線の場合 x = line2["x"] y = line1["m"] * x + line1["n"] else: x = (line2["n"] - line1["n"]) / (line1["m"] - line2["m"]) y = line1["m"] * x + line1["n"] return {"x": x, "y": y} |
実際に動かしてみます。
1 2 3 4 5 6 7 8 |
# -*- coding: utf-8 import json line1 = {"m": 3,"n": 2} line2 = {"m": -3,"n": 2} # 2つの直線が交わる座標を求める print("2つの直線が交わる座標を求める") print(json.dumps(calcIntersection(line1, line2), indent=4)) |
1 2 3 4 5 |
2つの直線が交わる座標を求める { "x": 0.0, "y": 2.0 } |

1 2 3 4 5 6 7 8 |
# -*- coding: utf-8 import json line1 = {"x": 5} line2 = {"m": -3,"n": 2} # 2つの直線が交わる座標を求める print("2つの直線が交わる座標を求める") print(json.dumps(calcIntersection(line1, line2), indent=4)) |
1 2 3 4 5 |
2つの直線が交わる座標を求める { "x": 5, "y": -13 } |
