EssentialsofProgrammingin Mathematica

2y ago
8 Views
2 Downloads
233.09 KB
16 Pages
Last View : 10d ago
Last Download : 3m ago
Upload by : Elisha Lemon
Transcription

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationREssentials of Programming in Mathematica Essentials of Programming in Mathematica provides an introduction suitable for readerswith little or no background in the Mathematica language, as well as for those with someexperience using languages such as C, JAVA, or PERL. The author, an established authorityon Mathematica programming, has written an example-driven text that covers the languagefrom first principles, as well as including material from natural language processing, bioinformatics, graphs and networks, signal analysis, geometry, computer science, and manyother applied areas.The book is appropriate for self-study or as a text for a course in programming in computational science. Readers will benefit from the author’s tips, which provide insight andsuggestions on small and large points. He also provides more than 350 exercises fromnovice through to advanced level, with all of the solutions available online. Assumes no formal knowledge of programming More than 350 exercises from basic to advanced make the book ideal for teaching or forself-study Appeals to a broad readership by using examples derived from a wide variety of fields Solutions to exercises are available from www.cambridge.org/wellin essentialsPaul Wellin worked for Wolfram Research from the mid-1990s through 2011, directing theMathematica training efforts with the Wolfram Education Group. He has taught mathematics both at public schools and at university level for over 12 years. He has given talks,workshops, and seminars around the world on the integration of technical computing andeducation, and he has served on numerous government advisory panels on these issues. Heis the author and co-author of several books on Mathematica. in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore information in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationEssentials of Programming inRMathematica PAUL WELLIN in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationUniversity Printing House, Cambridge CB2 8BS, United KingdomCambridge University Press is part of the University of Cambridge.It furthers the University’s mission by disseminating knowledge in the pursuit ofeducation, learning and research at the highest international levels of excellence.www.cambridge.orgInformation on this title: www.cambridge.org/9781107116665c Paul Wellin 2016 This publication is in copyright. Subject to statutory exceptionand to the provisions of relevant collective licensing agreements,no reproduction of any part may take place without the writtenpermission of Cambridge University Press.First published 2016Printed in the United Kingdom by Bell and Bain LtdPage 267. Quotation from “The Library of Babel” by Jorge Luis Borges. Translated by James E. Irby,c 1962, 1964 by New Directions Publishing Corp. Reprinted byfrom LABYRINTHS, copyright permission of New Directions Publishing Corp.c 2012 Artists Rights Society (ARS), NewPage 296. Marcel Duchamp, “Roue de bicyclette” York/ADAGP, Paris/Succession Marcel Duchamp.RWolfram Mathematica is a registered trademark of Wolfram Research, Inc.A catalogue record for this publication is available from the British LibraryLibrary of Congress Cataloguing in Publication dataISBN 978-1-107-11666-5 HardbackText set in DTL Albertina 11/13; code set in Inconsolata; captions set in Syntax LT Std;RSystem Mathematica , Version 10.2.Designed and typeset by the authorAdditional resources for this publication at www.cambridge.org/wellin essentialsCambridge University Press has no responsibility for the persistence or accuracyof URLs for external or third-party internet websites referred to in this publication,and does not guarantee that any content on such websites is, or will remain,accurate or appropriate. in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationTo the memory of my fatherwhose love of books curiously led to this in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore information in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationContentsPreface · xi1 11 Programming with Mathematica · 1111 11.1 Introduction to programming · 2111 1Your1 �1Creating1programs1.2 Getting started · 811 1.3 Getting help · nformation1·1Documentation1.4 Notes and further reading · 181111 12 The Mathematica language · 19111 12.1 Expressions · 201 essions1·1Nesting1expressions ·1Exercises2.2 Numbers · 331 ndom1numbers1·1Exercises2.3 De nitions · 411 1De 1with1multiple1de nitions1·1Exercises2.4 Predicates and Boolean operations · 491111 1Predicates · Relational1and1logical1operators · Exercises2.5 Attributes · 551 ises2.6 Notes and further reading · 571111 1 in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationviiiContents3 Lists and associations · 59111 13.1 Creating and displaying lists · 601111 1Displaying1lists1·1Arrays1·1Exercises3.2 Testing and measuring lists · 691111 1Testing1a1list1·1Measuring1lists1·1Exercises3.3 Operations on lists · 72111 t1·1Multiple1lists1·1Exercises3.4 Associations · 841 ercises3.5 Differences from other languages · 901111 13.6 Notes and further reading · 931111 14 Patterns and rules · 95111 14.1 Patterns · 961 s4.2 Transformation rules · 11111 transformation1rules1·1Exercises4.3 Examples · 1161 �1Exercises4.4 Notes and further reading · 1311111 15 Functions · 1331 15.1 Functions for manipulating expressions · 1341111 ses5.2 Iterating functions · 14611 ses5.3 Recursive functions · 15211 mic1programming1·1Exercises5.4 Loops and ow control · 1591111 1Conditional1functions1·1Piecewise-de es5.5 Pure functions · 17611 for1attributes1·1Exercises in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationContentsix5.6 Examples · 1901 Exercises5.7 Notes and further reading · 2081111 16 Programs · 2091 16.1 Scoping constructs · 21011 ock on1·1Exercises6.2 Options and messages · 217111 1Options1·1Messages1·1Exercises6.3 Examples · 2231 g1plots1·1Random1walks1·1Exercises6.4 Notes and further reading · 2411111 17 Strings · 2431 17.1 Structure and syntax · 244111 g1strings1·1Character1codes1·1Exercises7.2 Operations on strings · 247111 ncoding1text1·1Anagrams1·1Exercises7.3 String patterns · 25511 1·1Exercises7.4 Regular expressions · 26111 1Contractions1·1Exercises7.5 Examples · 2671 DNA1sequences1·1Blanagrams1·1Exercises7.6 Notes and further reading · 2811111 18 Graphics and visualization · 283111 18.1 The graphics language · 284111 1Primitives1· xercises8.2 Dynamic graphics · 29211 s1·1Exercises8.3 Ef cient structures · 30311 ymbolic1expressions1·1Exercises in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationxContents8.4 Examples · 3141 ycloids1·1Space- polygon1·1Triangle1centers1·1Exercises8.5 Notes and further reading · 3431111 19 Program optimization · 34511 19.1 Ef cient programs · 34611 1·1Exercises9.2 Parallel processing · 36611 1Basic1examples1·1Pro ling1·1Exercises9.3 Compiling · 3721 1Compile1·1Compiling1to1C1·1Exercises9.4 Notes and further reading · 3781111 110 Packages · 3791 110.1 Working with packages · 379111 2 Creating packages · 38211 loyment10.3 RandomWalks package · 38911 rcises10.4 Notes and further reading · 3941111 1Bibliography · 3951 1Index · 4051 1 in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationPrefaceProgramming with Mathematica11In its brief history, the world of programming has undergone a remarkable evolution. Those of usold enough to remember boxes of punch cards and batch jobs couldn’t be happier about some ofthese changes. One could argue that the limitations, physical and conceptual, of the early programming environments helped to focus that world in a very singular manner. Eventually, efforts toovercome those limitations led to a very visible and broad transformation of the world of computerprogramming. We now have a plethora of languages, paradigms, and environments to choose from.At times this embarrassment of riches can be a bit overwhelming, but I think most would agree thatwe are fortunate to have such variety in programming languages with which to do our work.I learned about Mathematica as I suspect many people have – after using several languages overthe years, a colleague introduced me to a new and very different tool, Mathematica. I soon realizedthat it was going to help me in my work in ways that previous languages could not. Perhaps themost notable feature was how quickly I could translate the statement of a problem to a workingprogram. This was no doubt due to having a functional style of programming at my ngertips butalso being able to think in terms of rules and patterns seemed to t well with my background inmathematics.Well, Mathematica is no longer a young up-start in the programming world. It has been aroundnow for over 25 years, making it, if not an elder statesman, certainly a mature and familiar player.And one that is used by people in elds as varied as linguistics, bioinformatics, engineering, andinformation theory. Like myself, many people are rst introduced to it in an academic setting. Manymore are introduced through a colleague at work. Still others have seen it mentioned in variousmedia and are curious as to what it is all about. After using it to do basic or more advanced computation, most users soon nd the need to extend the default set of tools that come with Mathematica.Programming is the ticket.So what makes Mathematica such a useful programming tool? First, it is a well-designed language,one whose internal logic will be quite apparent as you get to know it. It is not only easier to use butit also provides an enjoyable programming experience. Second, it is a multi-paradigmatic language,meaning several different styles of programming are available under one roof: functional programming (like Lisp or Haskell), procedural programming (like C, Fortran, Java, Perl), logic programming (like Prolog), rule-based programming (Snobol and some of Prolog), and it has a 1111111111111111111111111111111111111111 11 in this web service Cambridge University 111111 111111111111111111111111111111111 ww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationxiiPrefacegp ggstring pattern language, including support for regular expressions (like Perl). In no other languagecan you program in so many styles and mix them at will.The generality of the Mathematica language is in sharp contrast to what are called domain-speci clanguages. As the name implies, these are languages designed to solve problems for a speci c application domain. HTML is a classic example – it is a markup language that is only really useful for itsintended purpose, marking up web pages. Similarly, TEX, used for page composition of technicalmaterial and GraphML, for representing, formatting, and operating on graph objects, can both bethought of as domain-speci c languages.Mathematica takes a different approach. The language is general enough that it can be used in avariety of different disciplines to represent and solve computational problems. As for speed, it is fastenough for many problems you will encounter. When the need to increase performance arises,options are available: parallel programming, compilation, connecting to external programs.Given the generality of Mathematica and the fact that you can choose different programmingparadigms with which to write your programs, the novice is often left feeling a little bewildered.Which style should you use for a particular problem? Which is fastest? Which approach makes themost sense for your particular domain? In general, although good Mathematica programmers rely ona functional style to a great degree, your Mathematica programs will contain a combination of styles.They tend to be more compact, easier to read, and easier to debug (although not always) than moretraditional procedural implementations. Well, perhaps I am showing my bias. It may be that I choseMathematica because it t well with how I think; or perhaps my adoption of Mathematica has shapedthe form of programs I write. Perhaps this is just another instance of the Sapir–Whorf hypothesis inlinguistics, which states that a spoken language in uences the patterns of thought of the speaker ofthat language. Rather than go down that rabbit hole, let’s just say that you will program differentlywith Mathematica, and, I think, more ef ciently and more enjoyably.1111111111111111111111111111111111111 1111111111111111111111111111111111 1111111111111111111 1111111111111111111111111111111 1111111 111Who is this book for?1111This book is designed for two overlapping audiences. First, it is intended as a self-contained, selfstudy book for anyone who wants to learn how to use the Mathematica language to solve problemsin their domain. Typically, this includes researchers, academics, students, and even hobbyists whoare accustomed to picking up and learning about any tools that will help them do what they dobetter. Comments from users of my previous books have persuaded me that an example-basedbook, such as this, is appreciated by many.Second, this book can also be used as a text in a course on Mathematica programming such as isused in many schools and universities as part of, or in preparation for, a computational sciencecourse. Toward that end, each section includes many exercises to check basic understanding of theconcepts in that section, as well as providing extended and (hopefully) interesting examples in theirown right. A complete set of solutions in both PDF format and as Mathematica notebooks is availableat the publisher’s website www.cambridge.org/wellin 1111111111111111111111 in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationPrefacexiiiThe examples and exercises in this book draw from many different elds, including:1 1111111111111111111111111111111111Computer science. Encoding/encryption, sorting, adjacency structures, Collatz sequences,Hamming numbers, Hamming weight, Tower of Hanoi, Fibonacci numbers, Fibonacci words,Euler numbers, root nders, Horner polynomial representation, inverse permutations,random number algorithms, sieving, associative arrays, Monte Carlo simulations,comparisons with other languages.111111111111111111111 1Bioinformatics. Analysis of nucleotide sequences, computing GC ratios, displaying blocks ofgenetic information, searching for subsequences, protein–protein interaction networks, dotplots, displaying amino acid sequences, space- lling plots.1 11111111111111111111Data and signal analysis. Filtering signals (smoothing, clipping, removing spikes), entropy ofsignals, Benford’s law, stem plots, lag plots, statistical analysis of data, random walks,visualizing extent of data, Hamming distance, cluster analysis.11111111111111111111111111111111 Finance and economics. Time-series analysis of economic and nancial data, trend plots, stockscreens. Geometry. Convex hull, diameter of point sets, point-in-polygon problems, traveling salesmantype problems, hypocycloids and epicycloids, area and perimeter problems, boundaries ofregions, Heron’s formula, triangle medians and centers.111111111111 1111111111111111111111111111Graphs and networks. Random graphs, regular graphs, bond percolation, connectedcomponents, dense graphs, directed acyclic graphs, neighborhood graphs, random walk ongraphs.11111111111111111111 Image processing. Resizing, ltering, segmentation. Mathematics. Palindromic numbers, triangular numbers, pyramidal numbers, truth tables,prime gaps, Vandermonde and Jacobian matrices, Mersenne numbers, Venn diagrams,geometric transformations.1111111111111111111111111 Solar physics and atmospheric science. Analyzing and visualizing sunspot activity using timeseries, analyzing global sea-surface temperature data, solar magnetic eld cycles.11111 1111111111111111Textual analysis and natural language processing. Corpus linguistics, word stemming, stop words,comparative textual analysis, scraping websites for data, sorting strings, bigrams and n-grams,word games (anagrams, blanagrams, palindromes), ltering text.111111111111111111111111111111The background necessary to successfully navigate and learn from this book includes someintroductory undergraduate mathematics (basic linear algebra, geometry). The science topics andproblems introduced in this book are mostly self-contained and, where necessary, they point toavailable references in the literature. Although no prior experience with programming is assumed,even the most basic experience with writing, running, or debugging programs will be helpful ingetting you up and running more 1111111111111111111111111 in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationxivPrefaceThis book is not a tutorial introduction to Mathematica. For that, fortunately, there are manyuseful resources available, including in-product tutorials, online courses, and many good books.Refer to the Wolfram Research website for a comprehensive listing of these materials.1111111111111111111111111111111111111How to use this book1111For those new to Mathematica, Chapter 1 will give you a sense of what it means to program, what itmeans to program in Mathematica, and introduces you to some of the basic tools every Mathematicauser should know about: entering and evaluating expressions, dealing with errors, getting help.The real meat of the book starts with Chapter 2, which provides a semi-formal description of theMathematica language with a particular focus on expressions. Chapters 3 through 5 (lists, patternsand rules, functions) are the core of the book. Lists are a fundamental data type in Mathematica andprovide a relatively simple structure for much of what follows. Pattern matching and the use oftransformation rules are an essential and somewhat unique aspect that every Mathematica programmer must master. Functional programming, introduced in Chapter 5, will likely be new to you, butonce you understand it, the speed and ef ciency of what you can do will increase dramatically.Chapter 6 introduces localization constructs, options and messages enabling your programs tolook and behave much like the built-in functions. Although you could skip this chapter if you weresolely focused on solving particular computational problems, spending some time with these topicswill help you to start thinking like a programmer. How will your programs be used by others? Howwill they likely interact with your programs? What should happen when something goes wrong?Strings are used of course in linguistics, but they also have broad applicability in computerscience, web search, and bioinformatics. They are discussed in Chapter 7, which includes an introduction to regular expressions. If you do little or no work with strings you could safely skim or skipthis chapter but there is a lot of useful material there if you do dive in.Chapter 8 on graphics and visualization gives an introduction to the Mathematica graphicslanguage as well as the dynamic expression language as it relates to graphics. Topics on optimizingyour graphics code are included.With all the different approaches available in Mathematica to solve problems, it is sometimesdif cult to determine the “best” approach. Chapter 9 on program optimization addresses this issuefrom the point of view of speed and ef ciency; that is, which approaches will help your programsrun faster and use fewer system resources.Chapter 10 provides a framework for those who wish to turn their programs into packages thatcan be shared with colleagues, students, or clients. It includes an extended example, random walks,so that you can begin to see examples of larger programs that include modularization, namespaceconstructs, messaging, options, testing, and other meta-programming issues that are important tothink about as your programming skills advance.To return to the question about which style of programming you should adopt for a particularproblem, I hope that this book will convince you that this is the wrong question to ask. As youbecome more familiar with the Mathematica programming language, you will start to reword andformulate your programs and implement them using all of the tools you have under your 11111111111111111111111111111111111111111 11111111 in this web service Cambridge University idge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationPrefacexvyp gpgyyLearning different paradigms does not point to an either/or approach, but allows you to use combinations of programming styles to solve your problems as ef ciently as possible.With that in mind, do not take the formal structure of this book too literally. Although books arepretty linear physical objects – one page or chapter follows another – learning is not linear. It is neto jump around as the need arises. In fact, you are encouraged to do so. Although, in general, lattermaterial presupposes knowledge of what has come before, several examples and exercises useconcepts that are developed later in the book and if you are not already familiar with them, youshould feel free to jump ahead.Numerous references are made throughout the book to tutorials and other help documents thatare found in Mathematica’s help system, the Wolfram Language and System Documentation Center,referred to as WLDC. This comprehensive help system is available in Mathematica under the Helpmenu and online at reference.wolfram.com.The exercises (over 350 of them) are an integral part of this book. Some test your knowledge ofbasic concepts in each section; some extend those concepts; and some use those concepts to solvemore substantial and interesting problems. “Life is not a spectator sport” and neither is programming. Try to do as many of the exercises as you can. There is much to learn there.Resource limitations have prevented the inclusion of the solutions to the exercises with thisbook (printed, they would stretch over 240 pages). Fortunately, the solutions to the exercises areavailable online at the publisher’s website (www.cambridge.org/wellin essentials) and the author’swebsite (www.programmingmathematica.com) in both Mathematica notebook format as well asPDF. These sites also contain most of the programs and packages developed in this book, the book’sbibliography with live clickable references, lists of errata, and some extra material that did not makeit into the printed book.Numerous data les are used throughout this book, many imported from the web and someresiding in a project directory for this book. To set up your environment so that import worksseamlessly, download the data les from the author’s or publisher’s website as indicated in theprevious paragraph. Then, wherever you put the directory of data les, use something like thefollowing to add that directory to your path. You may nd it convenient to put this command in aKernel/init.m le so that it is evaluated each time you start a new rependTo[ Path,ToFileName[{ UserBaseDirectory, "Applications", "EPM", "Data"}]];Finally, a word about Mathematica itself. As this book was being developed, a bifurcationoccurred and where there was one name, Mathematica, now there are two: the Wolfram Language andMathematica. The Wolfram Language is the name of the underlying language and Mathematica is thewider product in which that language occurs. Since I have used both the language and the productthroughout the book, in an attempt to simplify, I have opted to refer to the software simply by usingthe broader term Mathematica 111 11 111111111111111111111111111111 in this web service Cambridge University Presswww.cambridge.org

