• No results found

Relational and logical operators

Another type of predicate that is commonly used in programming are relational operators. These are used to compare two or more expressions and return a value of True or False. The relational operators in Mathematica are Equal ( ), Unequal ( ), Greater (>), Less (<), GreaterEqual( ), and LessEqual ( ). They can be used to compare num- bers or arbitrary expressions.

In[14]:= 7 5

In[15]:= Equal 3, 7 4, 6 2 Out[15]= True In[16]:= x2 1 x 4 1 x2 1 Simplify Out[16]= True

Note that the relational operators have lower precedence than arithmetic operators. The second example above is interpreted as 3 (7-4) and not as (3 7)-4. Table 2.1 lists the relational operators and their various input forms.

StandardForm Functional form Meaning

x y Equal x, y equal

x y Unequal x, y unequal

x y Greater x, y greater than

x y Less x, y less than

x y GreaterEqual x, y greater than or equal

x y LessEqual x, y less than or equal

Table 2.1: Relational operators

The logical operators (sometimes known as Boolean operators) determine the truth of an expression based on Boolean arithmetic. For example, the conjunction of two true statements is always true.

In[17]:= 4 5 && 8 1

Out[17]= True

The Boolean operation “and” is represented in Mathematica by And, with shorthand notation && or . Here is a table that gives all the possible values for the And operator. (The function TruthTable is developed in Chapter 10.)

In[18]:= TruthTable A B, A, B Out[18]//DisplayForm= A B A B T T T T F F F T F F F F

The logical “or” operator, represented by Or and with shorthand notation || (or ), is true when either of its arguments is true.

In[19]:= 4 3 3 6 2 Out[19]= True In[20]:= 0 0.0001 22 7 Out[20]= False

Note the difference between this Boolean “or” and the common notion of “or.” A phrase such as, “It is cold or it is hot,” uses the word “or” in an exclusive sense; that is, it excludes the possibility that it is both cold and hot. The logical Or is inclusive in the sense that if A and B are both true, then A||B is also true.

In[21]:= True True

Out[21]= True

Mathematica also contains an operator for the exclusive or, Xor.

In[22]:= Xor True, True

Out[22]= False

In[23]:= Xor True, False

Out[23]= True

Table 2.2 shows the logical operators and their input forms.

StandardForm Functional form Meaning

x Not x not

x y Unequal x, y unequal

x && y And x, y and

x y Or x, y or

x y && x && y Xor x, y exclusive or

Table 2.2: Logical operators

Introduced in Version 4 of Mathematica are the bitwise logical operators. These func- tions operate on integers as binary bits. For example, BitOr[x,y] gives the integer whose binary representation has 1s wherever the binary representation of x or y has 1s. Here is the bitwise OR of 21 and 19, given in binary form.

In[24]:= BaseForm BitOr 2^^10101, 2^^10011 , 2

Out[24]//BaseForm=

101112

Similarly, BitXor[x,y] gives the integer with 1s at positions where either x or y have 1s, but not both.

In[25]:= BaseForm BitXor 2^^10101, 2^^10011 , 2

Out[25]//BaseForm=

1102

Functional form Meaning

BitAnd x, y bitwise AND of x and y BitOr x, y bitwise OR of x and y BitNot x bitwise NOT of x BitXor x, y bitwise XOR of x and y

Table 2.3: Bitwise operators

In Chapter 4 we will look at an application of bitwise operators to an example involving error-correcting codes: the computation of Hamming distance.

Exercises

1. Create a predicate function that returns a value of True if its argument is between 1 and 1.

2. Write a predicate function NaturalQ[n] that returns a value of True if n is a natural number and False otherwise; that is, NaturalQ[n] is True if n is among 0, 1, 2, 3, ….

3. Create a predicate function SubsetQ[lis1,lis2] that returns a value of True if lis1 is a subset of lis2. Remember: the empty set {}, is a subset of every set.

2.4 Attributes

All functions in Mathematica have certain properties, called attributes. These attributes can make a function commutative or associative, or they may give the function the ability to be threaded over a list. The attributes of any function are displayed with the Attributes function.

In[1]:= Attributes Plus

Out[1]= Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected

The Flat attribute indicates that this function (Plus) is associative. That is, given three elements to add, it does not matter which two are added first. In mathematics, this is known as associativity and is written as a b c a b c. In Mathematica this could be

indicated by saying that the two expressions Plus[a, Plus[b, c]] and Plus[ Plus[a, b], c] are equivalent to the flattened form Plus[a, b, c]. When Mathe-

matica knows that a function has the attribute Flat, it writes it in flattened form.

In[2]:= Plus Plus a, b , c

Out[2]= a b c

The Orderless attribute indicates that the function is commutative; that is,

a b b a. This allows Mathematica to write such an expression in an order that is useful

