Using Integer Math instead of Floating Point for Speed

Using Integer Math instead of Floating Point for Speed

It’s a well-known fact that integer calculations are much faster than using real types like float, double or decimal. We don’t usually think about it that much these days because of the maths co-processors built into modern CPU’s. Recently, thanks to the Raspberry Pi and like, I’ve remembered my first love of Electronics and have being playing with a few CPU that are much less sophisticated.

On some small microprocessors you have to write code or use a library that will simulate and carry out your floating point calculations. The difference in execution speed between using an integer and using a float in a loop may be a factor of a 1000 times faster. I’ve noticed that the Raspberry Pi is slow and it got me thinking that JavaScript is no speed demon either.

It reminded me of a little trick we used to use in the old days of the Z80 and 8048, and that was to use integer calculations instead of floats. Let me explain:

You probably know that Pi can be approximated by 22/7, which only gives the value correct to 2 decimal places.

But 355/113 is correct to 6 decimal places.

And 103993/33102 is correct to 9 decimal places.

Pi is actually mathematically irrational (i.e. it cannot be written exactly as the ratio of two integers).

Some well known mathematical constants as Rational Number approximations (‘fractions’)

Constant Rational
Number

Decimal
Accuracy

Number
Generated
Actual
Number
Pi 22/7

2

3.14285 3.14159
Pi 355/113

6

3.141592920 3.141592653
Pi 103993/33102

9

3.141592653011 3.1415926535897
√2 19601/13860

8

1.41421356421 1.41421356237
√3 18817/10864

7

1.7320508100 1.7320508075
√10 27379/8658

8

3.16227766227 3.16227766016
c (speed light) 24559/8192

6

2.997924804 2.997924580
e (Eulers) 25946/9545

8

2.71828182294 2.71828182845

Floats may be more convenient, but integers are definitely faster. Have you got any useful ones to add?

2 thoughts on “Using Integer Math instead of Floating Point for Speed

  1. Fortunately, the latest version of Raspbian (2012-9-18) includes a tool to help you ramp up the speed while keeping an eye on the temperature. Since this is an official tool, using it won’t void your warrantee (unlike earlier unofficial methods).

  2. I can only offer a view based on my experience. I use 2 raspberry pi’s as mini servers and never turn them off. My first Pi is now well over 4 months old and has probably been ‘off’ for less than a few hours during all that time. I use it pretty heavily as an iPlayer download and podcast host, which does a reasonable amount of reads and writes of the SD card.

Comments are closed.