Cambridge University Press978-1-107-11666-5 - Essentials of Programming in Mathematica Paul WellinFrontmatterMore informationxviPrefaceAcknowledgmentsI have been using Mathematica for over 25 years now, but I still run into plenty of puzzling thingsthat I would not be able t

Essentials of Programming in Mathematica provides an introduction suitable for readers with little or no background in the Mathematica language, as well as for those with some experience using languages such as C, JAVA,orPERL. The author, an established authority

Related Documents:

1 Mathematica Basics This chapter is an introduction to Mathematica.We briefly describe many of the most important and basic elements of Mathematica and discuss a few of the more common technical issues related to using Mathematica.Since our primary goal is to use Mathematica to help us understand calculus, you should not initially spend a great amount of time pouring

Introduction.NET/Link Welcome to .NET/Link, a product that integrates Mathematica and Microsoft's .NET platform.NET/Link lets you call .NET from Mathematica in a completely transparent way, and allows you to use and control the Mathematica kernel from a .NET program. For Mathematica users,.NET/Link makes the entire .NET world an automatic extension to the Mathematica environ-

Dec 09, 2005 · Beginner’s Mathematica Tutorial Introduction This document is designed to act as a tutorial for an individual who has had no prior experience with Mathematica. For a more advanced tutorial, walk through the Mathematica built in tutorial located at Help Tutorial on the Mathematica Task Bar.

