Kahibaro
Discord Login Register

Rounding, Modulo, and Special Values

Overview

This chapter focuses on three related topics that appear all the time when you work with numbers in MATLAB: rounding, modulo operations, and special numeric values. You will see how MATLAB represents these operations, which functions are available, and what to pay attention to when using them in your own code.

Rounding Numbers

Rounding is the process of converting a number to a nearby integer, following some rule. MATLAB provides several functions that implement different rounding behaviors. You should choose the one that matches the mathematical or practical rule you need.

`round`: To the nearest integer

The function round returns the nearest integer. By default, halfway values are rounded away from zero. For example, round(2.5) gives 3, and round(-2.5) gives -3. The basic syntax is

matlab
y = round(x);

where x can be a scalar, vector, matrix, or higher dimensional array, and y has the same size as x. MATLAB applies the rounding elementwise.

MATLAB also supports rounding to a specified number of decimal digits. For instance,

matlab
y = round(x, 2);

rounds x to two decimal places. If x = 3.14159, round(x, 2) returns 3.14. You can also round to a power of ten using a third argument in newer versions, but for beginners the digits argument is usually enough.

`floor`: Round toward negative infinity

The function floor always rounds toward negative infinity. This means it returns the greatest integer less than or equal to the input. For example,

matlab
floor(2.9)    % returns 2
floor(-2.1)   % returns -3

This directional behavior is important. With negative numbers, floor does not “drop the decimal,” it moves to the more negative integer.

floor is often used when you need a “lower bound” integer index or when you need to convert continuous coordinates to discrete bins where you always want to go down.

`ceil`: Round toward positive infinity

The function ceil always rounds toward positive infinity. It returns the smallest integer greater than or equal to the input. For example,

matlab
ceil(2.1)     % returns 3
ceil(-2.9)    % returns -2

Again, observe the behavior for negative numbers. ceil(-2.9) goes to -2, because that is the next integer in the positive direction.

ceil is useful when you want an “upper bound” integer index or when you need to ensure you never underestimate.

`fix`: Round toward zero

The function fix rounds toward zero, that is, it truncates the fractional part. It behaves like chopping off the decimals for positive and negative values:

matlab
fix(2.9)      % returns 2
fix(-2.9)     % returns -2

You can think of fix as keeping the sign and taking the integer part in magnitude. This is often used when you want simple truncation behavior that is symmetric around zero.

Comparing rounding behaviors

To see the differences, consider the same value with each function:

matlab
x = [-2.7 -2.5 -2.3 2.3 2.5 2.7];
round(x)  % nearest, halves away from zero
floor(x)  % toward -Inf
ceil(x)   % toward +Inf
fix(x)    % toward 0

The results show that these functions only differ when the number has a fractional part or when it is exactly at a halfway point, like ±2.5 for round.

When working with arrays, all of these functions operate elementwise and preserve the size and shape of the input.

Modulo and Remainder

Modulo-related operations compute integer remainders, which are useful for cyclic behavior, periodic patterns, indexing, and many discrete math tasks. MATLAB provides two related operations: mod and rem. They are similar for positive numbers, but behave differently when negative numbers are involved.

`mod`: Modulo operation

The function mod computes the remainder after division, with the result having the same sign as the divisor. The basic syntax is

matlab
r = mod(a, b);

Here r is the remainder after dividing a by b. For positive a and positive b, this matches the usual idea of modulo arithmetic. For example,

matlab
mod(10, 3)   % returns 1
mod(7, 2)    % returns 1
mod(8, 4)    % returns 0

For negative numbers, mod is defined such that

$$
\text{mod}(a, b) = a - b \cdot \left\lfloor \frac{a}{b} \right\rfloor
$$

where the floor function is used. As a result, the outcome always lies between 0 and b if b is positive. For instance,

matlab
mod(-10, 3)  % returns 2
mod(-1, 4)   % returns 3

This property makes mod especially useful when you need to wrap indices or angles into a fixed interval, such as mapping any angle into [0, 2*pi) or any index into the range 1 to n (with some adjustment).

`rem`: Remainder operation

The function rem also computes a remainder but uses truncation toward zero internally. The basic syntax is the same:

matlab
r = rem(a, b);

For positive inputs, rem and mod agree:

matlab
rem(10, 3)   % returns 1

For negative values, rem uses the formula

$$
\text{rem}(a, b) = a - b \cdot \text{fix}\left(\frac{a}{b}\right)
$$

Since fix rounds toward zero, the remainder keeps the sign of the dividend a. For example,

matlab
rem(-10, 3)  % returns -1
rem(10, -3)  % returns 1
rem(-10, -3) % returns -1

This differs from mod. The choice between mod and rem depends on which sign convention you want. In many applications that involve wrapping or periodicity, mod is preferred, because it yields results in a fixed nonnegative range when the divisor is positive.

Choosing between `mod` and `rem`

If you want a remainder that behaves like “wraparound” and stays between 0 and b for positive b, use mod. For instance, to map arbitrary integer time steps into a repeating cycle of length n, you can write

