## Implementing fixed point arithmetic in fsharp.

15 April 2019 – Karelia

I’ve just finished reading of extremely interesting book “Starting FORTH” by Leo Brodie and found an implementation details for fixed-point arithmetic(FixedPA). Actually there are some libs for doing FixedPA on dot net and at the same time I found several blog posts related to dot net with different implementations in c# but some of them were incorrect. So, this is a short description how FixedPA was implemented in old days in some Forth systems.

# Do we have FixedPA types in dot net’s System?

No, we don’t. We have only floating-point types: float, double and decimal. Some people think that Decimal is FixedPA but actually it is floating point type but with 10 as base. We are going to build our FFA lib using Int16 as a main data type. But you could trivially change it to use other types like Int32.

# The magic of scale function

At the heart of our library we will use magic scale function.

As you could see we multiply two Int16 and put the result into Int32 to prevent overflow. After that we divide Int32 by Int16 and return result as Int16. So how could we use it?

It is very useful because it allows to avoid overflows during multiplication. Now it is time to FixedPA. We are going to map fractions and floating numbers (Double) into our representation of fixed point numbers (Int16).

We have possibility to store values from -32768s to 32767s in Int16. And for example, we are going to use only floating-point numbers from -2. to 2. So, we have 1. mapped to 16384(in other case it could be 256 and so on) and 1.9999 mapped to 32767s and -2. mapped to -32768s. And finally, we need to define two operations multiplication and division. So basically to map a value into fixed world we need to multiply it by 16384(or just do binary left shift 14).

Actually, we’ve done. That’s all. We need first operation ./ to convert any fraction into our representation. Second one is for multiplication. We also need some helpers to move between floating and fixed worlds.

And some tests

Hope you have enjoyed simplicity and elegance of this solution.

The Philosophy of Fixed Point

Full code 