7.  Loops  and Conditional Branching

2015-04-27

$Version

7.1	Sums and Summation of Infinite Series

Sum[f,  {i,imax}] 		(∑_(i =1)^(i =imax))  	f
 				        	   
  Sum[f, {i,imin,imax} ]	(∑_(i =imin)^(i =imax))  	f
 							   
  Sum[f, {i,imin,imax,di}]	same as above but with increment   di									   
  Sum[f,{i,imin,imax},{j,jmin,jmax}] (∑_(i =imin)^(i =imax))  (∑_(j =jmin)^(j =jmax))	f	multiple sum					
  
  NSum[...] 			Numeric Sum

NSum[...]  need not be the same as N[Sum[...]], as in the first command Mathematica  uses numeric procedures right from the beginning, whereas in the second command Mathematica may start with analytic calculations.

Sum[k^2, {k,4}]

f = Sum[1/(i+1), {i,0,4}]

Sum[k^2, {k,n}]

f = Sum[q^n, {n,0,Infinity}]

f = Sum[.9^n, {n,0,Infinity}]

f = Sum[1/n, {n,0,Infinity}]

Power::infy ; Infiniteexpression  ∞ encountered.

Sum[(-1)^n/n,{n,Infinity}]

Sum[ (n-2k)^2 Binomial[n, k], {k,0,n} ]

Sum[1/k^4, {k,Infinity}]

Sum[x^k /k! , {k,Infinity} ]

Sum[1/k^3, {k,Infinity}]

?Zeta

◼ ζ(s)=(∑_(k=1)^∞)(k^(-s)). 
◼ ζ(s,a)=(∑_(k=0)^∞)(((k+a))^(-s)), where any term with k+a=0 is excluded.

Zeta[3]//N

NSum[1/k^3,{k,Infinity}]

Sum[x^k /(k! k), {k,Infinity} ]

EulerGamma is Euler' s constant gamma, with numerical value  γ =  0.577216 ....

% /. x -> 1.37 //N//Chop

NSum[1.37^k /(k! k), {k,Infinity} ]

Clear[s1]
s1[n_,x_] = Sum[ Sin[(2i - 1)x]/i, {i,n} ]//Expand

?LerchPhi

It is a mathematical function, suitable for both symbolic and numerical manipulation.

Φ(z,s,a)=(∑_(k=0)^∞)(z^k)/(((k+a))^s).

s1[5,x]//Simplify//Expand//ExpToTrig

s1[n,x] /.{ x -> 27.31, n -> 5}//Chop

s1[n,x] /. { x -> 27.31, n -> 5.5}//Chop

s2[n_,x_] = Sum[ Sin[i x]/i, {i,1,n,2} ]//Expand

s2[7,.33]//Chop

s2[7,x]//Simplify//Expand//ExpToTrig

(% /. x -> .33)//Chop

Sum[ Sin[k x]/k, {k,Infinity} ]

Sum[ Sinh[k x] z^k/k, {k,Infinity} ] //Simplify //Apart

f = NSum[(-1)^k/k,  {k,1,Infinity} ]

- Log[2.]

f = NSum[(-1)^k/(2k+1),  {k,0,Infinity} ]

Pi/4 //N

NSum[ 1/Log[k], {k,2,Infinity}]

In reality the above sum diverges.

NSum[(-1)^k /Log[k], {k,2,Infinity}]

fc[n_,x_] = - (-1)^n Cos[n x]/n

