目次
工作HardwareHubからのお知らせ
Pythonの数値計算では、C言語などと比較して除算の扱いが多少異なりますが、概ね同じ感覚で記述できます。
sample.py
print int(3.14)
print float(3)
print int(3.14)/4 # バージョン3以降はこのような書き方でも小数点以下が切り捨てられなくなる (=> 0.75) 予定
print float(3)/4
print 3.0//4 # そのため、切り捨てたい場合は//演算子 (いかなる場合でも小数点以下を切り捨てる) を使用する
print round(2.189)
print round(2.189, 1)
print round(2.189, 2)
出力例
$ python sample.py
3
3.0
0
0.75
0.0
2.0
2.2
2.19
mathモジュール
sample.py
import math
print math.pi
print math.e
print math.sqrt(2.0)
print math.sin(math.pi/2.0)
出力例
$ python sample.py
3.14159265359
2.71828182846
1.41421356237
1.0
randomモジュール
sample.py
import random
print random.random()
print random.randint(1,10) # 1,2,3,...,10 (random integer in range [a, b])
print random.choice(['a','b','c'])
出力例
$ python sample.py
0.121619123686
9
a
関連記事
- Python コードスニペット (条件分岐)if-elif-else sample.py #!/usr/bin/python # -*- coding: utf-8 -*- # コメント内であっても、ASCII外の文字が含まれる場合はエンコーディング情報が必須 x = 1 # 一行スタイル if x==0: print 'a' # 参考: and,or,notが使用可能 (&&,||はエラー) elif x==1: p...
- Python コードスニペット (リスト、タプル、ディクショナリ)リスト range 「0から10まで」といった範囲をリスト形式で生成します。 sample.py print range(10) # for(int i=0; i<10; ++i) ← C言語などのfor文と比較 print range(5,10) # for(int i=5; i<10; ++i) print range(5,10,2) # for(int i=5; i<10;...
- ZeroMQ (zmq) の Python サンプルコードZeroMQ を Python から利用する場合のサンプルコードを記載します。 Fixing the World To fix the world, we needed to do two things. One, to solve the general problem of "how to connect any code to any code, anywhere". Two, to wra...
- Matplotlib/SciPy/pandas/NumPy サンプルコードPython で数学的なことを試すときに利用される Matplotlib/SciPy/pandas/NumPy についてサンプルコードを記載します。 Matplotlib SciPy pandas [NumPy](https://www.numpy
- pytest の基本的な使い方pytest の基本的な使い方を記載します。 適宜参照するための公式ドキュメントページ Full pytest documentation API Reference インストール 適当なパッケージ