Python における数値型とその演算

PythonBeginner
オンラインで実践に進む

はじめに

この実験(Lab)では、Python における数値型とその演算についての基礎的な理解を得ます。整数(integer)、ブール値(boolean)、浮動小数点数(floating-point)、複素数(complex number)の各型の特性、具体的にはそれらのイミュータビリティ(不変性)や、型およびメモリアドレスの確認方法を探ります。実践的な演習を通じて、異なる数値型間の変換方法や基本的な算術演算の実行方法を学び、Python の数値処理能力に関する知識を確固たるものにします。

整数型とブール型の探求

このステップでは、Python の整数型(int)とブール型(bool)のデータ型を探求します。整数は、10-50などの整数です。ブール値はTrueまたはFalseのいずれかの値を表し、整数のサブタイプです。

Python における重要な概念の一つがイミュータビリティ(不変性)です。数値型はイミュータブルであり、一度数値オブジェクトが作成されるとその値を変更することはできません。変数を新しい数値に再代入する場合、それはメモリ内の新しいオブジェクトを参照することになります。これを組み込み関数であるid()(オブジェクトの固有のメモリアドレスを返す)と、データ型を示すtype()関数を使用して確認できます。

実験(Lab)環境では、すでにファイルが作成されています。左側の WebIDE ファイルエクスプローラーで、~/project/number_types.pyファイルを開いてください。以下のコードをそのファイルに追加します。

## Demonstrate immutability of integers
a = 5
print(f"Initial value of a: {a}")
print(f"Type of a: {type(a)}")
print(f"ID of a: {id(a)}")

## Reassign 'a' to a new value
a = 6
print(f"\nNew value of a: {a}")
print(f"New ID of a: {id(a)}")

## Demonstrate boolean type
print("\n--- Boolean Types ---")
is_true = True
is_false = False
print(f"Value of is_true: {is_true}, Type: {type(is_true)}")
print(f"Value of is_false: {is_false}, Type: {type(is_false)}")

## Booleans behave like integers (1 and 0) in arithmetic
print(f"\nTrue + 5: {True + 5}")
print(f"False * 3: {False * 3}")

コードを追加した後、ファイルを保存します。スクリプトを実行するには、WebIDE の統合ターミナルを開き、次のコマンドを実行します。

python ~/project/number_types.py

以下のような出力が表示されるはずです。メモリアドレス(ID)はシステムによって異なりますので注意してください。

Initial value of a: 5
Type of a: <class 'int'>
ID of a: <memory_address_1>

New value of a: 6
New ID of a: <memory_address_2>

--- Boolean Types ---
Value of is_true: True, Type: <class 'bool'>
Value of is_false: False, Type: <class 'bool'>

True + 5: 6
False * 3: 0

この出力は、a5から6に再代入されたときに ID が変化したことを示しており、新しい整数オブジェクトが作成されたことを裏付けています。また、計算においてTrue1として、False0として扱われることも実証されています。

浮動小数点数の操作

このステップでは、小数点を持つ実数を表す浮動小数点数(float)を扱います。浮動小数点数でよくある問題は、それらがバイナリ形式で保存されるため、精度が限られていることです。これにより、計算でわずかな不正確さが生じることがあります。

この動作を探ってみましょう。再度~/project/number_types.pyを開き、ファイルの末尾に以下のコードを追加します。このコードは精度の問題を実証し、それに対処する 2 つの方法、すなわち単純な丸め処理のためのround()関数と、高精度な算術演算のためのdecimalモジュールを紹介します。

## Demonstrate floating-point numbers and precision
print("\n--- Floating-Point Numbers ---")
result = 1.1 + 2.2
print(f"1.1 + 2.2 = {result}")

## Using round() for approximation
print(f"round(result, 1) = {round(result, 1)}")

## Using the decimal module for accurate calculations
from decimal import Decimal

## Pass numbers as strings to Decimal to avoid initial float inaccuracy
d1 = Decimal('1.1')
d2 = Decimal('2.2')
decimal_result = d1 + d2
print(f"Decimal('1.1') + Decimal('2.2') = {decimal_result}")

ファイルを保存し、ターミナルからスクリプトを再度実行します。

python ~/project/number_types.py

出力には、以下のセクションが含まれるようになります。

--- Floating-Point Numbers ---
1.1 + 2.2 = 3.3000000000000003
round(result, 1) = 3.3
Decimal('1.1') + Decimal('2.2') = 3.3

ご覧のとおり、標準の浮動小数点数の加算 1.1 + 2.2 は厳密には 3.3 になりません。round()は出力の整形に役立ちますが、decimalモジュールは正確な小数表現で計算を実行する方法を提供し、正確な結果をもたらします。

複素数の導入

Python は複素数(complex numbers)を組み込みでサポートしており、これは多くの科学および工学分野で不可欠です。複素数は実部と虚部を持ち、a + bjの形式で記述されます。ここでjは虚数単位を表します。

この表記法を使用するか、complex(real, imag)コンストラクタを使用して複素数を作成できます。実部と虚部は、.realおよび.imag属性を使用してアクセスできます。

~/project/number_types.pyファイルの編集を続行します。複素数を探求するために、以下のコードをファイルの末尾に追加してください。

