0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

sympy「−3x+4y+3=0の垂線」をAI先生に聞きました。

0
Last updated at Posted at 2026-02-07

(本日の)ChatGPT先生へ

sympy で、−3x+4y+3=0 の直線上で x = x0 の位置にある点を通り、その直線に 垂直な直線のユーザー定義関数を教えて下さい。引数は直線とx0

「直線 L と x0 を与えると,L 上の x=x0 の点を通り,L に垂直な直線を返すユーザー定義関数」という理解で説明します。
(回答省略) わからなかったので。

(本日の)Gemini3先生へ

(途中経過省略)

from sympy import *

def get_perpendicular_line(line_expr, x0):
    """
    line_expr: SymPyの式 (例: Line(A, B).equation())
    x0: 垂線を通る点のx座標
    """
    # 1. 式の中に含まれるシンボルをすべて取得
    # symbols はセット形式で返ってくるので、名前順でソートしてリスト化
    # 通常、[0]がx系、[1]がy系のシンボルになる
    found_vars = sorted(list(line_expr.free_symbols), key=lambda s: s.name)
    
    if len(found_vars) < 2:
        raise ValueError("式に2つ以上の変数が必要です。")
    
    v_x, v_y = found_vars[0], found_vars[1]
    
    # 2. yについて解く(IndexError対策のため、解が存在するか確認)
    solutions = solve(line_expr, v_y)
    if not solutions:
        raise ValueError(f"変数 {v_y} について解けませんでした。式を確認してください。")
    
    y_on_line = solutions[0]
    
    # 3. 指定のx0におけるy座標を特定
    y0 = y_on_line.subs(v_x, x0)
    p1 = Point(x0, y0)
    
    # 4. 直線オブジェクトを作成 (傾きを保持するため)
    p_a = Point(0, y_on_line.subs(v_x, 0))
    p_b = Point(1, y_on_line.subs(v_x, 1))
    base_line = Line(p_a, p_b)
    
    # 5. 垂直な直線を求め、入力と同じ変数名で式を返す
    perp_line = base_line.perpendicular_line(p1)
    return perp_line.equation(x=v_x, y=v_y)

# --- 動作確認 ---
AD, BD = 4, 2
degADB = 120
A = Point(AD, 0).rotate(rad(180-degADB))
B = Point(BD, 0).rotate(rad(180))

# equation() を引数なしで呼ぶと _x, _y が作られるが、
# 関数側でこれらを自動検知するようにしました。
line_eq = Line(A, B).equation()
mid_x = A.midpoint(B).x

print(f"元の式: {line_eq} = 0")

# 実行
mySuisen = get_perpendicular_line(line_eq, mid_x)
print(f"垂直な直線の式: {mySuisen} = 0")

# 元の式: 2*sqrt(3)*x - 4*y + 4*sqrt(3) = 0
# 垂直な直線の式: -x - sqrt(3)*y/2 + 3/2 = 0

いつもの? sympyの実行環境と 参考のおすすめです。

(テンプレート)

いつもと違うおすすめです。

sympy doc

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?