Cookbook

From Octave
Jump to navigation Jump to search

An Octave cookbook. Each entry should go in a separate section and have the following subsection: problem, solution, discussion and maybe a see also.

Mathematics

Find if a number is even/odd

Problem

You have a number, or an array or matrix of them, and want to know if any of them is an odd or even number, i.e., their parity.

Solution

Check the remainder of a division by two. If the remainder is zero, the number is odd.

 mod (value, 2) ## 1 if odd, zero if even

Since mod() acceps a matrix, the following can be done:

 any  (mod (values, 2)) ## true if at least one number in values is even
 all  (mod (values, 2)) ## true if all numbers in values are odd
 
 any (!logical (mod (values, 2))) ## true if at least one number in values is even
 all (!logical (mod (values, 2))) ## true if all numbers in values are even

Discussion

Since we are checking for the remainder of a division, the first choice would be to use rem(). However, in the case of negative numbers mod() will still return a positive number making it easier for comparisons. Another alternative is to use bitand (X, 1) or bitget (X, 1) but those are a bit slower.

Note that this solution applies to integers only. Non-integers such as 1/2 or 4.201 are neither even nor odd. If the source of the numbers are unknown, such as user input, some sort of checking should be applied for NaN, Inf, non-integer values.

See also

Find if a number is an integer.

Plotting

User input