Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Show precision differences between float and Decimal - Python Program

The following program demonstrates the precision differences between float and Decimal types in Python, particularly when dealing with numbers that cannot be precisely represented in binary floating-point arithmetic.

Example 1: Simple Program

from decimal import Decimal a = 1.1 + 2.2 b = Decimal("1.1") + Decimal("2.2") print("Float result:", a) print("Decimal result:", b)

Output

 
OUTPUT  :
Float result: 3.3000000000000003
Decimal result: 3.3
    

Example 2: Advanced Program

from decimal import Decimal, getcontext # Set the precision for Decimal operations (e.g., 50 digits) getcontext().prec = 50 # Demonstrate float precision issues print("--- Float Precision Demonstration ---") float_sum = 0.1 + 0.1 + 0.1 print(f"0.1 + 0.1 + 0.1 (float): {float_sum}") print(f"Is float_sum == 0.3? {float_sum == 0.3}") # Demonstrate Decimal precision print("\n--- Decimal Precision Demonstration ---") decimal_sum = Decimal('0.1') + Decimal('0.1') + Decimal('0.1') print(f"Decimal('0.1') + Decimal('0.1') + Decimal('0.1'): {decimal_sum}") print(f"Is decimal_sum == Decimal('0.3')? {decimal_sum == Decimal('0.3')}") # Further illustrate with a division print("\n--- Division Example ---") float_division = 1 / 3 print(f"1 / 3 (float): {float_division}") decimal_division = Decimal(1) / Decimal(3) print(f"Decimal(1) / Decimal(3): {decimal_division}") # Note: Directly converting a float to Decimal can carry over float's imprecision print("\n--- Float to Decimal Conversion ---") imprecise_decimal = Decimal(0.1) print(f"Decimal(0.1) (from float): {imprecise_decimal}")

Output

 
OUTPUT  :
--- Float Precision Demonstration ---
0.1 + 0.1 + 0.1 (float): 0.30000000000000004
Is float_sum == 0.3? False

--- Decimal Precision Demonstration ---
Decimal('0.1') + Decimal('0.1') + Decimal('0.1'): 0.3
Is decimal_sum == Decimal('0.3')? True

--- Division Example ---
1 / 3 (float): 0.3333333333333333
Decimal(1) / Decimal(3): 0.33333333333333333333333333333333333333333333333333

--- Float to Decimal Conversion ---
Decimal(0.1) (from float): 0.1000000000000000055511151231257827021181583404541015625

=== Code Execution Successful ===