Navigation:  Tutorials > Beginners Guide to Smalltalk > Objects and Messages >

Arithmetic

Previous pageReturn to chapter overviewNext page

Let's have a look at the messages for performing simple arithmetic on numbers.

300 + 400 "Addition"

3.141926 - 3 "Subtraction"

365.25 * 24 "Multiplication"

8766 // 24 "Integer division with truncation"

8766 / 24 "Standard division"

The interesting thing to note with Smalltalk arithmetic is that it is not necessary to match the types of numbers involved or to predict the type of the result. For example, it is perfectly reasonable to subtract an integer from a floating point number and arrive at an appropriate floating point result. You should also be familiar with the difference between the integer division and standard division messages. The former (//) will always truncate the result to the nearest whole integer below it. The latter (/) will maintain precision in the result by answering a fractional or floating point result as best it can.

The fact that Smalltalk arithmetic is capable of switching between different number representations in order to maintain precision wherever possible is a valuable concept. Wherever possible it will try to avoid using a floating point object to hold a value since many floating point calculations are inherently inaccurate in the lower decimal places. Using objects (of class Fraction) to represent fractional values can mean that ultimate precision can be maintained where it would otherwise be lost. For example:

6 / 18

 

If this irrational result had been coerced to a floating point value (0.333333) then any subsequent calculations on this value might lose precision. However, the fractional value (1/3) remains entirely accurate. The only problem might be that you don't wish to display a fraction as the end result of your calculation since most people find floating point print outs more acceptable. The answer is simple, just forcibly convert to the appropriate representation when you want to display the result. You can try this with:

(6 / 18) asFloat