sn[x_]  := NSum[fc[n,x//N],{n,Infinity}]

fe[x_] = Log[2 Cos[x/2]];

fe[0]//N

sn[0]

fe[Pi/2]//N

sn[Pi/2//N]

The same troubles also turn up for other non-zero values of  x  as, e.g. for x = 0.15 .

fe[.15]

sn[.15]

Sum[(-1)^n,{n,Infinity}]

NSum[(-1)^n,{n,Infinity}]

NSum[(-1)^n,{n,0,Infinity}]

Common convergence of series 
In general, a series comprises an inﬁnity of terms: 
r1 + r2 + r3 + ... = (∑_(n=1)^N)  (Subscript[r, n])							(1)
partial sums = s(N) =  (∑_(n=1)^N) (Subscript[r, n]) 
The convergence of this sequence of numbers or functions: 
s1 , s2 , s3 , s4 , ..., sn , ...     
If this sequence tends toward a limit s, then this is called the sum of the series): 
s1 , s2 , s3 , s4 , ..., sn , ...     → s 						(2)

Convergence of Hölder means (arithmetic means of partial sums}
(Subscript[h, n]^((1))) =  (s1 + s2 + ... + sn)/N							(3)
li(Subscript[m, N->∞])  (Subscript[h, N]^((1)))  = S
If S  is finite,  the sequence (2)  is called limitable.

r[n]= (-1)^n ;
s[n]=Sum[r[n],{n,N}]

hs[N] = Sum[s[n]/N,{n,N}]

hos = Sum[hs[N],{N,NN}]/NN//ExpandAll

Limit[hos,NN -> Infinity]

f = Sum[q^n, {n,Infinity}]

f /. q -> - 1

7.1.1  Fourier Series and the  Gibb's  Phenomenon

In 1899  the Canadian theoretical phycisist W. Gibbs found a peculiar behaviour of Fourier series representing 
discontinuous functions. To show this peculiarity, called Gibb's phenomenon, the Fourier series belonging to 
the periodic step function displayed below  in the left picture is summed.

me={{-π,0},{-π,-1},{0,-1},{0,1},{π,1},{π,0}};p1=ListPlot[me,Joined->True,Ticks->{π Range[-2,2]/2,Range[-1,1]}, 
PlotStyle -> Hue[0], PlotRange -> 1.25 {-1,1}];

Clear[n,x]; pb = Black;
yf[n_,x_] = (4/Pi) Sin[n x]/n; 
sf[n_,x_] :=  Sum[ yf[i,x], {i,1,n,2}];
ssf  = Plot[ {sf[2,x], yf[3,x], sf[3,x]}, {x,Pi,-Pi},
PlotStyle -> {{pb,Dashing[{.02}]},{pb,Dashing[{.01}]},{pb,Dashing[{}]}},
Ticks->{π Range[-2,2]/2, Range[-1,1]}];

p2=Show[p1,ssf];Show[GraphicsRow[{p1,p2}]]

The picture at the right shows the first harmonic (curve with long dashes), the second harmonic (short dashes) and the sum of these two (continuous curve).  The first harmonic overshootes the value 1  at  x = ±π/2. The second harmonic (over)compensates this effect. and leads to overshooting near  x = ±π/4   and   x = ±3π/4.  The next harmonic will compensate all these overshootings but will introduce new overshootings at points stlll nearer to the original discontinuities of the step functions. At points in the interior of the intefvalls (-π,0) and (0,π) this wiggles will smooth out in the limit  N -> ∞.

   		 s(x)	 =     limN->∞  (∑_(n=1)^N) sn(x)     =   limN->∞  (∑_(n=1)^N)  bn  sin(n x)
   
But there remain steep narrow peaks approaching the points where the steps occur, as can be seen in the picture below.

p3=Plot[sf[30,x],{x,-π,π},Ticks->{π Range[-2,2]/2,Range[-1,1]},PlotStyle->pb,
PlotRange -> 1.2 {-1,1}];
Show[p1,p3,ImageSize->200]

Analytic analysis shows that these overshoots at the jumps remain in the limit   N -> ∞, but the value of  the limit  s(x) depends very sensitively upon the way the limits   N -> ∞   and  x -> 0+, for example, are taken. 
The most important point is:  Common summation  of Fourier series representing discontinuous functions leads to Gibb's phenomenon. This can be avoided by summing the Fourier series in a different way,  namely  by  Fejer's  arithmetic means (corresponding to the Hölder means treated in the previous section) :

s(x)	 =     limN->∞   (∑_(n=1)^N) σn (x),
			
				σn(x)   =   n-1  (∑_(n=1)^N)  si(x)   =  n-1  (∑_(n=1)^N) (∑_(k=1)^i)  bk sin(k x)

sff[n_,x_] :=  Sum[ sf[i,x], {i,n}]/n ; 
Plot[Evaluate[{sff[2,x], sf[3,x], sff[3,x]}], {x,Pi,-Pi},
 PlotStyle -> {{pb,Dashing[{.02}],pb},{pb,Dashing[{.01}]},{pb,Dashing[{}]}},
 Ticks -> {π Range[-2, 2]/2, Range[-1, 1]}];

ss3 = Show[%,p1];

p4 = Plot[Evaluate[sff[20,x]],{x,π,-π}, PlotStyle -> pb];
ss0=Show[p1,p4,Ticks->{π Range[-2,2]/2,Range[-1,1]}];GraphicsRow[{ss3,ss0}]

7.1.2  Sums of Fourier Series

Sum[] permits one to get closed expressions for some of the Fourier series as given below. These expressions display the periodic behaviour of the series. Summation of the series by residues (complex analysis) may lead to still simpler expressions (e.g. polynomials), which are valid in a limited interval. Below it is shown, how one may guess these expressions from plots and how these may be generalized to periodic expressions.

s1 = Sum[Sin[n x]/n, {n,1,Infinity}]

c1 = Sum[Cos[n x]/n, {n,1,Infinity}]//ExpandAll

pb = Black;

p1=Plot[s1,{x,-3 π,3 π},Ticks-> π {Range[-3,3],Range[-1,1]/2}, PlotStyle -> pb];
p2=Plot[c1,{x,-3 π,3 π},Ticks->{π Range[-3,3],Range[1,5]},PlotStyle -> pb];
GraphicsRow[{p1,p2}, ImageSize -> 450]

From the left picture it is seen that   s1   is a piecewise linear function. One can guess that in the interval (0, 2π) this function is  (π - x)/2. This function must be continued periodically. This can be done with the help of the function  Floor[]. (for this function  cf. sect. 13.2).
By a simple evaluation one finds that   c1  =  - log(2 | sin(x/2)| ). This is a periodic function. 
This gives similar graphs as above:

ps=Plot[N[((π-x)/2)+π Floor[((x 0.5`)/π)]],{x,-4 π,4 π},Ticks-> π {Range[-3,3],Range[-1,1]/2}];pc=Plot[-Log[2 Abs[Sin[(x/2)]]],{x,-4 π,4 π},Ticks->{π Range[-3,3],Range[1,5]}];
GraphicsRow[{ps,pc}, ImageSize -> 450]

7.1.3  Evaluation  of  π

The value of Ludolph's number, π = 3.14159... , can be computed by various algorithms. One may sum the well known series:

(π/4)=1-(1/3)+(1/5)-(1/7)+... - ...

But this series converges extremely slowly so that it is hardly usable for numerical evaluations.

Clear[su]

su(NN_)= 4(∑_(k=1)^NN)((((-1))^(k-1))/(2 k-1))

SetPrecision[su[10^5],10]//Timing

SetPrecision[%[[2]],20]

SetPrecision[π,20]

% - %%

Earlier versions of Mathematia (Version 5.2) gave another formula for the above sum, which works much faster:

4((π/4)-(1/4) (((-1))^NN) (-PolyGamma[0,(1/4)+(NN/2)]+PolyGamma[0,(3/4)+(NN/2)])) /. NN ->  10^8;

SetPrecision[%,20]

SetPrecision[π,20]

% - %%

From the preceeding results one sees that (10^8) terms give an accuracy of about 8 decimal places. NSum[]   uses more powerful methods to extract numerical values from the series:

SetPrecision[4 NSum[((((-1))^(k-1))/(2 k-1)),{k,Infinity}],19]
% - π

Another method for computing π is Wallis' infinite product; but this also not very fast (s.7.2.1).
In recent years new methods have been developed for finding series, which converge faster.  Practical algorithms for integer relation detection have become a staple in the emerging discipline  of experimental mathematics -  using modern computer technology -  to explore mathematical questions. 
 (Computing in Science and Engineering 2 (#1,2000) 24-28, 7 (#3, 2005) 54-61).  
 Integer relation detection algorithms seek integers  (Subscript[a, i])  such that     
 			(Subscript[a, 1])(Subscript[x, 1]) + (Subscript[a, 2])(Subscript[x, 2]) + ... + (Subscript[a, n])(Subscript[x, n]) = 0 
 is fulfilled with given real or complex numbers   (Subscript[x, 1]), (Subscript[x, 2]), ... ,  (Subscript[x, n]). 
 By such a method the following series for π has been found (Bailey-Borwein-Plouffe (BBP) formula)

π = (∑_(k=0)^∞)(1/(16^k))[-(2/(8 k+4))-(1/(8 k+5))-(1/(8 k+6))+(4/(8 k+1))]

as=(∑_(k=0)^7)(1/(16^k))(-(2/(8 k+4))-(1/(8 k+5))-(1/(8 k+6))+(4/(8 k+1)))
as - π//N

Mathematica can calulate an arbitrary number of decimal places of   π.   For example:

SetPrecision[π,65]

π   =  ((426880 (Sqrt[10005]))/13591409 )/(HypergeometricPFQ[{(1/6),(1/2),(5/6)},{1,1},-(1/151931373056000)]-(30285563 HypergeometricPFQ[{(7/6),(3/2),(11/6)},{2,2},-(1/151931373056000)])/1651969144908540723200)

Mathematica currently uses the above formula, due to the Chudnovsky brothers, for calculating  π  to arbitrary precision.  
The function HpergeometricPFQ[]  will be explained at the end of the next section.

7.2  Products

Product[f,  {i,imax}] 			Πi=1imax   	f

Product[f, {i,imin,imax} ]	Πi=iminimax 	f
							   
Product[f, {i,imin,imax,di}]	same as above but with increment   di									   
Product[f, {i,imin,imax},{j,imin,jmax}]	Πi=iminimax  Πi=iminimax	f	multiple product
NProduct[...] 				numeric product

fact[n_]  = Product[i, {i,n}]

n! = Γ (n + 1)

?Gamma

The Gamma function satisfies Γ(z)=(∫_0^∞)(t^(z-1))(e^(-t))dt  =(n - 1)!   for  z = n = nonnegative integer.

fact[.5]

0.5!

Gamma[1.5]

fact[n_] := Product[i, {i,n}]

fact[.5]

fact[2.5]

2.5!

fact2[n_] = Product[i, {i,n,1,-2}]

n!!  =  n (n - 2) (n - 4)  ...  2  or 1   for non-negative integers. This definition of  n!!  by fact2[] is valid for such integers only !  The interpolation for  arbitrary  n  is shown in   Chap.13, Sect.6 .

fact2[5]

5!!

fact2[4]

4!!

5.5!!

fact2[5.5]

Comparing the last two outputs shows that   fact2[x] where  x  is not a non-negative integer does not agree with the interpolation used  for  x!!   in Mathematica (§ 13.6).

Product[4 k (1 + k)/(1 + 2 k)^2, {k,1,Infinity} ]

Product[ 1 - 1/(k + 5)^2, {k,0,n} ]

Product[ 1 - 1/(k + 5)^(5/2), {k,0,n} ]

NProduct[ 1 - 1/(k + 5)^(5/2), {k,0,10} ]

NProduct[ 1 - 1/(k + 5)^(5/2), {k,0,Infinity} ]

Product[ 1 - 1/(k + 5)^3, {k,0,n} ]

Product[ (1 - x^2/n^2), {n,Infinity}]

7.2.1	Wallis' Infinite Product for   π :

Lim n -> ∞ piu[n]   =    π  =  (2/1)(2/3)(4/3)(4/5)(6/5)(6/7)(8/7)(8/9) ...  =   ((((((∏_(k=1)^n)2 k)/((∏_(k=1)^n)(2 k-1)))))^2)/n

piu[n_] = (Product[2k,{k,n}]/Product[2k-1,{k,n}])^2/n

piu[10]

N[%]

piu[100000]//N

7.2.2    Hypergeometric, Confluent and Generalized Hypergeometric Functions

The Confluent Hypergeometric Function  is defined by the following series:

(Subscript[, 1])(Subscript[F, 1])(a';'b';'z)=  1+((a z)/b)+((a (1+a) (z^2))/(2 b (1+b)))+((a (1+a) (2+a) (z^3))/(6 b (1+b) (2+b)))+((a (1+a) (2+a) (3+a) (z^4))/(24 b (1+b) (2+b) (3+b)))+
... +  (((Subscript[(a), n]) (z^n))/((Subscript[(b), n]) n!)) + ...

(Subscript[(a), n]) :=  a (a + 1) (a + 2)... (a + n - 1)  = Pochhammer[a,n]=  Γ(a + n)/Γ(a) 
is  Pochhammer's  symbol.

This leads to defining the following function:

F11[a, b, z]   =
1 + Sum[ Product[(a+i-1)/(b+i-1) z/i, {i,k}],  {k,Infinity}]

F11[a_, b_, z_, n_]   :=
1 + Sum[ Product[(a+i-1)/(b+i-1) z/i, {i,k}],  {k,n}]

The series becomes a polynomial of degree  n  if  a  is a negative integer;  e.g.   a - - 5 gives:

F11[-5,b,z,9]

In Mathematica there is also a function programme for the confluent hypergeometric function:

Hypergeometric1F1[-5,b,z]

The genuine Hypergeometric Function as defined by Gauss  is:

(Subscript[, 2])(Subscript[F, 1])(a,b;c;z)=
1+((a b z)/c)+((a (1+a) b (1+b) (z^2))/(2 c (1+c)))+((a (1+a) (2+a) b (1+b) (2+b) (z^3))/(6 c (1+c) (2+c))) + ... + (((Subscript[(a), n]) (Subscript[(c), n]) (z^n))/((Subscript[(c), n])n!)) + ...

The generalized Hypergeometric Function is:

(Subscript[, p])(Subscript[F, q])((Subscript[a, 1]),(Subscript[a, 2]),...(Subscript[a, p])';'(Subscript[b, 1]),(Subscript[b, 2]),..(Subscript[b, q])';'z)=
 1 + (∑_(n=1)^∞) (((Subscript[((Subscript[a, 1])), n]) (Subscript[((Subscript[a, 2])), n]) ... (Subscript[((Subscript[a, p])), n]) (z^n))/((Subscript[((Subscript[b, 1])), n]) (Subscript[((Subscript[b, 2])), n]) ... (Subscript[((Subscript[b, q])), n])  n!))

In Mathematica it is written as:

 			HypergeometricPFQ[{(Subscript[a, 1]),(Subscript[a, 2]),...(Subscript[a, p])},{(Subscript[b, 1]),(Subscript[b, 2]),..(Subscript[b, q])},z]

7.3  General  Loops

7.3.1 Unconditional Loops

Do[f,  {n}]			Perform task  f  n   times		
	
Do[f,  {i,imax}] 	Perform task  f  from   i = 1   to    i = imax

Do[f, {i,imin,imax} ]	Perform task   f   from   i = imin   to     i = imax

Do[f, {i,imin,imax,di}]      Perform task    f   from    i = imin    to  
					i = imax   incrementing   i   by    di

Do[f, {i,imin,imax},{j,jmin,jmax}]	double loop

Do[ Print[i^2], {i,4} ]

Do[ Print[{i, i^3}], {i,3,12,4}]

Do[ Print[{i,j}], {i,4}, {j,i-1} ]

The following command gives a finite continued fraction (= Kettenbruch).

t = x; Do[t = 1/(1 + t),{3}];t

% /. x -> 5

7.3.2  Conditional Loops

Do-Loops may be stopped, interrupted  or branched by conditions; the conditions can be expressed  with the help of an  If[]  command. The action to be taken may be specified by one of the following commands:

Break[]  		exit the nearest enclosing loop

	Continue[] 		go to the next step in the current loop

	Return[expr]		return the value expr, exiting all procedures and loops in a function 

	Goto[name]    	go to the element Label[name] in the current procedure

Do[ t = k^2; Print[t]; If[t > 10, Break[] ], {k,7} ]

Do[ t = k^2;  If[t > 10,Break[],Print[t]], {k,7} ]

Do[ t = k^2;  If[t > 25, Return[t] ], {k,9} ]

Do[ t = k^2; Print[{k, t}]; 
	If[ t < 17, Continue[], Break[] ], {k,9} ]

There are several other commands for (unconditional and conditional) loops:

Nest, FixedPoint, For, While.

7.3.3  FixedPoint

FixedPoint[f, expr]                    starts with  expr , then applies  f  repeatedly until the result no longer changes.
FixedPoint[f, expr, n]        stops after at most  n   steps.

7.3.3.1	A simple example for FixedPoint

FixedPoint[Cos[#]&,1,7]

N[%]

FixedPoint[Cos[#]&,1,35]//N

FixedPoint[Cos[#]&,1.]

7.3.3.2	Implementing Newton's method

Newtons method computes an approximate zero of  f(x)  by the following iteration (s. § 9.5) :

			(Subscript[x, n+1]) = (Subscript[x, n]) -  ((f((Subscript[x, n])))/(f'((Subscript[x, n]))))

This formula is implemented in the following way:

myFindRoot[f_,init_]:=FixedPoint[#1-((f[#1])/(f'[#1]))&,init];

Clear[x, g]; g[x_] = Sin[x] + Cos[2x]/2;

Plot[g[t],{t,-1,4}, AxesLabel ->   {"x","g(x)"},PlotRange -> {-0.2,0.8}, ImageSize ->  300]

myFindRoot[g,3.]

7.4  Conditional Branching

There are several commands for conditional branching. The simplest is:

If[test, then, else]

If[test, then]

If[test,then, else, unknown]

If the answer to test is True, the statement(s) in position  then  are executed; if it is False, the statement(s) in position  else are executed. The  If[]  with four arguments provides for the case that the answer to test may be undecided; then unknown is executed.  
Now this is used to define the Heaviside unit step function:

theta[x_]  =  If[x > 0, 1, 0]

theta[1]

theta[0]

theta[-1]

Note the order of the symbols for   "ge" , viz.   >=   and   "le",    viz.    <= .

thetag[x_] = If[x >= 0, 1, 0]

thetag[1]

thetag[0]

thetag[-1]

thetal[x_] = If[x <= 0, 0, 1]

thetal[1]

thetal[0]

thetal[-1]

The Kronecker symbol   (Subscript[δ, nk])    may be defined as:

Remove[n,k]
krodel[n_,k_] = If[ k == n, 1, 0]

krodel[3,4]

krodel[3,3]

krodel[a,a]

Remove[n,k]
krodel[n_,k_] = If[ k != n, 0, 1]

krodel[3,4]

krodel[a,a]

k = 1;
If[k == 1,Print["yes"]]

If[k!= 1,Print["yes"]]

A more general type of command is:

Which[test1, value1, test2, value2, ....]

Tests are applied in the order given starting from left to right. The value belonging to the test which comes out  True  is given. A last condition  "True"  may cover the cases remaining after all preceeding tests have met "False".

theta[x_] = Which[x > 0, 1, x == 0, 1/2, x < 0, 0]

theta[1]

theta[0]

theta[-1]

Clear[x]
h[x_] = Which[x^2 < 1, Sqrt[1 - x^2], True, 0]

Plot[h[x],{x,-1.5`,1.5`}]

Note that logical equality must be expressed by  " == ".  Otherwise an error will occur:

theta[x_] = Which[x > 0, 1, x = 0, 1/2, x < 0, 0]

theta[1]

theta[0]

Set::setraw : Cannot assign to raw object 0 . >>

7.4.1	A Test Comprising Several Conditions

A test may comprise several conditions. These must be linked either by    &&    or by ||  :

&&  (=  ∧)  	Result of test is True  if all conditions are met.

||  (=  ∨)  	Result of test is True  if at least one conditions is met.

theta2[x_,y_] = If[x > 0  &&  y > 0, 1, 0]

theta2[1,1]

theta2[-1,1]

theta2[1,-1]

theta2[-1,-1]

theta2[x_,y_] = If[x > 0  ||  y > 0, 1, 0]

theta2[1,1]

theta2[-1,1]

theta2[1,-1]

theta2[-1,-1]

Clear[f,g,x,y]
g[x_,y_] = Abs[ Exp[ (x + I y)^-1 ] ];
f[x_,y_] = Which[ x < 0 && y < 0  (*third quadrant *), 0, 
		          True (* all other quadrants *), g[x,y] ];
re = Plot3D[f[x, y], {x, -2, 2}, {y, -π, π}, PlotPoints -> 50]; li = Show[re, PlotRange -> {0, 5}, ViewPoint -> {-4, -4, 3}, Axes -> None, Boxed -> False];
GraphicsRow[{re, li}, ImageSize -> 500]

f1[x_]:=Which[x<0,0,x<1,1,x<2,2]

SetAttributes[f1,Listable]

f1[{-0.5,0.,0.75,1.,1.5,2,3}]

f2[x_]:=Which[x<0,0,x<1,1,x<2,2, True,2.5]

SetAttributes[f2,Listable]

f2[{-0.5,0.,0.75,1.,1.5,2,3}]

p1 = Plot[f1[x],{x,-1,3},PlotStyle->Hue[0], PlotRange -> {0,3}];
p2 = Plot[f2[x],{x,-1,3},PlotStyle->Hue[0], PlotRange -> {0,3}];
GraphicsRow[{p1,p2}]

7.4.2	Functions for Testing Properties of Expressions

Besides the logical operators

< 	<=	 ==	 != 	> 	>=	 &&	 ||

there are also functions which may be used for expressing conditions by checking properties of expressions. They end with the letter  Q  (= Question).

NumberQ[expr]  		number
	
	IntegerQ[expr]		integer
	
	EvenQ[expr]		even number
	
	OddQ[expr]			odd numberr

	PrimeQ[expr]			prime numberr

	VectorQ[expr]			a list representing a vector
	
	MatrixQ[expr]		a list representing a matrix
	
	SameQ[expr1,expr2]	test whether expressions expr1 and expr2 are the same

NumberQ[x]

NumberQ[Pi]

NumberQ[3.14]

IntegerQ[3.14]

PrimeQ[5679]

PrimeQ[23]

fact[x_] = If[IntegerQ[x], Product[k,{k,x}], Gamma[x+1] ];

fact[x]

fact[5]

fact[4.5]

4.5!

fact2[x_] := 
If[IntegerQ[x],Print[Product[k,{k,x,1,-2}]], Print[x!!] ];

fact2[4.5]

fact2[5]

Defining the same function without using delayed definition does not work properly.

fact2[x_] = 
If[IntegerQ[x], Print[Product[k,{k,x,1,-2}]], Print[x!!] ];

fact2[4.5]

fact2[5]

fact2[x_] = If[IntegerQ[x],
Return[Product[k,{k,x,1,-2}]], Return[x!!] ];

For    Return[]   cf. Chp. 7.4 .

Clear[a,b,c,c,s,ma]
ma =  {{a + b,0,c - 1,0},{0,d 5,0,12 b},{s + 1,0,a- d,0},{0,1,0,4}}; MatrixForm[ma]

Below the structure of the above matrix is  to be displayed: All non-zero matrix elements are denoted by a letter x.

MatrixForm[Table[If[SameQ[ma[[i,j]],0],0,x],{i,Length[ma]},{j,Length[ma]}]]

7.5	Exercises

7.1  	Compute the sum of the following series :
	a) (∑_(k=0)^∞)1/(3^k) ;	b) (∑_(k=2)^∞) (-1)^k/ln(k) ; 	c)  (∑_(k=1)^∞)sin(n x)/n ,	insert  -π/2   and  1.6 ;
	d)   1 + 1/2  - 1/3 - 1/4 + 1/5 + 1/6 - 1/7 - ... + ...  +  ... 
	
7.2	The periodic saw tooth curve is given by the following Fourier series:
	x ~  [- sin(x) + sin(2x)/2 - sin(3x)/3 +- ... ],  	-π < x < π.
	Plot the exact saw tooth curve, results of the partial sums, Gibb's phenomenon and 
	Fejer sums.

7.3 	Compute the sum of the following Fourier series and  find the intervall in which 
	the series  represents the polynomial:
	 a)      (∑_(n=1)^∞)cos(nx)/(n^2)   =   π2/6  -  x π/2  + x2/4 ;  
	 b)   (∑_(n=1)^∞) sin(n x)/n3   =   x π2/6  -  x2 π/4  + x3/12.
	
7.4   	Compute and print  (Underoverscript[    ∏, (k=1), ( n)])  (1 - (e^(2 π i k/n)) )  	for  n = 1,2,....,9.

7.5	Compute the doubly infinite product   	(∏_( n=-∞)^( ∞))  (1 - z/(n - 1/2)) .

7.6    	Repeat ex. 6.7.  The lists for the options generating ticks and gridlines should be 
	generated by a combination of  the command Table and commands for branchings.

7.7    	Repeat  ex. 6.9.  The curve should be generated with  one Plot command  and a 
	branching command.

7.8	In the list d given below there are relative maxima. Find these and give these together
 	with their position in the list d.

d={1,2,3,6,11,7,6,4,6,8,11,17,12,10,8,6,3,3};