Python Floating Point (float) Type: Basics, E-notation, and Calculation Errors

In Python, besides integers (int) like 10 or -5, we often need to handle numbers with decimal points like 3.14 or 0.5. These are called Floating Point Numbers (float).float is essential for many programming tasks, such as scientific calculations, statistics, or simply representing the result of a division.

This article explains the basic usage of the float type, exponential notation, and the most important thing to watch out for: “calculation errors.”


目次

Basic Usage of float

By including a decimal point in a number, it is automatically treated as a float type.

# Approximate value of Pi
pi_approx = 3.14159

# Average score
average_score = 82.75

# Temperature
temperature = -12.5

# Check type with type()
print(f"Type of 'average_score': {type(average_score)}")

Output:

Type of 'average_score': <class 'float'>

Result of Division (/)

In Python, even if you divide two integers (int), using the / operator always results in a float.

total_items = 15
user_count = 4

# 15 / 4 = 3.75
items_per_user = total_items / user_count

print(f"Items per user: {items_per_user}")
print(f"Result type: {type(items_per_user)}")

Output:

Items per user: 3.75
Result type: <class 'float'>

Exponential Notation (E-notation)

When writing very large or very small numbers, Exponential Notation (Scientific Notation) is convenient. This is expressed using e or E.a e b means “a times 10 to the power of b” ($a \times 10^b$).

# 4.5e8 = 4.5 * 10^8 = 450,000,000.0
large_value = 4.5e8
print(f"Large value: {large_value}")

# 3.0e-5 = 3.0 * 10^-5 = 0.00003
small_value = 3.0e-5
print(f"Small value: {small_value}")

Output:

Large value: 450000000.0
Small value: 3e-05

The Most Important Note: Calculation Errors

The decisive difference between float and int is the issue of “Calculation Errors.”

Computers handle numbers internally in binary (0s and 1s). While some decimals like 0.5 ($1/2$) can be represented exactly in binary, others like 0.1 or 1.1 become infinite fractions in binary and cannot be represented exactly.

This can lead to counter-intuitive results.

# Calculate 1.1 + 2.2
val_a = 1.1
val_b = 2.2
sum_val = val_a + val_b

# Expected value is 3.3
print(f"Calculation Result: {sum_val}")
print(f"Is it equal to expected 3.3?: {sum_val == 3.3}")

Output:

Calculation Result: 3.3000000000000003
Is it equal to expected 3.3?: False

The result of 1.1 + 2.2 became slightly off, like 3.3000000000000003, instead of exactly 3.3. This is the float calculation error.

How to Handle Errors

This error is due to the float specification (IEEE 754 standard) and cannot be avoided, but there are ways to deal with it.

1. Rounding with round()

Use the round() function to round the number to a specific decimal place before comparing. Note that this is an approximate comparison.

# Round to 5 decimal places before comparing
if round(sum_val, 5) == 3.3:
    print("With round(), it is considered almost 3.3.")

Output:

With round(), it is considered almost 3.3.

2. Using the decimal Module (Strict Calculation)

For financial calculations (money) or scientific calculations where errors are not allowed, it is strongly recommended to use the decimal module instead of float.decimal calculates numbers as decimals without converting them to binary.

from decimal import Decimal

# Note: Pass as a string "..." when converting to Decimal, not as a float
dec_a = Decimal("1.1")
dec_b = Decimal("2.2")

dec_sum = dec_a + dec_b

print(f"Decimal Calculation Result: {dec_sum}")
print(f"Is it equal to Decimal('3.3')?: {dec_sum == Decimal('3.3')}")

Output:

Decimal Calculation Result: 3.3
Is it equal to Decimal('3.3')?: True

By using Decimal, we got the expected result of 3.3.


Summary

  • float handles numbers with decimal points.
  • The result of division / is always float.
  • You can use E-notation like 4.5e8.
  • float always comes with “Calculation Errors” due to binary representation. 1.1 + 2.2 does not equal 3.3.
  • If you need strict calculations (especially for money), consider using the decimal module instead of float.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次