Decimal Arithmetic Operations

in

Do your calculations leave you feeling like a mathematician on acid? Today we’re going to talk about decimal arithmetic operations the sane alternative to floating-point madness.
First: what is decimal arithmetic? It’s simply math using base 10 instead of base 2 (binary). Instead of dealing with those ***** bits and bytes, we can use whole numbers and decimals like normal humans do!
So how does it work in Python? Well, let me show you. First, import the decimal module:

# Import the decimal module
import decimal

# Create a decimal object with a value of 10
num1 = decimal.Decimal(10)

# Create a decimal object with a value of 3.5
num2 = decimal.Decimal(3.5)

# Add the two decimal objects and store the result in a new decimal object
result = num1 + num2

# Print the result
print(result)

# Output: 13.5

Now, set your context to 10 digits of precision (you can adjust this as needed):

# Set the precision of decimal numbers to 10 digits
decimal.getcontext().prec = 10

And that’s it! You’re ready to start doing some sane math. Let’s say you want to add two numbers:

# This script is used to add two decimal numbers and print the result.

# Import the decimal module to perform calculations with decimal numbers.
import decimal

# Define the first decimal number as a variable 'a' using the Decimal function from the decimal module.
a = decimal.Decimal('3.14')

# Define the second decimal number as a variable 'b' using the Decimal function from the decimal module.
b = decimal.Decimal('2.718')

# Add the two decimal numbers and store the result in a variable 'c'.
c = a + b

# Print the result of the addition.
print(c) # Output: 5.858

See how easy that was? No more worrying about rounding errors or floating-point weirdness! And what’s even better is that you can use decimal arithmetic for multiplication, division, and exponentiation as well:

# Import the decimal module to use decimal arithmetic
import decimal

# Create a decimal object with value 3 and assign it to variable a
a = decimal.Decimal('3')

# Create a decimal object with value 4 and assign it to variable b
b = decimal.Decimal('4')

# Multiply a and b and assign the result to variable c
c = a * b

# Print the value of c
print(c) # Output: 12

# Divide c by b and assign the result to variable d
d = c / b

# Print the value of d
print(d) # Output: 3.0

# Calculate the square of d and assign the result to variable e
e = d ** 2

# Print the value of e
print(e) # Output: 9.0

Decimal arithmetic operations in Python the sane alternative to floating-point madness. Give it a try !

SICORPS