for computation. It does this by sorting the elements into a canonical order. For expressions consisting of letters and words, this ordering is alphabetic.

In[3]:= t h i n

Out[3]= h i n t

Sometimes a canonical order is readily apparent. In[4]:= x3 x5 x4 x2 1 x

Out[4]= 1 x x2 x3 x4 x5

Other times, it is not so apparent.

In[5]:= x3y2 y7x5 y x4 y9x2 1 x

Out[5]= 1 x x4y x3y2 x5y7 x2y9

When a symbol has the attribute Protected, the user is prevented from modifying the function in any significant way. All built-in operations have this attribute.

Functions with the attribute OneIdentity have the property that repeated applica- tion of the function to the same argument will have no effect. For example, the expression

Plus[Plus[a, b]] is equivalent to Plus[a, b], hence only one addition is performed.

In[6]:= FullForm Plus Plus a b

Out[6]//FullForm=

Plus a, b

The other attributes for the Plus function, (Listable and NumericFunction) will be discussed in later chapters. Consult the manual (Wolfram 2003) for a complete list of the Attributes that symbols can have.

Although it is unusual to want to alter the attributes of a built-in function, it is fairly common to change the default attributes of a user-defined function. For example, suppose you had a function which you wanted to inherit the Orderless attribute. Without explicitly setting that attribute, the function does not reorder its arguments.

In[7]:= f x, a, m

Out[7]= f x, a, m

The SetAttributes function is used to change the attributes of a function. Explicitly setting f to have the Orderless attribute causes its arguments to be automatically sorted.

In[8]:= SetAttributes f, Orderless

In[9]:= f x, a, m

Out[9]= f a, m, x

The list is the fundamental data structure used in Mathematica to group objects together. A very extensive set of built-in functions is provided by Mathematica to manipulate lists in a variety of ways, ranging from simple operations, such as moving list elements around, to more sophisticated operations, such as applying a function to a list. We also discuss working with strings, as their structure and manipulation is so similar to lists.

3.1 Introduction

Many computations involve working with a collection of objects. For example, abstract mathematics deals with operations on arbitrary sets, represented notationally, but also conceptually, as lists.

In[1]:= a, b, c c, d, e

Out[1]= a, b, c, d, e

In[2]:= a, b, c c, d, e

Out[2]= c

Data, in Mathematica, is represented using lists. A large collection of functions is available for manipulating and analyzing lists of data. For example, you can sort any set of data.

In[3]:= Sort 4, 16, 1, 77, 23

Out[3]= 1, 4, 16, 23, 77

You can extract elements of a dataset based on some criteria. Here we select those numbers from a list that are greater than 0.

In[4]:= Select 4.9239, 1.24441, 0.80388, 3.27761 , Positive

Out[4]= 4.9239, 3.27761

Working with such collections of objects requires that the objects (also called data

to store data objects in a computer. The most often used data structure in Mathematica is the list. This is created using the built-in List function which has the standard input form of a sequence of arguments separated by commas and enclosed in braces.

arg1,arg2, …,argn

Lists are used throughout Mathematica, not only to represent a collection of data elements, but also to delineate a range of values for some variable or iterator. For example, the second argument to the Table function is a list that specifies the iterator variable and the values that it should range over.

In[5]:= Table i2, i, 1, 5

Out[5]= 1, 4, 9, 16, 25

Similarly, the plotting functions use lists to specify the range over which a variable should be evaluated.

In[6]:= Plot Sin x , x, 0, 2 ;

1 2 3 4 5 6

1 0.5 0.5 1

Internally, lists are stored in the functional form using the List function with some arbitrary number of arguments.

List arg1,arg2, …,argn

For example, using FullForm we can view the internal representation of the list {a,b,c}.

In[7]:= FullForm a, b, c

Out[7]//FullForm=

The arguments of the List function (the list elements) can be any type of expression, including numbers, symbols, functions, character strings, and even other lists.

In[8]:= 2.4, f, Sin, "ossifrage", 5, 3 , ,

Out[8]= 2.4, f, Sin, ossifrage, 5, 3 , ,

Elements in lists can be rearranged, sorted, removed, new elements added, and operations performed on select elements or on the list as a whole. In fact, lists are such general objects in Mathematica that they can be used to represent a vast array of objects.

In this chapter, we will demonstrate the use of built-in Mathematica functions to manipulate lists in various ways. In cases where the operation of a function is relatively straightforward, we will simply demonstrate its use without explanation (the on-line Help system and the The Mathematica Book (Wolfram 2003) should be consulted for more detailed explanations of all of the built-in functions). The underlying message here is that almost anything you might wish to do to a list can be accomplished using built-in func- tions. It is important to have as firm a handle on these functions as possible, since a key to good, efficient programming in Mathematica is to use the built-in functions whenever possible to manipulate list structures.

3.2 Creating and measuring lists