## Demonstrate complex numbers
print("\n--- Complex Numbers ---")
c1 = 3 + 4j
print(f"Complex number c1: {c1}")
print(f"Type of c1: {type(c1)}")
print(f"Real part of c1: {c1.real}")
print(f"Imaginary part of c1: {c1.imag}")

## Creating a complex number with the constructor
c2 = complex(5, -2)
print(f"\nComplex number c2: {c2}")
print(f"Real part of c2: {c2.real}")
print(f"Imaginary part of c2: {c2.imag}")

ファイルを保存し、ターミナルからスクリプトを再度実行します。

python ~/project/number_types.py

新しい出力は次のようになります。

--- Complex Numbers ---
Complex number c1: (3+4j)
Type of c1: <class 'complex'>
Real part of c1: 3.0
Imaginary part of c1: 4.0

Complex number c2: (5-2j)
Real part of c2: 5.0
Imaginary part of c2: -2.0

整数で定義した場合でも、実部と虚部の両方が浮動小数点数として格納されることに注意してください。

数値型の変換

Python には、int()float()complex()など、異なる数値型間を変換するための組み込み関数が用意されています。これは型キャスト(type casting)として知られています。

  • int(x): xを整数に変換します。浮動小数点数を変換する場合、小数部分を切り捨て(切り取る)し、丸めは行いません。
  • float(x): xを浮動小数点数に変換します。
  • complex(real, imag): 複素数を作成します。

型変換を練習してみましょう。~/project/number_types.pyスクリプトの末尾に、以下のコードを追加してください。

## Demonstrate type conversion
print("\n--- Type Conversion ---")

## Convert float to int (truncation)
float_num = 9.9
int_num = int(float_num)
print(f"float_num = {float_num}")
print(f"int(float_num) = {int_num}")

## Convert int to float
int_val = 10
float_val = float(int_val)
print(f"\nint_val = {int_val}")
print(f"float(int_val) = {float_val}")

## Convert string to number
str_num = "123.45"
converted_float = float(str_num)
converted_int = int(float(str_num)) ## Must convert to float first
print(f"\nstr_num = '{str_num}'")
print(f"float(str_num) = {converted_float}")
print(f"int(float(str_num)) = {converted_int}")

ファイルを保存し、スクリプトをもう一度実行します。

python ~/project/number_types.py

出力には、このセクションが含まれるようになります。

--- Type Conversion ---
float_num = 9.9
int(float_num) = 9

int_val = 10
float(int_val) = 10.0

str_num = '123.45'
float(str_num) = 123.45
int(float(str_num)) = 123

この出力は、int()9.9の小数部分を9にどのように切り捨てるかを明確に示しています。また、小数を含む文字列を整数に変換するために必要な 2 段階のプロセスも示しています。

基本的な算術演算の実行

Python は、すべての標準的な算術演算をサポートしています。異なる数値型(例:intfloat)のオペランドに対して演算を実行すると、Python は自動的に結果をより一般的な型に「昇格」(widens)させます。階層は int -> float -> complex です。

一般的な演算子を以下に示します。

  • + (加算)
  • - (減算)
  • * (乗算)
  • / (除算 - 常に float を返します)
  • // (切り捨て除算 - 割り算を行い、最も近い整数に切り捨てます)
  • % (剰余 - 除算の余りを返します)
  • ** (べき乗)

探求を締めくくるために、これらの演算を練習するために~/project/number_types.pyに最後のセクションを追加しましょう。

## Demonstrate basic arithmetic operations
print("\n--- Basic Arithmetic Operations ---")
a = 10
b = 3

print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b}")
print(f"{a} // {b} = {a // b}")
print(f"{a} % {b} = {a % b}")
print(f"{a} ** {b} = {a ** b}")

## Demonstrate mixed-type operations
print("\n--- Mixed-Type Operations ---")
int_op = 5
float_op = 2.5
result_mixed = int_op * float_op
print(f"{int_op} (int) * {float_op} (float) = {result_mixed} ({type(result_mixed)})")

ファイルを保存し、完全なスクリプトを実行します。

python ~/project/number_types.py

最終的な出力には以下が含まれます。

--- Basic Arithmetic Operations ---
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3.3333333333333335
10 // 3 = 3
10 % 3 = 1
10 ** 3 = 1000

--- Mixed-Type Operations ---
5 (int) * 2.5 (float) = 12.5 (<class 'float'>)

この出力は、各演算子の動作を確認するものです。標準除算 / が float を返し、切り捨て除算 // が整数を返すことに注目してください。整数と浮動小数点数間の混合型演算は、予想通り float になります。

まとめ

この実験(Lab)では、Python の数値データ型に関する強固な基礎を築きました。整数(integers)、ブール値(booleans)、浮動小数点数(floats)、複素数(complex numbers)について学びました。また、イミュータビリティ(immutability)の概念を探求し、id()関数とtype()関数を使用してオブジェクトを検査しました。さらに、decimalモジュールを使用した浮動小数点数の精度問題の処理、int()float()complex()を使用した異なる数値型間の変換、および一連の算術演算の実行を実践しました。この知識は、Python における今後のプログラミングやデータ分析タスクにとって極めて重要です。