Fixed Point Arithmetic in Python

Alright! Are you ready for some math-y goodness? Let’s talk about fixed point arithmetic in Python the coolest way to do calculations without using floating points (which can be a pain).

To begin with: what is fixed point arithmetic? It’s basically a fancy term for representing numbers with a fixed number of decimal places. For example, instead of storing 3.14 as a float in Python (which has an infinite number of decimal places), we can store it as a fixed-point number like this: 6550.

Wait, what? How did we get that value from pi? Well, let’s do some math! If you multiply 2 to the power of 16 (which is 65536) by 0.0009765625 (the first six decimal places of pi), you get 6550.4030536816 pretty close, right?

Now that we know how to convert a floating-point number into fixed point format, let’s see how it works in Python! Here’s an example:

import math # import the math module to access mathematical functions
from decimal import * # import the decimal module to work with fixed-point numbers
getcontext().prec = 32 # set the precision for our calculations to 32 decimal places

# define some constants as fixed-point numbers
PI_FP = int(math.pi*65536) # convert pi to fixed-point format by multiplying it by 2^16
TWO_16 = int(2**16) # calculate 2^16 and convert it to fixed-point format

def add_fp(x, y):
    """Adds two fixed-point numbers"""
    x_int = (x * TWO_16) // 1000 # convert x to integer with decimal places set to 3 by multiplying it by 2^16 and dividing by 1000
    y_int = (y * TWO_16) // 1000 # convert y to integer with decimal places set to 3 by multiplying it by 2^16 and dividing by 1000
    result = (x_int + y_int) // 1000 # add the integers and divide by 1000 to get fixed-point format back
    return result

def mul_fp(x, y):
    """Multiplies two fixed-point numbers"""
    x_int = (x * TWO_16) // 1000 # convert x to integer with decimal places set to 3 by multiplying it by 2^16 and dividing by 1000
    y_int = (y * TWO_16) // 1000 # convert y to integer with decimal places set to 3 by multiplying it by 2^16 and dividing by 1000
    result = ((x_int*y_int)//TWO_16)*1000 # multiply the integers and divide by 2^16 to get fixed-point format back
    return result

# test our functions with some examples!
print(add_fp(PI_FP, PI_FP)) # should print something close to 6550.810430816 (which is 2*pi)
print(mul_fp(PI_FP, 2)) # should print something close to 13107.2019638352 (which is 2*pi*2)

Fixed point arithmetic in Python a fun and efficient way to do calculations without worrying about floating-point errors. Give it a try !

SICORPS