• Aucun résultat trouvé

à 1.2.3 Symbolic Calculations

D[f[x], x] differentiates fHxL once with respect to x.

D[Sin[x], x]

Here is a slightly more complicated expression.

f = Sin[Log[Tan[(ξ^2 + Exp[x])/(Cos[ξ^2 - 1] + Sqrt[ξ])]]]

The resulting manual differentiation is somewhat unpleasant. The result of differentiating this expression twice with respect to x is quite big, so we use Short to force Mathematica to show only a part.

D[f, {ξ, 2}] // Short[#, 4]&

Here is a simple integral.

Integrate[Sin[x], x]

The following integral is tedious to find by hand.

Integrate[ξ^3 Sin[ξ]^4, ξ]

By differentiating and simplifying, we get x3 sinHxL4 again.

D[%, ξ] Simplify[%]

Here is the definite integral ŸIx4+4M-2 dx.

Integrate[1/(x^4 + 4)^2, {x, -Infinity, Infinity}]

We now consider a function that is complicated for integration.

g = t^(2/3) Exp[-2 t] (t - 1)^(4/5) It can be integrated analytically over the domain 1 to ¶.

Integrate[g, {t, 1, Infinity}]

Because all of the special functions are numerically implemented for arbitrary complex arguments (in their domains) with arbitrary accuracy, we can also compute the numerical value with 50 digits.

N[%, 50]

Here is the same integral calculated numerically to ten digits.

NIntegrate[Evaluate[g], {t, 1, Infinity}, PrecisionGoal -> 10] // InputForm Here, the function sinIx2M is integrated five times.

Integrate[Sin[x^2], x, x, x, x, x]

Differentiating the result five times brings us back to sinIx2M. D[%, x, x, x, x, x] // Simplify

The next input calculates the even Bernoulli numbers through the integral representation [580÷]

B2 n= -H-1Lm2-H2m+1L

dm-1 sech2HxL d xm-1

2

.

Table[-(-1)^n 2^-(2n + 1) Integrate[D[Sech[x]^2, {x, n - 1}]^2, {x, -Infinity, Infinity}], {n, 10}]

The Bernoulli numbers are built-in functions of Mathematica.

Table[BernoulliB[2n], {n, 10}]

Now let us consider a limit. The function e1êHx-1L has two different limit values, one from the left and from the right at the point x=1.

Limit[Exp[-1/(1 - x)], x -> 1, Direction -> +1]

Limit[Exp[-1/(1 - x)], x -> 1, Direction -> -1]

