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?

プログラミング習得ログ math関数を使って座標計算

Last updated at Posted at 2025-07-06

お題は以下

def calculate_distance_and_midpoint(point1, point2):
    """
    2つの座標点間の距離と中点を計算する関数
    """
    # 距離の公式: √((x2-x1)² + (y2-y1)²)
    # 中点の公式: ((x1+x2)/2, (y1+y2)/2)
    # math.sqrt() を使用(import math が必要)
    # ここにコードを書いてください
    pass

# 期待する動作
import math
point_a = (1, 2)
point_b = (4, 6)
distance, midpoint = calculate_distance_and_midpoint(point_a, point_b)
print(f"距離: {distance:.2f}")
print(f"中点: {midpoint}")
# 距離: 5.00
# 中点: (2.5, 4.0)

私がうんうんと考えて書いたコード

def calculate_distance_and_midpoint(point1, point2):
    """
    2つの座標点間の距離と中点を計算する関数
    引数: point1, point2 それぞれ (x, y) のタプル
    戻り値: (距離, 中点座標) のタプル
    """
    # 距離の公式: √((x2-x1)² + (y2-y1)²)
    # 中点の公式: ((x1+x2)/2, (y1+y2)/2)
    # math.sqrt() を使用(import math が必要)
    
    x1 , y1 = point1[0] , point1[1]
    x2 , y2 = point2[0] , point2[1]
    result1 = math.sqrt((x2-x1)**2 + (x2-x1)**2)
    result2 = math((x1+x2)/2 , (y1+y2)/2)
    return result1,result2

エラーが出る記述

 result2 = math((x1+x2)/2 , (y1+y2)/2)
 #math をモジュールとして関数呼び出している

モジュールは、関数、クラス、変数などをまとめた**Pythonファイル(.pyファイル)**のことです。コードを整理し、再利用可能にするための仕組みです。
モジュールの種類
標準ライブラリモジュール
Pythonに最初から含まれているモジュール

  • math - 数学関数
  • random - 乱数生成
  • datetime - 日時処理
  • os - オペレーティングシステム操作

外部モジュール(パッケージ)
別途インストールが必要:

  • numpy - 数値計算
  • pandas - データ分析
  • requests - HTTP通信

間違ってはないけどタプルのアンパックがまだ身についてない証拠

x1 , y1 = point1[0] , point1[1]
x2 , y2 = point2[0] , point2[1]
#以下が正解
x1 , y1 = point1
x2 , y2 = point2

以下の戻り値の名前はもっとわかりやすくしたほうがいいかも

return result1,result2
#変数のスコープから以下でも問題なし
return distance,midpoint
最終的に修正したコード

def calculate_distance_and_midpoint(point1, point2):
    """
    2つの座標点間の距離と中点を計算する関数
    """
    # 距離の公式: √((x2-x1)² + (y2-y1)²)
    # 中点の公式: ((x1+x2)/2, (y1+y2)/2)
    # math.sqrt() を使用(import math が必要)
    
    x1 , y1 = point1
    x2 , y2 = point2
    distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)
    midpoint = (x1+x2)/2 + (y1+y2)/2
    return distance,midpoint

# 期待する動作
import math
point_a = (1, 2)
point_b = (4, 6)
distance, midpoint = calculate_distance_and_midpoint(point_a, point_b)
print(f"距離: {distance:.2f}")
print(f"中点: {midpoint}")
# 距離: 5.00
# 中点: (2.5, 4.0)
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?