Changing the mode
Keywords: pame

Subsections

- Exercises

#
Changing the mode

We have seen that in a strong context, a value of mode `INT` can be coerced by widening to a value of mode `REAL`. What about the other way round? Is it possible to coerce a value of mode `REAL` to a value of mode `INT`? Fortunately, it is impossible using coercion. The reason behind this is related to the fact that real numbers can contain fractional parts. In replacing an integer by a real number there is no essential change in the value, but when a real number is changed to an integer, in general the fractional part will be lost. It is undesirable that data should be lost without the programmer noticing.

If you want to convert a `REAL` value to an `INT`, you must use one of the operators `ROUND` or `ENTIER`. The operator `ROUND` takes a single operand of mode `REAL` and yields an `INT` whose value is the operand rounded to the nearest integer. Thus `ROUND 2.7` yields `3`, and `ROUND 2.2` yields `2`. The same rule applies with negative numbers, thus `ROUND -3.6` yields `-4`. At the half way case, for example, `ROUND 2.5`, the value is rounded away from zero if the whole number part is odd, and rounded toward zero if it is even (zero, in this case, is taken to be an even number). This ensures that rounding errors over a large number of cases tend to cancel out.

The operator `ENTIER` (French for “whole”) takes a `REAL` operand and likewise yields an `INT` result, but the yield is the largest integer equal to or less than the operand. Thus `ENTIER 2.2` yields `2`, `ENTIER -2.2` yields `-3`.

The operator `SIGN` can also be used with a `REAL` operand. Its yield has mode `INT` with the same values as before, namely: `-1` if the operand is negative, `0` if it is zero, and `+1` if it is positive. We shall see in subsequent chapters that this property of `SIGN` can be useful.

## Exercises

2.9
  What is the value and mode of the yield of each of the following formulæ? Ans
  (a)
    `ROUND(3.0 - 2.5**2)`

  (b)
    `ENTIER -4.5 + ROUND -4.5`

  (c)
    `SIGN(ROUND 3.6 / 2.0) * 2.0`

2.10
  What is the value of the formula

      (ENTIER -2.9 + 3**2)/4.0

  Ans