0
1

More than 1 year has passed since last update.

40代おっさんPythonを勉強する(数学関連や時間表現のモジュール)

Posted at

本記事について

この記事はプログラミング初学者の私が学んでいく中でわからない単語や概要を分かりやすくまとめたものです。
もし不正などありましたらコメントにてお知らせいただければ幸いです。

random

  • 疑似乱数を生成する
import random

print(random.choice([1, 2, 3, 4, 5,])) # リストから無造作で1つを返す
print(random.randint(15, 50)) # 15から50までに整数を1つ返す
print(random.random()) # 0.0から1.0までの間に浮動小数点数を1つ返す
print(random.sample(range(1000), k=20)) # 1000の中に整数に20個の整数リストを返す
n = [1, 2, 3, 4, 5]
print(random.shuffle(n)) # リストnをシャッフルする
print(n)

math

  • 数学関数
import math

#  入力引数はxとする
print(math.ceil(2.7)) # x以上の最小の整数を返す
print(math.floor(2.7)) # x以上の最大の整数を返す
print(math.fabs(-25)) # xの絶対値を返す
print(math.factorial(5)) # xの階乗を返す
print(math.fsum([0.1, 0.1, 0.1])) # iterbleの中の値の浮動小数点数の正確な和を返す
print(math.gcd(126, 366)) # 整数aとbの最大公約数を返す
print(math.pow(2, 3)) # xのy乗を返す
print(math.sqrt(25)) # xの平方根を返す
print(math.pi) # 数学定数 π = 3.141592......(円周率)
print(math.e) # 数学定数 e = 2718281.....(自然対数の底)

# 組み込み関数
print(round(2.546721, 2)) # 小数点以下2桁で四捨五入
print(abs(-2.55)) # 絶対値
print(sum([0.1, 0.1, 0.1])) # 総和

decimal

  • decimalモジュールは正確に丸められた十進浮動小数点数
import decimal as d

d.getcontext().prec = 6 # 計算精度を変更
print(d.Decimal(1) / d.Decimal(7)) # 結果 0.142857
d.getcontext().prec = 28 # 計算精度を変更
print(d.Decimal(1) / d.Decimal(7)) # 結果 0.1428571428571428571428571429

#  普通の数値と同じ演算子が使える
a, b, c = d.Decimal('1.34'), d.Decimal('1.87'), d.Decimal('3.45')
print(sum([a, b, c]))
print(str(a))
print(float(a))
print(round(a, 1))
print(int(a))
print(a * 5)
print(a * b)
print(c % a)

# いくつかの数学的な関数も用意されている
print(c.sqrt()) # 平方根
print(c.exp()) # (自然)指数関数
print(c.ln()) # 自然対数(底eの対数)
print(c.log10()) # 底10の対数

datetime

  • 基本的な日付型および時間型
from datetime import date, datetime
today = date.today()
print(today)
print(today.strftime("%m-%d-%y. %d %b %Y. Today is %A")) # 書式化コード
#  dateオブジェクトは演算できる
#  自分の誕生日を入れてみよう
birthday = date(1980, 11, 15)
age = today - birthday
print(f'あなたは生後 {age.days} 日です')
y, d = divmod(age.days, 365) # 閏年がないと仮定
print(f'あなたは約 {y}{d} 日です')

years_old = today.year - birthday.year - \
    ((today.month, today.day) < (birthday.month, birthday.day)) # 誕生日過ぎているか判定
print(f'あなたは {years_old} 41歳です')

参考

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