Editing Cookbook
Jump to navigation
Jump to search
The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then publish the changes below to finish undoing the edit.
Latest revision | Your text | ||
Line 1: | Line 1: | ||
An Octave cookbook. Each entry should go in a separate section and have the following subsection: problem, solution, discussion and maybe a see also. | An Octave cookbook. Each entry should go in a separate section and have the following subsection: problem, solution, discussion and maybe a see also. | ||
== Input/output == | == Input/output == | ||
== Mathematics == | == Mathematics == | ||
=== Find if a number is even/odd === | === Find if a number is even/odd === | ||
==== Problem ==== | ==== 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. | 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 ==== | ==== 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 {{Codeline|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 ==== | ==== Discussion ==== | ||
Since we are checking for the remainder of a division, the first choice would be to use {{Codeline|rem()}}. However, in the case of negative numbers {{Codeline|mod()}} will still return a positive number making it easier for comparisons. Another alternative is to use {{Codeline|bitand (X, 1)}} or {{Codeline|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, or non-integer values. | |||
==== See also ==== | |||
Find if a number is an integer. | |||
== Plotting == | |||
== User input == |