Transcription of PROGRAMMING IN MATHEMATICA, A PROBLEM-CENTRED …
1 PROGRAMMINGINMATHEMATICA, A a ,=,:=,== ! bitof ,If , ,Mathematicarules! ;Multilinearalgebra66 References69 Date: March 8, , A PROBLEM-CENTREDAPPROACHT eachingthemechanicalperformanceof routinemathematicalop-erationsandnothing elseis wellunderthelevel of thecookbookbecausekitchenrecipes doleave somethingto theimaginationandjudgment of thecookbutthemathematicalrecipes olyaThisnotegrewoutof a moduleI gave at Queen'sUniversity Belfastin theWintersemester2004, booksalreadywrittenabouthow to useMathematica, I noticedtheyfallinto two categories:eithertheyprovideanexplanatio naboutthecommands,in thestyleof:enterthecommand,pushthebutton andseetheresult;or bookswhich the rstcategorydidnotinspireme(normy imagination)andthesecondcategoryweretoo di cultto understandandnotsuitableforlearning(orte aching) mathematica 's abilitiesto doprogrammingandsolve couldnot nda book thatI couldfollow to teach classonecannotgo on forevershowingstudents justhow commandsinMathematicawork;ontheotherhand it wouldbe verydi cultto follow thecodesif onewritesa programhavingmorethan ve linesin class(especiallyasMathematica's styleof programmingprovidesa condensedcode).
2 's styleof triedto show whenwe adoptthisapproach, hownaturallyonecansolve (nice)problemswith( mathematica ) anexample:Does theformulan2+n+ 41producea primenumber forn= 1 to 39?Solution.(#^2+#+ 1) & /@ Range[39]2 PrimesTrueOrin anotherProblemwe triedto show how onecane ectivelyusepatternmatchingto checkthatfortwo matricesAandB, (ABA 1)5=AB5A 1. Oneonlyneedsto introducethefactthatAA 1= 1 andthenMathematicawillcheck theproblemby cancellingtheinverseelements insteadof code might looklike Dutch now, thereaderwillobserve as we proceedhowthecodesstartmakingsense,as if thisis themostnaturalway to approach theproblems.(Peoplewhoapproach theproblemswitha proceduralstyleof programmingwillexperiencethatthisstylere placetheirway of thinking!)
3 We have triedto letthereaderlearnfromthecodesandavoidlon gandexhaustingexplanations,as have triedto showthatinMathematica(like in therealworld)therearemany ways to approach a have triedto inspiretheimagination!Someoneoncerightly saidtheMathematicaprogramminglanguageis rathera \Swissarmyknife"containinga vastarray of witha ,onecanfreelymixdi erent stylesof PROGRAMMING ,functional,list-baseandproce duralto achieve a elangeof programmingstylesis whatwe promotein mostlychooseproblemshavingsomethingto dowithnumbersas theydonotneedany consideredfora courseinMathematica, or forselfstudy. It mostlyconcentratesonprogrammingandproble msolvinginMathematica. Thereareexcellent booksPROGRAMMINGINMATHEMATICA, A PROBLEM-CENTREDAPPROACH3writtenaboutMath ematicaforexampleIlanVardi[3], StanWagon[4]or Shaw-Tigg[2]to namea encouragedto have a lookat themas :IlanVardi forhisinput,BrianMcMasterforpolishingmyE nglish4 PROGRAMMINGINMATHEMATICA, A give a quick a usedas a calculatorwiththebasicarith-meticoperati ons+; ; ; =and^ ^4+ 15365639^4+ 18796760^4180630077292169281088848499041 20615673^4180630077292169281088848499041 Thisshowsthat26824404+ 153656394+ 187967604= 206156734, disprovinga conjecturebyEulerthatthreefourthpowersca nnever sumto a fourthpower.
4 (Thisconjectureremainedopenforalmost200y ears,untilNoamElkiesat Harvardcameupwiththeabove counterexamplein1988)Mathematicacanhandl elargecalculations:2^9941-13460882824908 5121524296039576741331672262866890023854 7790489283445006220809834114464364375544 1537075336644867476350501864147070933237 3970608376690404229265789647993709760358 4695523190454849100503041498098185402835 0715968356223294196805976228133454473972 0849260904855192770626054911793590389060 7959811638387214329942787636330953774381 9484486647112496768579888817221203300082 1469684464956146997194126921284336206463 3138595375772004624420290646813260875582 5748847048938424398927023688497864306309 3004422939603370010546595386302009073043 9444822025590974067005973305707995078329 6313093873988508019841625863519452291304 2562936679859587495721031173747796418895 0607019417175060019371524300323636319342 6579851623604745120908986470743078036229 8307038193445486493756647991804258775574 9738339033157350828910293923593527586171 8501994255483467186107454877243988072960 6244911940066680112823824095816458261761 8617466040348020564668231437182554927847 7938099174958025526332332653645774389415 0848953969902818530057870876229329803338 2857354192282590221696026655322108347896 0205168654601146673798130605624748005507 1718250333737502267307344178512950738594 3306843408026982289639865627325971753720 8729564907283028974977135833086795150871 0859216743218522918811670637448496498549 0944305412774440794079895398574694527721 3216658088575436047740884291332729294869 6897496141614919739845432835894324473601 3876096437505146992150326837445270717186 8409183217094836939628006118459374614358 9068811190253101873595319156107319196071 1505984880700270887058427496052030631941 9116692210617615760936724194816062598903 2127984748081075324382632093913796444665 7006013912783603230022674342951943256072 8066126011937871940515149755518754925213 4264394645963853964913309697776533329401 8221580031828892780723686021289827103066 1811511896413189365784540029686001242039 1376964670183983594954112484565597312460 7377987770920717067108245037074572201550 1589959176624495776800680248297667392039 2995410164224776445671222149803657927708 4129255555428170455724308463899881299605 1922731398729120090206088206073376207589 2299473666405897427035811786879875694315 0786544200556034696253093996539559323104 6643003914646580545296501404001942389755 2675534768248624631951431493188170905972 5887801118502811905590736777711874328140 8867867428630210827514925847710129645183 3651979717375170900505673645964696355331 3698192960002673895832892991267383457269 8032599895599750117666420104288854608569 9446442834195232948787488410595750197438 7863531192042108558046924605825338329677 7194691145990192132498496881002118996828 4941331573164056304725480868921823442538 1 PROGRAMMINGINMATHEMATICA, A PROBLEM-CENTREDAPPROACH59959038385241278 6840833479611419970101792978355653650755 3291382986542462253468272075036067407459 5695812738374871782591852747316497058209 5181312905519242710280573023145554793628 4990105092960558497123779789849218399970 3741589767415483070862914548472453672457 2622450131479992681684310464449439022250 5048592508347618947888895525278984009881 9620001486857564023313650914562812719135 4858275083907891469979019426224883789463 551If a number of theform2n 1 happensto be prime,it is calleda primenumber is a number which is divisibleonlyby 1 is easyto see22 1 and23 1 and25 1 1963,Gilliesfoundthattheabovenumber,2994 1 1, is a laptopit takes 16secondsforMathematicatocheck thatthisis a [2^9941-1]TrueBack to easiercalculations:24/172417 Mathematicaalways triesto give a precisevalue,thusgives back2417insteadof [Pi/5]12q12(5 p5)In orderto getthenumericalvalue,onecanusethefunctio nN[].
5 N[24/17] [24/17,20] [expr]givesthe numericalvalueof [expr,n] attemptstogivea , Log,Exp,Sqrt,Sin,Cos,Tan,ArcSin,..For a completelisthave a lookatMathematicalFunctions:Elementary FunctionsintheMathematica's faris 230402457 1 which is discoveredin December 20056 PROGRAMMINGINMATHEMATICA, A numbernas a productof powersof primesandthisdecompositionis unique, ,n=pk11 pkttwherepi's 37534= 2 72 :FactorInteger[37534]{{2,1},{7,2},{383,1 }}FactorInteger[6473434456376432]{{2,4}, {3239053,1},{124909859,1}}PrimeQ[1249098 59]TruePrime[8]19 Prime[n] [n]determineswhethernis a 1640 Fermatconjecturedthattheformula22n+ 1 always producesa hundredyearslaterthe rstcounterexamplewas [2^(2^1)+1]TruePrimeQ[2^(2^2)+1]TruePrim eQ[2^(2^3)+1]TruePrimeQ[2^(2^4)+1]TruePr imeQ[2^(2^5)+1]False2^(2^5)+14294967297 FactorInteger[2^(2^5)+1]{{641,1},{670041 7,1}}PROGRAMMINGINMATHEMATICA, A theabilitiesofMathematicais to (x+ 1)2.
6 OnecanuseMathematicato expandthisexpression:Expand[(x+1)^2]1 + 2x+x2 Mathematicacanalsodotheinverseof thistask,namelyto factorizeanexpression:Factor[1+ 2x + x^2](1 +x)2 Myfavoriteexampleis to factorizetheexpressionx10+x5+ 1. Hereis onewayto dothat:x10+x5+ 1 =x10+x9 x9+x8 x8+ +x5 x5+x5+x4 x4+ +x x+ 1 =x10+x9+x8 x9 x8 x7+x7+x6+x5 x6 x5 x4+x5+x4+x3 x3 x2 x+x2+x+ 1 =x8(x2+x+1) x7(x2+x+1)+x5(x2+x+1) x4(x2+x+1)+x3(x2+x+1) x(x2+x+1)+x2+x+1 =(x2+x+ 1)(x8 x7+x5 x4+x3 x+ 1).Mathematicacaneasilycomeupwiththefact orization:Factor[x^10+ x^5 + 1](x2+x+ 1)(1 x+x3 x4+x5 x7+x8).It is a factthattheproductof fourconsecutive numbersplusoneis always a squarednumber:Factor[n*(n+1)*(n+2)*(n+3) +1](1 + 3n+n2) orderto feeddatato a computerprogramoneneedsto de nevariablesto beableto assigndatato youusecommonsense,any namesyouchooseforvariablesarevalidinMath ematica.
7 Nameslikex, y, x3, myfunc,xQuaternion,..areall de nea variable2. Theunderscoreis reservedandwillbe usedin thede nitionof functionsin ,=, :=, ==.PrimarilytherearethreeequalitiesinMat hematica. Thereis afundamentaldi erencesbetween= and:=.Studythefollowingexample:x=5;y=x+2 ;y7x=10102 Thisis quitecommonin Pascalor C, to de nevariablessuch asxprinter,comgraph,..8 PROGRAMMINGINMATHEMATICA, A PROBLEM-CENTREDAPPROACHy7x=1515y7 Now compareit withthefollowingone,whenwe replace= with:=x=5;y:=x+2;y7x=1010y12x=1515y17 Fromtheexampleit is clearthatwhenwe de ney=x+2theny takes thevalueof x+2andthiswillbe assignedto y. Nomatterif x changesitsvalue,thevalueof y ,y is independent of x. Butin y:=x+2,y is dependent onx, andwhenx changes,thevalueof y changestoo.
8 Namelyusing:=theny is a functionwithvariablex. Thefollowingis anexcellent exampleto show thedi erencebetween= and:=.?RandomRandom[] givesa uniformlydistributedpseudorandomRealin therange0 to [] , A :=Random[] willexaminethisdi erencebetween=and:=againin ==is usedto compare:5==5 True3==5 FalseWe willdiscussmoreonthisin , A ningfunctionsis oneof nea functionin severaldi erent ways inMathematicaas we willseein simpleexampleof de ningtheformulaf(n) =n2+ 4 as a functionandcalculatef( 2):f[n_]:=n^2 +4 Firstnoticethatin de ninga functionwe use:=.Thesymbolnis a dummy variableandasexpectedoneplugsin thedatain [-2]8In factas we willseelater,onecanplug\anything"in placeofnandthat'swhy functionsinMathematicaarefarsuperiorto thosein thede nitionof willbe calledblankheredeterminesthe\pattern"of shalltalkaboutpatternsandpatternmatching in Section9 andleave it as it is proceedby de ningthefunctiong(x) =x+sin(x).
9 G[x_]:=x+Sin[x]g[Pi] Onecande nefunctionsof a simpleexamplede ningf(x; y) =px2+y2f[x_,y_]:=Sqrt[x^2+y^2]f[3,4]5It is veryeasyto composefunctionsinMathematica, , anexampleof this:f[x_]:=x^2+1g[x_]:=Sin[x]+Cos[x]f[g [x]]1+(Cos[x]+Sin[x])^2g[f[x]]Cos[1+x^2] +Sin[1+x^2]Andthisis a littlefunctionto ndoutif then thFibonaccinumber is divisibleby [n_]:=Mod[Fibonacci[n],5]remain[14]2rema in[15]0 PROGRAMMINGINMATHEMATICA, A PROBLEM-CENTREDAPPROACH11 Thusthe15thFibonaccinumber is divisibleby itselfacompositionof two functions, ofremain[x], therearetwo otherways to applya functionto anargument as follows:15//remain0remain@50 Laterwe willde nefunctionswithconditions,functions