Simple Math Isn’t So Simple

240px-SRPProductsAs I was reviewing some of the WORKS message board posts the other day, I came across a discussion that focused on the known problems of floating point arithmetic. This has been addressed over the years within the Revelation community but it continues to haunt developers (especially those who are converting R/Basic code to Basic+ and are wondering why their math doesn’t work as well…) To summarize the problem, run the following code in Basic+:

A = 1.07625
B = 1.0762
C = A - B

The result will be:


Which is the same as:


In our heads we can easy see that the expected result should be .00005. There is an old saying, it’s close enough for government work, which now means it’s not perfect, but it is close enough. Usually this is true for math operations in computer systems. However, there are those times when precision is a requirement.

Bob Carten from Revelation Software responded by suggesting the original poster use the extended math operators instead:

A = 1.07625
B = 1.0762
C = _subx(A, B)

Sure enough, it works! However, as if to throw cold water on this great recommendation, the good folks from Sprezzatura reminded the audience that the original poster is using OpenInsight 8 and that the extended math operators were introduced in OpenInsight 9.3. Ah shucks…

This brought back to mind why SRP has been developing tools for ourselves and the Revelation community for so many years: To improve the functionality of OpenInsight in ways that are not possible with the native tool kit. While many of our products are commercially sold, we also provide a wealth of free tools. Most notable are the various functions contained in the SRP Utilities package.

One of the features of the SRP Utilities is the SRP Math function, which provides a way to perform precise arithmetic operations within Basic+. The above logic would look like this using SRP_Math:

A = 1.07625
B = 1.0762
C = SRP_Math('SUBTRACT', A, B)

The SRP Utilities can be installed in any 32bit version of OpenInsight. Therefore, with regard to floating point arithmetic problem, releases prior to OpenInsight 9.3 can have improved precision when required.

In parting we will say that the extended operators available in OpenInsight 9.3 might be a preferred solution. These are instrinsic functions, which means they do not have to be declared as SRP_Math would. Also, they perform faster than SRP Math, probably for the same reasons. In our tests, the performance difference is only detected when large amounts of operations have to be performed in succession. When running the above operations in a tight loop for 100,000 iterations, the regular Basic+ operator took 15ms, the extended Basic+ operator took 313ms, and SRP_Math took 1.125ms. Thus, the differences are virtually negligible, but that will depend on the requirements of the task at hand.

Leave a Reply

Subscribe to Blog

Enter your email address to sign up for email notifications of new posts.