【python】mathモジュールの使い方

python

python公式ドキュメントはこちら

mathモジュールはPythonで標準で用意されている数学計算用の関数を集めたモジュールです。

標準ライブラリなので、特にインストールをしなくてもPythonに最初から準備されています。そのため、文頭にimport mathと記述するだけで使用することができます。

目次

mathモジュールの書式

import math
math.関数名

mathモジュールの基本的な関数

math.pi(円周率)

math.piは戻り値として円周率を返します。

import math

print(math.pi)
# 3.141592653589793

from math import pi と宣言し、math.pi を呼びだしておけば、pi という名前で円周率を扱えます。

from math import pi

print(pi)
# 3.141592653589793

math.ceil(小数点以下の切り上げ)

math.ceilは戻り値として、小数点以下を切り上げた値を返します。

import math

print(math.ceil(4.3))
# 5
print(math.ceil(1.1))
# 2
print(math.ceil(6.8))
# 7

math.floor(小数点以下の切り捨て)

math.floorは戻り値として、小数点以下を切り捨てた値を返します。

import math

print(math.floor(4.3))
# 4
print(math.floor(1.1))
# 1
print(math.floor(6.8))
# 6

math.sqrt(平方根)

math.sqrtは戻り値として、平方根を返します。

import math

print(math.sqrt(1))
# 1.0
print(math.sqrt(4))
# 2.0
print(math.sqrt(9))
# 3.0

math.gcd(最大公約数)

math.gcdは戻り値として、引数に指定した最大公約数を返します。

import math

print(math.gcd(18, 30))
# 6
print(math.gcd(2, 16))
# 2
print(math.gcd(32, 68))
# 4

math.lcm(最小公倍数)

math.lcmは戻り値として、引数に指定した最小公倍数を返します。

import math

print(math.lcm(5, 12))
# 60
print(math.lcm(4, 6))
# 12
print(math.lcm(7, 9))
# 63

math.degrees(度)

math.degreesは戻り値として、引数に設定されたラジアン(弧度法)を度(度数法)に変換した値を返します。

import math

print(math.degrees(1))
# 57.29577951308232
print(math.degrees(4))
# 229.1831180523293
print(math.degrees(math.pi))
# 180.0

math.radians(ラジアン)

math.radiansは戻り値として、引数に設定された度(度数法)をラジアン(弧度法)に変換した値を返します。

import math

print(math.radians(30))
# 0.5235987755982988
print(math.radians(60))
# 1.0471975511965976
print(math.radians(90))
# 1.5707963267948966

math.sin(正弦)

math.sinは戻り値として、引数に指定したsinの値を返します。※引数はラジアン表記

import math

sin30 = math.sin(math.radians(30))
print(sin30)
# 0.49999999999999994
sin60 = math.sin(math.radians(60))
print(sin60)
# 0.8660254037844386
sin90 = math.sin(math.radians(90))
print(sin90)
# 1.0

math.cos(余弦)

math.cosは戻り値として、引数に指定したcosの値を返します。※引数はラジアン表記

import math

cos30 = math.cos(math.radians(30))
print(cos30)
# 0.8660254037844387
cos60 = math.cos(math.radians(60))
print(cos60)
# 0.5000000000000001
cos90 = math.cos(math.radians(90))
print(cos90)
# 6.123233995736766e-17

math.tan(正接)

math.tanは戻り値として、引数に指定したtanの値を返します。※引数はラジアン表記

import math

tan30 = math.tan(math.radians(30))
print(tan30)
# 0.5773502691896256
tan60 = math.tan(math.radians(60))
print(tan60)
# 1.7320508075688767
tan90 = math.tan(math.radians(90))
print(tan90)
# 1.633123935319537e+16
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

雇われのシステムエンジニアです。
普段は車載ECUのセキュリティー分野に従事しております。

■保有資格
Salesforce 認定 Platform アプリケーションビルダー
Salesforce 認定 Platform デベロッパー

コメント

コメントする

目次