Online Help from Mathematica 2 Mathematica Tutorial.nb. Introduction Mathematica is a system for doing mathematics on the computer.It can do numerics,symbolics,graphics and is also a programming language.Mathematica has infinite precision.It can plot functions of a single variable; make

mathematica Remarks This section provides an overview of what wolfram-mathematica is, and why a developer might want to use it. It should also mention any large subjects within wolfram-mathematica, and link out to the related topics. Since the Documentation for wolfram-mathematica is new, you may need to create initial versions of those related .

PROGRAMMING IN MATHEMATICA, A PROBLEM-CENTRED APPROACH 7 1.3. Algebraic computations. One of the abilities of Mathematica is to handle symbolic com-putations. Consider the expression (x 1)2. One can use Mathematica to expand this expression: Expand[(x 1) 2] 1 2x x2 Mathematica can also do the inverse of this task, namely to factorize an expression:

Start up Mathematica from a Linux desktop terminal window. Parallel Mathematica jobs can be submitted from with the Mathematica notebook interface as well as using PBS command files and the example scripts show how to setup and submit the jobs Documentation:Submitting Mathematica Parallel Jobs (UVACSE) October 8, 2014 44 / 46

API publications necessarily address problems of a general nature. With respect to particular circumstances, local, state, and federal laws and regulations should be reviewed. Neither API nor any of API's employees, subcontractors, consultants, committees, or other assignees make any