matlab
k = mod(t, n) + 1;

which gives indices in the range 1 to n.

If you want a remainder that aligns with truncation toward zero, for example when you conceptually think about a = q*b + r with q as fix(a/b), use rem.

When in doubt, for cyclical indexing, angle wrapping, and similar tasks, mod is usually the safer and more intuitive choice.

Special Numeric Values: `NaN`, `Inf`, and `-Inf`

MATLAB uses special numeric values to represent undefined or unbounded results. Understanding these values and how they behave is very important for numerical work, since they can propagate silently through calculations if you are not careful.

`Inf` and `-Inf`: Infinity

The values Inf and -Inf represent positive and negative infinity. They appear when an expression overflows the range of floating point numbers or when division by zero occurs in a meaningful mathematical sense. For example,

matlab
1 / 0       % returns Inf
-1 / 0      % returns -Inf
1e308 * 1e308

The last expression is too large to represent as a finite double precision number and produces Inf.

In arithmetic, Inf behaves as you would expect in many cases:

matlab
Inf + 1     % Inf
Inf * 2     % Inf
1 / Inf     % 0

However, some operations with infinity are undefined. For example,

matlab
Inf - Inf
0 * Inf
0 / 0
Inf / Inf

These yield NaN, which represents “Not a Number”.

`NaN`: Not a Number

The value NaN represents an undefined numeric result. It is still stored in numeric arrays and behaves like a numeric value in terms of type, but arithmetic with NaN usually produces NaN again. For example,

matlab
0/0        % NaN
Inf - Inf  % NaN
NaN + 1    % NaN
NaN * 5    % NaN

NaN is often used to mark missing data or invalid results, because it prevents you from accidentally using these values in further calculations without noticing. Many MATLAB functions provide options to ignore NaN values when computing statistics, but the default behavior is that NaN contaminates sums, means, and similar operations.

Testing for special values: `isnan`, `isinf`, and `isfinite`

You cannot compare NaN using ==. The expression NaN == NaN returns logical 0 (false). This is by design and follows the IEEE floating point standard. To test whether a value is NaN, use isnan:

matlab
x = [0/0, 1/0, 5];
isnan(x)    % returns [1 0 0]

Similarly, use isinf to test for infinity:

matlab
isinf(x)    % returns [0 1 0]

This is useful for detecting overflow or division by zero.

If you want to know whether a value is a finite number (that is, not Inf, not -Inf, and not NaN), use isfinite:

matlab
isfinite(x) % returns [0 0 1]

These functions work elementwise on numeric arrays and return logical arrays of the same size.

Behavior of rounding and modulo with special values

Rounding functions and modulo operations have specific behaviors with NaN and Inf.

If you apply round, floor, ceil, or fix to NaN, the result is NaN. If you apply them to Inf or -Inf, the result is still Inf or -Inf. For instance,

matlab
round(NaN)    % NaN
floor(Inf)    % Inf
ceil(-Inf)    % -Inf
fix(NaN)      % NaN

Similarly, if you pass NaN to mod or rem, the result is NaN. If you use Inf or -Inf as either operand in mod or rem, the behavior may not be meaningful and often results in NaN. For example,

matlab
mod(Inf, 3)   % NaN
rem(5, Inf)   % 5

In the second case, dividing 5 by infinity is effectively 0 with remainder 5, so the result is finite. Understanding these behaviors helps you reason about edge cases and avoid surprises.

Practical Considerations and Common Pitfalls

When writing code that uses rounding, modulo, and special values, there are a few patterns you will encounter frequently.

When you convert from continuous quantities to discrete indices, you should choose the rounding function that matches your indexing convention. In many cases floor or ceil is better than round, because it is asymmetric and easier to reason about for interval boundaries.

When you implement wrapping behavior, such as mapping any integer to a range 1:n, use mod with positive divisors and adjust for MATLAB’s one based indexing. A typical pattern is

matlab
idx = mod(k-1, n) + 1;

which maps any integer k into the set {1, 2, ..., n}.

When you read external data that has missing entries, you may convert missing markers to NaN. Many functions have options to ignore NaNs when computing statistics, which you will see elsewhere in the course. Until then, remember that basic arithmetic and simple aggregate functions like sum or mean will propagate NaN by default, so you should test for NaN when needed.

Finally, be cautious with comparisons. Testing equality with NaN using == never works as expected. Always use isnan. Likewise, if you suspect that some computations may overflow or divide by zero, use isinf or isfinite to detect these conditions and handle them explicitly in your code.

Important points to remember:
round, floor, ceil, and fix all round differently. Know which direction each one uses, especially for negative numbers.
Use mod for wraparound behavior. It returns nonnegative remainders for positive divisors, which is usually what you want for indexing and periodic patterns.
NaN represents undefined numeric results and spreads through calculations. You cannot use == to test for NaN. Use isnan instead.
Inf and -Inf represent overflow or division by zero. Use isinf and isfinite to detect and handle these special values.

Views: 3

Comments

Please login to add a comment.

Don't have an account? Register now!