We now solve a differential equation describing a damped oscillation x££HtL+ g x£HtL+ w2 xHtL=0. DSolve[x''[t] + γ x'[t] + ω^2 x[t] == 0, x[t], t]

Suppose we want to approximate a function fHxL with the following properties by a polynomial in x:

fH0L = 1 f£H0L = 2 fH4L = 8 f£H4L = 45 fH4L = 0.

InterpolatingPolynomial[{{0, {1, 2}}, {4, {8, 45, 0}}}, x]

Here is the same polynomial in a simpler, but less practical, form.

Simplify[%]

We check that it interpolates.

{% /. {x -> 0}, D[%, x] /. {x -> 0}, % /. {x -> 4}, D[%, x] /. {x -> 4}, D[%, {x, 2}] /. {x -> 4}}

Here is the piecewise-continuous function pwHxL= qHxL qH1-xLe5x6-1ufracIx4-4M3J¢ax2+2x-1q6¶N1ê3 defined.

pw[x_] = If[0 < x < 1, Floor[(5 x^6 - 1)] FractionalPart[x^4 - 4]^3*

Abs[Ceiling[x^2 + 2 x - 1]^6]^(1/3), 0]

Here is a canonical form of this function.

PiecewiseExpand[pw[x]]

The next input calculates ŸpwHxL2 dx.

Integrate[pw[x]^2, {x, -Infinity, Infinity}]

And here is a series expansion of this function at a point where a discontinuity occurs.

Series[pw[x], {x, Sqrt[3] - 1, 1}]

Next, we solve a well known-differential equation of mathematical physics describing (among other things) the behav-ior of a quantum particle in a constant electric field.

DSolve[ψ''[z] + e F z ψ[z] == ψ[z], ψ[z], z]

The Vandermonde matrix of the nth-order is easy to implement in the following way.

VandermondMatrix[n_, x_] := Table[x[i]^j, {i, 0, n}, {j, 0, n}]

Here is the Vandermonde matrix of the third order. x[i] is a typical Mathematica equivalent for xi. MatrixForm[VandermondMatrix[3, x]]

Here is the value of its determinant.

Det[VandermondMatrix[3, x]]

This product can also be written as a product.

Factor[%]

The following function LUMatricesVandermonde implements the LU-decomposition of the nth-order Vander-monde matrix [1401÷].

LUMatricesVandermonde[n_, x_] :=

Module[{X = Table[x[k], {k, 0, n}], e, h, b, L, U}, (* recursive definitions for elementary and complete

symmetric polynomials *)

e[0, _] := 1; e[_, {}] := 0; h[0, _] := 1; h[_, {}] := 0;

e[r_, l_] := Factor[e[r, Most[l]] + Last[l] e[r - 1, Most[l]]];

h[r_, l_] := Factor[h[r, Most[l]] + Last[l] h[r - 1, l]];

b[r_, y_] := Factor[Sum[(-1)^(r - k) e[r - k, Take[X, r]] y^k, {k, 0, r}]]

(* lower and upper triangular matrices *)

L = Table[If[i < j, 0, h[i - j, Take[X, j + 1]]], {i, 0, n}, {j, 0, n}];

U = Table[If[i > j, 0, b[i, X[[j + 1]]]], {i, 0, n}, {j, 0, n}];

(* return matrices *) {L, U}]

Here is the decomposition for the third order Vandermonde matrix.

{L, U} = LUMatricesVandermonde[3, x];

{L, U} // (MatrixForm /@ #)&

Multiplying the two matrices recovers the original matrix.

L.U // Expand

The last LU-decomposition is not unique. The next inputs use the function Solve to calculate the most general solu-tion.

(* general ansatz form for the matrices L and U *) With[{n = 3}, MatrixForm /@

{L = Table[If[i < j, 0, l[i, j]], {i, 0, n}, {j, 0, n}], U = Table[If[i > j, 0, u[i, j]], {i, 0, n}, {j, 0, n}]}]

Solve[(* the decomposition identity that must hold *) L.U == VandermondMatrix[3, x], (* the 10 variables l[i, j] and the 10 variables u[i, j] *)

Cases[{L, U}, _l | _u, Infinity]] // (Factor //@ #)&

Next, we calculate symbolically the eigenvalues of a 50μ50 Redheffer matrix. The matrix elements ai j are 1 if j=1 or if i divides j, and 0 otherwise.

Redheffer[d_] := Table[If[j == 1 || IntegerQ[j/i], 1, 0], {i, d}, {j, d}];

A Redheffer matrix of dimension n has n-elog2HnLu-1 eigenvalues 1 (see [1312÷] and [1313÷]). The remaining six (for n=50) eigenvalues are the roots of an irreducible polynomial of degree 6. They are represented as Root-objects.

Eigenvalues[Redheffer[50]]

The following example is a linear inhomogeneous system of equations with eight unknowns. (We show the equations in abbreviated form.)

gls = Table[Sum[(i + j)^j x[i], {i, 8}] == j, {j, 8}];

Short /@ gls We get its exact solution.

Solve[gls, Table[x[i], {i, 8}]]

Here is a simple system of nonlinear equations and its solution.

x2+y2 =1 x4+y4 =4

Solve[{x^2 + y^2 == 1, x^4 + y^4 == 4}, {x, y}]

The function Eliminate eliminates variables from a system of polynomial equations.

Eliminate[{x^6 + y^6 == 6, x^8 + y^8 == 8}, {y}]

Mathematica can also solve higher order univariate polynomial equations.

Solve[x^7 - a x + 3 == 0, x]

The result contained again the Root function. Root-objects are symbolic representations of the roots of polynomials.

The first argument specifies the polynomial, and the second, the root number. (See Chapter 1 of the Symbolics volume of the GuideBooks [1285÷] for details.) Like any other function in Mathematica, they can be manipulated, for instance, differentiated.

D[Root[-3 + a #1 - #1^7 &, 1], {a, 2}]

Here is the numerical value of the root for a given value of a to 50 digits.

N[Root[-3 + a #1 - #1^7 &, 1] /. a -> 7, 50]

Backsubstitution shows that the equation gives zero to a good approximation.

x^7 - a x + 3 /. a -> 7 /. x -> %

Here is a plot of the root; the parameter a varies between -10 and 10.

Plot[Root[-3 + a #1 - #1^7 &, 1], {a, -10, 10}]

The following input solves a transcendental equation.

Solve[Log[2 x] + Log[3 x] + Log[5 x] == 1/2, x]

The following example is a simple power series expansion up to the ninth order.

Series[Sqrt[1 + x], {x, 0, 9}]

The next one is not so simple. It is not a Taylor series because logarithms appear.

Series[x^x, {x, 0, 4}]

What is the first nonvanishing term in the series expansion of sinHtanHxLL-tanHsinHxLL [1235÷]?

Series[Sin[Tan[x]] - Tan[Sin[x]], {x, 0, 9}]

Here is a Laurent series.

Series[1/(Sin[x] - x - x^3/3 + x^5), {x, 0, 6}]

Here is a short program using l’Hôspital’s rule for determining the limit of sinHtanHxLL-tanHsinHxLL

arcsinHarctanHxLL-arctanHarcsinHxLL as xØ0. numerator = Sin[Tan[x]] - Tan[Sin[x]];

denominator = ArcSin[ArcTan[x]] - ArcTan[ArcSin[x]];

We differentiate the numerator and denominator until we get a determined quantity.

lHospitalList = Table[D[numerator, {x, i}]/D[denominator, {x, i}], {i, 7}];

If[(* zero denominator? *) (Denominator[#] /. x -> 0) == 0, Indeterminate, # /. x -> 0]& /@ lHospitalList

Of course, Mathematica can also calculate this limit directly. (Mathematica can also compute limits in cases in which l’Hôspital’s rule is not applicable [586÷], [163÷], [1131÷].)

Limit[(Sin[Tan[x]] - Tan[Sin[x]])/

(ArcSin[ArcTan[x]] - ArcTan[ArcSin[x]]), x -> 0]

Here is an exact value for the Gauss hypergeometric function with numeric arguments.

Hypergeometric2F1[3/2, 4, 1, z]

We can also evaluate a high-order Hermite polynomial.

HermiteH[23, z]

The command FunctionExpand rewrites an expression using a simpler function than the original one. In the following, a trigonometric expression is converted to one involving square roots only.

FunctionExpand[Sin[1/(2^3 3 5) Pi]]

Here is a similar example.

FunctionExpand[Tan[Pi/32]]

The previous expression is an algebraic number. It is a root of the polynomial that is the first argument of the following Root-object.

RootReduce[%]

Next, we find the prime factor decomposition of a relatively large number.

FactorInteger[4951486756871515]

Here is an abbreviated list of all numbers dividing the number 4951486756871515.

Divisors[4951486756871515] // Short[#, 6]&

This is the one-billionth prime number.

Prime[10^9]

We now decompose a polynomial into smaller ones that, when plugged into each other, give again the starting polyno-mial. (This specific example was already decomposed by Vieta in 1594 [232÷].)

Decompose[45 x 3795 x^3 + 95634 x^5 1138500 x^7 + 7811375 x^9 34512075 x^11 + 105306075 x^13 - 232676280 x^15 +

384942375 x^17 488494125 x^19 + 483841800 x^21 378658800 x^23 + 236030652 x^25 - 117679100 x^27 + 46955700 x^29 14945040 x^31 + 3764565 x^33 740259 x^35 + 111150 x^37 12300 x^39 + 945 x^41 45 x^43 + x^45, x]

Sums can also be computed symbolically. Here are the first few partial sums for k=1n kj. TableForm[Table[Sum[k^j, {k, n}], {j, 1, 8}]]

It is even possible to compute infinite sums analytically.

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

Here are two more complicated sums. The summands and the result contain Riemann’s Zeta function.

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

Sum[(Zeta[k] - 1) Exp[-k], {k, 2, Infinity}]

Here is a complicated finite sum. The result contains the Polygamma function and a sum of roots of a quartic polynomial.

Sum[(k^2 - 1)/(k^4 + 1), {k, 1, n}]

Mathematica’s functions Integrate, Sum, DSolve are very powerful and can integrate, sum, and solve differential equations of quite complicated functions. However, for efficiency, the solution is typically not automatically simplified.

But Mathematica provides a variety of functions allowing us to rewrite results from functions like Integrate, Sum,

DSolve in various ways. For instance, here is a more explicit form of the last result (not containing the function RootSum any more).

Normal[%] // Simplify

Using the function FullSimplify, we can further collapse the last result.

% // FullSimplify

A closed form for the partial sum of the first n Taylor coefficients of sinHxL.

Sum[(-1)^k/(2k + 1)! x^(2k + 1), {k, 0, n}] // FullSimplify For a given value of n, we recover the first n Taylor coefficients of sinHxL.

Series[% /. n -> 12, {x, 0, 12}]

Here is a complicated finite sum that can be expressed in polylogarithmic and Lerch functions:

The following sum calculates the interaction energy of a point charge at position z0 between two flat, parallel, perfectly conducting walls of distance a using mirror charges [1192÷].

Sum[1/(a n) - 1/(2n a - 2 z0) - 1/(2 (n - 1) a + 2 z0), {n, Infinity}] // Normal // Simplify

A Green’s function approach to the same problem yields the following integral and, of course, evaluates to the same result [1192÷].

Integrate[Cosh[k a]/Sinh[k a] - 1 - Cosh[k(a - 2 z0)]/Sinh[k a], {k, 0, Infinity},

Assumptions -> a > 0 && z0 > 0 && z0/a < 1]

A series expansion of the energy around z0=0 or z0=a yields the force on the point charge.

{Series[%, {z0, 0, 6}], Series[%, {z0, a, 6}]} // FullSimplify Next, we use Mathematica to prove a neat identity discovered by Ramanujan:

cos 2p

The last identity contains algebraic and trigonometric expressions. For algorithmic treatments, algebraic expressions are always preferable. In algebraic form, the identity has the following form.

Together[TrigToExp[%]]

The function RootReduce canonicalizes algebraic expressions. The identity can be simplified to 0.

RootReduce[%]

Here is more challenging example: A three-line proof of Legendre’s celebrated identity for complete elliptic integrals [442÷]

Integrate[integrand[x, y, m], {y, 0, Pi/2}, {x, 0, Pi/2},

GenerateConditions -> False] // FunctionExpand // Together Differentiation shows that the last expression is independent of m.

D[%, m] // Together

This means EHmLKH1-mL-KHmLKH1-mL+EH1-mLKHmL equals a constant, and evaluating the above integrand for m=0 shows that the constant is pê2.

Integrate[integrand[x, y, 0], {x, 0, Pi/2}, {y, 0, Pi/2}]

A powerful command for algebraic computations is GroebnerBasis. Given a set of polynomials, the function GroebnerBasis can transform this set into triangular form, so that a numerical solution is easily possible. Groeb nerBasis can also be used to eliminate certain variables from a set of polynomials. In the following example, we are looking for an equation connecting the area A of a triangle with the radius of its circumscribed circle, with radius R and the edge lengths l12,l13, andl23.

Clear[x1, y1, x2, y2, x3, y3, X, Y, R, A];

GroebnerBasis[{(* all equations of the problem *) (* defining equations for the circumscribed circle *) (X - x1)^2 + (Y - y1)^2 - R^2, (X - x2)^2 + (Y - y2)^2 - R^2, (X - x3)^2 + (Y - y3)^2 - R^2, (* defining equations for the length of the edges *) (x2 - x1)^2 + (y2 - y1)^2 - l12^2, (x3 - x2)^2 + (y3 - y2)^2 - l32^2, (x1 - x3)^2 + (y1 - y3)^2 - l13^2, (* defining equations for area *)

(1/2(-x2 y1 + x3 y1 + x1 y2 - x3 y2 - x1 y3 + x2 y3))^2 - A^2}, (* the variables to keep *) {R, l12, l23, l13, A},

(* the variables to eliminate *) {x1, y1, x2, y2, x3, y3, X, Y}]

The last polynomial in the result means that the relation we were looking for is A=l12 l23 l13ê H4 RL. The first polyno-mial in the result expresses the area in the edge lengths only.

Let us use GroebnerBasis [288÷] again to solve a slightly more complicated example: the area of the medial parallelogram [28÷] of a tetrahedron expressed through the edge length of the tetrahedron [1404÷], [65÷]. We start with a generic tetrahedron. From this tetrahedron, we remove two nonincident edges. The midpoints of the remaining

four edges form a parallelogram, the medial parallelogram. We want to express the area of this parallelogram through the six lengths of the edges of the original tetrahedron. Below is a sketch of the tetrahedron. The two red-colored edges P1P2 and P3P4 are the removed edges.

P1

P2

P3

P4

The next input calculates the formula we are looking for.

Module[{(* coordinates of the four vertices *)

p1 = {0, 0, 0}, p2 = {p2x, 0, 0},

p3 = {p3x, p3y, 0}, p4 = {p4x, p4y, p4z}, p13, p14, p23, p24},

(* coordinates of the midpoints of the edges *)

p13 = (p1 + p3)/2; p14 = (p1 - p4)/2;

p23 = (p2 + p3)/2; p24 = (p2 + p4)/2;

GroebnerBasis[

{(* edge lengths expressed through coordinates of vertices *)

l12^2 - (p1 - p2).(p1 - p2), l13^2 - (p1 - p3).(p1 - p3), l23^2 - (p2 - p3).(p2 - p3), l14^2 - (p1 - p4).(p1 - p4), l24^2 - (p2 - p4).(p2 - p4), l34^2 - (p3 - p4).(p3 - p4), (* medial parallelogram area A expressed

through coordinates of vertices *)

A^2 - Cross[p14 - p13, p23 - p13].Cross[p14 - p13, p23 - p13]}, (* the variables to keep *)

{l12, l13, l14, l23, l24, l34, A}, (* the variables to eliminate *)

{p2x, p3x, p3y, p4x, p4y, p4z}, MonomialOrder -> EliminationOrder]]

In the last subsection, we made use of the Polyhedra` package. Mathematica comes with a wide set of standard packages carrying out various numerical, graphical, and symbolic operations not built into the Mathematica kernel. Let us make use of the package Algebra`InequalitySolve` for doing some symbolic calculations. The package implements the function InequalitySolve.

Needs["Algebra`InequalitySolve`"]

As the function name indicates, InequalitySolve “solves” inequalities. Solving an inequality here means describ-ing the solution sets in a canonicalized manner. The canonicalized form is a hierarchical description of the allowed intervals for the variables.

?InequalitySolve

Next, we “solve” the inequality I-16x6+24x4-9x2-4y4+4y2M2-1ê8<0.

[x_, y_] = (24x^4 - 9x^2 - 16x^6 + 4y^2 - 4y^4)^2 - 1/8;

iSol = InequalitySolve[[x, y] < 0, {x, y}];

Because the result iSol is quite large and its structure is not immediately recognizable, we do not display the result. It has 25 independent parts.

iSol // Length

Here is the first part.

First[iSol]

It is of the form x1<x<x2Ï Iy1HxL<y<y2HxL Íyè

1HxL<y<yè

2HxLM. This form is the canonicalized description of one region where the above inequality holds. The regions are areas or lines extending along the y-direction over a fixed x -interval. (For a more detailed description, see Section 1.2.3 of the Symbolics volume [1285÷] of the GuideBooks.) Similar to the above Solve example, when “solving” inequalities, one often ends up with Root-objects. The x1,x2 are algebraic numbers and y1HxL,y2HxL,yè

1HxL, and yè

2HxL are algebraic functions of x1 and x2, which means they are inverse functions of polynomials that generically cannot be inverted using elementary functions.

It is straightforward to visualize the canonicalized regions where the inequality holds. We just form polygons by traversing y1HxL from x1 to x2 and going back along y2HxL from x2 to x1 and similarly for yè

1HxL, yè

2HxL. The little function makePolygon forms a polygon from a logical combination of inequalities.

makePolygon[Inequality[x1_, Less, x, Less, x2_] &&

Inequality[y1_, Less, y, Less, y2_], plotpoints:pp_Integer] :=

With[{(* avoid endpoints *) ∂ = 10.^-12}, Polygon[Join[

(* bottom and top boundaries *)

Table[{x, y1}, {x, x1 + ∂, x2 - ∂, (x2 - x1 - 2∂)/pp}], Table[{x, y2}, {x, x2 - ∂, x1 + ∂, (x1 - x2 + 2∂)/pp}]]]]

iSol contains 41 independent 2D regions. Here, we show them; each one has a randomly assigned color. (The regions described by the inequality are “thickened” versions of the Lissajous curve 8x, y<=8sinH2 JL, cosH3 JL<. As a guide for the eye, we display this curve in gray on top of the colored regions.)

Show[{Graphics[{Thickness[0.01], the above inequality is positive (meaning the maximal spatial extension of the set defined by the inequality from the origin). [1244÷]. We specify the inequality using the forall quantifier.

ForAll[{a, b, c}, Element[{a, b, c}, Reals] && a > 0 && b > 0 && c > 0, a/(b + c) + b/(a + c) + c/(a + b) >= 3/2] // Resolve

In case the constant 3ê2 were not known in advance, one could easily determine it, either through quantifier elimination or minimization.

ForAll[{a, b, c}, Element[{a, b, c, R}, Reals] && a > 0 && b > 0 && c > 0, a/(b + c) + b/(a + c) + c/(a + b) >= R] // Resolve

Minimize[a/(b + c) + b/(a + c) + c/(a + b), a > 0 && b > 0 && c > 0, {a, b, c}]

While being inherently of algebraic nature, functions like Resultant and GroebnerBasis can often be fruitfully used to deal with analysis problems (as we will do repeatedly in the GuideBooks). Here we use them to derive nonlinear polynomial differential equations for the function @HzL=tanHlnHzLL. Differentiating @HzL repeatedly shows powers of the secHlnHzLL and @HzL.

Table[Derivative[k][@][z] - D[Tan[Log[z]], {z, k}], {k, 0, 3}] //

Together // Numerator

Eliminating secHlnHzLLn and tanHlnHzLLm yields polynomial differential equations such as z@HzL=@£HzLH2 @HzL -1L in z, @HzL, @£HzL, @HzL and maybe higher derivatives of @HzL.

GroebnerBasis[%, {}, {Tan[Log[z]], Sec[Log[z]]},

MonomialOrder -> EliminationOrder] // Factor

Taking two such differential equations yields a z-free, nonlinear, third-order differential equation for @HzL=tanHlnHzLL. Resultant[%[[1, -1]], %[[2, -1]], z] // Simplify

Substituting tanHlnHzLL for @HzL in the last differential equations gives zero.

% /. {@[z] :> Tan[Log[z]],

Derivative[k_][@][z] :> D[Tan[Log[z]], {z, k}]} // Simplify

Next, we examine a self-defined rule. The function xp sinHxqL lnHxrL cannot be integrated by Mathematica with respect to x (it is not possible to express this integral in named special functions).

Integrate[x^p Tan[x^q] Log[x^r], {x, 0, Pi}]

However, we can create a new symbol XtoPowerαTimesSinOfXtoPowerβTimesLogOfXtoPowerγ[p, q, r] for this integral.

Unprotect[Integrate];

Integrate[x_^α_. Tan[x_^β_.] Log[x_^γ_.], {x_, 0, Pi}] :=

XtoPowerαTimesTanOfXtoPowerβTimesLogOfXtoPowerγ[α, β, γ];

Protect[Integrate];

Mathematica can use this rule when it is possible.

Integrate[z^I Tan[z^23] Log[z], {z, 0, Pi}]

Mathematica is good at matching patterns. For example, we can extract all elements from a list that are the product of x with any factor, including the not explicitly written factor 1.

Cases[{3, 2 + 7 I, 6 x, I x, u x, x, a x, u}, Optional[_] x]

Here is an umbral example [380÷]. When one interprets the even powers ,k in the expanded form of H,-iLn=0 as indexed numbers ,k, then the ,k are just the absolute values of the Euler numbers Ek§ [439÷], [479÷]. Here is an example for n=12. This is the expanded form.

Expand[(, - Sqrt[-1])^12]

Using patterns and replacements is straightforward to go from the monomials ,k to the indexed quantities ,k.

% /. ,^k_. :> Subscript[,, k]

This checks the above statement about the Euler numbers.

% /. Subscript[,, k_] :> Abs[EulerE[k]]

The next input tests if the first four digits of p appear somewhere within the first 50000 digits of the decimal representa-tion of 17-1000. (It turns out that within the periodic part of the decimal expansion of 17-1000, the first 1230 digits of p appear many times [1251÷], [1252÷]; almost all real numbers are lexicons [226÷], [584÷].)

MatchQ[First[RealDigits[N[1/17^1000, 50000]]], {___, 3, 1, 4, 1, ___}]

The first four digits of p appear also in the (integer) digits of 171000.

MatchQ[IntegerDigits[17^1000], {___, 3, 1, 4, 1, ___}]

Mathematica can simplify expressions when it knows properties of the variables. In the next input, it is assumed that p is an odd prime.

Simplify[Sin[p^2 Pi] + (-1)^p, Element[p, Primes] && p > 2]

The following expression does not automatically “simplify” to x+1. Sqrt[x^2 + 2 x + 1]

Actually, such a transformation would be mathematically wrong for many complex numbers.

{Sqrt[x^2 + 2 x + 1], x + 1} /. x -> -3 + 2I

Under the additional assumption that x is a positive real number, Mathematica can simplify x2+2 x+1 to x+1. Simplify[Sqrt[x^2 + 2 x + 1], Element[x, Reals] && x > 0]

Many more functions in Mathematica perform symbolic mathematics. The Numerics [1284÷] and Symbolics [1285÷]

volumes of the GuideBooks discuss many more details.

Mathematica can carry out complicated and never-before-carried out calculations in various mathematical topics with great ease. The following short code, for instance, searches for a number whose digits of its decimal expansion digits agree with the terms of its (nonsimple) continued fraction expansion.

Make Input

(* difference between decimal expansion and continued fraction *) δ[l_] := N[Abs[FromDigits[{l, 1}, 10] -

Fold[#2[[2]]/(#2[[1]] + #1)&, l[[-2]]/l[[-1]], Partition[Reverse[Drop[l, -2]], 2]]]];

(* recursively add digit pair and keep a set of best lists *)

Nest[First /@ Take[#, Min[43, Length[#]]]&[Sort[{#, δ[#]}& /@

Flatten[Flatten[Table[Join[#, {i, j}],

{i, 0, 9}, {j, 9}], 1]& /@ #, 1],

(#1[[2]] < #2[[2]])&]]&, {{0}}, 72][[1]]

After running, the code above returns the following result.

{0, 2, 7, 3, 9, 4, 4, 1, 9, 5, 7, 3, 9, 2, 7, 1, 6, 1,

The next input forms the continued fraction corresponding to the last list.

With[{b = C /@ %},

DeleteCases[Hold[0 + #]& @@ {Fold[#2[[2]]/(#2[[1]] + #1)&,

b[[-2]]/b[[-1]], Partition[Reverse[Drop[b, -2]], 2]]}, C, Infinity, Heads -> True]] // InputForm

Collapsing the last expression into a fraction and then calculating a high-precision approximation of this fraction yields a decimal number, showing that the first 100 digits agree with the continued fraction terms.

ReleaseHold[%]

N[%, 100]

Here is a short way to show the agreement of the first 100 digits using Mathematica.

RealDigits[%%, 10, 100, 0][[1]] == Take[%%%%, 100]

The code above can easily be adapted to calculate numbers with many identical decimal and continued fraction digits, for the case of a simple continued fraction, and to deal with the case for a base different from 10.

Mathematica also allows larger mathematical formulas and algorithms to be entered in a direct way. As a small exam-ple, let us implement the calculation of the series of the conformal map w= fHzL after Szegö’s method (see [346÷],

Here, l is the length of the boundary of the square, and the integration has to be carried out along the boundary of the square. The pnHxL form orthogonal polynomials. HHnL and GHnL are square matrices of dimension n with elements hj,k,

and gj,k respectively.

Here, the above-described method is implemented. ord determines the order in z.

ConformalMapSquareToUnitDisk[ord_, z_] :=

Module[{h, H, G, d, l, p, k, t, a, b, λ, integrand, edgeList = {-1 + I, 1 + I, 1 - I, -1 - I}},

lineSegments = Partition[Append[edgeList, First[edgeList]], 2, 1];

(* edge length *)

λ = Total[Abs[#[[2]] - #[[1]]]& /@ lineSegments];

(* the h-integrals *)

Cancel[Pi/(4 k[0, 0]) Expand[Integrate[k[0, ξ]^2, {ξ, 0, z}]]]]

Here is an example (for ord=8, the constant term deviates about 0.09 % from its exact value).

ConformalMapSquareToUnitDisk[8, z]

Using Mathematica’s graphics capabilities, we can easily visualize the conformal map generated by the last function.

The left picture shows a mesh in the square with the corners -1+i, 1+i, 1-i, -1-i, and the right picture shows the mesh after mapping; the unit disk is shown underlying in gray.

With[{pp = 15},

Module[{points, opts}, (* points forming the grid *)

points = Table[N[x + I y], {x, -1, 1, 1/pp}, {y, -1, 1, 1/pp}];

(* common graphics options *)

opts[label_] := Sequence[AspectRatio -> Automatic, PlotLabel -> label, PlotRange -> {{-1.2, 1.2}, {-1.2, 1.2}}];

Show[GraphicsArray[{

(* the original square *)

Graphics[{Thickness[0.001], Line /@ #, Line /@ Transpose[#]}&[

Map[{Re[#], Im[#]}&, points, {-1}]], opts["z-plane"]], [1285÷] of the GuideBooks) [865÷]. Using elliptic functions, it is possible to find an exact formula for a conformal map from a rectangle to the unit disk [1013÷]. The next graphic visualizes the exact map. To avoid repeating the last input, we modify the last input in a programmatic way and then evaluate the new code.

Module[{wExact, k = InverseEllipticNomeQ[Exp[-2. Pi]], K},

The typesetting capabilities of Mathematica allow mathematical formulas and algorithms to be entered in a still more direct way.

ConformalMapSquareToUnitDiskSF@ω_Integer ? Positive, z_D :=

ModuleB8h, H, G, d, l, p, k, t, a, b,ρ,

While the availability of numerical values of special functions is an important part of Mathematica, in many instances its problem-solving power arises from connecting numerics, symbolics, and graphics. Here is another simple example:

the path of a point vortex in an inviscid fluid in a rectangular region. The path of the vortex 8xHtL,yHtL< is given by the following Hamiltonian system [1305÷], [1327÷] (for spherical rectangles, see [592÷]). Here ƒHz;g2,g3L is the Weier-strass ƒ function and g2Hw1,w3L and g3Hw1,w3L are the invariants as a function of the half-periods.

x£HtL= ∑H

It is straightforward to get the explicit form of the equations of motions.

odes = {x'[t] == D[H, y[t]], y'[t] == - D[H, x[t]]};

odes // TraditionalForm

And it is straightforward to solve these equations numerically for different initial conditions. (We choose G =1, a=2, and b=1 in the following input). The picture shows periodic, self-intersection-free trajectories that are ellipse-shaped for initial conditions near the center and that approximate the rectangle for starting values near the edges.

Module[{odesN, T = 3, nsol}, (* substitute values for G, a, and b *)

odesN = odes /. {{g2, g3} -> WeierstrassInvariants[{2 a, 2 I b}], {N2, N3} -> WeierstrassInvariants[{2 b, 2 I a}]} /.

{a -> 2, b -> 1., Γ -> 1};

Show[(* use different initial conditions of the form {x0, 0} *) Table[(* solve equations of motion *)

nsol = NDSolve[Join[odesN, {x[0] == x0, y[0] == 0}], {x, y}, {t, 0, 2T/x0}, MaxSteps -> 10000];

DisplayFunction -> $DisplayFunction, Frame -> True, FrameTicks -> False, FrameStyle -> {Thickness[0.02]}]]

The penultimate example of this subsection deals with a slightly more complicated example: the lines of magnetic induction (which in a 2D cylindrical geometry are also the lines of constant vector potential) of a cylindrical magnet with an air gap. The z component Az of the vector potential A (a is the inner radius, b is the outer radius of the magnet,

As the result shows, Mathematica was able to sum all three of the above symbolic infinite sums in closed form. The normal component of the field is everywhere differentiable.

Plot@Evaluate@A@3ê2,θ, 81, 2, 7ê8π<DD, 8θ, 0, 2π<, Frame→True, Axes→False,

PlotStyle→88GrayLevel@0D, Thickness@0.003D<<, Prolog→8Hue@0D, Rectangle@80, 0.77<, 87ê8π, 0.869<D,

Rectangle@89 πê8, 0.77<,82 π, 0.869<D<D The tangential component has a discontinuity in its first derivative at the magnet.

Plot@Evaluate@A@r, 0,81, 2, 7ê8π<DD, 8r, 0, 3<, Frame→True, Axes→False, PlotStyle→88GrayLevel@0D, Thickness@0.003D<<,

Prolog→8Hue@0D, Rectangle@81,−0.1<, 82, 2.<D<D

The field lines (for a cylindrical geometry, they are the equi-Az-potential lines) are shown in the following graphics.

The homogeneous field in the air gap is nicely visible (although running the following input will take a few minutes).

ContourPlotBEvaluateBReBAB x2+y2 , ArcTan@x, yD, 81, 2, 7ê8π<FFF, 8x,−3, 3<, 8y,−3, 3<, PlotPoints→160,

Contours→Range@−0.1, 2.2, 0.1D, ContourShading→False, Compiled→False, FrameTicks→None,

ContourStyle→88Thickness@0.001D, GrayLevel@0D<<,

Prolog→8Thickness@0.006D, Hue@0D, Disk@80, 0<, 2,8−7ê8 π, 7 ê8 π<D, GrayLevel@1D, Disk@80, 0<, 1,8−7π, 7π< ê8D<F

Here is a 3D picture of the field strength.

ListPlot3D@H*take out data from last graphic*LFirst@%D,

ListPlot3D@H*take out data from last graphic*LFirst@%D,