calc.texi 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094
  1. \input texinfo @c -*- mode: texinfo; coding: utf-8 -*-
  2. @comment %**start of header (This is for running Texinfo on a region.)
  3. @c smallbook
  4. @setfilename ../../info/calc.info
  5. @c [title]
  6. @settitle GNU Emacs Calc Manual
  7. @include docstyle.texi
  8. @setchapternewpage odd
  9. @comment %**end of header (This is for running Texinfo on a region.)
  10. @include emacsver.texi
  11. @c The following macros are used for conditional output for single lines.
  12. @c @texline foo
  13. @c 'foo' will appear only in TeX output
  14. @c @infoline foo
  15. @c 'foo' will appear only in non-TeX output
  16. @c @expr{expr} will typeset an expression;
  17. @c $x$ in TeX, @samp{x} otherwise.
  18. @iftex
  19. @macro texline
  20. @end macro
  21. @alias infoline=comment
  22. @alias expr=math
  23. @alias tfn=code
  24. @alias mathit=expr
  25. @alias summarykey=key
  26. @macro cpi{}
  27. @math{@pi{}}
  28. @end macro
  29. @macro cpiover{den}
  30. @math{@pi/\den\}
  31. @end macro
  32. @end iftex
  33. @ifnottex
  34. @alias texline=comment
  35. @macro infoline{stuff}
  36. \stuff\
  37. @end macro
  38. @alias expr=samp
  39. @alias tfn=t
  40. @alias mathit=i
  41. @macro summarykey{ky}
  42. \ky\
  43. @end macro
  44. @macro cpi{}
  45. @expr{pi}
  46. @end macro
  47. @macro cpiover{den}
  48. @expr{pi/\den\}
  49. @end macro
  50. @end ifnottex
  51. @tex
  52. % Suggested by Karl Berry <karl@@freefriends.org>
  53. \gdef\!{\mskip-\thinmuskip}
  54. @end tex
  55. @c Fix some other things specifically for this manual.
  56. @iftex
  57. @finalout
  58. @mathcode`@:=`@: @c Make Calc fractions come out right in math mode
  59. @tex
  60. \gdef\coloneq{\mathrel{\mathord:\mathord=}}
  61. \gdef\beforedisplay{\vskip-10pt}
  62. \gdef\afterdisplay{\vskip-5pt}
  63. \gdef\beforedisplayh{\vskip-25pt}
  64. \gdef\afterdisplayh{\vskip-10pt}
  65. @end tex
  66. @newdimen@kyvpos @kyvpos=0pt
  67. @newdimen@kyhpos @kyhpos=0pt
  68. @newcount@calcclubpenalty @calcclubpenalty=1000
  69. @ignore
  70. @newcount@calcpageno
  71. @newtoks@calcoldeverypar @calcoldeverypar=@everypar
  72. @everypar={@calceverypar@the@calcoldeverypar}
  73. @ifx@ninett@undefinedzzz@font@ninett=cmtt9@fi
  74. @catcode`@\=0 \catcode`\@=11
  75. \r@ggedbottomtrue
  76. \catcode`\@=0 @catcode`@\=@active
  77. @end ignore
  78. @end iftex
  79. @copying
  80. @ifinfo
  81. This file documents Calc, the GNU Emacs calculator.
  82. @end ifinfo
  83. @ifnotinfo
  84. This file documents Calc, the GNU Emacs calculator, included with
  85. GNU Emacs @value{EMACSVER}.
  86. @end ifnotinfo
  87. Copyright @copyright{} 1990--1991, 2001--2015 Free Software Foundation, Inc.
  88. @quotation
  89. Permission is granted to copy, distribute and/or modify this document
  90. under the terms of the GNU Free Documentation License, Version 1.3 or
  91. any later version published by the Free Software Foundation; with the
  92. Invariant Sections being just ``GNU GENERAL PUBLIC LICENSE'', with the
  93. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  94. Texts as in (a) below. A copy of the license is included in the section
  95. entitled ``GNU Free Documentation License.''
  96. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  97. modify this GNU manual.''
  98. @end quotation
  99. @end copying
  100. @dircategory Emacs misc features
  101. @direntry
  102. * Calc: (calc). Advanced desk calculator and mathematical tool.
  103. @end direntry
  104. @titlepage
  105. @sp 6
  106. @center @titlefont{Calc Manual}
  107. @sp 4
  108. @center GNU Emacs Calc
  109. @c [volume]
  110. @sp 5
  111. @center Dave Gillespie
  112. @center daveg@@synaptics.com
  113. @page
  114. @vskip 0pt plus 1filll
  115. @insertcopying
  116. @end titlepage
  117. @summarycontents
  118. @c [end]
  119. @contents
  120. @c [begin]
  121. @ifnottex
  122. @node Top, Getting Started, (dir), (dir)
  123. @top The GNU Emacs Calculator
  124. @noindent
  125. @dfn{Calc} is an advanced desk calculator and mathematical tool
  126. written by Dave Gillespie that runs as part of the GNU Emacs environment.
  127. This manual, also written (mostly) by Dave Gillespie, is divided into
  128. three major parts: ``Getting Started,'' the ``Calc Tutorial,'' and the
  129. ``Calc Reference.'' The Tutorial introduces all the major aspects of
  130. Calculator use in an easy, hands-on way. The remainder of the manual is
  131. a complete reference to the features of the Calculator.
  132. @end ifnottex
  133. @ifinfo
  134. For help in the Emacs Info system (which you are using to read this
  135. file), type @kbd{?}. (You can also type @kbd{h} to run through a
  136. longer Info tutorial.)
  137. @end ifinfo
  138. @insertcopying
  139. @menu
  140. * Getting Started:: General description and overview.
  141. @ifinfo
  142. * Interactive Tutorial::
  143. @end ifinfo
  144. * Tutorial:: A step-by-step introduction for beginners.
  145. * Introduction:: Introduction to the Calc reference manual.
  146. * Data Types:: Types of objects manipulated by Calc.
  147. * Stack and Trail:: Manipulating the stack and trail buffers.
  148. * Mode Settings:: Adjusting display format and other modes.
  149. * Arithmetic:: Basic arithmetic functions.
  150. * Scientific Functions:: Transcendentals and other scientific functions.
  151. * Matrix Functions:: Operations on vectors and matrices.
  152. * Algebra:: Manipulating expressions algebraically.
  153. * Units:: Operations on numbers with units.
  154. * Store and Recall:: Storing and recalling variables.
  155. * Graphics:: Commands for making graphs of data.
  156. * Kill and Yank:: Moving data into and out of Calc.
  157. * Keypad Mode:: Operating Calc from a keypad.
  158. * Embedded Mode:: Working with formulas embedded in a file.
  159. * Programming:: Calc as a programmable calculator.
  160. * Copying:: How you can copy and share Calc.
  161. * GNU Free Documentation License:: The license for this documentation.
  162. * Customizing Calc:: Customizing Calc.
  163. * Reporting Bugs:: How to report bugs and make suggestions.
  164. * Summary:: Summary of Calc commands and functions.
  165. * Key Index:: The standard Calc key sequences.
  166. * Command Index:: The interactive Calc commands.
  167. * Function Index:: Functions (in algebraic formulas).
  168. * Concept Index:: General concepts.
  169. * Variable Index:: Variables used by Calc (both user and internal).
  170. * Lisp Function Index:: Internal Lisp math functions.
  171. @end menu
  172. @ifinfo
  173. @node Getting Started, Interactive Tutorial, Top, Top
  174. @end ifinfo
  175. @ifnotinfo
  176. @node Getting Started, Tutorial, Top, Top
  177. @end ifnotinfo
  178. @chapter Getting Started
  179. @noindent
  180. This chapter provides a general overview of Calc, the GNU Emacs
  181. Calculator: What it is, how to start it and how to exit from it,
  182. and what are the various ways that it can be used.
  183. @menu
  184. * What is Calc::
  185. * About This Manual::
  186. * Notations Used in This Manual::
  187. * Demonstration of Calc::
  188. * Using Calc::
  189. * History and Acknowledgments::
  190. @end menu
  191. @node What is Calc, About This Manual, Getting Started, Getting Started
  192. @section What is Calc?
  193. @noindent
  194. @dfn{Calc} is an advanced calculator and mathematical tool that runs as
  195. part of the GNU Emacs environment. Very roughly based on the HP-28/48
  196. series of calculators, its many features include:
  197. @itemize @bullet
  198. @item
  199. Choice of algebraic or RPN (stack-based) entry of calculations.
  200. @item
  201. Arbitrary precision integers and floating-point numbers.
  202. @item
  203. Arithmetic on rational numbers, complex numbers (rectangular and polar),
  204. error forms with standard deviations, open and closed intervals, vectors
  205. and matrices, dates and times, infinities, sets, quantities with units,
  206. and algebraic formulas.
  207. @item
  208. Mathematical operations such as logarithms and trigonometric functions.
  209. @item
  210. Programmer's features (bitwise operations, non-decimal numbers).
  211. @item
  212. Financial functions such as future value and internal rate of return.
  213. @item
  214. Number theoretical features such as prime factorization and arithmetic
  215. modulo @var{m} for any @var{m}.
  216. @item
  217. Algebraic manipulation features, including symbolic calculus.
  218. @item
  219. Moving data to and from regular editing buffers.
  220. @item
  221. Embedded mode for manipulating Calc formulas and data directly
  222. inside any editing buffer.
  223. @item
  224. Graphics using GNUPLOT, a versatile (and free) plotting program.
  225. @item
  226. Easy programming using keyboard macros, algebraic formulas,
  227. algebraic rewrite rules, or extended Emacs Lisp.
  228. @end itemize
  229. Calc tries to include a little something for everyone; as a result it is
  230. large and might be intimidating to the first-time user. If you plan to
  231. use Calc only as a traditional desk calculator, all you really need to
  232. read is the ``Getting Started'' chapter of this manual and possibly the
  233. first few sections of the tutorial. As you become more comfortable with
  234. the program you can learn its additional features. Calc does not
  235. have the scope and depth of a fully-functional symbolic math package,
  236. but Calc has the advantages of convenience, portability, and freedom.
  237. @node About This Manual, Notations Used in This Manual, What is Calc, Getting Started
  238. @section About This Manual
  239. @noindent
  240. This document serves as a complete description of the GNU Emacs
  241. Calculator. It works both as an introduction for novices and as
  242. a reference for experienced users. While it helps to have some
  243. experience with GNU Emacs in order to get the most out of Calc,
  244. this manual ought to be readable even if you don't know or use Emacs
  245. regularly.
  246. This manual is divided into three major parts: the ``Getting
  247. Started'' chapter you are reading now, the Calc tutorial, and the Calc
  248. reference manual.
  249. @c [when-split]
  250. @c This manual has been printed in two volumes, the @dfn{Tutorial} and the
  251. @c @dfn{Reference}. Both volumes include a copy of the ``Getting Started''
  252. @c chapter.
  253. If you are in a hurry to use Calc, there is a brief ``demonstration''
  254. below which illustrates the major features of Calc in just a couple of
  255. pages. If you don't have time to go through the full tutorial, this
  256. will show you everything you need to know to begin.
  257. @xref{Demonstration of Calc}.
  258. The tutorial chapter walks you through the various parts of Calc
  259. with lots of hands-on examples and explanations. If you are new
  260. to Calc and you have some time, try going through at least the
  261. beginning of the tutorial. The tutorial includes about 70 exercises
  262. with answers. These exercises give you some guided practice with
  263. Calc, as well as pointing out some interesting and unusual ways
  264. to use its features.
  265. The reference section discusses Calc in complete depth. You can read
  266. the reference from start to finish if you want to learn every aspect
  267. of Calc. Or, you can look in the table of contents or the Concept
  268. Index to find the parts of the manual that discuss the things you
  269. need to know.
  270. @c @cindex Marginal notes
  271. Every Calc keyboard command is listed in the Calc Summary, and also
  272. in the Key Index. Algebraic functions, @kbd{M-x} commands, and
  273. variables also have their own indices.
  274. @c @texline Each
  275. @c @infoline In the printed manual, each
  276. @c paragraph that is referenced in the Key or Function Index is marked
  277. @c in the margin with its index entry.
  278. @c [fix-ref Help Commands]
  279. You can access this manual on-line at any time within Calc by pressing
  280. the @kbd{h i} key sequence. Outside of the Calc window, you can press
  281. @kbd{C-x * i} to read the manual on-line. From within Calc the command
  282. @kbd{h t} will jump directly to the Tutorial; from outside of Calc the
  283. command @kbd{C-x * t} will jump to the Tutorial and start Calc if
  284. necessary. Pressing @kbd{h s} or @kbd{C-x * s} will take you directly
  285. to the Calc Summary. Within Calc, you can also go to the part of the
  286. manual describing any Calc key, function, or variable using
  287. @w{@kbd{h k}}, @kbd{h f}, or @kbd{h v}, respectively. @xref{Help Commands}.
  288. @ifnottex
  289. The Calc manual can be printed, but because the manual is so large, you
  290. should only make a printed copy if you really need it. To print the
  291. manual, you will need the @TeX{} typesetting program (this is a free
  292. program by Donald Knuth at Stanford University) as well as the
  293. @file{texindex} program and @file{texinfo.tex} file, both of which can
  294. be obtained from the FSF as part of the @code{texinfo} package.
  295. To print the Calc manual in one huge tome, you will need the
  296. Emacs source, which contains the source code to this manual,
  297. @file{calc.texi}. Change to the @file{doc/misc} subdirectory of the
  298. Emacs source distribution, which contains source code for this manual,
  299. and type @kbd{make calc.pdf}. (Don't worry if you get some ``overfull
  300. box'' warnings while @TeX{} runs.) The result will be this entire
  301. manual as a pdf file.
  302. @end ifnottex
  303. @c Printed copies of this manual are also available from the Free Software
  304. @c Foundation.
  305. @node Notations Used in This Manual, Demonstration of Calc, About This Manual, Getting Started
  306. @section Notations Used in This Manual
  307. @noindent
  308. This section describes the various notations that are used
  309. throughout the Calc manual.
  310. In keystroke sequences, uppercase letters mean you must hold down
  311. the shift key while typing the letter. Keys pressed with Control
  312. held down are shown as @kbd{C-x}. Keys pressed with Meta held down
  313. are shown as @kbd{M-x}. Other notations are @key{RET} for the
  314. Return key, @key{SPC} for the space bar, @key{TAB} for the Tab key,
  315. @key{DEL} for the Delete key, and @key{LFD} for the Line-Feed key.
  316. The @key{DEL} key is called Backspace on some keyboards, it is
  317. whatever key you would use to correct a simple typing error when
  318. regularly using Emacs.
  319. (If you don't have the @key{LFD} or @key{TAB} keys on your keyboard,
  320. the @kbd{C-j} and @kbd{C-i} keys are equivalent to them, respectively.
  321. If you don't have a Meta key, look for Alt or Extend Char. You can
  322. also press @key{ESC} or @kbd{C-[} first to get the same effect, so
  323. that @kbd{M-x}, @kbd{@key{ESC} x}, and @kbd{C-[ x} are all equivalent.)
  324. Sometimes the @key{RET} key is not shown when it is ``obvious''
  325. that you must press @key{RET} to proceed. For example, the @key{RET}
  326. is usually omitted in key sequences like @kbd{M-x calc-keypad @key{RET}}.
  327. Commands are generally shown like this: @kbd{p} (@code{calc-precision})
  328. or @kbd{C-x * k} (@code{calc-keypad}). This means that the command is
  329. normally used by pressing the @kbd{p} key or @kbd{C-x * k} key sequence,
  330. but it also has the full-name equivalent shown, e.g., @kbd{M-x calc-precision}.
  331. Commands that correspond to functions in algebraic notation
  332. are written: @kbd{C} (@code{calc-cos}) [@code{cos}]. This means
  333. the @kbd{C} key is equivalent to @kbd{M-x calc-cos}, and that
  334. the corresponding function in an algebraic-style formula would
  335. be @samp{cos(@var{x})}.
  336. A few commands don't have key equivalents: @code{calc-sincos}
  337. [@code{sincos}].
  338. @node Demonstration of Calc, Using Calc, Notations Used in This Manual, Getting Started
  339. @section A Demonstration of Calc
  340. @noindent
  341. @cindex Demonstration of Calc
  342. This section will show some typical small problems being solved with
  343. Calc. The focus is more on demonstration than explanation, but
  344. everything you see here will be covered more thoroughly in the
  345. Tutorial.
  346. To begin, start Emacs if necessary (usually the command @code{emacs}
  347. does this), and type @kbd{C-x * c} to start the
  348. Calculator. (You can also use @kbd{M-x calc} if this doesn't work.
  349. @xref{Starting Calc}, for various ways of starting the Calculator.)
  350. Be sure to type all the sample input exactly, especially noting the
  351. difference between lower-case and upper-case letters. Remember,
  352. @key{RET}, @key{TAB}, @key{DEL}, and @key{SPC} are the Return, Tab,
  353. Delete, and Space keys.
  354. @strong{RPN calculation.} In RPN, you type the input number(s) first,
  355. then the command to operate on the numbers.
  356. @noindent
  357. Type @kbd{2 @key{RET} 3 + Q} to compute
  358. @texline @math{\sqrt{2+3} = 2.2360679775}.
  359. @infoline the square root of 2+3, which is 2.2360679775.
  360. @noindent
  361. Type @kbd{P 2 ^} to compute
  362. @texline @math{\pi^2 = 9.86960440109}.
  363. @infoline the value of @cpi{} squared, 9.86960440109.
  364. @noindent
  365. Type @key{TAB} to exchange the order of these two results.
  366. @noindent
  367. Type @kbd{- I H S} to subtract these results and compute the Inverse
  368. Hyperbolic sine of the difference, 2.72996136574.
  369. @noindent
  370. Type @key{DEL} to erase this result.
  371. @strong{Algebraic calculation.} You can also enter calculations using
  372. conventional ``algebraic'' notation. To enter an algebraic formula,
  373. use the apostrophe key.
  374. @noindent
  375. Type @kbd{' sqrt(2+3) @key{RET}} to compute
  376. @texline @math{\sqrt{2+3}}.
  377. @infoline the square root of 2+3.
  378. @noindent
  379. Type @kbd{' pi^2 @key{RET}} to enter
  380. @texline @math{\pi^2}.
  381. @infoline @cpi{} squared.
  382. To evaluate this symbolic formula as a number, type @kbd{=}.
  383. @noindent
  384. Type @kbd{' arcsinh($ - $$) @key{RET}} to subtract the second-most-recent
  385. result from the most-recent and compute the Inverse Hyperbolic sine.
  386. @strong{Keypad mode.} If you are using the X window system, press
  387. @w{@kbd{C-x * k}} to get Keypad mode. (If you don't use X, skip to
  388. the next section.)
  389. @noindent
  390. Click on the @key{2}, @key{ENTER}, @key{3}, @key{+}, and @key{SQRT}
  391. ``buttons'' using your left mouse button.
  392. @noindent
  393. Click on @key{PI}, @key{2}, and @tfn{y^x}.
  394. @noindent
  395. Click on @key{INV}, then @key{ENTER} to swap the two results.
  396. @noindent
  397. Click on @key{-}, @key{INV}, @key{HYP}, and @key{SIN}.
  398. @noindent
  399. Click on @key{<-} to erase the result, then click @key{OFF} to turn
  400. the Keypad Calculator off.
  401. @strong{Grabbing data.} Type @kbd{C-x * x} if necessary to exit Calc.
  402. Now select the following numbers as an Emacs region: ``Mark'' the
  403. front of the list by typing @kbd{C-@key{SPC}} or @kbd{C-@@} there,
  404. then move to the other end of the list. (Either get this list from
  405. the on-line copy of this manual, accessed by @w{@kbd{C-x * i}}, or just
  406. type these numbers into a scratch file.) Now type @kbd{C-x * g} to
  407. ``grab'' these numbers into Calc.
  408. @example
  409. @group
  410. 1.23 1.97
  411. 1.6 2
  412. 1.19 1.08
  413. @end group
  414. @end example
  415. @noindent
  416. The result @samp{[1.23, 1.97, 1.6, 2, 1.19, 1.08]} is a Calc ``vector.''
  417. Type @w{@kbd{V R +}} to compute the sum of these numbers.
  418. @noindent
  419. Type @kbd{U} to Undo this command, then type @kbd{V R *} to compute
  420. the product of the numbers.
  421. @noindent
  422. You can also grab data as a rectangular matrix. Place the cursor on
  423. the upper-leftmost @samp{1} and set the mark, then move to just after
  424. the lower-right @samp{8} and press @kbd{C-x * r}.
  425. @noindent
  426. Type @kbd{v t} to transpose this
  427. @texline @math{3\times2}
  428. @infoline 3x2
  429. matrix into a
  430. @texline @math{2\times3}
  431. @infoline 2x3
  432. matrix. Type @w{@kbd{v u}} to unpack the rows into two separate
  433. vectors. Now type @w{@kbd{V R + @key{TAB} V R +}} to compute the sums
  434. of the two original columns. (There is also a special
  435. grab-and-sum-columns command, @kbd{C-x * :}.)
  436. @strong{Units conversion.} Units are entered algebraically.
  437. Type @w{@kbd{' 43 mi/hr @key{RET}}} to enter the quantity 43 miles-per-hour.
  438. Type @w{@kbd{u c km/hr @key{RET}}}. Type @w{@kbd{u c m/s @key{RET}}}.
  439. @strong{Date arithmetic.} Type @kbd{t N} to get the current date and
  440. time. Type @kbd{90 +} to find the date 90 days from now. Type
  441. @kbd{' <25 dec 87> @key{RET}} to enter a date, then @kbd{- 7 /} to see how
  442. many weeks have passed since then.
  443. @strong{Algebra.} Algebraic entries can also include formulas
  444. or equations involving variables. Type @kbd{@w{' [x + y} = a, x y = 1] @key{RET}}
  445. to enter a pair of equations involving three variables.
  446. (Note the leading apostrophe in this example; also, note that the space
  447. in @samp{x y} is required.) Type @w{@kbd{a S x,y @key{RET}}} to solve
  448. these equations for the variables @expr{x} and @expr{y}.
  449. @noindent
  450. Type @kbd{d B} to view the solutions in more readable notation.
  451. Type @w{@kbd{d C}} to view them in C language notation, @kbd{d T}
  452. to view them in the notation for the @TeX{} typesetting system,
  453. and @kbd{d L} to view them in the notation for the @LaTeX{} typesetting
  454. system. Type @kbd{d N} to return to normal notation.
  455. @noindent
  456. Type @kbd{7.5}, then @kbd{s l a @key{RET}} to let @expr{a = 7.5} in these formulas.
  457. (That's the letter @kbd{l}, not the numeral @kbd{1}.)
  458. @ifnotinfo
  459. @strong{Help functions.} You can read about any command in the on-line
  460. manual. Type @kbd{C-x * c} to return to Calc after each of these
  461. commands: @kbd{h k t N} to read about the @kbd{t N} command,
  462. @kbd{h f sqrt @key{RET}} to read about the @code{sqrt} function, and
  463. @kbd{h s} to read the Calc summary.
  464. @end ifnotinfo
  465. @ifinfo
  466. @strong{Help functions.} You can read about any command in the on-line
  467. manual. Remember to type the letter @kbd{l}, then @kbd{C-x * c}, to
  468. return here after each of these commands: @w{@kbd{h k t N}} to read
  469. about the @w{@kbd{t N}} command, @kbd{h f sqrt @key{RET}} to read about the
  470. @code{sqrt} function, and @kbd{h s} to read the Calc summary.
  471. @end ifinfo
  472. Press @key{DEL} repeatedly to remove any leftover results from the stack.
  473. To exit from Calc, press @kbd{q} or @kbd{C-x * c} again.
  474. @node Using Calc, History and Acknowledgments, Demonstration of Calc, Getting Started
  475. @section Using Calc
  476. @noindent
  477. Calc has several user interfaces that are specialized for
  478. different kinds of tasks. As well as Calc's standard interface,
  479. there are Quick mode, Keypad mode, and Embedded mode.
  480. @menu
  481. * Starting Calc::
  482. * The Standard Interface::
  483. * Quick Mode Overview::
  484. * Keypad Mode Overview::
  485. * Standalone Operation::
  486. * Embedded Mode Overview::
  487. * Other C-x * Commands::
  488. @end menu
  489. @node Starting Calc, The Standard Interface, Using Calc, Using Calc
  490. @subsection Starting Calc
  491. @noindent
  492. On most systems, you can type @kbd{C-x *} to start the Calculator.
  493. The key sequence @kbd{C-x *} is bound to the command @code{calc-dispatch},
  494. which can be rebound if convenient (@pxref{Customizing Calc}).
  495. When you press @kbd{C-x *}, Emacs waits for you to press a second key to
  496. complete the command. In this case, you will follow @kbd{C-x *} with a
  497. letter (upper- or lower-case, it doesn't matter for @kbd{C-x *}) that says
  498. which Calc interface you want to use.
  499. To get Calc's standard interface, type @kbd{C-x * c}. To get
  500. Keypad mode, type @kbd{C-x * k}. Type @kbd{C-x * ?} to get a brief
  501. list of the available options, and type a second @kbd{?} to get
  502. a complete list.
  503. To ease typing, @kbd{C-x * *} also works to start Calc. It starts the
  504. same interface (either @kbd{C-x * c} or @w{@kbd{C-x * k}}) that you last
  505. used, selecting the @kbd{C-x * c} interface by default.
  506. If @kbd{C-x *} doesn't work for you, you can always type explicit
  507. commands like @kbd{M-x calc} (for the standard user interface) or
  508. @w{@kbd{M-x calc-keypad}} (for Keypad mode). First type @kbd{M-x}
  509. (that's Meta with the letter @kbd{x}), then, at the prompt,
  510. type the full command (like @kbd{calc-keypad}) and press Return.
  511. The same commands (like @kbd{C-x * c} or @kbd{C-x * *}) that start
  512. the Calculator also turn it off if it is already on.
  513. @node The Standard Interface, Quick Mode Overview, Starting Calc, Using Calc
  514. @subsection The Standard Calc Interface
  515. @noindent
  516. @cindex Standard user interface
  517. Calc's standard interface acts like a traditional RPN calculator,
  518. operated by the normal Emacs keyboard. When you type @kbd{C-x * c}
  519. to start the Calculator, the Emacs screen splits into two windows
  520. with the file you were editing on top and Calc on the bottom.
  521. @smallexample
  522. @group
  523. ...
  524. --**-Emacs: myfile (Fundamental)----All----------------------
  525. --- Emacs Calculator Mode --- |Emacs Calculator Trail
  526. 2: 17.3 | 17.3
  527. 1: -5 | 3
  528. . | 2
  529. | 4
  530. | * 8
  531. | ->-5
  532. |
  533. --%*-Calc: 12 Deg (Calculator)----All----- --%*- *Calc Trail*
  534. @end group
  535. @end smallexample
  536. In this figure, the mode-line for @file{myfile} has moved up and the
  537. ``Calculator'' window has appeared below it. As you can see, Calc
  538. actually makes two windows side-by-side. The lefthand one is
  539. called the @dfn{stack window} and the righthand one is called the
  540. @dfn{trail window.} The stack holds the numbers involved in the
  541. calculation you are currently performing. The trail holds a complete
  542. record of all calculations you have done. In a desk calculator with
  543. a printer, the trail corresponds to the paper tape that records what
  544. you do.
  545. In this case, the trail shows that four numbers (17.3, 3, 2, and 4)
  546. were first entered into the Calculator, then the 2 and 4 were
  547. multiplied to get 8, then the 3 and 8 were subtracted to get @mathit{-5}.
  548. (The @samp{>} symbol shows that this was the most recent calculation.)
  549. The net result is the two numbers 17.3 and @mathit{-5} sitting on the stack.
  550. Most Calculator commands deal explicitly with the stack only, but
  551. there is a set of commands that allow you to search back through
  552. the trail and retrieve any previous result.
  553. Calc commands use the digits, letters, and punctuation keys.
  554. Shifted (i.e., upper-case) letters are different from lowercase
  555. letters. Some letters are @dfn{prefix} keys that begin two-letter
  556. commands. For example, @kbd{e} means ``enter exponent'' and shifted
  557. @kbd{E} means @expr{e^x}. With the @kbd{d} (``display modes'') prefix
  558. the letter ``e'' takes on very different meanings: @kbd{d e} means
  559. ``engineering notation'' and @kbd{d E} means ``@dfn{eqn} language mode.''
  560. There is nothing stopping you from switching out of the Calc
  561. window and back into your editing window, say by using the Emacs
  562. @w{@kbd{C-x o}} (@code{other-window}) command. When the cursor is
  563. inside a regular window, Emacs acts just like normal. When the
  564. cursor is in the Calc stack or trail windows, keys are interpreted
  565. as Calc commands.
  566. When you quit by pressing @kbd{C-x * c} a second time, the Calculator
  567. windows go away but the actual Stack and Trail are not gone, just
  568. hidden. When you press @kbd{C-x * c} once again you will get the
  569. same stack and trail contents you had when you last used the
  570. Calculator.
  571. The Calculator does not remember its state between Emacs sessions.
  572. Thus if you quit Emacs and start it again, @kbd{C-x * c} will give you
  573. a fresh stack and trail. There is a command (@kbd{m m}) that lets
  574. you save your favorite mode settings between sessions, though.
  575. One of the things it saves is which user interface (standard or
  576. Keypad) you last used; otherwise, a freshly started Emacs will
  577. always treat @kbd{C-x * *} the same as @kbd{C-x * c}.
  578. The @kbd{q} key is another equivalent way to turn the Calculator off.
  579. If you type @kbd{C-x * b} first and then @kbd{C-x * c}, you get a
  580. full-screen version of Calc (@code{full-calc}) in which the stack and
  581. trail windows are still side-by-side but are now as tall as the whole
  582. Emacs screen. When you press @kbd{q} or @kbd{C-x * c} again to quit,
  583. the file you were editing before reappears. The @kbd{C-x * b} key
  584. switches back and forth between ``big'' full-screen mode and the
  585. normal partial-screen mode.
  586. Finally, @kbd{C-x * o} (@code{calc-other-window}) is like @kbd{C-x * c}
  587. except that the Calc window is not selected. The buffer you were
  588. editing before remains selected instead. If you are in a Calc window,
  589. then @kbd{C-x * o} will switch you out of it, being careful not to
  590. switch you to the Calc Trail window. So @kbd{C-x * o} is a handy
  591. way to switch out of Calc momentarily to edit your file; you can then
  592. type @kbd{C-x * c} to switch back into Calc when you are done.
  593. @node Quick Mode Overview, Keypad Mode Overview, The Standard Interface, Using Calc
  594. @subsection Quick Mode (Overview)
  595. @noindent
  596. @dfn{Quick mode} is a quick way to use Calc when you don't need the
  597. full complexity of the stack and trail. To use it, type @kbd{C-x * q}
  598. (@code{quick-calc}) in any regular editing buffer.
  599. Quick mode is very simple: It prompts you to type any formula in
  600. standard algebraic notation (like @samp{4 - 2/3}) and then displays
  601. the result at the bottom of the Emacs screen (@mathit{3.33333333333}
  602. in this case). You are then back in the same editing buffer you
  603. were in before, ready to continue editing or to type @kbd{C-x * q}
  604. again to do another quick calculation. The result of the calculation
  605. will also be in the Emacs ``kill ring'' so that a @kbd{C-y} command
  606. at this point will yank the result into your editing buffer.
  607. Calc mode settings affect Quick mode, too, though you will have to
  608. go into regular Calc (with @kbd{C-x * c}) to change the mode settings.
  609. @c [fix-ref Quick Calculator mode]
  610. @xref{Quick Calculator}, for further information.
  611. @node Keypad Mode Overview, Standalone Operation, Quick Mode Overview, Using Calc
  612. @subsection Keypad Mode (Overview)
  613. @noindent
  614. @dfn{Keypad mode} is a mouse-based interface to the Calculator.
  615. It is designed for use with terminals that support a mouse. If you
  616. don't have a mouse, you will have to operate Keypad mode with your
  617. arrow keys (which is probably more trouble than it's worth).
  618. Type @kbd{C-x * k} to turn Keypad mode on or off. Once again you
  619. get two new windows, this time on the righthand side of the screen
  620. instead of at the bottom. The upper window is the familiar Calc
  621. Stack; the lower window is a picture of a typical calculator keypad.
  622. @tex
  623. \dimen0=\pagetotal%
  624. \advance \dimen0 by 24\baselineskip%
  625. \ifdim \dimen0>\pagegoal \vfill\eject \fi%
  626. \medskip
  627. @end tex
  628. @smallexample
  629. @group
  630. |--- Emacs Calculator Mode ---
  631. |2: 17.3
  632. |1: -5
  633. | .
  634. |--%*-Calc: 12 Deg (Calcul
  635. |----+----+--Calc---+----+----1
  636. |FLR |CEIL|RND |TRNC|CLN2|FLT |
  637. |----+----+----+----+----+----|
  638. | LN |EXP | |ABS |IDIV|MOD |
  639. |----+----+----+----+----+----|
  640. |SIN |COS |TAN |SQRT|y^x |1/x |
  641. |----+----+----+----+----+----|
  642. | ENTER |+/- |EEX |UNDO| <- |
  643. |-----+---+-+--+--+-+---++----|
  644. | INV | 7 | 8 | 9 | / |
  645. |-----+-----+-----+-----+-----|
  646. | HYP | 4 | 5 | 6 | * |
  647. |-----+-----+-----+-----+-----|
  648. |EXEC | 1 | 2 | 3 | - |
  649. |-----+-----+-----+-----+-----|
  650. | OFF | 0 | . | PI | + |
  651. |-----+-----+-----+-----+-----+
  652. @end group
  653. @end smallexample
  654. Keypad mode is much easier for beginners to learn, because there
  655. is no need to memorize lots of obscure key sequences. But not all
  656. commands in regular Calc are available on the Keypad. You can
  657. always switch the cursor into the Calc stack window to use
  658. standard Calc commands if you need. Serious Calc users, though,
  659. often find they prefer the standard interface over Keypad mode.
  660. To operate the Calculator, just click on the ``buttons'' of the
  661. keypad using your left mouse button. To enter the two numbers
  662. shown here you would click @w{@kbd{1 7 .@: 3 ENTER 5 +/- ENTER}}; to
  663. add them together you would then click @kbd{+} (to get 12.3 on
  664. the stack).
  665. If you click the right mouse button, the top three rows of the
  666. keypad change to show other sets of commands, such as advanced
  667. math functions, vector operations, and operations on binary
  668. numbers.
  669. Because Keypad mode doesn't use the regular keyboard, Calc leaves
  670. the cursor in your original editing buffer. You can type in
  671. this buffer in the usual way while also clicking on the Calculator
  672. keypad. One advantage of Keypad mode is that you don't need an
  673. explicit command to switch between editing and calculating.
  674. If you press @kbd{C-x * b} first, you get a full-screen Keypad mode
  675. (@code{full-calc-keypad}) with three windows: The keypad in the lower
  676. left, the stack in the lower right, and the trail on top.
  677. @c [fix-ref Keypad Mode]
  678. @xref{Keypad Mode}, for further information.
  679. @node Standalone Operation, Embedded Mode Overview, Keypad Mode Overview, Using Calc
  680. @subsection Standalone Operation
  681. @noindent
  682. @cindex Standalone Operation
  683. If you are not in Emacs at the moment but you wish to use Calc,
  684. you must start Emacs first. If all you want is to run Calc, you
  685. can give the commands:
  686. @example
  687. emacs -f full-calc
  688. @end example
  689. @noindent
  690. or
  691. @example
  692. emacs -f full-calc-keypad
  693. @end example
  694. @noindent
  695. which run a full-screen Calculator (as if by @kbd{C-x * b C-x * c}) or
  696. a full-screen X-based Calculator (as if by @kbd{C-x * b C-x * k}).
  697. In standalone operation, quitting the Calculator (by pressing
  698. @kbd{q} or clicking on the keypad @key{EXIT} button) quits Emacs
  699. itself.
  700. @node Embedded Mode Overview, Other C-x * Commands, Standalone Operation, Using Calc
  701. @subsection Embedded Mode (Overview)
  702. @noindent
  703. @dfn{Embedded mode} is a way to use Calc directly from inside an
  704. editing buffer. Suppose you have a formula written as part of a
  705. document like this:
  706. @smallexample
  707. @group
  708. The derivative of
  709. ln(ln(x))
  710. is
  711. @end group
  712. @end smallexample
  713. @noindent
  714. and you wish to have Calc compute and format the derivative for
  715. you and store this derivative in the buffer automatically. To
  716. do this with Embedded mode, first copy the formula down to where
  717. you want the result to be, leaving a blank line before and after the
  718. formula:
  719. @smallexample
  720. @group
  721. The derivative of
  722. ln(ln(x))
  723. is
  724. ln(ln(x))
  725. @end group
  726. @end smallexample
  727. Now, move the cursor onto this new formula and press @kbd{C-x * e}.
  728. Calc will read the formula (using the surrounding blank lines to tell
  729. how much text to read), then push this formula (invisibly) onto the Calc
  730. stack. The cursor will stay on the formula in the editing buffer, but
  731. the line with the formula will now appear as it would on the Calc stack
  732. (in this case, it will be left-aligned) and the buffer's mode line will
  733. change to look like the Calc mode line (with mode indicators like
  734. @samp{12 Deg} and so on). Even though you are still in your editing
  735. buffer, the keyboard now acts like the Calc keyboard, and any new result
  736. you get is copied from the stack back into the buffer. To take the
  737. derivative, you would type @kbd{a d x @key{RET}}.
  738. @smallexample
  739. @group
  740. The derivative of
  741. ln(ln(x))
  742. is
  743. 1 / x ln(x)
  744. @end group
  745. @end smallexample
  746. (Note that by default, Calc gives division lower precedence than multiplication,
  747. so that @samp{1 / x ln(x)} is equivalent to @samp{1 / (x ln(x))}.)
  748. To make this look nicer, you might want to press @kbd{d =} to center
  749. the formula, and even @kbd{d B} to use Big display mode.
  750. @smallexample
  751. @group
  752. The derivative of
  753. ln(ln(x))
  754. is
  755. % [calc-mode: justify: center]
  756. % [calc-mode: language: big]
  757. 1
  758. -------
  759. x ln(x)
  760. @end group
  761. @end smallexample
  762. Calc has added annotations to the file to help it remember the modes
  763. that were used for this formula. They are formatted like comments
  764. in the @TeX{} typesetting language, just in case you are using @TeX{} or
  765. @LaTeX{}. (In this example @TeX{} is not being used, so you might want
  766. to move these comments up to the top of the file or otherwise put them
  767. out of the way.)
  768. As an extra flourish, we can add an equation number using a
  769. righthand label: Type @kbd{d @} (1) @key{RET}}.
  770. @smallexample
  771. @group
  772. % [calc-mode: justify: center]
  773. % [calc-mode: language: big]
  774. % [calc-mode: right-label: " (1)"]
  775. 1
  776. ------- (1)
  777. ln(x) x
  778. @end group
  779. @end smallexample
  780. To leave Embedded mode, type @kbd{C-x * e} again. The mode line
  781. and keyboard will revert to the way they were before.
  782. The related command @kbd{C-x * w} operates on a single word, which
  783. generally means a single number, inside text. It searches for an
  784. expression which ``looks'' like a number containing the point.
  785. Here's an example of its use (before you try this, remove the Calc
  786. annotations or use a new buffer so that the extra settings in the
  787. annotations don't take effect):
  788. @smallexample
  789. A slope of one-third corresponds to an angle of 1 degrees.
  790. @end smallexample
  791. Place the cursor on the @samp{1}, then type @kbd{C-x * w} to enable
  792. Embedded mode on that number. Now type @kbd{3 /} (to get one-third),
  793. and @kbd{I T} (the Inverse Tangent converts a slope into an angle),
  794. then @w{@kbd{C-x * w}} again to exit Embedded mode.
  795. @smallexample
  796. A slope of one-third corresponds to an angle of 18.4349488229 degrees.
  797. @end smallexample
  798. @c [fix-ref Embedded Mode]
  799. @xref{Embedded Mode}, for full details.
  800. @node Other C-x * Commands, , Embedded Mode Overview, Using Calc
  801. @subsection Other @kbd{C-x *} Commands
  802. @noindent
  803. Two more Calc-related commands are @kbd{C-x * g} and @kbd{C-x * r},
  804. which ``grab'' data from a selected region of a buffer into the
  805. Calculator. The region is defined in the usual Emacs way, by
  806. a ``mark'' placed at one end of the region, and the Emacs
  807. cursor or ``point'' placed at the other.
  808. The @kbd{C-x * g} command reads the region in the usual left-to-right,
  809. top-to-bottom order. The result is packaged into a Calc vector
  810. of numbers and placed on the stack. Calc (in its standard
  811. user interface) is then started. Type @kbd{v u} if you want
  812. to unpack this vector into separate numbers on the stack. Also,
  813. @kbd{C-u C-x * g} interprets the region as a single number or
  814. formula.
  815. The @kbd{C-x * r} command reads a rectangle, with the point and
  816. mark defining opposite corners of the rectangle. The result
  817. is a matrix of numbers on the Calculator stack.
  818. Complementary to these is @kbd{C-x * y}, which ``yanks'' the
  819. value at the top of the Calc stack back into an editing buffer.
  820. If you type @w{@kbd{C-x * y}} while in such a buffer, the value is
  821. yanked at the current position. If you type @kbd{C-x * y} while
  822. in the Calc buffer, Calc makes an educated guess as to which
  823. editing buffer you want to use. The Calc window does not have
  824. to be visible in order to use this command, as long as there
  825. is something on the Calc stack.
  826. Here, for reference, is the complete list of @kbd{C-x *} commands.
  827. The shift, control, and meta keys are ignored for the keystroke
  828. following @kbd{C-x *}.
  829. @noindent
  830. Commands for turning Calc on and off:
  831. @table @kbd
  832. @item *
  833. Turn Calc on or off, employing the same user interface as last time.
  834. @item =, +, -, /, \, &, #
  835. Alternatives for @kbd{*}.
  836. @item C
  837. Turn Calc on or off using its standard bottom-of-the-screen
  838. interface. If Calc is already turned on but the cursor is not
  839. in the Calc window, move the cursor into the window.
  840. @item O
  841. Same as @kbd{C}, but don't select the new Calc window. If
  842. Calc is already turned on and the cursor is in the Calc window,
  843. move it out of that window.
  844. @item B
  845. Control whether @kbd{C-x * c} and @kbd{C-x * k} use the full screen.
  846. @item Q
  847. Use Quick mode for a single short calculation.
  848. @item K
  849. Turn Calc Keypad mode on or off.
  850. @item E
  851. Turn Calc Embedded mode on or off at the current formula.
  852. @item J
  853. Turn Calc Embedded mode on or off, select the interesting part.
  854. @item W
  855. Turn Calc Embedded mode on or off at the current word (number).
  856. @item Z
  857. Turn Calc on in a user-defined way, as defined by a @kbd{Z I} command.
  858. @item X
  859. Quit Calc; turn off standard, Keypad, or Embedded mode if on.
  860. (This is like @kbd{q} or @key{OFF} inside of Calc.)
  861. @end table
  862. @iftex
  863. @sp 2
  864. @end iftex
  865. @noindent
  866. Commands for moving data into and out of the Calculator:
  867. @table @kbd
  868. @item G
  869. Grab the region into the Calculator as a vector.
  870. @item R
  871. Grab the rectangular region into the Calculator as a matrix.
  872. @item :
  873. Grab the rectangular region and compute the sums of its columns.
  874. @item _
  875. Grab the rectangular region and compute the sums of its rows.
  876. @item Y
  877. Yank a value from the Calculator into the current editing buffer.
  878. @end table
  879. @iftex
  880. @sp 2
  881. @end iftex
  882. @noindent
  883. Commands for use with Embedded mode:
  884. @table @kbd
  885. @item A
  886. ``Activate'' the current buffer. Locate all formulas that
  887. contain @samp{:=} or @samp{=>} symbols and record their locations
  888. so that they can be updated automatically as variables are changed.
  889. @item D
  890. Duplicate the current formula immediately below and select
  891. the duplicate.
  892. @item F
  893. Insert a new formula at the current point.
  894. @item N
  895. Move the cursor to the next active formula in the buffer.
  896. @item P
  897. Move the cursor to the previous active formula in the buffer.
  898. @item U
  899. Update (i.e., as if by the @kbd{=} key) the formula at the current point.
  900. @item `
  901. Edit (as if by @code{calc-edit}) the formula at the current point.
  902. @end table
  903. @iftex
  904. @sp 2
  905. @end iftex
  906. @noindent
  907. Miscellaneous commands:
  908. @table @kbd
  909. @item I
  910. Run the Emacs Info system to read the Calc manual.
  911. (This is the same as @kbd{h i} inside of Calc.)
  912. @item T
  913. Run the Emacs Info system to read the Calc Tutorial.
  914. @item S
  915. Run the Emacs Info system to read the Calc Summary.
  916. @item L
  917. Load Calc entirely into memory. (Normally the various parts
  918. are loaded only as they are needed.)
  919. @item M
  920. Read a region of written keystroke names (like @kbd{C-n a b c @key{RET}})
  921. and record them as the current keyboard macro.
  922. @item 0
  923. (This is the ``zero'' digit key.) Reset the Calculator to
  924. its initial state: Empty stack, and initial mode settings.
  925. @end table
  926. @node History and Acknowledgments, , Using Calc, Getting Started
  927. @section History and Acknowledgments
  928. @noindent
  929. Calc was originally started as a two-week project to occupy a lull
  930. in the author's schedule. Basically, a friend asked if I remembered
  931. the value of
  932. @texline @math{2^{32}}.
  933. @infoline @expr{2^32}.
  934. I didn't offhand, but I said, ``that's easy, just call up an
  935. @code{xcalc}.'' @code{Xcalc} duly reported that the answer to our
  936. question was @samp{4.294967e+09}---with no way to see the full ten
  937. digits even though we knew they were there in the program's memory! I
  938. was so annoyed, I vowed to write a calculator of my own, once and for
  939. all.
  940. I chose Emacs Lisp, a) because I had always been curious about it
  941. and b) because, being only a text editor extension language after
  942. all, Emacs Lisp would surely reach its limits long before the project
  943. got too far out of hand.
  944. To make a long story short, Emacs Lisp turned out to be a distressingly
  945. solid implementation of Lisp, and the humble task of calculating
  946. turned out to be more open-ended than one might have expected.
  947. Emacs Lisp didn't have built-in floating point math (now it does), so
  948. this had to be simulated in software. In fact, Emacs integers would
  949. only comfortably fit six decimal digits or so (at the time)---not
  950. enough for a decent calculator. So I had to write my own
  951. high-precision integer code as well, and once I had this I figured
  952. that arbitrary-size integers were just as easy as large integers.
  953. Arbitrary floating-point precision was the logical next step. Also,
  954. since the large integer arithmetic was there anyway it seemed only
  955. fair to give the user direct access to it, which in turn made it
  956. practical to support fractions as well as floats. All these features
  957. inspired me to look around for other data types that might be worth
  958. having.
  959. Around this time, my friend Rick Koshi showed me his nifty new HP-28
  960. calculator. It allowed the user to manipulate formulas as well as
  961. numerical quantities, and it could also operate on matrices. I
  962. decided that these would be good for Calc to have, too. And once
  963. things had gone this far, I figured I might as well take a look at
  964. serious algebra systems for further ideas. Since these systems did
  965. far more than I could ever hope to implement, I decided to focus on
  966. rewrite rules and other programming features so that users could
  967. implement what they needed for themselves.
  968. Rick complained that matrices were hard to read, so I put in code to
  969. format them in a 2D style. Once these routines were in place, Big mode
  970. was obligatory. Gee, what other language modes would be useful?
  971. Scott Hemphill and Allen Knutson, two friends with a strong mathematical
  972. bent, contributed ideas and algorithms for a number of Calc features
  973. including modulo forms, primality testing, and float-to-fraction conversion.
  974. Units were added at the eager insistence of Mass Sivilotti. Later,
  975. Ulrich Mueller at CERN and Przemek Klosowski at NIST provided invaluable
  976. expert assistance with the units table. As far as I can remember, the
  977. idea of using algebraic formulas and variables to represent units dates
  978. back to an ancient article in Byte magazine about muMath, an early
  979. algebra system for microcomputers.
  980. Many people have contributed to Calc by reporting bugs and suggesting
  981. features, large and small. A few deserve special mention: Tim Peters,
  982. who helped develop the ideas that led to the selection commands, rewrite
  983. rules, and many other algebra features; François
  984. Pinard, who contributed an early prototype of the Calc Summary appendix
  985. as well as providing valuable suggestions in many other areas of Calc;
  986. Carl Witty, whose eagle eyes discovered many typographical and factual
  987. errors in the Calc manual; Tim Kay, who drove the development of
  988. Embedded mode; Ove Ewerlid, who made many suggestions relating to the
  989. algebra commands and contributed some code for polynomial operations;
  990. Randal Schwartz, who suggested the @code{calc-eval} function; Juha
  991. Sarlin, who first worked out how to split Calc into quickly-loading
  992. parts; Bob Weiner, who helped immensely with the Lucid Emacs port; and
  993. Robert J. Chassell, who suggested the Calc Tutorial and exercises as
  994. well as many other things.
  995. @cindex Bibliography
  996. @cindex Knuth, Art of Computer Programming
  997. @cindex Numerical Recipes
  998. @c Should these be expanded into more complete references?
  999. Among the books used in the development of Calc were Knuth's @emph{Art
  1000. of Computer Programming} (especially volume II, @emph{Seminumerical
  1001. Algorithms}); @emph{Numerical Recipes} by Press, Flannery, Teukolsky,
  1002. and Vetterling; Bevington's @emph{Data Reduction and Error Analysis
  1003. for the Physical Sciences}; @emph{Concrete Mathematics} by Graham,
  1004. Knuth, and Patashnik; Steele's @emph{Common Lisp, the Language}; the
  1005. @emph{CRC Standard Math Tables} (William H. Beyer, ed.); and
  1006. Abramowitz and Stegun's venerable @emph{Handbook of Mathematical
  1007. Functions}. Also, of course, Calc could not have been written without
  1008. the excellent @emph{GNU Emacs Lisp Reference Manual}, by Bil Lewis and
  1009. Dan LaLiberte.
  1010. Final thanks go to Richard Stallman, without whose fine implementations
  1011. of the Emacs editor, language, and environment, Calc would have been
  1012. finished in two weeks.
  1013. @c [tutorial]
  1014. @ifinfo
  1015. @c This node is accessed by the 'C-x * t' command.
  1016. @node Interactive Tutorial, Tutorial, Getting Started, Top
  1017. @chapter Tutorial
  1018. @noindent
  1019. Some brief instructions on using the Emacs Info system for this tutorial:
  1020. Press the space bar and Delete keys to go forward and backward in a
  1021. section by screenfuls (or use the regular Emacs scrolling commands
  1022. for this).
  1023. Press @kbd{n} or @kbd{p} to go to the Next or Previous section.
  1024. If the section has a @dfn{menu}, press a digit key like @kbd{1}
  1025. or @kbd{2} to go to a sub-section from the menu. Press @kbd{u} to
  1026. go back up from a sub-section to the menu it is part of.
  1027. Exercises in the tutorial all have cross-references to the
  1028. appropriate page of the ``answers'' section. Press @kbd{f}, then
  1029. the exercise number, to see the answer to an exercise. After
  1030. you have followed a cross-reference, you can press the letter
  1031. @kbd{l} to return to where you were before.
  1032. You can press @kbd{?} at any time for a brief summary of Info commands.
  1033. Press the number @kbd{1} now to enter the first section of the Tutorial.
  1034. @menu
  1035. * Tutorial::
  1036. @end menu
  1037. @node Tutorial, Introduction, Interactive Tutorial, Top
  1038. @end ifinfo
  1039. @ifnotinfo
  1040. @node Tutorial, Introduction, Getting Started, Top
  1041. @end ifnotinfo
  1042. @chapter Tutorial
  1043. @noindent
  1044. This chapter explains how to use Calc and its many features, in
  1045. a step-by-step, tutorial way. You are encouraged to run Calc and
  1046. work along with the examples as you read (@pxref{Starting Calc}).
  1047. If you are already familiar with advanced calculators, you may wish
  1048. @c [not-split]
  1049. to skip on to the rest of this manual.
  1050. @c [when-split]
  1051. @c to skip on to volume II of this manual, the @dfn{Calc Reference}.
  1052. @c [fix-ref Embedded Mode]
  1053. This tutorial describes the standard user interface of Calc only.
  1054. The Quick mode and Keypad mode interfaces are fairly
  1055. self-explanatory. @xref{Embedded Mode}, for a description of
  1056. the Embedded mode interface.
  1057. The easiest way to read this tutorial on-line is to have two windows on
  1058. your Emacs screen, one with Calc and one with the Info system. Press
  1059. @kbd{C-x * t} to set this up; the on-line tutorial will be opened in the
  1060. current window and Calc will be started in another window. From the
  1061. Info window, the command @kbd{C-x * c} can be used to switch to the Calc
  1062. window and @kbd{C-x * o} can be used to switch back to the Info window.
  1063. (If you have a printed copy of the manual you can use that instead; in
  1064. that case you only need to press @kbd{C-x * c} to start Calc.)
  1065. This tutorial is designed to be done in sequence. But the rest of this
  1066. manual does not assume you have gone through the tutorial. The tutorial
  1067. does not cover everything in the Calculator, but it touches on most
  1068. general areas.
  1069. @ifnottex
  1070. You may wish to print out a copy of the Calc Summary and keep notes on
  1071. it as you learn Calc. @xref{About This Manual}, to see how to make a
  1072. printed summary. @xref{Summary}.
  1073. @end ifnottex
  1074. @iftex
  1075. The Calc Summary at the end of the reference manual includes some blank
  1076. space for your own use. You may wish to keep notes there as you learn
  1077. Calc.
  1078. @end iftex
  1079. @menu
  1080. * Basic Tutorial::
  1081. * Arithmetic Tutorial::
  1082. * Vector/Matrix Tutorial::
  1083. * Types Tutorial::
  1084. * Algebra Tutorial::
  1085. * Programming Tutorial::
  1086. * Answers to Exercises::
  1087. @end menu
  1088. @node Basic Tutorial, Arithmetic Tutorial, Tutorial, Tutorial
  1089. @section Basic Tutorial
  1090. @noindent
  1091. In this section, we learn how RPN and algebraic-style calculations
  1092. work, how to undo and redo an operation done by mistake, and how
  1093. to control various modes of the Calculator.
  1094. @menu
  1095. * RPN Tutorial:: Basic operations with the stack.
  1096. * Algebraic Tutorial:: Algebraic entry; variables.
  1097. * Undo Tutorial:: If you make a mistake: Undo and the trail.
  1098. * Modes Tutorial:: Common mode-setting commands.
  1099. @end menu
  1100. @node RPN Tutorial, Algebraic Tutorial, Basic Tutorial, Basic Tutorial
  1101. @subsection RPN Calculations and the Stack
  1102. @cindex RPN notation
  1103. @noindent
  1104. @ifnottex
  1105. Calc normally uses RPN notation. You may be familiar with the RPN
  1106. system from Hewlett-Packard calculators, FORTH, or PostScript.
  1107. (Reverse Polish Notation, RPN, is named after the Polish mathematician
  1108. Jan Lukasiewicz.)
  1109. @end ifnottex
  1110. @tex
  1111. Calc normally uses RPN notation. You may be familiar with the RPN
  1112. system from Hewlett-Packard calculators, FORTH, or PostScript.
  1113. (Reverse Polish Notation, RPN, is named after the Polish mathematician
  1114. Jan \L ukasiewicz.)
  1115. @end tex
  1116. The central component of an RPN calculator is the @dfn{stack}. A
  1117. calculator stack is like a stack of dishes. New dishes (numbers) are
  1118. added at the top of the stack, and numbers are normally only removed
  1119. from the top of the stack.
  1120. @cindex Operators
  1121. @cindex Operands
  1122. In an operation like @expr{2+3}, the 2 and 3 are called the @dfn{operands}
  1123. and the @expr{+} is the @dfn{operator}. In an RPN calculator you always
  1124. enter the operands first, then the operator. Each time you type a
  1125. number, Calc adds or @dfn{pushes} it onto the top of the Stack.
  1126. When you press an operator key like @kbd{+}, Calc @dfn{pops} the appropriate
  1127. number of operands from the stack and pushes back the result.
  1128. Thus we could add the numbers 2 and 3 in an RPN calculator by typing:
  1129. @kbd{2 @key{RET} 3 @key{RET} +}. (The @key{RET} key, Return, corresponds to
  1130. the @key{ENTER} key on traditional RPN calculators.) Try this now if
  1131. you wish; type @kbd{C-x * c} to switch into the Calc window (you can type
  1132. @kbd{C-x * c} again or @kbd{C-x * o} to switch back to the Tutorial window).
  1133. The first four keystrokes ``push'' the numbers 2 and 3 onto the stack.
  1134. The @kbd{+} key ``pops'' the top two numbers from the stack, adds them,
  1135. and pushes the result (5) back onto the stack. Here's how the stack
  1136. will look at various points throughout the calculation:
  1137. @smallexample
  1138. @group
  1139. . 1: 2 2: 2 1: 5 .
  1140. . 1: 3 .
  1141. .
  1142. C-x * c 2 @key{RET} 3 @key{RET} + @key{DEL}
  1143. @end group
  1144. @end smallexample
  1145. The @samp{.} symbol is a marker that represents the top of the stack.
  1146. Note that the ``top'' of the stack is really shown at the bottom of
  1147. the Stack window. This may seem backwards, but it turns out to be
  1148. less distracting in regular use.
  1149. @cindex Stack levels
  1150. @cindex Levels of stack
  1151. The numbers @samp{1:} and @samp{2:} on the left are @dfn{stack level
  1152. numbers}. Old RPN calculators always had four stack levels called
  1153. @expr{x}, @expr{y}, @expr{z}, and @expr{t}. Calc's stack can grow
  1154. as large as you like, so it uses numbers instead of letters. Some
  1155. stack-manipulation commands accept a numeric argument that says
  1156. which stack level to work on. Normal commands like @kbd{+} always
  1157. work on the top few levels of the stack.
  1158. @c [fix-ref Truncating the Stack]
  1159. The Stack buffer is just an Emacs buffer, and you can move around in
  1160. it using the regular Emacs motion commands. But no matter where the
  1161. cursor is, even if you have scrolled the @samp{.} marker out of
  1162. view, most Calc commands always move the cursor back down to level 1
  1163. before doing anything. It is possible to move the @samp{.} marker
  1164. upwards through the stack, temporarily ``hiding'' some numbers from
  1165. commands like @kbd{+}. This is called @dfn{stack truncation} and
  1166. we will not cover it in this tutorial; @pxref{Truncating the Stack},
  1167. if you are interested.
  1168. You don't really need the second @key{RET} in @kbd{2 @key{RET} 3
  1169. @key{RET} +}. That's because if you type any operator name or
  1170. other non-numeric key when you are entering a number, the Calculator
  1171. automatically enters that number and then does the requested command.
  1172. Thus @kbd{2 @key{RET} 3 +} will work just as well.
  1173. Examples in this tutorial will often omit @key{RET} even when the
  1174. stack displays shown would only happen if you did press @key{RET}:
  1175. @smallexample
  1176. @group
  1177. 1: 2 2: 2 1: 5
  1178. . 1: 3 .
  1179. .
  1180. 2 @key{RET} 3 +
  1181. @end group
  1182. @end smallexample
  1183. @noindent
  1184. Here, after pressing @kbd{3} the stack would really show @samp{1: 2}
  1185. with @samp{Calc:@: 3} in the minibuffer. In these situations, you can
  1186. press the optional @key{RET} to see the stack as the figure shows.
  1187. (@bullet{}) @strong{Exercise 1.} (This tutorial will include exercises
  1188. at various points. Try them if you wish. Answers to all the exercises
  1189. are located at the end of the Tutorial chapter. Each exercise will
  1190. include a cross-reference to its particular answer. If you are
  1191. reading with the Emacs Info system, press @kbd{f} and the
  1192. exercise number to go to the answer, then the letter @kbd{l} to
  1193. return to where you were.)
  1194. @noindent
  1195. Here's the first exercise: What will the keystrokes @kbd{1 @key{RET} 2
  1196. @key{RET} 3 @key{RET} 4 + * -} compute? (@samp{*} is the symbol for
  1197. multiplication.) Figure it out by hand, then try it with Calc to see
  1198. if you're right. @xref{RPN Answer 1, 1}. (@bullet{})
  1199. (@bullet{}) @strong{Exercise 2.} Compute
  1200. @texline @math{(2\times4) + (7\times9.5) + {5\over4}}
  1201. @infoline @expr{2*4 + 7*9.5 + 5/4}
  1202. using the stack. @xref{RPN Answer 2, 2}. (@bullet{})
  1203. The @key{DEL} key is called Backspace on some keyboards. It is
  1204. whatever key you would use to correct a simple typing error when
  1205. regularly using Emacs. The @key{DEL} key pops and throws away the
  1206. top value on the stack. (You can still get that value back from
  1207. the Trail if you should need it later on.) There are many places
  1208. in this tutorial where we assume you have used @key{DEL} to erase the
  1209. results of the previous example at the beginning of a new example.
  1210. In the few places where it is really important to use @key{DEL} to
  1211. clear away old results, the text will remind you to do so.
  1212. (It won't hurt to let things accumulate on the stack, except that
  1213. whenever you give a display-mode-changing command Calc will have to
  1214. spend a long time reformatting such a large stack.)
  1215. Since the @kbd{-} key is also an operator (it subtracts the top two
  1216. stack elements), how does one enter a negative number? Calc uses
  1217. the @kbd{_} (underscore) key to act like the minus sign in a number.
  1218. So, typing @kbd{-5 @key{RET}} won't work because the @kbd{-} key
  1219. will try to do a subtraction, but @kbd{_5 @key{RET}} works just fine.
  1220. You can also press @kbd{n}, which means ``change sign.'' It changes
  1221. the number at the top of the stack (or the number being entered)
  1222. from positive to negative or vice-versa: @kbd{5 n @key{RET}}.
  1223. @cindex Duplicating a stack entry
  1224. If you press @key{RET} when you're not entering a number, the effect
  1225. is to duplicate the top number on the stack. Consider this calculation:
  1226. @smallexample
  1227. @group
  1228. 1: 3 2: 3 1: 9 2: 9 1: 81
  1229. . 1: 3 . 1: 9 .
  1230. . .
  1231. 3 @key{RET} @key{RET} * @key{RET} *
  1232. @end group
  1233. @end smallexample
  1234. @noindent
  1235. (Of course, an easier way to do this would be @kbd{3 @key{RET} 4 ^},
  1236. to raise 3 to the fourth power.)
  1237. The space-bar key (denoted @key{SPC} here) performs the same function
  1238. as @key{RET}; you could replace all three occurrences of @key{RET} in
  1239. the above example with @key{SPC} and the effect would be the same.
  1240. @cindex Exchanging stack entries
  1241. Another stack manipulation key is @key{TAB}. This exchanges the top
  1242. two stack entries. Suppose you have computed @kbd{2 @key{RET} 3 +}
  1243. to get 5, and then you realize what you really wanted to compute
  1244. was @expr{20 / (2+3)}.
  1245. @smallexample
  1246. @group
  1247. 1: 5 2: 5 2: 20 1: 4
  1248. . 1: 20 1: 5 .
  1249. . .
  1250. 2 @key{RET} 3 + 20 @key{TAB} /
  1251. @end group
  1252. @end smallexample
  1253. @noindent
  1254. Planning ahead, the calculation would have gone like this:
  1255. @smallexample
  1256. @group
  1257. 1: 20 2: 20 3: 20 2: 20 1: 4
  1258. . 1: 2 2: 2 1: 5 .
  1259. . 1: 3 .
  1260. .
  1261. 20 @key{RET} 2 @key{RET} 3 + /
  1262. @end group
  1263. @end smallexample
  1264. A related stack command is @kbd{M-@key{TAB}} (hold @key{META} and type
  1265. @key{TAB}). It rotates the top three elements of the stack upward,
  1266. bringing the object in level 3 to the top.
  1267. @smallexample
  1268. @group
  1269. 1: 10 2: 10 3: 10 3: 20 3: 30
  1270. . 1: 20 2: 20 2: 30 2: 10
  1271. . 1: 30 1: 10 1: 20
  1272. . . .
  1273. 10 @key{RET} 20 @key{RET} 30 @key{RET} M-@key{TAB} M-@key{TAB}
  1274. @end group
  1275. @end smallexample
  1276. (@bullet{}) @strong{Exercise 3.} Suppose the numbers 10, 20, and 30 are
  1277. on the stack. Figure out how to add one to the number in level 2
  1278. without affecting the rest of the stack. Also figure out how to add
  1279. one to the number in level 3. @xref{RPN Answer 3, 3}. (@bullet{})
  1280. Operations like @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, and @kbd{^} pop two
  1281. arguments from the stack and push a result. Operations like @kbd{n} and
  1282. @kbd{Q} (square root) pop a single number and push the result. You can
  1283. think of them as simply operating on the top element of the stack.
  1284. @smallexample
  1285. @group
  1286. 1: 3 1: 9 2: 9 1: 25 1: 5
  1287. . . 1: 16 . .
  1288. .
  1289. 3 @key{RET} @key{RET} * 4 @key{RET} @key{RET} * + Q
  1290. @end group
  1291. @end smallexample
  1292. @noindent
  1293. (Note that capital @kbd{Q} means to hold down the Shift key while
  1294. typing @kbd{q}. Remember, plain unshifted @kbd{q} is the Quit command.)
  1295. @cindex Pythagorean Theorem
  1296. Here we've used the Pythagorean Theorem to determine the hypotenuse of a
  1297. right triangle. Calc actually has a built-in command for that called
  1298. @kbd{f h}, but let's suppose we can't remember the necessary keystrokes.
  1299. We can still enter it by its full name using @kbd{M-x} notation:
  1300. @smallexample
  1301. @group
  1302. 1: 3 2: 3 1: 5
  1303. . 1: 4 .
  1304. .
  1305. 3 @key{RET} 4 @key{RET} M-x calc-hypot
  1306. @end group
  1307. @end smallexample
  1308. All Calculator commands begin with the word @samp{calc-}. Since it
  1309. gets tiring to type this, Calc provides an @kbd{x} key which is just
  1310. like the regular Emacs @kbd{M-x} key except that it types the @samp{calc-}
  1311. prefix for you:
  1312. @smallexample
  1313. @group
  1314. 1: 3 2: 3 1: 5
  1315. . 1: 4 .
  1316. .
  1317. 3 @key{RET} 4 @key{RET} x hypot
  1318. @end group
  1319. @end smallexample
  1320. What happens if you take the square root of a negative number?
  1321. @smallexample
  1322. @group
  1323. 1: 4 1: -4 1: (0, 2)
  1324. . . .
  1325. 4 @key{RET} n Q
  1326. @end group
  1327. @end smallexample
  1328. @noindent
  1329. The notation @expr{(a, b)} represents a complex number.
  1330. Complex numbers are more traditionally written @expr{a + b i};
  1331. Calc can display in this format, too, but for now we'll stick to the
  1332. @expr{(a, b)} notation.
  1333. If you don't know how complex numbers work, you can safely ignore this
  1334. feature. Complex numbers only arise from operations that would be
  1335. errors in a calculator that didn't have complex numbers. (For example,
  1336. taking the square root or logarithm of a negative number produces a
  1337. complex result.)
  1338. Complex numbers are entered in the notation shown. The @kbd{(} and
  1339. @kbd{,} and @kbd{)} keys manipulate ``incomplete complex numbers.''
  1340. @smallexample
  1341. @group
  1342. 1: ( ... 2: ( ... 1: (2, ... 1: (2, ... 1: (2, 3)
  1343. . 1: 2 . 3 .
  1344. . .
  1345. ( 2 , 3 )
  1346. @end group
  1347. @end smallexample
  1348. You can perform calculations while entering parts of incomplete objects.
  1349. However, an incomplete object cannot actually participate in a calculation:
  1350. @smallexample
  1351. @group
  1352. 1: ( ... 2: ( ... 3: ( ... 1: ( ... 1: ( ...
  1353. . 1: 2 2: 2 5 5
  1354. . 1: 3 . .
  1355. .
  1356. (error)
  1357. ( 2 @key{RET} 3 + +
  1358. @end group
  1359. @end smallexample
  1360. @noindent
  1361. Adding 5 to an incomplete object makes no sense, so the last command
  1362. produces an error message and leaves the stack the same.
  1363. Incomplete objects can't participate in arithmetic, but they can be
  1364. moved around by the regular stack commands.
  1365. @smallexample
  1366. @group
  1367. 2: 2 3: 2 3: 3 1: ( ... 1: (2, 3)
  1368. 1: 3 2: 3 2: ( ... 2 .
  1369. . 1: ( ... 1: 2 3
  1370. . . .
  1371. 2 @key{RET} 3 @key{RET} ( M-@key{TAB} M-@key{TAB} )
  1372. @end group
  1373. @end smallexample
  1374. @noindent
  1375. Note that the @kbd{,} (comma) key did not have to be used here.
  1376. When you press @kbd{)} all the stack entries between the incomplete
  1377. entry and the top are collected, so there's never really a reason
  1378. to use the comma. It's up to you.
  1379. (@bullet{}) @strong{Exercise 4.} To enter the complex number @expr{(2, 3)},
  1380. your friend Joe typed @kbd{( 2 , @key{SPC} 3 )}. What happened?
  1381. (Joe thought of a clever way to correct his mistake in only two
  1382. keystrokes, but it didn't quite work. Try it to find out why.)
  1383. @xref{RPN Answer 4, 4}. (@bullet{})
  1384. Vectors are entered the same way as complex numbers, but with square
  1385. brackets in place of parentheses. We'll meet vectors again later in
  1386. the tutorial.
  1387. Any Emacs command can be given a @dfn{numeric prefix argument} by
  1388. typing a series of @key{META}-digits beforehand. If @key{META} is
  1389. awkward for you, you can instead type @kbd{C-u} followed by the
  1390. necessary digits. Numeric prefix arguments can be negative, as in
  1391. @kbd{M-- M-3 M-5} or @w{@kbd{C-u - 3 5}}. Calc commands use numeric
  1392. prefix arguments in a variety of ways. For example, a numeric prefix
  1393. on the @kbd{+} operator adds any number of stack entries at once:
  1394. @smallexample
  1395. @group
  1396. 1: 10 2: 10 3: 10 3: 10 1: 60
  1397. . 1: 20 2: 20 2: 20 .
  1398. . 1: 30 1: 30
  1399. . .
  1400. 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u 3 +
  1401. @end group
  1402. @end smallexample
  1403. For stack manipulation commands like @key{RET}, a positive numeric
  1404. prefix argument operates on the top @var{n} stack entries at once. A
  1405. negative argument operates on the entry in level @var{n} only. An
  1406. argument of zero operates on the entire stack. In this example, we copy
  1407. the second-to-top element of the stack:
  1408. @smallexample
  1409. @group
  1410. 1: 10 2: 10 3: 10 3: 10 4: 10
  1411. . 1: 20 2: 20 2: 20 3: 20
  1412. . 1: 30 1: 30 2: 30
  1413. . . 1: 20
  1414. .
  1415. 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u -2 @key{RET}
  1416. @end group
  1417. @end smallexample
  1418. @cindex Clearing the stack
  1419. @cindex Emptying the stack
  1420. Another common idiom is @kbd{M-0 @key{DEL}}, which clears the stack.
  1421. (The @kbd{M-0} numeric prefix tells @key{DEL} to operate on the
  1422. entire stack.)
  1423. @node Algebraic Tutorial, Undo Tutorial, RPN Tutorial, Basic Tutorial
  1424. @subsection Algebraic-Style Calculations
  1425. @noindent
  1426. If you are not used to RPN notation, you may prefer to operate the
  1427. Calculator in Algebraic mode, which is closer to the way
  1428. non-RPN calculators work. In Algebraic mode, you enter formulas
  1429. in traditional @expr{2+3} notation.
  1430. @strong{Notice:} Calc gives @samp{/} lower precedence than @samp{*}, so
  1431. that @samp{a/b*c} is interpreted as @samp{a/(b*c)}; this is not
  1432. standard across all computer languages. See below for details.
  1433. You don't really need any special ``mode'' to enter algebraic formulas.
  1434. You can enter a formula at any time by pressing the apostrophe (@kbd{'})
  1435. key. Answer the prompt with the desired formula, then press @key{RET}.
  1436. The formula is evaluated and the result is pushed onto the RPN stack.
  1437. If you don't want to think in RPN at all, you can enter your whole
  1438. computation as a formula, read the result from the stack, then press
  1439. @key{DEL} to delete it from the stack.
  1440. Try pressing the apostrophe key, then @kbd{2+3+4}, then @key{RET}.
  1441. The result should be the number 9.
  1442. Algebraic formulas use the operators @samp{+}, @samp{-}, @samp{*},
  1443. @samp{/}, and @samp{^}. You can use parentheses to make the order
  1444. of evaluation clear. In the absence of parentheses, @samp{^} is
  1445. evaluated first, then @samp{*}, then @samp{/}, then finally
  1446. @samp{+} and @samp{-}. For example, the expression
  1447. @example
  1448. 2 + 3*4*5 / 6*7^8 - 9
  1449. @end example
  1450. @noindent
  1451. is equivalent to
  1452. @example
  1453. 2 + ((3*4*5) / (6*(7^8)) - 9
  1454. @end example
  1455. @noindent
  1456. or, in large mathematical notation,
  1457. @ifnottex
  1458. @example
  1459. @group
  1460. 3 * 4 * 5
  1461. 2 + --------- - 9
  1462. 8
  1463. 6 * 7
  1464. @end group
  1465. @end example
  1466. @end ifnottex
  1467. @tex
  1468. \beforedisplay
  1469. $$ 2 + { 3 \times 4 \times 5 \over 6 \times 7^8 } - 9 $$
  1470. \afterdisplay
  1471. @end tex
  1472. @noindent
  1473. The result of this expression will be the number @mathit{-6.99999826533}.
  1474. Calc's order of evaluation is the same as for most computer languages,
  1475. except that @samp{*} binds more strongly than @samp{/}, as the above
  1476. example shows. As in normal mathematical notation, the @samp{*} symbol
  1477. can often be omitted: @samp{2 a} is the same as @samp{2*a}.
  1478. Operators at the same level are evaluated from left to right, except
  1479. that @samp{^} is evaluated from right to left. Thus, @samp{2-3-4} is
  1480. equivalent to @samp{(2-3)-4} or @mathit{-5}, whereas @samp{2^3^4} is equivalent
  1481. to @samp{2^(3^4)} (a very large integer; try it!).
  1482. If you tire of typing the apostrophe all the time, there is
  1483. Algebraic mode, where Calc automatically senses
  1484. when you are about to type an algebraic expression. To enter this
  1485. mode, press the two letters @w{@kbd{m a}}. (An @samp{Alg} indicator
  1486. should appear in the Calc window's mode line.)
  1487. Press @kbd{m a}, then @kbd{2+3+4} with no apostrophe, then @key{RET}.
  1488. In Algebraic mode, when you press any key that would normally begin
  1489. entering a number (such as a digit, a decimal point, or the @kbd{_}
  1490. key), or if you press @kbd{(} or @kbd{[}, Calc automatically begins
  1491. an algebraic entry.
  1492. Functions which do not have operator symbols like @samp{+} and @samp{*}
  1493. must be entered in formulas using function-call notation. For example,
  1494. the function name corresponding to the square-root key @kbd{Q} is
  1495. @code{sqrt}. To compute a square root in a formula, you would use
  1496. the notation @samp{sqrt(@var{x})}.
  1497. Press the apostrophe, then type @kbd{sqrt(5*2) - 3}. The result should
  1498. be @expr{0.16227766017}.
  1499. Note that if the formula begins with a function name, you need to use
  1500. the apostrophe even if you are in Algebraic mode. If you type @kbd{arcsin}
  1501. out of the blue, the @kbd{a r} will be taken as an Algebraic Rewrite
  1502. command, and the @kbd{csin} will be taken as the name of the rewrite
  1503. rule to use!
  1504. Some people prefer to enter complex numbers and vectors in algebraic
  1505. form because they find RPN entry with incomplete objects to be too
  1506. distracting, even though they otherwise use Calc as an RPN calculator.
  1507. Still in Algebraic mode, type:
  1508. @smallexample
  1509. @group
  1510. 1: (2, 3) 2: (2, 3) 1: (8, -1) 2: (8, -1) 1: (9, -1)
  1511. . 1: (1, -2) . 1: 1 .
  1512. . .
  1513. (2,3) @key{RET} (1,-2) @key{RET} * 1 @key{RET} +
  1514. @end group
  1515. @end smallexample
  1516. Algebraic mode allows us to enter complex numbers without pressing
  1517. an apostrophe first, but it also means we need to press @key{RET}
  1518. after every entry, even for a simple number like @expr{1}.
  1519. (You can type @kbd{C-u m a} to enable a special Incomplete Algebraic
  1520. mode in which the @kbd{(} and @kbd{[} keys use algebraic entry even
  1521. though regular numeric keys still use RPN numeric entry. There is also
  1522. Total Algebraic mode, started by typing @kbd{m t}, in which all
  1523. normal keys begin algebraic entry. You must then use the @key{META} key
  1524. to type Calc commands: @kbd{M-m t} to get back out of Total Algebraic
  1525. mode, @kbd{M-q} to quit, etc.)
  1526. If you're still in Algebraic mode, press @kbd{m a} again to turn it off.
  1527. Actual non-RPN calculators use a mixture of algebraic and RPN styles.
  1528. In general, operators of two numbers (like @kbd{+} and @kbd{*})
  1529. use algebraic form, but operators of one number (like @kbd{n} and @kbd{Q})
  1530. use RPN form. Also, a non-RPN calculator allows you to see the
  1531. intermediate results of a calculation as you go along. You can
  1532. accomplish this in Calc by performing your calculation as a series
  1533. of algebraic entries, using the @kbd{$} sign to tie them together.
  1534. In an algebraic formula, @kbd{$} represents the number on the top
  1535. of the stack. Here, we perform the calculation
  1536. @texline @math{\sqrt{2\times4+1}},
  1537. @infoline @expr{sqrt(2*4+1)},
  1538. which on a traditional calculator would be done by pressing
  1539. @kbd{2 * 4 + 1 =} and then the square-root key.
  1540. @smallexample
  1541. @group
  1542. 1: 8 1: 9 1: 3
  1543. . . .
  1544. ' 2*4 @key{RET} $+1 @key{RET} Q
  1545. @end group
  1546. @end smallexample
  1547. @noindent
  1548. Notice that we didn't need to press an apostrophe for the @kbd{$+1},
  1549. because the dollar sign always begins an algebraic entry.
  1550. (@bullet{}) @strong{Exercise 1.} How could you get the same effect as
  1551. pressing @kbd{Q} but using an algebraic entry instead? How about
  1552. if the @kbd{Q} key on your keyboard were broken?
  1553. @xref{Algebraic Answer 1, 1}. (@bullet{})
  1554. The notations @kbd{$$}, @kbd{$$$}, and so on stand for higher stack
  1555. entries. For example, @kbd{' $$+$ @key{RET}} is just like typing @kbd{+}.
  1556. Algebraic formulas can include @dfn{variables}. To store in a
  1557. variable, press @kbd{s s}, then type the variable name, then press
  1558. @key{RET}. (There are actually two flavors of store command:
  1559. @kbd{s s} stores a number in a variable but also leaves the number
  1560. on the stack, while @w{@kbd{s t}} removes a number from the stack and
  1561. stores it in the variable.) A variable name should consist of one
  1562. or more letters or digits, beginning with a letter.
  1563. @smallexample
  1564. @group
  1565. 1: 17 . 1: a + a^2 1: 306
  1566. . . .
  1567. 17 s t a @key{RET} ' a+a^2 @key{RET} =
  1568. @end group
  1569. @end smallexample
  1570. @noindent
  1571. The @kbd{=} key @dfn{evaluates} a formula by replacing all its
  1572. variables by the values that were stored in them.
  1573. For RPN calculations, you can recall a variable's value on the
  1574. stack either by entering its name as a formula and pressing @kbd{=},
  1575. or by using the @kbd{s r} command.
  1576. @smallexample
  1577. @group
  1578. 1: 17 2: 17 3: 17 2: 17 1: 306
  1579. . 1: 17 2: 17 1: 289 .
  1580. . 1: 2 .
  1581. .
  1582. s r a @key{RET} ' a @key{RET} = 2 ^ +
  1583. @end group
  1584. @end smallexample
  1585. If you press a single digit for a variable name (as in @kbd{s t 3}, you
  1586. get one of ten @dfn{quick variables} @code{q0} through @code{q9}.
  1587. They are ``quick'' simply because you don't have to type the letter
  1588. @code{q} or the @key{RET} after their names. In fact, you can type
  1589. simply @kbd{s 3} as a shorthand for @kbd{s s 3}, and likewise for
  1590. @kbd{t 3} and @w{@kbd{r 3}}.
  1591. Any variables in an algebraic formula for which you have not stored
  1592. values are left alone, even when you evaluate the formula.
  1593. @smallexample
  1594. @group
  1595. 1: 2 a + 2 b 1: 2 b + 34
  1596. . .
  1597. ' 2a+2b @key{RET} =
  1598. @end group
  1599. @end smallexample
  1600. Calls to function names which are undefined in Calc are also left
  1601. alone, as are calls for which the value is undefined.
  1602. @smallexample
  1603. @group
  1604. 1: log10(0) + log10(x) + log10(5, 6) + foo(3) + 2
  1605. .
  1606. ' log10(100) + log10(0) + log10(x) + log10(5,6) + foo(3) @key{RET}
  1607. @end group
  1608. @end smallexample
  1609. @noindent
  1610. In this example, the first call to @code{log10} works, but the other
  1611. calls are not evaluated. In the second call, the logarithm is
  1612. undefined for that value of the argument; in the third, the argument
  1613. is symbolic, and in the fourth, there are too many arguments. In the
  1614. fifth case, there is no function called @code{foo}. You will see a
  1615. ``Wrong number of arguments'' message referring to @samp{log10(5,6)}.
  1616. Press the @kbd{w} (``why'') key to see any other messages that may
  1617. have arisen from the last calculation. In this case you will get
  1618. ``logarithm of zero,'' then ``number expected: @code{x}''. Calc
  1619. automatically displays the first message only if the message is
  1620. sufficiently important; for example, Calc considers ``wrong number
  1621. of arguments'' and ``logarithm of zero'' to be important enough to
  1622. report automatically, while a message like ``number expected: @code{x}''
  1623. will only show up if you explicitly press the @kbd{w} key.
  1624. (@bullet{}) @strong{Exercise 2.} Joe entered the formula @samp{2 x y},
  1625. stored 5 in @code{x}, pressed @kbd{=}, and got the expected result,
  1626. @samp{10 y}. He then tried the same for the formula @samp{2 x (1+y)},
  1627. expecting @samp{10 (1+y)}, but it didn't work. Why not?
  1628. @xref{Algebraic Answer 2, 2}. (@bullet{})
  1629. (@bullet{}) @strong{Exercise 3.} What result would you expect
  1630. @kbd{1 @key{RET} 0 /} to give? What if you then type @kbd{0 *}?
  1631. @xref{Algebraic Answer 3, 3}. (@bullet{})
  1632. One interesting way to work with variables is to use the
  1633. @dfn{evaluates-to} (@samp{=>}) operator. It works like this:
  1634. Enter a formula algebraically in the usual way, but follow
  1635. the formula with an @samp{=>} symbol. (There is also an @kbd{s =}
  1636. command which builds an @samp{=>} formula using the stack.) On
  1637. the stack, you will see two copies of the formula with an @samp{=>}
  1638. between them. The lefthand formula is exactly like you typed it;
  1639. the righthand formula has been evaluated as if by typing @kbd{=}.
  1640. @smallexample
  1641. @group
  1642. 2: 2 + 3 => 5 2: 2 + 3 => 5
  1643. 1: 2 a + 2 b => 34 + 2 b 1: 2 a + 2 b => 20 + 2 b
  1644. . .
  1645. ' 2+3 => @key{RET} ' 2a+2b @key{RET} s = 10 s t a @key{RET}
  1646. @end group
  1647. @end smallexample
  1648. @noindent
  1649. Notice that the instant we stored a new value in @code{a}, all
  1650. @samp{=>} operators already on the stack that referred to @expr{a}
  1651. were updated to use the new value. With @samp{=>}, you can push a
  1652. set of formulas on the stack, then change the variables experimentally
  1653. to see the effects on the formulas' values.
  1654. You can also ``unstore'' a variable when you are through with it:
  1655. @smallexample
  1656. @group
  1657. 2: 2 + 5 => 5
  1658. 1: 2 a + 2 b => 2 a + 2 b
  1659. .
  1660. s u a @key{RET}
  1661. @end group
  1662. @end smallexample
  1663. We will encounter formulas involving variables and functions again
  1664. when we discuss the algebra and calculus features of the Calculator.
  1665. @node Undo Tutorial, Modes Tutorial, Algebraic Tutorial, Basic Tutorial
  1666. @subsection Undo and Redo
  1667. @noindent
  1668. If you make a mistake, you can usually correct it by pressing shift-@kbd{U},
  1669. the ``undo'' command. First, clear the stack (@kbd{M-0 @key{DEL}}) and exit
  1670. and restart Calc (@kbd{C-x * * C-x * *}) to make sure things start off
  1671. with a clean slate. Now:
  1672. @smallexample
  1673. @group
  1674. 1: 2 2: 2 1: 8 2: 2 1: 6
  1675. . 1: 3 . 1: 3 .
  1676. . .
  1677. 2 @key{RET} 3 ^ U *
  1678. @end group
  1679. @end smallexample
  1680. You can undo any number of times. Calc keeps a complete record of
  1681. all you have done since you last opened the Calc window. After the
  1682. above example, you could type:
  1683. @smallexample
  1684. @group
  1685. 1: 6 2: 2 1: 2 . .
  1686. . 1: 3 .
  1687. .
  1688. (error)
  1689. U U U U
  1690. @end group
  1691. @end smallexample
  1692. You can also type @kbd{D} to ``redo'' a command that you have undone
  1693. mistakenly.
  1694. @smallexample
  1695. @group
  1696. . 1: 2 2: 2 1: 6 1: 6
  1697. . 1: 3 . .
  1698. .
  1699. (error)
  1700. D D D D
  1701. @end group
  1702. @end smallexample
  1703. @noindent
  1704. It was not possible to redo past the @expr{6}, since that was placed there
  1705. by something other than an undo command.
  1706. @cindex Time travel
  1707. You can think of undo and redo as a sort of ``time machine.'' Press
  1708. @kbd{U} to go backward in time, @kbd{D} to go forward. If you go
  1709. backward and do something (like @kbd{*}) then, as any science fiction
  1710. reader knows, you have changed your future and you cannot go forward
  1711. again. Thus, the inability to redo past the @expr{6} even though there
  1712. was an earlier undo command.
  1713. You can always recall an earlier result using the Trail. We've ignored
  1714. the trail so far, but it has been faithfully recording everything we
  1715. did since we loaded the Calculator. If the Trail is not displayed,
  1716. press @kbd{t d} now to turn it on.
  1717. Let's try grabbing an earlier result. The @expr{8} we computed was
  1718. undone by a @kbd{U} command, and was lost even to Redo when we pressed
  1719. @kbd{*}, but it's still there in the trail. There should be a little
  1720. @samp{>} arrow (the @dfn{trail pointer}) resting on the last trail
  1721. entry. If there isn't, press @kbd{t ]} to reset the trail pointer.
  1722. Now, press @w{@kbd{t p}} to move the arrow onto the line containing
  1723. @expr{8}, and press @w{@kbd{t y}} to ``yank'' that number back onto the
  1724. stack.
  1725. If you press @kbd{t ]} again, you will see that even our Yank command
  1726. went into the trail.
  1727. Let's go further back in time. Earlier in the tutorial we computed
  1728. a huge integer using the formula @samp{2^3^4}. We don't remember
  1729. what it was, but the first digits were ``241''. Press @kbd{t r}
  1730. (which stands for trail-search-reverse), then type @kbd{241}.
  1731. The trail cursor will jump back to the next previous occurrence of
  1732. the string ``241'' in the trail. This is just a regular Emacs
  1733. incremental search; you can now press @kbd{C-s} or @kbd{C-r} to
  1734. continue the search forwards or backwards as you like.
  1735. To finish the search, press @key{RET}. This halts the incremental
  1736. search and leaves the trail pointer at the thing we found. Now we
  1737. can type @kbd{t y} to yank that number onto the stack. If we hadn't
  1738. remembered the ``241'', we could simply have searched for @kbd{2^3^4},
  1739. then pressed @kbd{@key{RET} t n} to halt and then move to the next item.
  1740. You may have noticed that all the trail-related commands begin with
  1741. the letter @kbd{t}. (The store-and-recall commands, on the other hand,
  1742. all began with @kbd{s}.) Calc has so many commands that there aren't
  1743. enough keys for all of them, so various commands are grouped into
  1744. two-letter sequences where the first letter is called the @dfn{prefix}
  1745. key. If you type a prefix key by accident, you can press @kbd{C-g}
  1746. to cancel it. (In fact, you can press @kbd{C-g} to cancel almost
  1747. anything in Emacs.) To get help on a prefix key, press that key
  1748. followed by @kbd{?}. Some prefixes have several lines of help,
  1749. so you need to press @kbd{?} repeatedly to see them all.
  1750. You can also type @kbd{h h} to see all the help at once.
  1751. Try pressing @kbd{t ?} now. You will see a line of the form,
  1752. @smallexample
  1753. trail/time: Display; Fwd, Back; Next, Prev, Here, [, ]; Yank: [MORE] t-
  1754. @end smallexample
  1755. @noindent
  1756. The word ``trail'' indicates that the @kbd{t} prefix key contains
  1757. trail-related commands. Each entry on the line shows one command,
  1758. with a single capital letter showing which letter you press to get
  1759. that command. We have used @kbd{t n}, @kbd{t p}, @kbd{t ]}, and
  1760. @kbd{t y} so far. The @samp{[MORE]} means you can press @kbd{?}
  1761. again to see more @kbd{t}-prefix commands. Notice that the commands
  1762. are roughly divided (by semicolons) into related groups.
  1763. When you are in the help display for a prefix key, the prefix is
  1764. still active. If you press another key, like @kbd{y} for example,
  1765. it will be interpreted as a @kbd{t y} command. If all you wanted
  1766. was to look at the help messages, press @kbd{C-g} afterwards to cancel
  1767. the prefix.
  1768. One more way to correct an error is by editing the stack entries.
  1769. The actual Stack buffer is marked read-only and must not be edited
  1770. directly, but you can press @kbd{`} (grave accent)
  1771. to edit a stack entry.
  1772. Try entering @samp{3.141439} now. If this is supposed to represent
  1773. @cpi{}, it's got several errors. Press @kbd{`} to edit this number.
  1774. Now use the normal Emacs cursor motion and editing keys to change
  1775. the second 4 to a 5, and to transpose the 3 and the 9. When you
  1776. press @key{RET}, the number on the stack will be replaced by your
  1777. new number. This works for formulas, vectors, and all other types
  1778. of values you can put on the stack. The @kbd{`} key also works
  1779. during entry of a number or algebraic formula.
  1780. @node Modes Tutorial, , Undo Tutorial, Basic Tutorial
  1781. @subsection Mode-Setting Commands
  1782. @noindent
  1783. Calc has many types of @dfn{modes} that affect the way it interprets
  1784. your commands or the way it displays data. We have already seen one
  1785. mode, namely Algebraic mode. There are many others, too; we'll
  1786. try some of the most common ones here.
  1787. Perhaps the most fundamental mode in Calc is the current @dfn{precision}.
  1788. Notice the @samp{12} on the Calc window's mode line:
  1789. @smallexample
  1790. --%*-Calc: 12 Deg (Calculator)----All------
  1791. @end smallexample
  1792. @noindent
  1793. Most of the symbols there are Emacs things you don't need to worry
  1794. about, but the @samp{12} and the @samp{Deg} are mode indicators.
  1795. The @samp{12} means that calculations should always be carried to
  1796. 12 significant figures. That is why, when we type @kbd{1 @key{RET} 7 /},
  1797. we get @expr{0.142857142857} with exactly 12 digits, not counting
  1798. leading and trailing zeros.
  1799. You can set the precision to anything you like by pressing @kbd{p},
  1800. then entering a suitable number. Try pressing @kbd{p 30 @key{RET}},
  1801. then doing @kbd{1 @key{RET} 7 /} again:
  1802. @smallexample
  1803. @group
  1804. 1: 0.142857142857
  1805. 2: 0.142857142857142857142857142857
  1806. .
  1807. @end group
  1808. @end smallexample
  1809. Although the precision can be set arbitrarily high, Calc always
  1810. has to have @emph{some} value for the current precision. After
  1811. all, the true value @expr{1/7} is an infinitely repeating decimal;
  1812. Calc has to stop somewhere.
  1813. Of course, calculations are slower the more digits you request.
  1814. Press @w{@kbd{p 12}} now to set the precision back down to the default.
  1815. Calculations always use the current precision. For example, even
  1816. though we have a 30-digit value for @expr{1/7} on the stack, if
  1817. we use it in a calculation in 12-digit mode it will be rounded
  1818. down to 12 digits before it is used. Try it; press @key{RET} to
  1819. duplicate the number, then @w{@kbd{1 +}}. Notice that the @key{RET}
  1820. key didn't round the number, because it doesn't do any calculation.
  1821. But the instant we pressed @kbd{+}, the number was rounded down.
  1822. @smallexample
  1823. @group
  1824. 1: 0.142857142857
  1825. 2: 0.142857142857142857142857142857
  1826. 3: 1.14285714286
  1827. .
  1828. @end group
  1829. @end smallexample
  1830. @noindent
  1831. In fact, since we added a digit on the left, we had to lose one
  1832. digit on the right from even the 12-digit value of @expr{1/7}.
  1833. How did we get more than 12 digits when we computed @samp{2^3^4}? The
  1834. answer is that Calc makes a distinction between @dfn{integers} and
  1835. @dfn{floating-point} numbers, or @dfn{floats}. An integer is a number
  1836. that does not contain a decimal point. There is no such thing as an
  1837. ``infinitely repeating fraction integer,'' so Calc doesn't have to limit
  1838. itself. If you asked for @samp{2^10000} (don't try this!), you would
  1839. have to wait a long time but you would eventually get an exact answer.
  1840. If you ask for @samp{2.^10000}, you will quickly get an answer which is
  1841. correct only to 12 places. The decimal point tells Calc that it should
  1842. use floating-point arithmetic to get the answer, not exact integer
  1843. arithmetic.
  1844. You can use the @kbd{F} (@code{calc-floor}) command to convert a
  1845. floating-point value to an integer, and @kbd{c f} (@code{calc-float})
  1846. to convert an integer to floating-point form.
  1847. Let's try entering that last calculation:
  1848. @smallexample
  1849. @group
  1850. 1: 2. 2: 2. 1: 1.99506311689e3010
  1851. . 1: 10000 .
  1852. .
  1853. 2.0 @key{RET} 10000 @key{RET} ^
  1854. @end group
  1855. @end smallexample
  1856. @noindent
  1857. @cindex Scientific notation, entry of
  1858. Notice the letter @samp{e} in there. It represents ``times ten to the
  1859. power of,'' and is used by Calc automatically whenever writing the
  1860. number out fully would introduce more extra zeros than you probably
  1861. want to see. You can enter numbers in this notation, too.
  1862. @smallexample
  1863. @group
  1864. 1: 2. 2: 2. 1: 1.99506311678e3010
  1865. . 1: 10000. .
  1866. .
  1867. 2.0 @key{RET} 1e4 @key{RET} ^
  1868. @end group
  1869. @end smallexample
  1870. @cindex Round-off errors
  1871. @noindent
  1872. Hey, the answer is different! Look closely at the middle columns
  1873. of the two examples. In the first, the stack contained the
  1874. exact integer @expr{10000}, but in the second it contained
  1875. a floating-point value with a decimal point. When you raise a
  1876. number to an integer power, Calc uses repeated squaring and
  1877. multiplication to get the answer. When you use a floating-point
  1878. power, Calc uses logarithms and exponentials. As you can see,
  1879. a slight error crept in during one of these methods. Which
  1880. one should we trust? Let's raise the precision a bit and find
  1881. out:
  1882. @smallexample
  1883. @group
  1884. . 1: 2. 2: 2. 1: 1.995063116880828e3010
  1885. . 1: 10000. .
  1886. .
  1887. p 16 @key{RET} 2. @key{RET} 1e4 ^ p 12 @key{RET}
  1888. @end group
  1889. @end smallexample
  1890. @noindent
  1891. @cindex Guard digits
  1892. Presumably, it doesn't matter whether we do this higher-precision
  1893. calculation using an integer or floating-point power, since we
  1894. have added enough ``guard digits'' to trust the first 12 digits
  1895. no matter what. And the verdict is@dots{} Integer powers were more
  1896. accurate; in fact, the result was only off by one unit in the
  1897. last place.
  1898. @cindex Guard digits
  1899. Calc does many of its internal calculations to a slightly higher
  1900. precision, but it doesn't always bump the precision up enough.
  1901. In each case, Calc added about two digits of precision during
  1902. its calculation and then rounded back down to 12 digits
  1903. afterward. In one case, it was enough; in the other, it
  1904. wasn't. If you really need @var{x} digits of precision, it
  1905. never hurts to do the calculation with a few extra guard digits.
  1906. What if we want guard digits but don't want to look at them?
  1907. We can set the @dfn{float format}. Calc supports four major
  1908. formats for floating-point numbers, called @dfn{normal},
  1909. @dfn{fixed-point}, @dfn{scientific notation}, and @dfn{engineering
  1910. notation}. You get them by pressing @w{@kbd{d n}}, @kbd{d f},
  1911. @kbd{d s}, and @kbd{d e}, respectively. In each case, you can
  1912. supply a numeric prefix argument which says how many digits
  1913. should be displayed. As an example, let's put a few numbers
  1914. onto the stack and try some different display modes. First,
  1915. use @kbd{M-0 @key{DEL}} to clear the stack, then enter the four
  1916. numbers shown here:
  1917. @smallexample
  1918. @group
  1919. 4: 12345 4: 12345 4: 12345 4: 12345 4: 12345
  1920. 3: 12345. 3: 12300. 3: 1.2345e4 3: 1.23e4 3: 12345.000
  1921. 2: 123.45 2: 123. 2: 1.2345e2 2: 1.23e2 2: 123.450
  1922. 1: 12.345 1: 12.3 1: 1.2345e1 1: 1.23e1 1: 12.345
  1923. . . . . .
  1924. d n M-3 d n d s M-3 d s M-3 d f
  1925. @end group
  1926. @end smallexample
  1927. @noindent
  1928. Notice that when we typed @kbd{M-3 d n}, the numbers were rounded down
  1929. to three significant digits, but then when we typed @kbd{d s} all
  1930. five significant figures reappeared. The float format does not
  1931. affect how numbers are stored, it only affects how they are
  1932. displayed. Only the current precision governs the actual rounding
  1933. of numbers in the Calculator's memory.
  1934. Engineering notation, not shown here, is like scientific notation
  1935. except the exponent (the power-of-ten part) is always adjusted to be
  1936. a multiple of three (as in ``kilo,'' ``micro,'' etc.). As a result
  1937. there will be one, two, or three digits before the decimal point.
  1938. Whenever you change a display-related mode, Calc redraws everything
  1939. in the stack. This may be slow if there are many things on the stack,
  1940. so Calc allows you to type shift-@kbd{H} before any mode command to
  1941. prevent it from updating the stack. Anything Calc displays after the
  1942. mode-changing command will appear in the new format.
  1943. @smallexample
  1944. @group
  1945. 4: 12345 4: 12345 4: 12345 4: 12345 4: 12345
  1946. 3: 12345.000 3: 12345.000 3: 12345.000 3: 1.2345e4 3: 12345.
  1947. 2: 123.450 2: 123.450 2: 1.2345e1 2: 1.2345e1 2: 123.45
  1948. 1: 12.345 1: 1.2345e1 1: 1.2345e2 1: 1.2345e2 1: 12.345
  1949. . . . . .
  1950. H d s @key{DEL} U @key{TAB} d @key{SPC} d n
  1951. @end group
  1952. @end smallexample
  1953. @noindent
  1954. Here the @kbd{H d s} command changes to scientific notation but without
  1955. updating the screen. Deleting the top stack entry and undoing it back
  1956. causes it to show up in the new format; swapping the top two stack
  1957. entries reformats both entries. The @kbd{d @key{SPC}} command refreshes the
  1958. whole stack. The @kbd{d n} command changes back to the normal float
  1959. format; since it doesn't have an @kbd{H} prefix, it also updates all
  1960. the stack entries to be in @kbd{d n} format.
  1961. Notice that the integer @expr{12345} was not affected by any
  1962. of the float formats. Integers are integers, and are always
  1963. displayed exactly.
  1964. @cindex Large numbers, readability
  1965. Large integers have their own problems. Let's look back at
  1966. the result of @kbd{2^3^4}.
  1967. @example
  1968. 2417851639229258349412352
  1969. @end example
  1970. @noindent
  1971. Quick---how many digits does this have? Try typing @kbd{d g}:
  1972. @example
  1973. 2,417,851,639,229,258,349,412,352
  1974. @end example
  1975. @noindent
  1976. Now how many digits does this have? It's much easier to tell!
  1977. We can actually group digits into clumps of any size. Some
  1978. people prefer @kbd{M-5 d g}:
  1979. @example
  1980. 24178,51639,22925,83494,12352
  1981. @end example
  1982. Let's see what happens to floating-point numbers when they are grouped.
  1983. First, type @kbd{p 25 @key{RET}} to make sure we have enough precision
  1984. to get ourselves into trouble. Now, type @kbd{1e13 /}:
  1985. @example
  1986. 24,17851,63922.9258349412352
  1987. @end example
  1988. @noindent
  1989. The integer part is grouped but the fractional part isn't. Now try
  1990. @kbd{M-- M-5 d g} (that's meta-minus-sign, meta-five):
  1991. @example
  1992. 24,17851,63922.92583,49412,352
  1993. @end example
  1994. If you find it hard to tell the decimal point from the commas, try
  1995. changing the grouping character to a space with @kbd{d , @key{SPC}}:
  1996. @example
  1997. 24 17851 63922.92583 49412 352
  1998. @end example
  1999. Type @kbd{d , ,} to restore the normal grouping character, then
  2000. @kbd{d g} again to turn grouping off. Also, press @kbd{p 12} to
  2001. restore the default precision.
  2002. Press @kbd{U} enough times to get the original big integer back.
  2003. (Notice that @kbd{U} does not undo each mode-setting command; if
  2004. you want to undo a mode-setting command, you have to do it yourself.)
  2005. Now, type @kbd{d r 16 @key{RET}}:
  2006. @example
  2007. 16#200000000000000000000
  2008. @end example
  2009. @noindent
  2010. The number is now displayed in @dfn{hexadecimal}, or ``base-16'' form.
  2011. Suddenly it looks pretty simple; this should be no surprise, since we
  2012. got this number by computing a power of two, and 16 is a power of 2.
  2013. In fact, we can use @w{@kbd{d r 2 @key{RET}}} to see it in actual binary
  2014. form:
  2015. @example
  2016. 2#1000000000000000000000000000000000000000000000000000000 @dots{}
  2017. @end example
  2018. @noindent
  2019. We don't have enough space here to show all the zeros! They won't
  2020. fit on a typical screen, either, so you will have to use horizontal
  2021. scrolling to see them all. Press @kbd{<} and @kbd{>} to scroll the
  2022. stack window left and right by half its width. Another way to view
  2023. something large is to press @kbd{`} (grave accent) to edit the top of
  2024. stack in a separate window. (Press @kbd{C-c C-c} when you are done.)
  2025. You can enter non-decimal numbers using the @kbd{#} symbol, too.
  2026. Let's see what the hexadecimal number @samp{5FE} looks like in
  2027. binary. Type @kbd{16#5FE} (the letters can be typed in upper or
  2028. lower case; they will always appear in upper case). It will also
  2029. help to turn grouping on with @kbd{d g}:
  2030. @example
  2031. 2#101,1111,1110
  2032. @end example
  2033. Notice that @kbd{d g} groups by fours by default if the display radix
  2034. is binary or hexadecimal, but by threes if it is decimal, octal, or any
  2035. other radix.
  2036. Now let's see that number in decimal; type @kbd{d r 10}:
  2037. @example
  2038. 1,534
  2039. @end example
  2040. Numbers are not @emph{stored} with any particular radix attached. They're
  2041. just numbers; they can be entered in any radix, and are always displayed
  2042. in whatever radix you've chosen with @kbd{d r}. The current radix applies
  2043. to integers, fractions, and floats.
  2044. @cindex Roundoff errors, in non-decimal numbers
  2045. (@bullet{}) @strong{Exercise 1.} Your friend Joe tried to enter one-third
  2046. as @samp{3#0.1} in @kbd{d r 3} mode with a precision of 12. He got
  2047. @samp{3#0.0222222...} (with 25 2's) in the display. When he multiplied
  2048. that by three, he got @samp{3#0.222222...} instead of the expected
  2049. @samp{3#1}. Next, Joe entered @samp{3#0.2} and, to his great relief,
  2050. saw @samp{3#0.2} on the screen. But when he typed @kbd{2 /}, he got
  2051. @samp{3#0.10000001} (some zeros omitted). What's going on here?
  2052. @xref{Modes Answer 1, 1}. (@bullet{})
  2053. @cindex Scientific notation, in non-decimal numbers
  2054. (@bullet{}) @strong{Exercise 2.} Scientific notation works in non-decimal
  2055. modes in the natural way (the exponent is a power of the radix instead of
  2056. a power of ten, although the exponent itself is always written in decimal).
  2057. Thus @samp{8#1.23e3 = 8#1230.0}. Suppose we have the hexadecimal number
  2058. @samp{f.e8f} times 16 to the 15th power: We write @samp{16#f.e8fe15}.
  2059. What is wrong with this picture? What could we write instead that would
  2060. work better? @xref{Modes Answer 2, 2}. (@bullet{})
  2061. The @kbd{m} prefix key has another set of modes, relating to the way
  2062. Calc interprets your inputs and does computations. Whereas @kbd{d}-prefix
  2063. modes generally affect the way things look, @kbd{m}-prefix modes affect
  2064. the way they are actually computed.
  2065. The most popular @kbd{m}-prefix mode is the @dfn{angular mode}. Notice
  2066. the @samp{Deg} indicator in the mode line. This means that if you use
  2067. a command that interprets a number as an angle, it will assume the
  2068. angle is measured in degrees. For example,
  2069. @smallexample
  2070. @group
  2071. 1: 45 1: 0.707106781187 1: 0.500000000001 1: 0.5
  2072. . . . .
  2073. 45 S 2 ^ c 1
  2074. @end group
  2075. @end smallexample
  2076. @noindent
  2077. The shift-@kbd{S} command computes the sine of an angle. The sine
  2078. of 45 degrees is
  2079. @texline @math{\sqrt{2}/2};
  2080. @infoline @expr{sqrt(2)/2};
  2081. squaring this yields @expr{2/4 = 0.5}. However, there has been a slight
  2082. roundoff error because the representation of
  2083. @texline @math{\sqrt{2}/2}
  2084. @infoline @expr{sqrt(2)/2}
  2085. wasn't exact. The @kbd{c 1} command is a handy way to clean up numbers
  2086. in this case; it temporarily reduces the precision by one digit while it
  2087. re-rounds the number on the top of the stack.
  2088. @cindex Roundoff errors, examples
  2089. (@bullet{}) @strong{Exercise 3.} Your friend Joe computed the sine
  2090. of 45 degrees as shown above, then, hoping to avoid an inexact
  2091. result, he increased the precision to 16 digits before squaring.
  2092. What happened? @xref{Modes Answer 3, 3}. (@bullet{})
  2093. To do this calculation in radians, we would type @kbd{m r} first.
  2094. (The indicator changes to @samp{Rad}.) 45 degrees corresponds to
  2095. @cpiover{4} radians. To get @cpi{}, press the @kbd{P} key. (Once
  2096. again, this is a shifted capital @kbd{P}. Remember, unshifted
  2097. @kbd{p} sets the precision.)
  2098. @smallexample
  2099. @group
  2100. 1: 3.14159265359 1: 0.785398163398 1: 0.707106781187
  2101. . . .
  2102. P 4 / m r S
  2103. @end group
  2104. @end smallexample
  2105. Likewise, inverse trigonometric functions generate results in
  2106. either radians or degrees, depending on the current angular mode.
  2107. @smallexample
  2108. @group
  2109. 1: 0.707106781187 1: 0.785398163398 1: 45.
  2110. . . .
  2111. .5 Q m r I S m d U I S
  2112. @end group
  2113. @end smallexample
  2114. @noindent
  2115. Here we compute the Inverse Sine of
  2116. @texline @math{\sqrt{0.5}},
  2117. @infoline @expr{sqrt(0.5)},
  2118. first in radians, then in degrees.
  2119. Use @kbd{c d} and @kbd{c r} to convert a number from radians to degrees
  2120. and vice-versa.
  2121. @smallexample
  2122. @group
  2123. 1: 45 1: 0.785398163397 1: 45.
  2124. . . .
  2125. 45 c r c d
  2126. @end group
  2127. @end smallexample
  2128. Another interesting mode is @dfn{Fraction mode}. Normally,
  2129. dividing two integers produces a floating-point result if the
  2130. quotient can't be expressed as an exact integer. Fraction mode
  2131. causes integer division to produce a fraction, i.e., a rational
  2132. number, instead.
  2133. @smallexample
  2134. @group
  2135. 2: 12 1: 1.33333333333 1: 4:3
  2136. 1: 9 . .
  2137. .
  2138. 12 @key{RET} 9 / m f U / m f
  2139. @end group
  2140. @end smallexample
  2141. @noindent
  2142. In the first case, we get an approximate floating-point result.
  2143. In the second case, we get an exact fractional result (four-thirds).
  2144. You can enter a fraction at any time using @kbd{:} notation.
  2145. (Calc uses @kbd{:} instead of @kbd{/} as the fraction separator
  2146. because @kbd{/} is already used to divide the top two stack
  2147. elements.) Calculations involving fractions will always
  2148. produce exact fractional results; Fraction mode only says
  2149. what to do when dividing two integers.
  2150. @cindex Fractions vs. floats
  2151. @cindex Floats vs. fractions
  2152. (@bullet{}) @strong{Exercise 4.} If fractional arithmetic is exact,
  2153. why would you ever use floating-point numbers instead?
  2154. @xref{Modes Answer 4, 4}. (@bullet{})
  2155. Typing @kbd{m f} doesn't change any existing values in the stack.
  2156. In the above example, we had to Undo the division and do it over
  2157. again when we changed to Fraction mode. But if you use the
  2158. evaluates-to operator you can get commands like @kbd{m f} to
  2159. recompute for you.
  2160. @smallexample
  2161. @group
  2162. 1: 12 / 9 => 1.33333333333 1: 12 / 9 => 1.333 1: 12 / 9 => 4:3
  2163. . . .
  2164. ' 12/9 => @key{RET} p 4 @key{RET} m f
  2165. @end group
  2166. @end smallexample
  2167. @noindent
  2168. In this example, the righthand side of the @samp{=>} operator
  2169. on the stack is recomputed when we change the precision, then
  2170. again when we change to Fraction mode. All @samp{=>} expressions
  2171. on the stack are recomputed every time you change any mode that
  2172. might affect their values.
  2173. @node Arithmetic Tutorial, Vector/Matrix Tutorial, Basic Tutorial, Tutorial
  2174. @section Arithmetic Tutorial
  2175. @noindent
  2176. In this section, we explore the arithmetic and scientific functions
  2177. available in the Calculator.
  2178. The standard arithmetic commands are @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/},
  2179. and @kbd{^}. Each normally takes two numbers from the top of the stack
  2180. and pushes back a result. The @kbd{n} and @kbd{&} keys perform
  2181. change-sign and reciprocal operations, respectively.
  2182. @smallexample
  2183. @group
  2184. 1: 5 1: 0.2 1: 5. 1: -5. 1: 5.
  2185. . . . . .
  2186. 5 & & n n
  2187. @end group
  2188. @end smallexample
  2189. @cindex Binary operators
  2190. You can apply a ``binary operator'' like @kbd{+} across any number of
  2191. stack entries by giving it a numeric prefix. You can also apply it
  2192. pairwise to several stack elements along with the top one if you use
  2193. a negative prefix.
  2194. @smallexample
  2195. @group
  2196. 3: 2 1: 9 3: 2 4: 2 3: 12
  2197. 2: 3 . 2: 3 3: 3 2: 13
  2198. 1: 4 1: 4 2: 4 1: 14
  2199. . . 1: 10 .
  2200. .
  2201. 2 @key{RET} 3 @key{RET} 4 M-3 + U 10 M-- M-3 +
  2202. @end group
  2203. @end smallexample
  2204. @cindex Unary operators
  2205. You can apply a ``unary operator'' like @kbd{&} to the top @var{n}
  2206. stack entries with a numeric prefix, too.
  2207. @smallexample
  2208. @group
  2209. 3: 2 3: 0.5 3: 0.5
  2210. 2: 3 2: 0.333333333333 2: 3.
  2211. 1: 4 1: 0.25 1: 4.
  2212. . . .
  2213. 2 @key{RET} 3 @key{RET} 4 M-3 & M-2 &
  2214. @end group
  2215. @end smallexample
  2216. Notice that the results here are left in floating-point form.
  2217. We can convert them back to integers by pressing @kbd{F}, the
  2218. ``floor'' function. This function rounds down to the next lower
  2219. integer. There is also @kbd{R}, which rounds to the nearest
  2220. integer.
  2221. @smallexample
  2222. @group
  2223. 7: 2. 7: 2 7: 2
  2224. 6: 2.4 6: 2 6: 2
  2225. 5: 2.5 5: 2 5: 3
  2226. 4: 2.6 4: 2 4: 3
  2227. 3: -2. 3: -2 3: -2
  2228. 2: -2.4 2: -3 2: -2
  2229. 1: -2.6 1: -3 1: -3
  2230. . . .
  2231. M-7 F U M-7 R
  2232. @end group
  2233. @end smallexample
  2234. Since dividing-and-flooring (i.e., ``integer quotient'') is such a
  2235. common operation, Calc provides a special command for that purpose, the
  2236. backslash @kbd{\}. Another common arithmetic operator is @kbd{%}, which
  2237. computes the remainder that would arise from a @kbd{\} operation, i.e.,
  2238. the ``modulo'' of two numbers. For example,
  2239. @smallexample
  2240. @group
  2241. 2: 1234 1: 12 2: 1234 1: 34
  2242. 1: 100 . 1: 100 .
  2243. . .
  2244. 1234 @key{RET} 100 \ U %
  2245. @end group
  2246. @end smallexample
  2247. These commands actually work for any real numbers, not just integers.
  2248. @smallexample
  2249. @group
  2250. 2: 3.1415 1: 3 2: 3.1415 1: 0.1415
  2251. 1: 1 . 1: 1 .
  2252. . .
  2253. 3.1415 @key{RET} 1 \ U %
  2254. @end group
  2255. @end smallexample
  2256. (@bullet{}) @strong{Exercise 1.} The @kbd{\} command would appear to be a
  2257. frill, since you could always do the same thing with @kbd{/ F}. Think
  2258. of a situation where this is not true---@kbd{/ F} would be inadequate.
  2259. Now think of a way you could get around the problem if Calc didn't
  2260. provide a @kbd{\} command. @xref{Arithmetic Answer 1, 1}. (@bullet{})
  2261. We've already seen the @kbd{Q} (square root) and @kbd{S} (sine)
  2262. commands. Other commands along those lines are @kbd{C} (cosine),
  2263. @kbd{T} (tangent), @kbd{E} (@expr{e^x}) and @kbd{L} (natural
  2264. logarithm). These can be modified by the @kbd{I} (inverse) and
  2265. @kbd{H} (hyperbolic) prefix keys.
  2266. Let's compute the sine and cosine of an angle, and verify the
  2267. identity
  2268. @texline @math{\sin^2x + \cos^2x = 1}.
  2269. @infoline @expr{sin(x)^2 + cos(x)^2 = 1}.
  2270. We'll arbitrarily pick @mathit{-64} degrees as a good value for @expr{x}.
  2271. With the angular mode set to degrees (type @w{@kbd{m d}}), do:
  2272. @smallexample
  2273. @group
  2274. 2: -64 2: -64 2: -0.89879 2: -0.89879 1: 1.
  2275. 1: -64 1: -0.89879 1: -64 1: 0.43837 .
  2276. . . . .
  2277. 64 n @key{RET} @key{RET} S @key{TAB} C f h
  2278. @end group
  2279. @end smallexample
  2280. @noindent
  2281. (For brevity, we're showing only five digits of the results here.
  2282. You can of course do these calculations to any precision you like.)
  2283. Remember, @kbd{f h} is the @code{calc-hypot}, or square-root of sum
  2284. of squares, command.
  2285. Another identity is
  2286. @texline @math{\displaystyle\tan x = {\sin x \over \cos x}}.
  2287. @infoline @expr{tan(x) = sin(x) / cos(x)}.
  2288. @smallexample
  2289. @group
  2290. 2: -0.89879 1: -2.0503 1: -64.
  2291. 1: 0.43837 . .
  2292. .
  2293. U / I T
  2294. @end group
  2295. @end smallexample
  2296. A physical interpretation of this calculation is that if you move
  2297. @expr{0.89879} units downward and @expr{0.43837} units to the right,
  2298. your direction of motion is @mathit{-64} degrees from horizontal. Suppose
  2299. we move in the opposite direction, up and to the left:
  2300. @smallexample
  2301. @group
  2302. 2: -0.89879 2: 0.89879 1: -2.0503 1: -64.
  2303. 1: 0.43837 1: -0.43837 . .
  2304. . .
  2305. U U M-2 n / I T
  2306. @end group
  2307. @end smallexample
  2308. @noindent
  2309. How can the angle be the same? The answer is that the @kbd{/} operation
  2310. loses information about the signs of its inputs. Because the quotient
  2311. is negative, we know exactly one of the inputs was negative, but we
  2312. can't tell which one. There is an @kbd{f T} [@code{arctan2}] function which
  2313. computes the inverse tangent of the quotient of a pair of numbers.
  2314. Since you feed it the two original numbers, it has enough information
  2315. to give you a full 360-degree answer.
  2316. @smallexample
  2317. @group
  2318. 2: 0.89879 1: 116. 3: 116. 2: 116. 1: 180.
  2319. 1: -0.43837 . 2: -0.89879 1: -64. .
  2320. . 1: 0.43837 .
  2321. .
  2322. U U f T M-@key{RET} M-2 n f T -
  2323. @end group
  2324. @end smallexample
  2325. @noindent
  2326. The resulting angles differ by 180 degrees; in other words, they
  2327. point in opposite directions, just as we would expect.
  2328. The @key{META}-@key{RET} we used in the third step is the
  2329. ``last-arguments'' command. It is sort of like Undo, except that it
  2330. restores the arguments of the last command to the stack without removing
  2331. the command's result. It is useful in situations like this one,
  2332. where we need to do several operations on the same inputs. We could
  2333. have accomplished the same thing by using @kbd{M-2 @key{RET}} to duplicate
  2334. the top two stack elements right after the @kbd{U U}, then a pair of
  2335. @kbd{M-@key{TAB}} commands to cycle the 116 up around the duplicates.
  2336. A similar identity is supposed to hold for hyperbolic sines and cosines,
  2337. except that it is the @emph{difference}
  2338. @texline @math{\cosh^2x - \sinh^2x}
  2339. @infoline @expr{cosh(x)^2 - sinh(x)^2}
  2340. that always equals one. Let's try to verify this identity.
  2341. @smallexample
  2342. @group
  2343. 2: -64 2: -64 2: -64 2: 9.7192e54 2: 9.7192e54
  2344. 1: -64 1: -3.1175e27 1: 9.7192e54 1: -64 1: 9.7192e54
  2345. . . . . .
  2346. 64 n @key{RET} @key{RET} H C 2 ^ @key{TAB} H S 2 ^
  2347. @end group
  2348. @end smallexample
  2349. @noindent
  2350. @cindex Roundoff errors, examples
  2351. Something's obviously wrong, because when we subtract these numbers
  2352. the answer will clearly be zero! But if you think about it, if these
  2353. numbers @emph{did} differ by one, it would be in the 55th decimal
  2354. place. The difference we seek has been lost entirely to roundoff
  2355. error.
  2356. We could verify this hypothesis by doing the actual calculation with,
  2357. say, 60 decimal places of precision. This will be slow, but not
  2358. enormously so. Try it if you wish; sure enough, the answer is
  2359. 0.99999, reasonably close to 1.
  2360. Of course, a more reasonable way to verify the identity is to use
  2361. a more reasonable value for @expr{x}!
  2362. @cindex Common logarithm
  2363. Some Calculator commands use the Hyperbolic prefix for other purposes.
  2364. The logarithm and exponential functions, for example, work to the base
  2365. @expr{e} normally but use base-10 instead if you use the Hyperbolic
  2366. prefix.
  2367. @smallexample
  2368. @group
  2369. 1: 1000 1: 6.9077 1: 1000 1: 3
  2370. . . . .
  2371. 1000 L U H L
  2372. @end group
  2373. @end smallexample
  2374. @noindent
  2375. First, we mistakenly compute a natural logarithm. Then we undo
  2376. and compute a common logarithm instead.
  2377. The @kbd{B} key computes a general base-@var{b} logarithm for any
  2378. value of @var{b}.
  2379. @smallexample
  2380. @group
  2381. 2: 1000 1: 3 1: 1000. 2: 1000. 1: 6.9077
  2382. 1: 10 . . 1: 2.71828 .
  2383. . .
  2384. 1000 @key{RET} 10 B H E H P B
  2385. @end group
  2386. @end smallexample
  2387. @noindent
  2388. Here we first use @kbd{B} to compute the base-10 logarithm, then use
  2389. the ``hyperbolic'' exponential as a cheap hack to recover the number
  2390. 1000, then use @kbd{B} again to compute the natural logarithm. Note
  2391. that @kbd{P} with the hyperbolic prefix pushes the constant @expr{e}
  2392. onto the stack.
  2393. You may have noticed that both times we took the base-10 logarithm
  2394. of 1000, we got an exact integer result. Calc always tries to give
  2395. an exact rational result for calculations involving rational numbers
  2396. where possible. But when we used @kbd{H E}, the result was a
  2397. floating-point number for no apparent reason. In fact, if we had
  2398. computed @kbd{10 @key{RET} 3 ^} we @emph{would} have gotten an
  2399. exact integer 1000. But the @kbd{H E} command is rigged to generate
  2400. a floating-point result all of the time so that @kbd{1000 H E} will
  2401. not waste time computing a thousand-digit integer when all you
  2402. probably wanted was @samp{1e1000}.
  2403. (@bullet{}) @strong{Exercise 2.} Find a pair of integer inputs to
  2404. the @kbd{B} command for which Calc could find an exact rational
  2405. result but doesn't. @xref{Arithmetic Answer 2, 2}. (@bullet{})
  2406. The Calculator also has a set of functions relating to combinatorics
  2407. and statistics. You may be familiar with the @dfn{factorial} function,
  2408. which computes the product of all the integers up to a given number.
  2409. @smallexample
  2410. @group
  2411. 1: 100 1: 93326215443... 1: 100. 1: 9.3326e157
  2412. . . . .
  2413. 100 ! U c f !
  2414. @end group
  2415. @end smallexample
  2416. @noindent
  2417. Recall, the @kbd{c f} command converts the integer or fraction at the
  2418. top of the stack to floating-point format. If you take the factorial
  2419. of a floating-point number, you get a floating-point result
  2420. accurate to the current precision. But if you give @kbd{!} an
  2421. exact integer, you get an exact integer result (158 digits long
  2422. in this case).
  2423. If you take the factorial of a non-integer, Calc uses a generalized
  2424. factorial function defined in terms of Euler's Gamma function
  2425. @texline @math{\Gamma(n)}
  2426. @infoline @expr{gamma(n)}
  2427. (which is itself available as the @kbd{f g} command).
  2428. @smallexample
  2429. @group
  2430. 3: 4. 3: 24. 1: 5.5 1: 52.342777847
  2431. 2: 4.5 2: 52.3427777847 . .
  2432. 1: 5. 1: 120.
  2433. . .
  2434. M-3 ! M-0 @key{DEL} 5.5 f g
  2435. @end group
  2436. @end smallexample
  2437. @noindent
  2438. Here we verify the identity
  2439. @texline @math{n! = \Gamma(n+1)}.
  2440. @infoline @expr{@var{n}!@: = gamma(@var{n}+1)}.
  2441. The binomial coefficient @var{n}-choose-@var{m}
  2442. @texline or @math{\displaystyle {n \choose m}}
  2443. is defined by
  2444. @texline @math{\displaystyle {n! \over m! \, (n-m)!}}
  2445. @infoline @expr{n!@: / m!@: (n-m)!}
  2446. for all reals @expr{n} and @expr{m}. The intermediate results in this
  2447. formula can become quite large even if the final result is small; the
  2448. @kbd{k c} command computes a binomial coefficient in a way that avoids
  2449. large intermediate values.
  2450. The @kbd{k} prefix key defines several common functions out of
  2451. combinatorics and number theory. Here we compute the binomial
  2452. coefficient 30-choose-20, then determine its prime factorization.
  2453. @smallexample
  2454. @group
  2455. 2: 30 1: 30045015 1: [3, 3, 5, 7, 11, 13, 23, 29]
  2456. 1: 20 . .
  2457. .
  2458. 30 @key{RET} 20 k c k f
  2459. @end group
  2460. @end smallexample
  2461. @noindent
  2462. You can verify these prime factors by using @kbd{V R *} to multiply
  2463. together the elements of this vector. The result is the original
  2464. number, 30045015.
  2465. @cindex Hash tables
  2466. Suppose a program you are writing needs a hash table with at least
  2467. 10000 entries. It's best to use a prime number as the actual size
  2468. of a hash table. Calc can compute the next prime number after 10000:
  2469. @smallexample
  2470. @group
  2471. 1: 10000 1: 10007 1: 9973
  2472. . . .
  2473. 10000 k n I k n
  2474. @end group
  2475. @end smallexample
  2476. @noindent
  2477. Just for kicks we've also computed the next prime @emph{less} than
  2478. 10000.
  2479. @c [fix-ref Financial Functions]
  2480. @xref{Financial Functions}, for a description of the Calculator
  2481. commands that deal with business and financial calculations (functions
  2482. like @code{pv}, @code{rate}, and @code{sln}).
  2483. @c [fix-ref Binary Number Functions]
  2484. @xref{Binary Functions}, to read about the commands for operating
  2485. on binary numbers (like @code{and}, @code{xor}, and @code{lsh}).
  2486. @node Vector/Matrix Tutorial, Types Tutorial, Arithmetic Tutorial, Tutorial
  2487. @section Vector/Matrix Tutorial
  2488. @noindent
  2489. A @dfn{vector} is a list of numbers or other Calc data objects.
  2490. Calc provides a large set of commands that operate on vectors. Some
  2491. are familiar operations from vector analysis. Others simply treat
  2492. a vector as a list of objects.
  2493. @menu
  2494. * Vector Analysis Tutorial::
  2495. * Matrix Tutorial::
  2496. * List Tutorial::
  2497. @end menu
  2498. @node Vector Analysis Tutorial, Matrix Tutorial, Vector/Matrix Tutorial, Vector/Matrix Tutorial
  2499. @subsection Vector Analysis
  2500. @noindent
  2501. If you add two vectors, the result is a vector of the sums of the
  2502. elements, taken pairwise.
  2503. @smallexample
  2504. @group
  2505. 1: [1, 2, 3] 2: [1, 2, 3] 1: [8, 8, 3]
  2506. . 1: [7, 6, 0] .
  2507. .
  2508. [1,2,3] s 1 [7 6 0] s 2 +
  2509. @end group
  2510. @end smallexample
  2511. @noindent
  2512. Note that we can separate the vector elements with either commas or
  2513. spaces. This is true whether we are using incomplete vectors or
  2514. algebraic entry. The @kbd{s 1} and @kbd{s 2} commands save these
  2515. vectors so we can easily reuse them later.
  2516. If you multiply two vectors, the result is the sum of the products
  2517. of the elements taken pairwise. This is called the @dfn{dot product}
  2518. of the vectors.
  2519. @smallexample
  2520. @group
  2521. 2: [1, 2, 3] 1: 19
  2522. 1: [7, 6, 0] .
  2523. .
  2524. r 1 r 2 *
  2525. @end group
  2526. @end smallexample
  2527. @cindex Dot product
  2528. The dot product of two vectors is equal to the product of their
  2529. lengths times the cosine of the angle between them. (Here the vector
  2530. is interpreted as a line from the origin @expr{(0,0,0)} to the
  2531. specified point in three-dimensional space.) The @kbd{A}
  2532. (absolute value) command can be used to compute the length of a
  2533. vector.
  2534. @smallexample
  2535. @group
  2536. 3: 19 3: 19 1: 0.550782 1: 56.579
  2537. 2: [1, 2, 3] 2: 3.741657 . .
  2538. 1: [7, 6, 0] 1: 9.219544
  2539. . .
  2540. M-@key{RET} M-2 A * / I C
  2541. @end group
  2542. @end smallexample
  2543. @noindent
  2544. First we recall the arguments to the dot product command, then
  2545. we compute the absolute values of the top two stack entries to
  2546. obtain the lengths of the vectors, then we divide the dot product
  2547. by the product of the lengths to get the cosine of the angle.
  2548. The inverse cosine finds that the angle between the vectors
  2549. is about 56 degrees.
  2550. @cindex Cross product
  2551. @cindex Perpendicular vectors
  2552. The @dfn{cross product} of two vectors is a vector whose length
  2553. is the product of the lengths of the inputs times the sine of the
  2554. angle between them, and whose direction is perpendicular to both
  2555. input vectors. Unlike the dot product, the cross product is
  2556. defined only for three-dimensional vectors. Let's double-check
  2557. our computation of the angle using the cross product.
  2558. @smallexample
  2559. @group
  2560. 2: [1, 2, 3] 3: [-18, 21, -8] 1: [-0.52, 0.61, -0.23] 1: 56.579
  2561. 1: [7, 6, 0] 2: [1, 2, 3] . .
  2562. . 1: [7, 6, 0]
  2563. .
  2564. r 1 r 2 V C s 3 M-@key{RET} M-2 A * / A I S
  2565. @end group
  2566. @end smallexample
  2567. @noindent
  2568. First we recall the original vectors and compute their cross product,
  2569. which we also store for later reference. Now we divide the vector
  2570. by the product of the lengths of the original vectors. The length of
  2571. this vector should be the sine of the angle; sure enough, it is!
  2572. @c [fix-ref General Mode Commands]
  2573. Vector-related commands generally begin with the @kbd{v} prefix key.
  2574. Some are uppercase letters and some are lowercase. To make it easier
  2575. to type these commands, the shift-@kbd{V} prefix key acts the same as
  2576. the @kbd{v} key. (@xref{General Mode Commands}, for a way to make all
  2577. prefix keys have this property.)
  2578. If we take the dot product of two perpendicular vectors we expect
  2579. to get zero, since the cosine of 90 degrees is zero. Let's check
  2580. that the cross product is indeed perpendicular to both inputs:
  2581. @smallexample
  2582. @group
  2583. 2: [1, 2, 3] 1: 0 2: [7, 6, 0] 1: 0
  2584. 1: [-18, 21, -8] . 1: [-18, 21, -8] .
  2585. . .
  2586. r 1 r 3 * @key{DEL} r 2 r 3 *
  2587. @end group
  2588. @end smallexample
  2589. @cindex Normalizing a vector
  2590. @cindex Unit vectors
  2591. (@bullet{}) @strong{Exercise 1.} Given a vector on the top of the
  2592. stack, what keystrokes would you use to @dfn{normalize} the
  2593. vector, i.e., to reduce its length to one without changing its
  2594. direction? @xref{Vector Answer 1, 1}. (@bullet{})
  2595. (@bullet{}) @strong{Exercise 2.} Suppose a certain particle can be
  2596. at any of several positions along a ruler. You have a list of
  2597. those positions in the form of a vector, and another list of the
  2598. probabilities for the particle to be at the corresponding positions.
  2599. Find the average position of the particle.
  2600. @xref{Vector Answer 2, 2}. (@bullet{})
  2601. @node Matrix Tutorial, List Tutorial, Vector Analysis Tutorial, Vector/Matrix Tutorial
  2602. @subsection Matrices
  2603. @noindent
  2604. A @dfn{matrix} is just a vector of vectors, all the same length.
  2605. This means you can enter a matrix using nested brackets. You can
  2606. also use the semicolon character to enter a matrix. We'll show
  2607. both methods here:
  2608. @smallexample
  2609. @group
  2610. 1: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
  2611. [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
  2612. . .
  2613. [[1 2 3] [4 5 6]] ' [1 2 3; 4 5 6] @key{RET}
  2614. @end group
  2615. @end smallexample
  2616. @noindent
  2617. We'll be using this matrix again, so type @kbd{s 4} to save it now.
  2618. Note that semicolons work with incomplete vectors, but they work
  2619. better in algebraic entry. That's why we use the apostrophe in
  2620. the second example.
  2621. When two matrices are multiplied, the lefthand matrix must have
  2622. the same number of columns as the righthand matrix has rows.
  2623. Row @expr{i}, column @expr{j} of the result is effectively the
  2624. dot product of row @expr{i} of the left matrix by column @expr{j}
  2625. of the right matrix.
  2626. If we try to duplicate this matrix and multiply it by itself,
  2627. the dimensions are wrong and the multiplication cannot take place:
  2628. @smallexample
  2629. @group
  2630. 1: [ [ 1, 2, 3 ] * [ [ 1, 2, 3 ]
  2631. [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
  2632. .
  2633. @key{RET} *
  2634. @end group
  2635. @end smallexample
  2636. @noindent
  2637. Though rather hard to read, this is a formula which shows the product
  2638. of two matrices. The @samp{*} function, having invalid arguments, has
  2639. been left in symbolic form.
  2640. We can multiply the matrices if we @dfn{transpose} one of them first.
  2641. @smallexample
  2642. @group
  2643. 2: [ [ 1, 2, 3 ] 1: [ [ 14, 32 ] 1: [ [ 17, 22, 27 ]
  2644. [ 4, 5, 6 ] ] [ 32, 77 ] ] [ 22, 29, 36 ]
  2645. 1: [ [ 1, 4 ] . [ 27, 36, 45 ] ]
  2646. [ 2, 5 ] .
  2647. [ 3, 6 ] ]
  2648. .
  2649. U v t * U @key{TAB} *
  2650. @end group
  2651. @end smallexample
  2652. Matrix multiplication is not commutative; indeed, switching the
  2653. order of the operands can even change the dimensions of the result
  2654. matrix, as happened here!
  2655. If you multiply a plain vector by a matrix, it is treated as a
  2656. single row or column depending on which side of the matrix it is
  2657. on. The result is a plain vector which should also be interpreted
  2658. as a row or column as appropriate.
  2659. @smallexample
  2660. @group
  2661. 2: [ [ 1, 2, 3 ] 1: [14, 32]
  2662. [ 4, 5, 6 ] ] .
  2663. 1: [1, 2, 3]
  2664. .
  2665. r 4 r 1 *
  2666. @end group
  2667. @end smallexample
  2668. Multiplying in the other order wouldn't work because the number of
  2669. rows in the matrix is different from the number of elements in the
  2670. vector.
  2671. (@bullet{}) @strong{Exercise 1.} Use @samp{*} to sum along the rows
  2672. of the above
  2673. @texline @math{2\times3}
  2674. @infoline 2x3
  2675. matrix to get @expr{[6, 15]}. Now use @samp{*} to sum along the columns
  2676. to get @expr{[5, 7, 9]}.
  2677. @xref{Matrix Answer 1, 1}. (@bullet{})
  2678. @cindex Identity matrix
  2679. An @dfn{identity matrix} is a square matrix with ones along the
  2680. diagonal and zeros elsewhere. It has the property that multiplication
  2681. by an identity matrix, on the left or on the right, always produces
  2682. the original matrix.
  2683. @smallexample
  2684. @group
  2685. 1: [ [ 1, 2, 3 ] 2: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
  2686. [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
  2687. . 1: [ [ 1, 0, 0 ] .
  2688. [ 0, 1, 0 ]
  2689. [ 0, 0, 1 ] ]
  2690. .
  2691. r 4 v i 3 @key{RET} *
  2692. @end group
  2693. @end smallexample
  2694. If a matrix is square, it is often possible to find its @dfn{inverse},
  2695. that is, a matrix which, when multiplied by the original matrix, yields
  2696. an identity matrix. The @kbd{&} (reciprocal) key also computes the
  2697. inverse of a matrix.
  2698. @smallexample
  2699. @group
  2700. 1: [ [ 1, 2, 3 ] 1: [ [ -2.4, 1.2, -0.2 ]
  2701. [ 4, 5, 6 ] [ 2.8, -1.4, 0.4 ]
  2702. [ 7, 6, 0 ] ] [ -0.73333, 0.53333, -0.2 ] ]
  2703. . .
  2704. r 4 r 2 | s 5 &
  2705. @end group
  2706. @end smallexample
  2707. @noindent
  2708. The vertical bar @kbd{|} @dfn{concatenates} numbers, vectors, and
  2709. matrices together. Here we have used it to add a new row onto
  2710. our matrix to make it square.
  2711. We can multiply these two matrices in either order to get an identity.
  2712. @smallexample
  2713. @group
  2714. 1: [ [ 1., 0., 0. ] 1: [ [ 1., 0., 0. ]
  2715. [ 0., 1., 0. ] [ 0., 1., 0. ]
  2716. [ 0., 0., 1. ] ] [ 0., 0., 1. ] ]
  2717. . .
  2718. M-@key{RET} * U @key{TAB} *
  2719. @end group
  2720. @end smallexample
  2721. @cindex Systems of linear equations
  2722. @cindex Linear equations, systems of
  2723. Matrix inverses are related to systems of linear equations in algebra.
  2724. Suppose we had the following set of equations:
  2725. @ifnottex
  2726. @group
  2727. @example
  2728. a + 2b + 3c = 6
  2729. 4a + 5b + 6c = 2
  2730. 7a + 6b = 3
  2731. @end example
  2732. @end group
  2733. @end ifnottex
  2734. @tex
  2735. \beforedisplayh
  2736. $$ \openup1\jot \tabskip=0pt plus1fil
  2737. \halign to\displaywidth{\tabskip=0pt
  2738. $\hfil#$&$\hfil{}#{}$&
  2739. $\hfil#$&$\hfil{}#{}$&
  2740. $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
  2741. a&+&2b&+&3c&=6 \cr
  2742. 4a&+&5b&+&6c&=2 \cr
  2743. 7a&+&6b& & &=3 \cr}
  2744. $$
  2745. \afterdisplayh
  2746. @end tex
  2747. @noindent
  2748. This can be cast into the matrix equation,
  2749. @ifnottex
  2750. @group
  2751. @example
  2752. [ [ 1, 2, 3 ] [ [ a ] [ [ 6 ]
  2753. [ 4, 5, 6 ] * [ b ] = [ 2 ]
  2754. [ 7, 6, 0 ] ] [ c ] ] [ 3 ] ]
  2755. @end example
  2756. @end group
  2757. @end ifnottex
  2758. @tex
  2759. \beforedisplay
  2760. $$ \pmatrix{ 1 & 2 & 3 \cr 4 & 5 & 6 \cr 7 & 6 & 0 }
  2761. \times
  2762. \pmatrix{ a \cr b \cr c } = \pmatrix{ 6 \cr 2 \cr 3 }
  2763. $$
  2764. \afterdisplay
  2765. @end tex
  2766. We can solve this system of equations by multiplying both sides by the
  2767. inverse of the matrix. Calc can do this all in one step:
  2768. @smallexample
  2769. @group
  2770. 2: [6, 2, 3] 1: [-12.6, 15.2, -3.93333]
  2771. 1: [ [ 1, 2, 3 ] .
  2772. [ 4, 5, 6 ]
  2773. [ 7, 6, 0 ] ]
  2774. .
  2775. [6,2,3] r 5 /
  2776. @end group
  2777. @end smallexample
  2778. @noindent
  2779. The result is the @expr{[a, b, c]} vector that solves the equations.
  2780. (Dividing by a square matrix is equivalent to multiplying by its
  2781. inverse.)
  2782. Let's verify this solution:
  2783. @smallexample
  2784. @group
  2785. 2: [ [ 1, 2, 3 ] 1: [6., 2., 3.]
  2786. [ 4, 5, 6 ] .
  2787. [ 7, 6, 0 ] ]
  2788. 1: [-12.6, 15.2, -3.93333]
  2789. .
  2790. r 5 @key{TAB} *
  2791. @end group
  2792. @end smallexample
  2793. @noindent
  2794. Note that we had to be careful about the order in which we multiplied
  2795. the matrix and vector. If we multiplied in the other order, Calc would
  2796. assume the vector was a row vector in order to make the dimensions
  2797. come out right, and the answer would be incorrect. If you
  2798. don't feel safe letting Calc take either interpretation of your
  2799. vectors, use explicit
  2800. @texline @math{N\times1}
  2801. @infoline Nx1
  2802. or
  2803. @texline @math{1\times N}
  2804. @infoline 1xN
  2805. matrices instead. In this case, you would enter the original column
  2806. vector as @samp{[[6], [2], [3]]} or @samp{[6; 2; 3]}.
  2807. (@bullet{}) @strong{Exercise 2.} Algebraic entry allows you to make
  2808. vectors and matrices that include variables. Solve the following
  2809. system of equations to get expressions for @expr{x} and @expr{y}
  2810. in terms of @expr{a} and @expr{b}.
  2811. @ifnottex
  2812. @group
  2813. @example
  2814. x + a y = 6
  2815. x + b y = 10
  2816. @end example
  2817. @end group
  2818. @end ifnottex
  2819. @tex
  2820. \beforedisplay
  2821. $$ \eqalign{ x &+ a y = 6 \cr
  2822. x &+ b y = 10}
  2823. $$
  2824. \afterdisplay
  2825. @end tex
  2826. @noindent
  2827. @xref{Matrix Answer 2, 2}. (@bullet{})
  2828. @cindex Least-squares for over-determined systems
  2829. @cindex Over-determined systems of equations
  2830. (@bullet{}) @strong{Exercise 3.} A system of equations is ``over-determined''
  2831. if it has more equations than variables. It is often the case that
  2832. there are no values for the variables that will satisfy all the
  2833. equations at once, but it is still useful to find a set of values
  2834. which ``nearly'' satisfy all the equations. In terms of matrix equations,
  2835. you can't solve @expr{A X = B} directly because the matrix @expr{A}
  2836. is not square for an over-determined system. Matrix inversion works
  2837. only for square matrices. One common trick is to multiply both sides
  2838. on the left by the transpose of @expr{A}:
  2839. @ifnottex
  2840. @samp{trn(A)*A*X = trn(A)*B}.
  2841. @end ifnottex
  2842. @tex
  2843. $A^T A \, X = A^T B$, where $A^T$ is the transpose \samp{trn(A)}.
  2844. @end tex
  2845. Now
  2846. @texline @math{A^T A}
  2847. @infoline @expr{trn(A)*A}
  2848. is a square matrix so a solution is possible. It turns out that the
  2849. @expr{X} vector you compute in this way will be a ``least-squares''
  2850. solution, which can be regarded as the ``closest'' solution to the set
  2851. of equations. Use Calc to solve the following over-determined
  2852. system:
  2853. @ifnottex
  2854. @group
  2855. @example
  2856. a + 2b + 3c = 6
  2857. 4a + 5b + 6c = 2
  2858. 7a + 6b = 3
  2859. 2a + 4b + 6c = 11
  2860. @end example
  2861. @end group
  2862. @end ifnottex
  2863. @tex
  2864. \beforedisplayh
  2865. $$ \openup1\jot \tabskip=0pt plus1fil
  2866. \halign to\displaywidth{\tabskip=0pt
  2867. $\hfil#$&$\hfil{}#{}$&
  2868. $\hfil#$&$\hfil{}#{}$&
  2869. $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
  2870. a&+&2b&+&3c&=6 \cr
  2871. 4a&+&5b&+&6c&=2 \cr
  2872. 7a&+&6b& & &=3 \cr
  2873. 2a&+&4b&+&6c&=11 \cr}
  2874. $$
  2875. \afterdisplayh
  2876. @end tex
  2877. @noindent
  2878. @xref{Matrix Answer 3, 3}. (@bullet{})
  2879. @node List Tutorial, , Matrix Tutorial, Vector/Matrix Tutorial
  2880. @subsection Vectors as Lists
  2881. @noindent
  2882. @cindex Lists
  2883. Although Calc has a number of features for manipulating vectors and
  2884. matrices as mathematical objects, you can also treat vectors as
  2885. simple lists of values. For example, we saw that the @kbd{k f}
  2886. command returns a vector which is a list of the prime factors of a
  2887. number.
  2888. You can pack and unpack stack entries into vectors:
  2889. @smallexample
  2890. @group
  2891. 3: 10 1: [10, 20, 30] 3: 10
  2892. 2: 20 . 2: 20
  2893. 1: 30 1: 30
  2894. . .
  2895. M-3 v p v u
  2896. @end group
  2897. @end smallexample
  2898. You can also build vectors out of consecutive integers, or out
  2899. of many copies of a given value:
  2900. @smallexample
  2901. @group
  2902. 1: [1, 2, 3, 4] 2: [1, 2, 3, 4] 2: [1, 2, 3, 4]
  2903. . 1: 17 1: [17, 17, 17, 17]
  2904. . .
  2905. v x 4 @key{RET} 17 v b 4 @key{RET}
  2906. @end group
  2907. @end smallexample
  2908. You can apply an operator to every element of a vector using the
  2909. @dfn{map} command.
  2910. @smallexample
  2911. @group
  2912. 1: [17, 34, 51, 68] 1: [289, 1156, 2601, 4624] 1: [17, 34, 51, 68]
  2913. . . .
  2914. V M * 2 V M ^ V M Q
  2915. @end group
  2916. @end smallexample
  2917. @noindent
  2918. In the first step, we multiply the vector of integers by the vector
  2919. of 17's elementwise. In the second step, we raise each element to
  2920. the power two. (The general rule is that both operands must be
  2921. vectors of the same length, or else one must be a vector and the
  2922. other a plain number.) In the final step, we take the square root
  2923. of each element.
  2924. (@bullet{}) @strong{Exercise 1.} Compute a vector of powers of two
  2925. from
  2926. @texline @math{2^{-4}}
  2927. @infoline @expr{2^-4}
  2928. to @expr{2^4}. @xref{List Answer 1, 1}. (@bullet{})
  2929. You can also @dfn{reduce} a binary operator across a vector.
  2930. For example, reducing @samp{*} computes the product of all the
  2931. elements in the vector:
  2932. @smallexample
  2933. @group
  2934. 1: 123123 1: [3, 7, 11, 13, 41] 1: 123123
  2935. . . .
  2936. 123123 k f V R *
  2937. @end group
  2938. @end smallexample
  2939. @noindent
  2940. In this example, we decompose 123123 into its prime factors, then
  2941. multiply those factors together again to yield the original number.
  2942. We could compute a dot product ``by hand'' using mapping and
  2943. reduction:
  2944. @smallexample
  2945. @group
  2946. 2: [1, 2, 3] 1: [7, 12, 0] 1: 19
  2947. 1: [7, 6, 0] . .
  2948. .
  2949. r 1 r 2 V M * V R +
  2950. @end group
  2951. @end smallexample
  2952. @noindent
  2953. Recalling two vectors from the previous section, we compute the
  2954. sum of pairwise products of the elements to get the same answer
  2955. for the dot product as before.
  2956. A slight variant of vector reduction is the @dfn{accumulate} operation,
  2957. @kbd{V U}. This produces a vector of the intermediate results from
  2958. a corresponding reduction. Here we compute a table of factorials:
  2959. @smallexample
  2960. @group
  2961. 1: [1, 2, 3, 4, 5, 6] 1: [1, 2, 6, 24, 120, 720]
  2962. . .
  2963. v x 6 @key{RET} V U *
  2964. @end group
  2965. @end smallexample
  2966. Calc allows vectors to grow as large as you like, although it gets
  2967. rather slow if vectors have more than about a hundred elements.
  2968. Actually, most of the time is spent formatting these large vectors
  2969. for display, not calculating on them. Try the following experiment
  2970. (if your computer is very fast you may need to substitute a larger
  2971. vector size).
  2972. @smallexample
  2973. @group
  2974. 1: [1, 2, 3, 4, ... 1: [2, 3, 4, 5, ...
  2975. . .
  2976. v x 500 @key{RET} 1 V M +
  2977. @end group
  2978. @end smallexample
  2979. Now press @kbd{v .} (the letter @kbd{v}, then a period) and try the
  2980. experiment again. In @kbd{v .} mode, long vectors are displayed
  2981. ``abbreviated'' like this:
  2982. @smallexample
  2983. @group
  2984. 1: [1, 2, 3, ..., 500] 1: [2, 3, 4, ..., 501]
  2985. . .
  2986. v x 500 @key{RET} 1 V M +
  2987. @end group
  2988. @end smallexample
  2989. @noindent
  2990. (where now the @samp{...} is actually part of the Calc display).
  2991. You will find both operations are now much faster. But notice that
  2992. even in @w{@kbd{v .}} mode, the full vectors are still shown in the Trail.
  2993. Type @w{@kbd{t .}} to cause the trail to abbreviate as well, and try the
  2994. experiment one more time. Operations on long vectors are now quite
  2995. fast! (But of course if you use @kbd{t .} you will lose the ability
  2996. to get old vectors back using the @kbd{t y} command.)
  2997. An easy way to view a full vector when @kbd{v .} mode is active is
  2998. to press @kbd{`} (grave accent) to edit the vector; editing always works
  2999. with the full, unabbreviated value.
  3000. @cindex Least-squares for fitting a straight line
  3001. @cindex Fitting data to a line
  3002. @cindex Line, fitting data to
  3003. @cindex Data, extracting from buffers
  3004. @cindex Columns of data, extracting
  3005. As a larger example, let's try to fit a straight line to some data,
  3006. using the method of least squares. (Calc has a built-in command for
  3007. least-squares curve fitting, but we'll do it by hand here just to
  3008. practice working with vectors.) Suppose we have the following list
  3009. of values in a file we have loaded into Emacs:
  3010. @smallexample
  3011. x y
  3012. --- ---
  3013. 1.34 0.234
  3014. 1.41 0.298
  3015. 1.49 0.402
  3016. 1.56 0.412
  3017. 1.64 0.466
  3018. 1.73 0.473
  3019. 1.82 0.601
  3020. 1.91 0.519
  3021. 2.01 0.603
  3022. 2.11 0.637
  3023. 2.22 0.645
  3024. 2.33 0.705
  3025. 2.45 0.917
  3026. 2.58 1.009
  3027. 2.71 0.971
  3028. 2.85 1.062
  3029. 3.00 1.148
  3030. 3.15 1.157
  3031. 3.32 1.354
  3032. @end smallexample
  3033. @noindent
  3034. If you are reading this tutorial in printed form, you will find it
  3035. easiest to press @kbd{C-x * i} to enter the on-line Info version of
  3036. the manual and find this table there. (Press @kbd{g}, then type
  3037. @kbd{List Tutorial}, to jump straight to this section.)
  3038. Position the cursor at the upper-left corner of this table, just
  3039. to the left of the @expr{1.34}. Press @kbd{C-@@} to set the mark.
  3040. (On your system this may be @kbd{C-2}, @kbd{C-@key{SPC}}, or @kbd{NUL}.)
  3041. Now position the cursor to the lower-right, just after the @expr{1.354}.
  3042. You have now defined this region as an Emacs ``rectangle.'' Still
  3043. in the Info buffer, type @kbd{C-x * r}. This command
  3044. (@code{calc-grab-rectangle}) will pop you back into the Calculator, with
  3045. the contents of the rectangle you specified in the form of a matrix.
  3046. @smallexample
  3047. @group
  3048. 1: [ [ 1.34, 0.234 ]
  3049. [ 1.41, 0.298 ]
  3050. @dots{}
  3051. @end group
  3052. @end smallexample
  3053. @noindent
  3054. (You may wish to use @kbd{v .} mode to abbreviate the display of this
  3055. large matrix.)
  3056. We want to treat this as a pair of lists. The first step is to
  3057. transpose this matrix into a pair of rows. Remember, a matrix is
  3058. just a vector of vectors. So we can unpack the matrix into a pair
  3059. of row vectors on the stack.
  3060. @smallexample
  3061. @group
  3062. 1: [ [ 1.34, 1.41, 1.49, ... ] 2: [1.34, 1.41, 1.49, ... ]
  3063. [ 0.234, 0.298, 0.402, ... ] ] 1: [0.234, 0.298, 0.402, ... ]
  3064. . .
  3065. v t v u
  3066. @end group
  3067. @end smallexample
  3068. @noindent
  3069. Let's store these in quick variables 1 and 2, respectively.
  3070. @smallexample
  3071. @group
  3072. 1: [1.34, 1.41, 1.49, ... ] .
  3073. .
  3074. t 2 t 1
  3075. @end group
  3076. @end smallexample
  3077. @noindent
  3078. (Recall that @kbd{t 2} is a variant of @kbd{s 2} that removes the
  3079. stored value from the stack.)
  3080. In a least squares fit, the slope @expr{m} is given by the formula
  3081. @ifnottex
  3082. @example
  3083. m = (N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)
  3084. @end example
  3085. @end ifnottex
  3086. @tex
  3087. \beforedisplay
  3088. $$ m = {N \sum x y - \sum x \sum y \over
  3089. N \sum x^2 - \left( \sum x \right)^2} $$
  3090. \afterdisplay
  3091. @end tex
  3092. @noindent
  3093. where
  3094. @texline @math{\sum x}
  3095. @infoline @expr{sum(x)}
  3096. represents the sum of all the values of @expr{x}. While there is an
  3097. actual @code{sum} function in Calc, it's easier to sum a vector using a
  3098. simple reduction. First, let's compute the four different sums that
  3099. this formula uses.
  3100. @smallexample
  3101. @group
  3102. 1: 41.63 1: 98.0003
  3103. . .
  3104. r 1 V R + t 3 r 1 2 V M ^ V R + t 4
  3105. @end group
  3106. @end smallexample
  3107. @noindent
  3108. @smallexample
  3109. @group
  3110. 1: 13.613 1: 33.36554
  3111. . .
  3112. r 2 V R + t 5 r 1 r 2 V M * V R + t 6
  3113. @end group
  3114. @end smallexample
  3115. @ifnottex
  3116. @noindent
  3117. These are @samp{sum(x)}, @samp{sum(x^2)}, @samp{sum(y)}, and @samp{sum(x y)},
  3118. respectively. (We could have used @kbd{*} to compute @samp{sum(x^2)} and
  3119. @samp{sum(x y)}.)
  3120. @end ifnottex
  3121. @tex
  3122. These are $\sum x$, $\sum x^2$, $\sum y$, and $\sum x y$,
  3123. respectively. (We could have used \kbd{*} to compute $\sum x^2$ and
  3124. $\sum x y$.)
  3125. @end tex
  3126. Finally, we also need @expr{N}, the number of data points. This is just
  3127. the length of either of our lists.
  3128. @smallexample
  3129. @group
  3130. 1: 19
  3131. .
  3132. r 1 v l t 7
  3133. @end group
  3134. @end smallexample
  3135. @noindent
  3136. (That's @kbd{v} followed by a lower-case @kbd{l}.)
  3137. Now we grind through the formula:
  3138. @smallexample
  3139. @group
  3140. 1: 633.94526 2: 633.94526 1: 67.23607
  3141. . 1: 566.70919 .
  3142. .
  3143. r 7 r 6 * r 3 r 5 * -
  3144. @end group
  3145. @end smallexample
  3146. @noindent
  3147. @smallexample
  3148. @group
  3149. 2: 67.23607 3: 67.23607 2: 67.23607 1: 0.52141679
  3150. 1: 1862.0057 2: 1862.0057 1: 128.9488 .
  3151. . 1: 1733.0569 .
  3152. .
  3153. r 7 r 4 * r 3 2 ^ - / t 8
  3154. @end group
  3155. @end smallexample
  3156. That gives us the slope @expr{m}. The y-intercept @expr{b} can now
  3157. be found with the simple formula,
  3158. @ifnottex
  3159. @example
  3160. b = (sum(y) - m sum(x)) / N
  3161. @end example
  3162. @end ifnottex
  3163. @tex
  3164. \beforedisplay
  3165. $$ b = {\sum y - m \sum x \over N} $$
  3166. \afterdisplay
  3167. \vskip10pt
  3168. @end tex
  3169. @smallexample
  3170. @group
  3171. 1: 13.613 2: 13.613 1: -8.09358 1: -0.425978
  3172. . 1: 21.70658 . .
  3173. .
  3174. r 5 r 8 r 3 * - r 7 / t 9
  3175. @end group
  3176. @end smallexample
  3177. Let's ``plot'' this straight line approximation,
  3178. @texline @math{y \approx m x + b},
  3179. @infoline @expr{m x + b},
  3180. and compare it with the original data.
  3181. @smallexample
  3182. @group
  3183. 1: [0.699, 0.735, ... ] 1: [0.273, 0.309, ... ]
  3184. . .
  3185. r 1 r 8 * r 9 + s 0
  3186. @end group
  3187. @end smallexample
  3188. @noindent
  3189. Notice that multiplying a vector by a constant, and adding a constant
  3190. to a vector, can be done without mapping commands since these are
  3191. common operations from vector algebra. As far as Calc is concerned,
  3192. we've just been doing geometry in 19-dimensional space!
  3193. We can subtract this vector from our original @expr{y} vector to get
  3194. a feel for the error of our fit. Let's find the maximum error:
  3195. @smallexample
  3196. @group
  3197. 1: [0.0387, 0.0112, ... ] 1: [0.0387, 0.0112, ... ] 1: 0.0897
  3198. . . .
  3199. r 2 - V M A V R X
  3200. @end group
  3201. @end smallexample
  3202. @noindent
  3203. First we compute a vector of differences, then we take the absolute
  3204. values of these differences, then we reduce the @code{max} function
  3205. across the vector. (The @code{max} function is on the two-key sequence
  3206. @kbd{f x}; because it is so common to use @code{max} in a vector
  3207. operation, the letters @kbd{X} and @kbd{N} are also accepted for
  3208. @code{max} and @code{min} in this context. In general, you answer
  3209. the @kbd{V M} or @kbd{V R} prompt with the actual key sequence that
  3210. invokes the function you want. You could have typed @kbd{V R f x} or
  3211. even @kbd{V R x max @key{RET}} if you had preferred.)
  3212. If your system has the GNUPLOT program, you can see graphs of your
  3213. data and your straight line to see how well they match. (If you have
  3214. GNUPLOT 3.0 or higher, the following instructions will work regardless
  3215. of the kind of display you have. Some GNUPLOT 2.0, non-X-windows systems
  3216. may require additional steps to view the graphs.)
  3217. Let's start by plotting the original data. Recall the ``@var{x}'' and ``@var{y}''
  3218. vectors onto the stack and press @kbd{g f}. This ``fast'' graphing
  3219. command does everything you need to do for simple, straightforward
  3220. plotting of data.
  3221. @smallexample
  3222. @group
  3223. 2: [1.34, 1.41, 1.49, ... ]
  3224. 1: [0.234, 0.298, 0.402, ... ]
  3225. .
  3226. r 1 r 2 g f
  3227. @end group
  3228. @end smallexample
  3229. If all goes well, you will shortly get a new window containing a graph
  3230. of the data. (If not, contact your GNUPLOT or Calc installer to find
  3231. out what went wrong.) In the X window system, this will be a separate
  3232. graphics window. For other kinds of displays, the default is to
  3233. display the graph in Emacs itself using rough character graphics.
  3234. Press @kbd{q} when you are done viewing the character graphics.
  3235. Next, let's add the line we got from our least-squares fit.
  3236. @ifinfo
  3237. (If you are reading this tutorial on-line while running Calc, typing
  3238. @kbd{g a} may cause the tutorial to disappear from its window and be
  3239. replaced by a buffer named @file{*Gnuplot Commands*}. The tutorial
  3240. will reappear when you terminate GNUPLOT by typing @kbd{g q}.)
  3241. @end ifinfo
  3242. @smallexample
  3243. @group
  3244. 2: [1.34, 1.41, 1.49, ... ]
  3245. 1: [0.273, 0.309, 0.351, ... ]
  3246. .
  3247. @key{DEL} r 0 g a g p
  3248. @end group
  3249. @end smallexample
  3250. It's not very useful to get symbols to mark the data points on this
  3251. second curve; you can type @kbd{g S g p} to remove them. Type @kbd{g q}
  3252. when you are done to remove the X graphics window and terminate GNUPLOT.
  3253. (@bullet{}) @strong{Exercise 2.} An earlier exercise showed how to do
  3254. least squares fitting to a general system of equations. Our 19 data
  3255. points are really 19 equations of the form @expr{y_i = m x_i + b} for
  3256. different pairs of @expr{(x_i,y_i)}. Use the matrix-transpose method
  3257. to solve for @expr{m} and @expr{b}, duplicating the above result.
  3258. @xref{List Answer 2, 2}. (@bullet{})
  3259. @cindex Geometric mean
  3260. (@bullet{}) @strong{Exercise 3.} If the input data do not form a
  3261. rectangle, you can use @w{@kbd{C-x * g}} (@code{calc-grab-region})
  3262. to grab the data the way Emacs normally works with regions---it reads
  3263. left-to-right, top-to-bottom, treating line breaks the same as spaces.
  3264. Use this command to find the geometric mean of the following numbers.
  3265. (The geometric mean is the @var{n}th root of the product of @var{n} numbers.)
  3266. @example
  3267. 2.3 6 22 15.1 7
  3268. 15 14 7.5
  3269. 2.5
  3270. @end example
  3271. @noindent
  3272. The @kbd{C-x * g} command accepts numbers separated by spaces or commas,
  3273. with or without surrounding vector brackets.
  3274. @xref{List Answer 3, 3}. (@bullet{})
  3275. @ifnottex
  3276. As another example, a theorem about binomial coefficients tells
  3277. us that the alternating sum of binomial coefficients
  3278. @var{n}-choose-0 minus @var{n}-choose-1 plus @var{n}-choose-2, and so
  3279. on up to @var{n}-choose-@var{n},
  3280. always comes out to zero. Let's verify this
  3281. for @expr{n=6}.
  3282. @end ifnottex
  3283. @tex
  3284. As another example, a theorem about binomial coefficients tells
  3285. us that the alternating sum of binomial coefficients
  3286. ${n \choose 0} - {n \choose 1} + {n \choose 2} - \cdots \pm {n \choose n}$
  3287. always comes out to zero. Let's verify this
  3288. for \cite{n=6}.
  3289. @end tex
  3290. @smallexample
  3291. @group
  3292. 1: [1, 2, 3, 4, 5, 6, 7] 1: [0, 1, 2, 3, 4, 5, 6]
  3293. . .
  3294. v x 7 @key{RET} 1 -
  3295. @end group
  3296. @end smallexample
  3297. @noindent
  3298. @smallexample
  3299. @group
  3300. 1: [1, -6, 15, -20, 15, -6, 1] 1: 0
  3301. . .
  3302. V M ' (-1)^$ choose(6,$) @key{RET} V R +
  3303. @end group
  3304. @end smallexample
  3305. The @kbd{V M '} command prompts you to enter any algebraic expression
  3306. to define the function to map over the vector. The symbol @samp{$}
  3307. inside this expression represents the argument to the function.
  3308. The Calculator applies this formula to each element of the vector,
  3309. substituting each element's value for the @samp{$} sign(s) in turn.
  3310. To define a two-argument function, use @samp{$$} for the first
  3311. argument and @samp{$} for the second: @kbd{V M ' $$-$ @key{RET}} is
  3312. equivalent to @kbd{V M -}. This is analogous to regular algebraic
  3313. entry, where @samp{$$} would refer to the next-to-top stack entry
  3314. and @samp{$} would refer to the top stack entry, and @kbd{' $$-$ @key{RET}}
  3315. would act exactly like @kbd{-}.
  3316. Notice that the @kbd{V M '} command has recorded two things in the
  3317. trail: The result, as usual, and also a funny-looking thing marked
  3318. @samp{oper} that represents the operator function you typed in.
  3319. The function is enclosed in @samp{< >} brackets, and the argument is
  3320. denoted by a @samp{#} sign. If there were several arguments, they
  3321. would be shown as @samp{#1}, @samp{#2}, and so on. (For example,
  3322. @kbd{V M ' $$-$} will put the function @samp{<#1 - #2>} on the
  3323. trail.) This object is a ``nameless function''; you can use nameless
  3324. @w{@samp{< >}} notation to answer the @kbd{V M '} prompt if you like.
  3325. Nameless function notation has the interesting, occasionally useful
  3326. property that a nameless function is not actually evaluated until
  3327. it is used. For example, @kbd{V M ' $+random(2.0)} evaluates
  3328. @samp{random(2.0)} once and adds that random number to all elements
  3329. of the vector, but @kbd{V M ' <#+random(2.0)>} evaluates the
  3330. @samp{random(2.0)} separately for each vector element.
  3331. Another group of operators that are often useful with @kbd{V M} are
  3332. the relational operators: @kbd{a =}, for example, compares two numbers
  3333. and gives the result 1 if they are equal, or 0 if not. Similarly,
  3334. @w{@kbd{a <}} checks for one number being less than another.
  3335. Other useful vector operations include @kbd{v v}, to reverse a
  3336. vector end-for-end; @kbd{V S}, to sort the elements of a vector
  3337. into increasing order; and @kbd{v r} and @w{@kbd{v c}}, to extract
  3338. one row or column of a matrix, or (in both cases) to extract one
  3339. element of a plain vector. With a negative argument, @kbd{v r}
  3340. and @kbd{v c} instead delete one row, column, or vector element.
  3341. @cindex Divisor functions
  3342. (@bullet{}) @strong{Exercise 4.} The @expr{k}th @dfn{divisor function}
  3343. @tex
  3344. $\sigma_k(n)$
  3345. @end tex
  3346. is the sum of the @expr{k}th powers of all the divisors of an
  3347. integer @expr{n}. Figure out a method for computing the divisor
  3348. function for reasonably small values of @expr{n}. As a test,
  3349. the 0th and 1st divisor functions of 30 are 8 and 72, respectively.
  3350. @xref{List Answer 4, 4}. (@bullet{})
  3351. @cindex Square-free numbers
  3352. @cindex Duplicate values in a list
  3353. (@bullet{}) @strong{Exercise 5.} The @kbd{k f} command produces a
  3354. list of prime factors for a number. Sometimes it is important to
  3355. know that a number is @dfn{square-free}, i.e., that no prime occurs
  3356. more than once in its list of prime factors. Find a sequence of
  3357. keystrokes to tell if a number is square-free; your method should
  3358. leave 1 on the stack if it is, or 0 if it isn't.
  3359. @xref{List Answer 5, 5}. (@bullet{})
  3360. @cindex Triangular lists
  3361. (@bullet{}) @strong{Exercise 6.} Build a list of lists that looks
  3362. like the following diagram. (You may wish to use the @kbd{v /}
  3363. command to enable multi-line display of vectors.)
  3364. @smallexample
  3365. @group
  3366. 1: [ [1],
  3367. [1, 2],
  3368. [1, 2, 3],
  3369. [1, 2, 3, 4],
  3370. [1, 2, 3, 4, 5],
  3371. [1, 2, 3, 4, 5, 6] ]
  3372. @end group
  3373. @end smallexample
  3374. @noindent
  3375. @xref{List Answer 6, 6}. (@bullet{})
  3376. (@bullet{}) @strong{Exercise 7.} Build the following list of lists.
  3377. @smallexample
  3378. @group
  3379. 1: [ [0],
  3380. [1, 2],
  3381. [3, 4, 5],
  3382. [6, 7, 8, 9],
  3383. [10, 11, 12, 13, 14],
  3384. [15, 16, 17, 18, 19, 20] ]
  3385. @end group
  3386. @end smallexample
  3387. @noindent
  3388. @xref{List Answer 7, 7}. (@bullet{})
  3389. @cindex Maximizing a function over a list of values
  3390. @c [fix-ref Numerical Solutions]
  3391. (@bullet{}) @strong{Exercise 8.} Compute a list of values of Bessel's
  3392. @texline @math{J_1(x)}
  3393. @infoline @expr{J1}
  3394. function @samp{besJ(1,x)} for @expr{x} from 0 to 5 in steps of 0.25.
  3395. Find the value of @expr{x} (from among the above set of values) for
  3396. which @samp{besJ(1,x)} is a maximum. Use an ``automatic'' method,
  3397. i.e., just reading along the list by hand to find the largest value
  3398. is not allowed! (There is an @kbd{a X} command which does this kind
  3399. of thing automatically; @pxref{Numerical Solutions}.)
  3400. @xref{List Answer 8, 8}. (@bullet{})
  3401. @cindex Digits, vectors of
  3402. (@bullet{}) @strong{Exercise 9.} You are given an integer in the range
  3403. @texline @math{0 \le N < 10^m}
  3404. @infoline @expr{0 <= N < 10^m}
  3405. for @expr{m=12} (i.e., an integer of less than
  3406. twelve digits). Convert this integer into a vector of @expr{m}
  3407. digits, each in the range from 0 to 9. In vector-of-digits notation,
  3408. add one to this integer to produce a vector of @expr{m+1} digits
  3409. (since there could be a carry out of the most significant digit).
  3410. Convert this vector back into a regular integer. A good integer
  3411. to try is 25129925999. @xref{List Answer 9, 9}. (@bullet{})
  3412. (@bullet{}) @strong{Exercise 10.} Your friend Joe tried to use
  3413. @kbd{V R a =} to test if all numbers in a list were equal. What
  3414. happened? How would you do this test? @xref{List Answer 10, 10}. (@bullet{})
  3415. (@bullet{}) @strong{Exercise 11.} The area of a circle of radius one
  3416. is @cpi{}. The area of the
  3417. @texline @math{2\times2}
  3418. @infoline 2x2
  3419. square that encloses that circle is 4. So if we throw @var{n} darts at
  3420. random points in the square, about @cpiover{4} of them will land inside
  3421. the circle. This gives us an entertaining way to estimate the value of
  3422. @cpi{}. The @w{@kbd{k r}}
  3423. command picks a random number between zero and the value on the stack.
  3424. We could get a random floating-point number between @mathit{-1} and 1 by typing
  3425. @w{@kbd{2.0 k r 1 -}}. Build a vector of 100 random @expr{(x,y)} points in
  3426. this square, then use vector mapping and reduction to count how many
  3427. points lie inside the unit circle. Hint: Use the @kbd{v b} command.
  3428. @xref{List Answer 11, 11}. (@bullet{})
  3429. @cindex Matchstick problem
  3430. (@bullet{}) @strong{Exercise 12.} The @dfn{matchstick problem} provides
  3431. another way to calculate @cpi{}. Say you have an infinite field
  3432. of vertical lines with a spacing of one inch. Toss a one-inch matchstick
  3433. onto the field. The probability that the matchstick will land crossing
  3434. a line turns out to be
  3435. @texline @math{2/\pi}.
  3436. @infoline @expr{2/pi}.
  3437. Toss 100 matchsticks to estimate @cpi{}. (If you want still more fun,
  3438. the probability that the GCD (@w{@kbd{k g}}) of two large integers is
  3439. one turns out to be
  3440. @texline @math{6/\pi^2}.
  3441. @infoline @expr{6/pi^2}.
  3442. That provides yet another way to estimate @cpi{}.)
  3443. @xref{List Answer 12, 12}. (@bullet{})
  3444. (@bullet{}) @strong{Exercise 13.} An algebraic entry of a string in
  3445. double-quote marks, @samp{"hello"}, creates a vector of the numerical
  3446. (ASCII) codes of the characters (here, @expr{[104, 101, 108, 108, 111]}).
  3447. Sometimes it is convenient to compute a @dfn{hash code} of a string,
  3448. which is just an integer that represents the value of that string.
  3449. Two equal strings have the same hash code; two different strings
  3450. @dfn{probably} have different hash codes. (For example, Calc has
  3451. over 400 function names, but Emacs can quickly find the definition for
  3452. any given name because it has sorted the functions into ``buckets'' by
  3453. their hash codes. Sometimes a few names will hash into the same bucket,
  3454. but it is easier to search among a few names than among all the names.)
  3455. One popular hash function is computed as follows: First set @expr{h = 0}.
  3456. Then, for each character from the string in turn, set @expr{h = 3h + c_i}
  3457. where @expr{c_i} is the character's ASCII code. If we have 511 buckets,
  3458. we then take the hash code modulo 511 to get the bucket number. Develop a
  3459. simple command or commands for converting string vectors into hash codes.
  3460. The hash code for @samp{"Testing, 1, 2, 3"} is 1960915098, which modulo
  3461. 511 is 121. @xref{List Answer 13, 13}. (@bullet{})
  3462. (@bullet{}) @strong{Exercise 14.} The @kbd{H V R} and @kbd{H V U}
  3463. commands do nested function evaluations. @kbd{H V U} takes a starting
  3464. value and a number of steps @var{n} from the stack; it then applies the
  3465. function you give to the starting value 0, 1, 2, up to @var{n} times
  3466. and returns a vector of the results. Use this command to create a
  3467. ``random walk'' of 50 steps. Start with the two-dimensional point
  3468. @expr{(0,0)}; then take one step a random distance between @mathit{-1} and 1
  3469. in both @expr{x} and @expr{y}; then take another step, and so on. Use the
  3470. @kbd{g f} command to display this random walk. Now modify your random
  3471. walk to walk a unit distance, but in a random direction, at each step.
  3472. (Hint: The @code{sincos} function returns a vector of the cosine and
  3473. sine of an angle.) @xref{List Answer 14, 14}. (@bullet{})
  3474. @node Types Tutorial, Algebra Tutorial, Vector/Matrix Tutorial, Tutorial
  3475. @section Types Tutorial
  3476. @noindent
  3477. Calc understands a variety of data types as well as simple numbers.
  3478. In this section, we'll experiment with each of these types in turn.
  3479. The numbers we've been using so far have mainly been either @dfn{integers}
  3480. or @dfn{floats}. We saw that floats are usually a good approximation to
  3481. the mathematical concept of real numbers, but they are only approximations
  3482. and are susceptible to roundoff error. Calc also supports @dfn{fractions},
  3483. which can exactly represent any rational number.
  3484. @smallexample
  3485. @group
  3486. 1: 3628800 2: 3628800 1: 518400:7 1: 518414:7 1: 7:518414
  3487. . 1: 49 . . .
  3488. .
  3489. 10 ! 49 @key{RET} : 2 + &
  3490. @end group
  3491. @end smallexample
  3492. @noindent
  3493. The @kbd{:} command divides two integers to get a fraction; @kbd{/}
  3494. would normally divide integers to get a floating-point result.
  3495. Notice we had to type @key{RET} between the @kbd{49} and the @kbd{:}
  3496. since the @kbd{:} would otherwise be interpreted as part of a
  3497. fraction beginning with 49.
  3498. You can convert between floating-point and fractional format using
  3499. @kbd{c f} and @kbd{c F}:
  3500. @smallexample
  3501. @group
  3502. 1: 1.35027217629e-5 1: 7:518414
  3503. . .
  3504. c f c F
  3505. @end group
  3506. @end smallexample
  3507. The @kbd{c F} command replaces a floating-point number with the
  3508. ``simplest'' fraction whose floating-point representation is the
  3509. same, to within the current precision.
  3510. @smallexample
  3511. @group
  3512. 1: 3.14159265359 1: 1146408:364913 1: 3.1416 1: 355:113
  3513. . . . .
  3514. P c F @key{DEL} p 5 @key{RET} P c F
  3515. @end group
  3516. @end smallexample
  3517. (@bullet{}) @strong{Exercise 1.} A calculation has produced the
  3518. result 1.26508260337. You suspect it is the square root of the
  3519. product of @cpi{} and some rational number. Is it? (Be sure
  3520. to allow for roundoff error!) @xref{Types Answer 1, 1}. (@bullet{})
  3521. @dfn{Complex numbers} can be stored in both rectangular and polar form.
  3522. @smallexample
  3523. @group
  3524. 1: -9 1: (0, 3) 1: (3; 90.) 1: (6; 90.) 1: (2.4495; 45.)
  3525. . . . . .
  3526. 9 n Q c p 2 * Q
  3527. @end group
  3528. @end smallexample
  3529. @noindent
  3530. The square root of @mathit{-9} is by default rendered in rectangular form
  3531. (@w{@expr{0 + 3i}}), but we can convert it to polar form (3 with a
  3532. phase angle of 90 degrees). All the usual arithmetic and scientific
  3533. operations are defined on both types of complex numbers.
  3534. Another generalized kind of number is @dfn{infinity}. Infinity
  3535. isn't really a number, but it can sometimes be treated like one.
  3536. Calc uses the symbol @code{inf} to represent positive infinity,
  3537. i.e., a value greater than any real number. Naturally, you can
  3538. also write @samp{-inf} for minus infinity, a value less than any
  3539. real number. The word @code{inf} can only be input using
  3540. algebraic entry.
  3541. @smallexample
  3542. @group
  3543. 2: inf 2: -inf 2: -inf 2: -inf 1: nan
  3544. 1: -17 1: -inf 1: -inf 1: inf .
  3545. . . . .
  3546. ' inf @key{RET} 17 n * @key{RET} 72 + A +
  3547. @end group
  3548. @end smallexample
  3549. @noindent
  3550. Since infinity is infinitely large, multiplying it by any finite
  3551. number (like @mathit{-17}) has no effect, except that since @mathit{-17}
  3552. is negative, it changes a plus infinity to a minus infinity.
  3553. (``A huge positive number, multiplied by @mathit{-17}, yields a huge
  3554. negative number.'') Adding any finite number to infinity also
  3555. leaves it unchanged. Taking an absolute value gives us plus
  3556. infinity again. Finally, we add this plus infinity to the minus
  3557. infinity we had earlier. If you work it out, you might expect
  3558. the answer to be @mathit{-72} for this. But the 72 has been completely
  3559. lost next to the infinities; by the time we compute @w{@samp{inf - inf}}
  3560. the finite difference between them, if any, is undetectable.
  3561. So we say the result is @dfn{indeterminate}, which Calc writes
  3562. with the symbol @code{nan} (for Not A Number).
  3563. Dividing by zero is normally treated as an error, but you can get
  3564. Calc to write an answer in terms of infinity by pressing @kbd{m i}
  3565. to turn on Infinite mode.
  3566. @smallexample
  3567. @group
  3568. 3: nan 2: nan 2: nan 2: nan 1: nan
  3569. 2: 1 1: 1 / 0 1: uinf 1: uinf .
  3570. 1: 0 . . .
  3571. .
  3572. 1 @key{RET} 0 / m i U / 17 n * +
  3573. @end group
  3574. @end smallexample
  3575. @noindent
  3576. Dividing by zero normally is left unevaluated, but after @kbd{m i}
  3577. it instead gives an infinite result. The answer is actually
  3578. @code{uinf}, ``undirected infinity.'' If you look at a graph of
  3579. @expr{1 / x} around @w{@expr{x = 0}}, you'll see that it goes toward
  3580. plus infinity as you approach zero from above, but toward minus
  3581. infinity as you approach from below. Since we said only @expr{1 / 0},
  3582. Calc knows that the answer is infinite but not in which direction.
  3583. That's what @code{uinf} means. Notice that multiplying @code{uinf}
  3584. by a negative number still leaves plain @code{uinf}; there's no
  3585. point in saying @samp{-uinf} because the sign of @code{uinf} is
  3586. unknown anyway. Finally, we add @code{uinf} to our @code{nan},
  3587. yielding @code{nan} again. It's easy to see that, because
  3588. @code{nan} means ``totally unknown'' while @code{uinf} means
  3589. ``unknown sign but known to be infinite,'' the more mysterious
  3590. @code{nan} wins out when it is combined with @code{uinf}, or, for
  3591. that matter, with anything else.
  3592. (@bullet{}) @strong{Exercise 2.} Predict what Calc will answer
  3593. for each of these formulas: @samp{inf / inf}, @samp{exp(inf)},
  3594. @samp{exp(-inf)}, @samp{sqrt(-inf)}, @samp{sqrt(uinf)},
  3595. @samp{abs(uinf)}, @samp{ln(0)}.
  3596. @xref{Types Answer 2, 2}. (@bullet{})
  3597. (@bullet{}) @strong{Exercise 3.} We saw that @samp{inf - inf = nan},
  3598. which stands for an unknown value. Can @code{nan} stand for
  3599. a complex number? Can it stand for infinity?
  3600. @xref{Types Answer 3, 3}. (@bullet{})
  3601. @dfn{HMS forms} represent a value in terms of hours, minutes, and
  3602. seconds.
  3603. @smallexample
  3604. @group
  3605. 1: 2@@ 30' 0" 1: 3@@ 30' 0" 2: 3@@ 30' 0" 1: 2.
  3606. . . 1: 1@@ 45' 0." .
  3607. .
  3608. 2@@ 30' @key{RET} 1 + @key{RET} 2 / /
  3609. @end group
  3610. @end smallexample
  3611. HMS forms can also be used to hold angles in degrees, minutes, and
  3612. seconds.
  3613. @smallexample
  3614. @group
  3615. 1: 0.5 1: 26.56505 1: 26@@ 33' 54.18" 1: 0.44721
  3616. . . . .
  3617. 0.5 I T c h S
  3618. @end group
  3619. @end smallexample
  3620. @noindent
  3621. First we convert the inverse tangent of 0.5 to degrees-minutes-seconds
  3622. form, then we take the sine of that angle. Note that the trigonometric
  3623. functions will accept HMS forms directly as input.
  3624. @cindex Beatles
  3625. (@bullet{}) @strong{Exercise 4.} The Beatles' @emph{Abbey Road} is
  3626. 47 minutes and 26 seconds long, and contains 17 songs. What is the
  3627. average length of a song on @emph{Abbey Road}? If the Extended Disco
  3628. Version of @emph{Abbey Road} added 20 seconds to the length of each
  3629. song, how long would the album be? @xref{Types Answer 4, 4}. (@bullet{})
  3630. A @dfn{date form} represents a date, or a date and time. Dates must
  3631. be entered using algebraic entry. Date forms are surrounded by
  3632. @samp{< >} symbols; most standard formats for dates are recognized.
  3633. @smallexample
  3634. @group
  3635. 2: <Sun Jan 13, 1991> 1: 2.25
  3636. 1: <6:00pm Thu Jan 10, 1991> .
  3637. .
  3638. ' <13 Jan 1991>, <1/10/91, 6pm> @key{RET} -
  3639. @end group
  3640. @end smallexample
  3641. @noindent
  3642. In this example, we enter two dates, then subtract to find the
  3643. number of days between them. It is also possible to add an
  3644. HMS form or a number (of days) to a date form to get another
  3645. date form.
  3646. @smallexample
  3647. @group
  3648. 1: <4:45:59pm Mon Jan 14, 1991> 1: <2:50:59am Thu Jan 17, 1991>
  3649. . .
  3650. t N 2 + 10@@ 5' +
  3651. @end group
  3652. @end smallexample
  3653. @c [fix-ref Date Arithmetic]
  3654. @noindent
  3655. The @kbd{t N} (``now'') command pushes the current date and time on the
  3656. stack; then we add two days, ten hours and five minutes to the date and
  3657. time. Other date-and-time related commands include @kbd{t J}, which
  3658. does Julian day conversions, @kbd{t W}, which finds the beginning of
  3659. the week in which a date form lies, and @kbd{t I}, which increments a
  3660. date by one or several months. @xref{Date Arithmetic}, for more.
  3661. (@bullet{}) @strong{Exercise 5.} How many days until the next
  3662. Friday the 13th? @xref{Types Answer 5, 5}. (@bullet{})
  3663. (@bullet{}) @strong{Exercise 6.} How many leap years will there be
  3664. between now and the year 10001 AD@? @xref{Types Answer 6, 6}. (@bullet{})
  3665. @cindex Slope and angle of a line
  3666. @cindex Angle and slope of a line
  3667. An @dfn{error form} represents a mean value with an attached standard
  3668. deviation, or error estimate. Suppose our measurements indicate that
  3669. a certain telephone pole is about 30 meters away, with an estimated
  3670. error of 1 meter, and 8 meters tall, with an estimated error of 0.2
  3671. meters. What is the slope of a line from here to the top of the
  3672. pole, and what is the equivalent angle in degrees?
  3673. @smallexample
  3674. @group
  3675. 1: 8 +/- 0.2 2: 8 +/- 0.2 1: 0.266 +/- 0.011 1: 14.93 +/- 0.594
  3676. . 1: 30 +/- 1 . .
  3677. .
  3678. 8 p .2 @key{RET} 30 p 1 / I T
  3679. @end group
  3680. @end smallexample
  3681. @noindent
  3682. This means that the angle is about 15 degrees, and, assuming our
  3683. original error estimates were valid standard deviations, there is about
  3684. a 60% chance that the result is correct within 0.59 degrees.
  3685. @cindex Torus, volume of
  3686. (@bullet{}) @strong{Exercise 7.} The volume of a torus (a donut shape) is
  3687. @texline @math{2 \pi^2 R r^2}
  3688. @infoline @w{@expr{2 pi^2 R r^2}}
  3689. where @expr{R} is the radius of the circle that
  3690. defines the center of the tube and @expr{r} is the radius of the tube
  3691. itself. Suppose @expr{R} is 20 cm and @expr{r} is 4 cm, each known to
  3692. within 5 percent. What is the volume and the relative uncertainty of
  3693. the volume? @xref{Types Answer 7, 7}. (@bullet{})
  3694. An @dfn{interval form} represents a range of values. While an
  3695. error form is best for making statistical estimates, intervals give
  3696. you exact bounds on an answer. Suppose we additionally know that
  3697. our telephone pole is definitely between 28 and 31 meters away,
  3698. and that it is between 7.7 and 8.1 meters tall.
  3699. @smallexample
  3700. @group
  3701. 1: [7.7 .. 8.1] 2: [7.7 .. 8.1] 1: [0.24 .. 0.28] 1: [13.9 .. 16.1]
  3702. . 1: [28 .. 31] . .
  3703. .
  3704. [ 7.7 .. 8.1 ] [ 28 .. 31 ] / I T
  3705. @end group
  3706. @end smallexample
  3707. @noindent
  3708. If our bounds were correct, then the angle to the top of the pole
  3709. is sure to lie in the range shown.
  3710. The square brackets around these intervals indicate that the endpoints
  3711. themselves are allowable values. In other words, the distance to the
  3712. telephone pole is between 28 and 31, @emph{inclusive}. You can also
  3713. make an interval that is exclusive of its endpoints by writing
  3714. parentheses instead of square brackets. You can even make an interval
  3715. which is inclusive (``closed'') on one end and exclusive (``open'') on
  3716. the other.
  3717. @smallexample
  3718. @group
  3719. 1: [1 .. 10) 1: (0.1 .. 1] 2: (0.1 .. 1] 1: (0.2 .. 3)
  3720. . . 1: [2 .. 3) .
  3721. .
  3722. [ 1 .. 10 ) & [ 2 .. 3 ) *
  3723. @end group
  3724. @end smallexample
  3725. @noindent
  3726. The Calculator automatically keeps track of which end values should
  3727. be open and which should be closed. You can also make infinite or
  3728. semi-infinite intervals by using @samp{-inf} or @samp{inf} for one
  3729. or both endpoints.
  3730. (@bullet{}) @strong{Exercise 8.} What answer would you expect from
  3731. @samp{@w{1 /} @w{(0 .. 10)}}? What about @samp{@w{1 /} @w{(-10 .. 0)}}? What
  3732. about @samp{@w{1 /} @w{[0 .. 10]}} (where the interval actually includes
  3733. zero)? What about @samp{@w{1 /} @w{(-10 .. 10)}}?
  3734. @xref{Types Answer 8, 8}. (@bullet{})
  3735. (@bullet{}) @strong{Exercise 9.} Two easy ways of squaring a number
  3736. are @kbd{@key{RET} *} and @w{@kbd{2 ^}}. Normally these produce the same
  3737. answer. Would you expect this still to hold true for interval forms?
  3738. If not, which of these will result in a larger interval?
  3739. @xref{Types Answer 9, 9}. (@bullet{})
  3740. A @dfn{modulo form} is used for performing arithmetic modulo @var{m}.
  3741. For example, arithmetic involving time is generally done modulo 12
  3742. or 24 hours.
  3743. @smallexample
  3744. @group
  3745. 1: 17 mod 24 1: 3 mod 24 1: 21 mod 24 1: 9 mod 24
  3746. . . . .
  3747. 17 M 24 @key{RET} 10 + n 5 /
  3748. @end group
  3749. @end smallexample
  3750. @noindent
  3751. In this last step, Calc has divided by 5 modulo 24; i.e., it has found a
  3752. new number which, when multiplied by 5 modulo 24, produces the original
  3753. number, 21. If @var{m} is prime and the divisor is not a multiple of
  3754. @var{m}, it is always possible to find such a number. For non-prime
  3755. @var{m} like 24, it is only sometimes possible.
  3756. @smallexample
  3757. @group
  3758. 1: 10 mod 24 1: 16 mod 24 1: 1000000... 1: 16
  3759. . . . .
  3760. 10 M 24 @key{RET} 100 ^ 10 @key{RET} 100 ^ 24 %
  3761. @end group
  3762. @end smallexample
  3763. @noindent
  3764. These two calculations get the same answer, but the first one is
  3765. much more efficient because it avoids the huge intermediate value
  3766. that arises in the second one.
  3767. @cindex Fermat, primality test of
  3768. (@bullet{}) @strong{Exercise 10.} A theorem of Pierre de Fermat
  3769. says that
  3770. @texline @math{x^{n-1} \bmod n = 1}
  3771. @infoline @expr{x^(n-1) mod n = 1}
  3772. if @expr{n} is a prime number and @expr{x} is an integer less than
  3773. @expr{n}. If @expr{n} is @emph{not} a prime number, this will
  3774. @emph{not} be true for most values of @expr{x}. Thus we can test
  3775. informally if a number is prime by trying this formula for several
  3776. values of @expr{x}. Use this test to tell whether the following numbers
  3777. are prime: 811749613, 15485863. @xref{Types Answer 10, 10}. (@bullet{})
  3778. It is possible to use HMS forms as parts of error forms, intervals,
  3779. modulo forms, or as the phase part of a polar complex number.
  3780. For example, the @code{calc-time} command pushes the current time
  3781. of day on the stack as an HMS/modulo form.
  3782. @smallexample
  3783. @group
  3784. 1: 17@@ 34' 45" mod 24@@ 0' 0" 1: 6@@ 22' 15" mod 24@@ 0' 0"
  3785. . .
  3786. x time @key{RET} n
  3787. @end group
  3788. @end smallexample
  3789. @noindent
  3790. This calculation tells me it is six hours and 22 minutes until midnight.
  3791. (@bullet{}) @strong{Exercise 11.} A rule of thumb is that one year
  3792. is about
  3793. @texline @math{\pi \times 10^7}
  3794. @infoline @w{@expr{pi * 10^7}}
  3795. seconds. What time will it be that many seconds from right now?
  3796. @xref{Types Answer 11, 11}. (@bullet{})
  3797. (@bullet{}) @strong{Exercise 12.} You are preparing to order packaging
  3798. for the CD release of the Extended Disco Version of @emph{Abbey Road}.
  3799. You are told that the songs will actually be anywhere from 20 to 60
  3800. seconds longer than the originals. One CD can hold about 75 minutes
  3801. of music. Should you order single or double packages?
  3802. @xref{Types Answer 12, 12}. (@bullet{})
  3803. Another kind of data the Calculator can manipulate is numbers with
  3804. @dfn{units}. This isn't strictly a new data type; it's simply an
  3805. application of algebraic expressions, where we use variables with
  3806. suggestive names like @samp{cm} and @samp{in} to represent units
  3807. like centimeters and inches.
  3808. @smallexample
  3809. @group
  3810. 1: 2 in 1: 5.08 cm 1: 0.027778 fath 1: 0.0508 m
  3811. . . . .
  3812. ' 2in @key{RET} u c cm @key{RET} u c fath @key{RET} u b
  3813. @end group
  3814. @end smallexample
  3815. @noindent
  3816. We enter the quantity ``2 inches'' (actually an algebraic expression
  3817. which means two times the variable @samp{in}), then we convert it
  3818. first to centimeters, then to fathoms, then finally to ``base'' units,
  3819. which in this case means meters.
  3820. @smallexample
  3821. @group
  3822. 1: 9 acre 1: 3 sqrt(acre) 1: 190.84 m 1: 190.84 m + 30 cm
  3823. . . . .
  3824. ' 9 acre @key{RET} Q u s ' $+30 cm @key{RET}
  3825. @end group
  3826. @end smallexample
  3827. @noindent
  3828. @smallexample
  3829. @group
  3830. 1: 191.14 m 1: 36536.3046 m^2 1: 365363046 cm^2
  3831. . . .
  3832. u s 2 ^ u c cgs
  3833. @end group
  3834. @end smallexample
  3835. @noindent
  3836. Since units expressions are really just formulas, taking the square
  3837. root of @samp{acre} is undefined. After all, @code{acre} might be an
  3838. algebraic variable that you will someday assign a value. We use the
  3839. ``units-simplify'' command to simplify the expression with variables
  3840. being interpreted as unit names.
  3841. In the final step, we have converted not to a particular unit, but to a
  3842. units system. The ``cgs'' system uses centimeters instead of meters
  3843. as its standard unit of length.
  3844. There is a wide variety of units defined in the Calculator.
  3845. @smallexample
  3846. @group
  3847. 1: 55 mph 1: 88.5139 kph 1: 88.5139 km / hr 1: 8.201407e-8 c
  3848. . . . .
  3849. ' 55 mph @key{RET} u c kph @key{RET} u c km/hr @key{RET} u c c @key{RET}
  3850. @end group
  3851. @end smallexample
  3852. @noindent
  3853. We express a speed first in miles per hour, then in kilometers per
  3854. hour, then again using a slightly more explicit notation, then
  3855. finally in terms of fractions of the speed of light.
  3856. Temperature conversions are a bit more tricky. There are two ways to
  3857. interpret ``20 degrees Fahrenheit''---it could mean an actual
  3858. temperature, or it could mean a change in temperature. For normal
  3859. units there is no difference, but temperature units have an offset
  3860. as well as a scale factor and so there must be two explicit commands
  3861. for them.
  3862. @smallexample
  3863. @group
  3864. 1: 20 degF 1: 11.1111 degC 1: -6.666 degC
  3865. . . . .
  3866. ' 20 degF @key{RET} u c degC @key{RET} U u t degC @key{RET}
  3867. @end group
  3868. @end smallexample
  3869. @noindent
  3870. First we convert a change of 20 degrees Fahrenheit into an equivalent
  3871. change in degrees Celsius (or Centigrade). Then, we convert the
  3872. absolute temperature 20 degrees Fahrenheit into Celsius.
  3873. For simple unit conversions, you can put a plain number on the stack.
  3874. Then @kbd{u c} and @kbd{u t} will prompt for both old and new units.
  3875. When you use this method, you're responsible for remembering which
  3876. numbers are in which units:
  3877. @smallexample
  3878. @group
  3879. 1: 55 1: 88.5139 1: 8.201407e-8
  3880. . . .
  3881. 55 u c mph @key{RET} kph @key{RET} u c km/hr @key{RET} c @key{RET}
  3882. @end group
  3883. @end smallexample
  3884. To see a complete list of built-in units, type @kbd{u v}. Press
  3885. @w{@kbd{C-x * c}} again to re-enter the Calculator when you're done looking
  3886. at the units table.
  3887. (@bullet{}) @strong{Exercise 13.} How many seconds are there really
  3888. in a year? @xref{Types Answer 13, 13}. (@bullet{})
  3889. @cindex Speed of light
  3890. (@bullet{}) @strong{Exercise 14.} Supercomputer designs are limited by
  3891. the speed of light (and of electricity, which is nearly as fast).
  3892. Suppose a computer has a 4.1 ns (nanosecond) clock cycle, and its
  3893. cabinet is one meter across. Is speed of light going to be a
  3894. significant factor in its design? @xref{Types Answer 14, 14}. (@bullet{})
  3895. (@bullet{}) @strong{Exercise 15.} Sam the Slug normally travels about
  3896. five yards in an hour. He has obtained a supply of Power Pills; each
  3897. Power Pill he eats doubles his speed. How many Power Pills can he
  3898. swallow and still travel legally on most US highways?
  3899. @xref{Types Answer 15, 15}. (@bullet{})
  3900. @node Algebra Tutorial, Programming Tutorial, Types Tutorial, Tutorial
  3901. @section Algebra and Calculus Tutorial
  3902. @noindent
  3903. This section shows how to use Calc's algebra facilities to solve
  3904. equations, do simple calculus problems, and manipulate algebraic
  3905. formulas.
  3906. @menu
  3907. * Basic Algebra Tutorial::
  3908. * Rewrites Tutorial::
  3909. @end menu
  3910. @node Basic Algebra Tutorial, Rewrites Tutorial, Algebra Tutorial, Algebra Tutorial
  3911. @subsection Basic Algebra
  3912. @noindent
  3913. If you enter a formula in Algebraic mode that refers to variables,
  3914. the formula itself is pushed onto the stack. You can manipulate
  3915. formulas as regular data objects.
  3916. @smallexample
  3917. @group
  3918. 1: 2 x^2 - 6 1: 6 - 2 x^2 1: (3 x^2 + y) (6 - 2 x^2)
  3919. . . .
  3920. ' 2x^2-6 @key{RET} n ' 3x^2+y @key{RET} *
  3921. @end group
  3922. @end smallexample
  3923. (@bullet{}) @strong{Exercise 1.} Do @kbd{' x @key{RET} Q 2 ^} and
  3924. @kbd{' x @key{RET} 2 ^ Q} both wind up with the same result (@samp{x})?
  3925. Why or why not? @xref{Algebra Answer 1, 1}. (@bullet{})
  3926. There are also commands for doing common algebraic operations on
  3927. formulas. Continuing with the formula from the last example,
  3928. @smallexample
  3929. @group
  3930. 1: 18 x^2 - 6 x^4 + 6 y - 2 y x^2 1: (18 - 2 y) x^2 - 6 x^4 + 6 y
  3931. . .
  3932. a x a c x @key{RET}
  3933. @end group
  3934. @end smallexample
  3935. @noindent
  3936. First we ``expand'' using the distributive law, then we ``collect''
  3937. terms involving like powers of @expr{x}.
  3938. Let's find the value of this expression when @expr{x} is 2 and @expr{y}
  3939. is one-half.
  3940. @smallexample
  3941. @group
  3942. 1: 17 x^2 - 6 x^4 + 3 1: -25
  3943. . .
  3944. 1:2 s l y @key{RET} 2 s l x @key{RET}
  3945. @end group
  3946. @end smallexample
  3947. @noindent
  3948. The @kbd{s l} command means ``let''; it takes a number from the top of
  3949. the stack and temporarily assigns it as the value of the variable
  3950. you specify. It then evaluates (as if by the @kbd{=} key) the
  3951. next expression on the stack. After this command, the variable goes
  3952. back to its original value, if any.
  3953. (An earlier exercise in this tutorial involved storing a value in the
  3954. variable @code{x}; if this value is still there, you will have to
  3955. unstore it with @kbd{s u x @key{RET}} before the above example will work
  3956. properly.)
  3957. @cindex Maximum of a function using Calculus
  3958. Let's find the maximum value of our original expression when @expr{y}
  3959. is one-half and @expr{x} ranges over all possible values. We can
  3960. do this by taking the derivative with respect to @expr{x} and examining
  3961. values of @expr{x} for which the derivative is zero. If the second
  3962. derivative of the function at that value of @expr{x} is negative,
  3963. the function has a local maximum there.
  3964. @smallexample
  3965. @group
  3966. 1: 17 x^2 - 6 x^4 + 3 1: 34 x - 24 x^3
  3967. . .
  3968. U @key{DEL} s 1 a d x @key{RET} s 2
  3969. @end group
  3970. @end smallexample
  3971. @noindent
  3972. Well, the derivative is clearly zero when @expr{x} is zero. To find
  3973. the other root(s), let's divide through by @expr{x} and then solve:
  3974. @smallexample
  3975. @group
  3976. 1: (34 x - 24 x^3) / x 1: 34 - 24 x^2
  3977. . .
  3978. ' x @key{RET} / a x
  3979. @end group
  3980. @end smallexample
  3981. @noindent
  3982. @smallexample
  3983. @group
  3984. 1: 0.70588 x^2 = 1 1: x = 1.19023
  3985. . .
  3986. 0 a = s 3 a S x @key{RET}
  3987. @end group
  3988. @end smallexample
  3989. @noindent
  3990. Now we compute the second derivative and plug in our values of @expr{x}:
  3991. @smallexample
  3992. @group
  3993. 1: 1.19023 2: 1.19023 2: 1.19023
  3994. . 1: 34 x - 24 x^3 1: 34 - 72 x^2
  3995. . .
  3996. a . r 2 a d x @key{RET} s 4
  3997. @end group
  3998. @end smallexample
  3999. @noindent
  4000. (The @kbd{a .} command extracts just the righthand side of an equation.
  4001. Another method would have been to use @kbd{v u} to unpack the equation
  4002. @w{@samp{x = 1.19}} to @samp{x} and @samp{1.19}, then use @kbd{M-- M-2 @key{DEL}}
  4003. to delete the @samp{x}.)
  4004. @smallexample
  4005. @group
  4006. 2: 34 - 72 x^2 1: -68. 2: 34 - 72 x^2 1: 34
  4007. 1: 1.19023 . 1: 0 .
  4008. . .
  4009. @key{TAB} s l x @key{RET} U @key{DEL} 0 s l x @key{RET}
  4010. @end group
  4011. @end smallexample
  4012. @noindent
  4013. The first of these second derivatives is negative, so we know the function
  4014. has a maximum value at @expr{x = 1.19023}. (The function also has a
  4015. local @emph{minimum} at @expr{x = 0}.)
  4016. When we solved for @expr{x}, we got only one value even though
  4017. @expr{0.70588 x^2 = 1} is a quadratic equation that ought to have
  4018. two solutions. The reason is that @w{@kbd{a S}} normally returns a
  4019. single ``principal'' solution. If it needs to come up with an
  4020. arbitrary sign (as occurs in the quadratic formula) it picks @expr{+}.
  4021. If it needs an arbitrary integer, it picks zero. We can get a full
  4022. solution by pressing @kbd{H} (the Hyperbolic flag) before @kbd{a S}.
  4023. @smallexample
  4024. @group
  4025. 1: 0.70588 x^2 = 1 1: x = 1.19023 s1 1: x = -1.19023
  4026. . . .
  4027. r 3 H a S x @key{RET} s 5 1 n s l s1 @key{RET}
  4028. @end group
  4029. @end smallexample
  4030. @noindent
  4031. Calc has invented the variable @samp{s1} to represent an unknown sign;
  4032. it is supposed to be either @mathit{+1} or @mathit{-1}. Here we have used
  4033. the ``let'' command to evaluate the expression when the sign is negative.
  4034. If we plugged this into our second derivative we would get the same,
  4035. negative, answer, so @expr{x = -1.19023} is also a maximum.
  4036. To find the actual maximum value, we must plug our two values of @expr{x}
  4037. into the original formula.
  4038. @smallexample
  4039. @group
  4040. 2: 17 x^2 - 6 x^4 + 3 1: 24.08333 s1^2 - 12.04166 s1^4 + 3
  4041. 1: x = 1.19023 s1 .
  4042. .
  4043. r 1 r 5 s l @key{RET}
  4044. @end group
  4045. @end smallexample
  4046. @noindent
  4047. (Here we see another way to use @kbd{s l}; if its input is an equation
  4048. with a variable on the lefthand side, then @kbd{s l} treats the equation
  4049. like an assignment to that variable if you don't give a variable name.)
  4050. It's clear that this will have the same value for either sign of
  4051. @code{s1}, but let's work it out anyway, just for the exercise:
  4052. @smallexample
  4053. @group
  4054. 2: [-1, 1] 1: [15.04166, 15.04166]
  4055. 1: 24.08333 s1^2 ... .
  4056. .
  4057. [ 1 n , 1 ] @key{TAB} V M $ @key{RET}
  4058. @end group
  4059. @end smallexample
  4060. @noindent
  4061. Here we have used a vector mapping operation to evaluate the function
  4062. at several values of @samp{s1} at once. @kbd{V M $} is like @kbd{V M '}
  4063. except that it takes the formula from the top of the stack. The
  4064. formula is interpreted as a function to apply across the vector at the
  4065. next-to-top stack level. Since a formula on the stack can't contain
  4066. @samp{$} signs, Calc assumes the variables in the formula stand for
  4067. different arguments. It prompts you for an @dfn{argument list}, giving
  4068. the list of all variables in the formula in alphabetical order as the
  4069. default list. In this case the default is @samp{(s1)}, which is just
  4070. what we want so we simply press @key{RET} at the prompt.
  4071. If there had been several different values, we could have used
  4072. @w{@kbd{V R X}} to find the global maximum.
  4073. Calc has a built-in @kbd{a P} command that solves an equation using
  4074. @w{@kbd{H a S}} and returns a vector of all the solutions. It simply
  4075. automates the job we just did by hand. Applied to our original
  4076. cubic polynomial, it would produce the vector of solutions
  4077. @expr{[1.19023, -1.19023, 0]}. (There is also an @kbd{a X} command
  4078. which finds a local maximum of a function. It uses a numerical search
  4079. method rather than examining the derivatives, and thus requires you
  4080. to provide some kind of initial guess to show it where to look.)
  4081. (@bullet{}) @strong{Exercise 2.} Given a vector of the roots of a
  4082. polynomial (such as the output of an @kbd{a P} command), what
  4083. sequence of commands would you use to reconstruct the original
  4084. polynomial? (The answer will be unique to within a constant
  4085. multiple; choose the solution where the leading coefficient is one.)
  4086. @xref{Algebra Answer 2, 2}. (@bullet{})
  4087. The @kbd{m s} command enables Symbolic mode, in which formulas
  4088. like @samp{sqrt(5)} that can't be evaluated exactly are left in
  4089. symbolic form rather than giving a floating-point approximate answer.
  4090. Fraction mode (@kbd{m f}) is also useful when doing algebra.
  4091. @smallexample
  4092. @group
  4093. 2: 34 x - 24 x^3 2: 34 x - 24 x^3
  4094. 1: 34 x - 24 x^3 1: [sqrt(51) / 6, sqrt(51) / -6, 0]
  4095. . .
  4096. r 2 @key{RET} m s m f a P x @key{RET}
  4097. @end group
  4098. @end smallexample
  4099. One more mode that makes reading formulas easier is Big mode.
  4100. @smallexample
  4101. @group
  4102. 3
  4103. 2: 34 x - 24 x
  4104. ____ ____
  4105. V 51 V 51
  4106. 1: [-----, -----, 0]
  4107. 6 -6
  4108. .
  4109. d B
  4110. @end group
  4111. @end smallexample
  4112. Here things like powers, square roots, and quotients and fractions
  4113. are displayed in a two-dimensional pictorial form. Calc has other
  4114. language modes as well, such as C mode, FORTRAN mode, @TeX{} mode
  4115. and @LaTeX{} mode.
  4116. @smallexample
  4117. @group
  4118. 2: 34*x - 24*pow(x, 3) 2: 34*x - 24*x**3
  4119. 1: @{sqrt(51) / 6, sqrt(51) / -6, 0@} 1: /sqrt(51) / 6, sqrt(51) / -6, 0/
  4120. . .
  4121. d C d F
  4122. @end group
  4123. @end smallexample
  4124. @noindent
  4125. @smallexample
  4126. @group
  4127. 3: 34 x - 24 x^3
  4128. 2: [@{\sqrt@{51@} \over 6@}, @{\sqrt@{51@} \over -6@}, 0]
  4129. 1: @{2 \over 3@} \sqrt@{5@}
  4130. .
  4131. d T ' 2 \sqrt@{5@} \over 3 @key{RET}
  4132. @end group
  4133. @end smallexample
  4134. @noindent
  4135. As you can see, language modes affect both entry and display of
  4136. formulas. They affect such things as the names used for built-in
  4137. functions, the set of arithmetic operators and their precedences,
  4138. and notations for vectors and matrices.
  4139. Notice that @samp{sqrt(51)} may cause problems with older
  4140. implementations of C and FORTRAN, which would require something more
  4141. like @samp{sqrt(51.0)}. It is always wise to check over the formulas
  4142. produced by the various language modes to make sure they are fully
  4143. correct.
  4144. Type @kbd{m s}, @kbd{m f}, and @kbd{d N} to reset these modes. (You
  4145. may prefer to remain in Big mode, but all the examples in the tutorial
  4146. are shown in normal mode.)
  4147. @cindex Area under a curve
  4148. What is the area under the portion of this curve from @expr{x = 1} to @expr{2}?
  4149. This is simply the integral of the function:
  4150. @smallexample
  4151. @group
  4152. 1: 17 x^2 - 6 x^4 + 3 1: 5.6666 x^3 - 1.2 x^5 + 3 x
  4153. . .
  4154. r 1 a i x
  4155. @end group
  4156. @end smallexample
  4157. @noindent
  4158. We want to evaluate this at our two values for @expr{x} and subtract.
  4159. One way to do it is again with vector mapping and reduction:
  4160. @smallexample
  4161. @group
  4162. 2: [2, 1] 1: [12.93333, 7.46666] 1: 5.46666
  4163. 1: 5.6666 x^3 ... . .
  4164. [ 2 , 1 ] @key{TAB} V M $ @key{RET} V R -
  4165. @end group
  4166. @end smallexample
  4167. (@bullet{}) @strong{Exercise 3.} Find the integral from 1 to @expr{y}
  4168. of
  4169. @texline @math{x \sin \pi x}
  4170. @infoline @w{@expr{x sin(pi x)}}
  4171. (where the sine is calculated in radians). Find the values of the
  4172. integral for integers @expr{y} from 1 to 5. @xref{Algebra Answer 3,
  4173. 3}. (@bullet{})
  4174. Calc's integrator can do many simple integrals symbolically, but many
  4175. others are beyond its capabilities. Suppose we wish to find the area
  4176. under the curve
  4177. @texline @math{\sin x \ln x}
  4178. @infoline @expr{sin(x) ln(x)}
  4179. over the same range of @expr{x}. If you entered this formula and typed
  4180. @kbd{a i x @key{RET}} (don't bother to try this), Calc would work for a
  4181. long time but would be unable to find a solution. In fact, there is no
  4182. closed-form solution to this integral. Now what do we do?
  4183. @cindex Integration, numerical
  4184. @cindex Numerical integration
  4185. One approach would be to do the integral numerically. It is not hard
  4186. to do this by hand using vector mapping and reduction. It is rather
  4187. slow, though, since the sine and logarithm functions take a long time.
  4188. We can save some time by reducing the working precision.
  4189. @smallexample
  4190. @group
  4191. 3: 10 1: [1, 1.1, 1.2, ... , 1.8, 1.9]
  4192. 2: 1 .
  4193. 1: 0.1
  4194. .
  4195. 10 @key{RET} 1 @key{RET} .1 @key{RET} C-u v x
  4196. @end group
  4197. @end smallexample
  4198. @noindent
  4199. (Note that we have used the extended version of @kbd{v x}; we could
  4200. also have used plain @kbd{v x} as follows: @kbd{v x 10 @key{RET} 9 + .1 *}.)
  4201. @smallexample
  4202. @group
  4203. 2: [1, 1.1, ... ] 1: [0., 0.084941, 0.16993, ... ]
  4204. 1: ln(x) sin(x) .
  4205. .
  4206. ' sin(x) ln(x) @key{RET} s 1 m r p 5 @key{RET} V M $ @key{RET}
  4207. @end group
  4208. @end smallexample
  4209. @noindent
  4210. @smallexample
  4211. @group
  4212. 1: 3.4195 0.34195
  4213. . .
  4214. V R + 0.1 *
  4215. @end group
  4216. @end smallexample
  4217. @noindent
  4218. (If you got wildly different results, did you remember to switch
  4219. to Radians mode?)
  4220. Here we have divided the curve into ten segments of equal width;
  4221. approximating these segments as rectangular boxes (i.e., assuming
  4222. the curve is nearly flat at that resolution), we compute the areas
  4223. of the boxes (height times width), then sum the areas. (It is
  4224. faster to sum first, then multiply by the width, since the width
  4225. is the same for every box.)
  4226. The true value of this integral turns out to be about 0.374, so
  4227. we're not doing too well. Let's try another approach.
  4228. @smallexample
  4229. @group
  4230. 1: ln(x) sin(x) 1: 0.84147 x + 0.11957 (x - 1)^2 - ...
  4231. . .
  4232. r 1 a t x=1 @key{RET} 4 @key{RET}
  4233. @end group
  4234. @end smallexample
  4235. @noindent
  4236. Here we have computed the Taylor series expansion of the function
  4237. about the point @expr{x=1}. We can now integrate this polynomial
  4238. approximation, since polynomials are easy to integrate.
  4239. @smallexample
  4240. @group
  4241. 1: 0.42074 x^2 + ... 1: [-0.0446, -0.42073] 1: 0.3761
  4242. . . .
  4243. a i x @key{RET} [ 2 , 1 ] @key{TAB} V M $ @key{RET} V R -
  4244. @end group
  4245. @end smallexample
  4246. @noindent
  4247. Better! By increasing the precision and/or asking for more terms
  4248. in the Taylor series, we can get a result as accurate as we like.
  4249. (Taylor series converge better away from singularities in the
  4250. function such as the one at @code{ln(0)}, so it would also help to
  4251. expand the series about the points @expr{x=2} or @expr{x=1.5} instead
  4252. of @expr{x=1}.)
  4253. @cindex Simpson's rule
  4254. @cindex Integration by Simpson's rule
  4255. (@bullet{}) @strong{Exercise 4.} Our first method approximated the
  4256. curve by stairsteps of width 0.1; the total area was then the sum
  4257. of the areas of the rectangles under these stairsteps. Our second
  4258. method approximated the function by a polynomial, which turned out
  4259. to be a better approximation than stairsteps. A third method is
  4260. @dfn{Simpson's rule}, which is like the stairstep method except
  4261. that the steps are not required to be flat. Simpson's rule boils
  4262. down to the formula,
  4263. @ifnottex
  4264. @example
  4265. (h/3) * (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + ...
  4266. + 2 f(a+(n-2)*h) + 4 f(a+(n-1)*h) + f(a+n*h))
  4267. @end example
  4268. @end ifnottex
  4269. @tex
  4270. \beforedisplay
  4271. $$ \displaylines{
  4272. \qquad {h \over 3} (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + \cdots
  4273. \hfill \cr \hfill {} + 2 f(a+(n-2)h) + 4 f(a+(n-1)h) + f(a+n h)) \qquad
  4274. } $$
  4275. \afterdisplay
  4276. @end tex
  4277. @noindent
  4278. where @expr{n} (which must be even) is the number of slices and @expr{h}
  4279. is the width of each slice. These are 10 and 0.1 in our example.
  4280. For reference, here is the corresponding formula for the stairstep
  4281. method:
  4282. @ifnottex
  4283. @example
  4284. h * (f(a) + f(a+h) + f(a+2h) + f(a+3h) + ...
  4285. + f(a+(n-2)*h) + f(a+(n-1)*h))
  4286. @end example
  4287. @end ifnottex
  4288. @tex
  4289. \beforedisplay
  4290. $$ h (f(a) + f(a+h) + f(a+2h) + f(a+3h) + \cdots
  4291. + f(a+(n-2)h) + f(a+(n-1)h)) $$
  4292. \afterdisplay
  4293. @end tex
  4294. Compute the integral from 1 to 2 of
  4295. @texline @math{\sin x \ln x}
  4296. @infoline @expr{sin(x) ln(x)}
  4297. using Simpson's rule with 10 slices.
  4298. @xref{Algebra Answer 4, 4}. (@bullet{})
  4299. Calc has a built-in @kbd{a I} command for doing numerical integration.
  4300. It uses @dfn{Romberg's method}, which is a more sophisticated cousin
  4301. of Simpson's rule. In particular, it knows how to keep refining the
  4302. result until the current precision is satisfied.
  4303. @c [fix-ref Selecting Sub-Formulas]
  4304. Aside from the commands we've seen so far, Calc also provides a
  4305. large set of commands for operating on parts of formulas. You
  4306. indicate the desired sub-formula by placing the cursor on any part
  4307. of the formula before giving a @dfn{selection} command. Selections won't
  4308. be covered in the tutorial; @pxref{Selecting Subformulas}, for
  4309. details and examples.
  4310. @c hard exercise: simplify (2^(n r) - 2^(r*(n - 1))) / (2^r - 1) 2^(n - 1)
  4311. @c to 2^((n-1)*(r-1)).
  4312. @node Rewrites Tutorial, , Basic Algebra Tutorial, Algebra Tutorial
  4313. @subsection Rewrite Rules
  4314. @noindent
  4315. No matter how many built-in commands Calc provided for doing algebra,
  4316. there would always be something you wanted to do that Calc didn't have
  4317. in its repertoire. So Calc also provides a @dfn{rewrite rule} system
  4318. that you can use to define your own algebraic manipulations.
  4319. Suppose we want to simplify this trigonometric formula:
  4320. @smallexample
  4321. @group
  4322. 1: 2 sec(x)^2 / tan(x)^2 - 2 / tan(x)^2
  4323. .
  4324. ' 2sec(x)^2/tan(x)^2 - 2/tan(x)^2 @key{RET} s 1
  4325. @end group
  4326. @end smallexample
  4327. @noindent
  4328. If we were simplifying this by hand, we'd probably combine over the common
  4329. denominator. The @kbd{a n} algebra command will do this, but we'll do
  4330. it with a rewrite rule just for practice.
  4331. Rewrite rules are written with the @samp{:=} symbol.
  4332. @smallexample
  4333. @group
  4334. 1: (2 sec(x)^2 - 2) / tan(x)^2
  4335. .
  4336. a r a/x + b/x := (a+b)/x @key{RET}
  4337. @end group
  4338. @end smallexample
  4339. @noindent
  4340. (The ``assignment operator'' @samp{:=} has several uses in Calc. All
  4341. by itself the formula @samp{a/x + b/x := (a+b)/x} doesn't do anything,
  4342. but when it is given to the @kbd{a r} command, that command interprets
  4343. it as a rewrite rule.)
  4344. The lefthand side, @samp{a/x + b/x}, is called the @dfn{pattern} of the
  4345. rewrite rule. Calc searches the formula on the stack for parts that
  4346. match the pattern. Variables in a rewrite pattern are called
  4347. @dfn{meta-variables}, and when matching the pattern each meta-variable
  4348. can match any sub-formula. Here, the meta-variable @samp{a} matched
  4349. the expression @samp{2 sec(x)^2}, the meta-variable @samp{b} matched
  4350. the constant @samp{-2} and the meta-variable @samp{x} matched
  4351. the expression @samp{tan(x)^2}.
  4352. This rule points out several interesting features of rewrite patterns.
  4353. First, if a meta-variable appears several times in a pattern, it must
  4354. match the same thing everywhere. This rule detects common denominators
  4355. because the same meta-variable @samp{x} is used in both of the
  4356. denominators.
  4357. Second, meta-variable names are independent from variables in the
  4358. target formula. Notice that the meta-variable @samp{x} here matches
  4359. the subformula @samp{tan(x)^2}; Calc never confuses the two meanings of
  4360. @samp{x}.
  4361. And third, rewrite patterns know a little bit about the algebraic
  4362. properties of formulas. The pattern called for a sum of two quotients;
  4363. Calc was able to match a difference of two quotients by matching
  4364. @samp{a = 2 sec(x)^2}, @samp{b = -2}, and @samp{x = tan(x)^2}.
  4365. When the pattern part of a rewrite rule matches a part of the formula,
  4366. that part is replaced by the righthand side with all the meta-variables
  4367. substituted with the things they matched. So the result is
  4368. @samp{(2 sec(x)^2 - 2) / tan(x)^2}.
  4369. @c [fix-ref Algebraic Properties of Rewrite Rules]
  4370. We could just as easily have written @samp{a/x - b/x := (a-b)/x} for
  4371. the rule. It would have worked just the same in all cases. (If we
  4372. really wanted the rule to apply only to @samp{+} or only to @samp{-},
  4373. we could have used the @code{plain} symbol. @xref{Algebraic Properties
  4374. of Rewrite Rules}, for some examples of this.)
  4375. One more rewrite will complete the job. We want to use the identity
  4376. @samp{tan(x)^2 + 1 = sec(x)^2}, but of course we must first rearrange
  4377. the identity in a way that matches our formula. The obvious rule
  4378. would be @samp{@w{2 sec(x)^2 - 2} := 2 tan(x)^2}, but a little thought shows
  4379. that the rule @samp{sec(x)^2 := 1 + tan(x)^2} will also work. The
  4380. latter rule has a more general pattern so it will work in many other
  4381. situations, too.
  4382. @smallexample
  4383. @group
  4384. 1: 2
  4385. .
  4386. a r sec(x)^2 := 1 + tan(x)^2 @key{RET}
  4387. @end group
  4388. @end smallexample
  4389. You may ask, what's the point of using the most general rule if you
  4390. have to type it in every time anyway? The answer is that Calc allows
  4391. you to store a rewrite rule in a variable, then give the variable
  4392. name in the @kbd{a r} command. In fact, this is the preferred way to
  4393. use rewrites. For one, if you need a rule once you'll most likely
  4394. need it again later. Also, if the rule doesn't work quite right you
  4395. can simply Undo, edit the variable, and run the rule again without
  4396. having to retype it.
  4397. @smallexample
  4398. @group
  4399. ' a/x + b/x := (a+b)/x @key{RET} s t merge @key{RET}
  4400. ' sec(x)^2 := 1 + tan(x)^2 @key{RET} s t secsqr @key{RET}
  4401. 1: 2 sec(x)^2 / tan(x)^2 - 2 / tan(x)^2 1: 2
  4402. . .
  4403. r 1 a r merge @key{RET} a r secsqr @key{RET}
  4404. @end group
  4405. @end smallexample
  4406. To edit a variable, type @kbd{s e} and the variable name, use regular
  4407. Emacs editing commands as necessary, then type @kbd{C-c C-c} to store
  4408. the edited value back into the variable.
  4409. You can also use @w{@kbd{s e}} to create a new variable if you wish.
  4410. Notice that the first time you use each rule, Calc puts up a ``compiling''
  4411. message briefly. The pattern matcher converts rules into a special
  4412. optimized pattern-matching language rather than using them directly.
  4413. This allows @kbd{a r} to apply even rather complicated rules very
  4414. efficiently. If the rule is stored in a variable, Calc compiles it
  4415. only once and stores the compiled form along with the variable. That's
  4416. another good reason to store your rules in variables rather than
  4417. entering them on the fly.
  4418. (@bullet{}) @strong{Exercise 1.} Type @kbd{m s} to get Symbolic
  4419. mode, then enter the formula @samp{@w{(2 + sqrt(2))} / @w{(1 + sqrt(2))}}.
  4420. Using a rewrite rule, simplify this formula by multiplying the top and
  4421. bottom by the conjugate @w{@samp{1 - sqrt(2)}}. The result will have
  4422. to be expanded by the distributive law; do this with another
  4423. rewrite. @xref{Rewrites Answer 1, 1}. (@bullet{})
  4424. The @kbd{a r} command can also accept a vector of rewrite rules, or
  4425. a variable containing a vector of rules.
  4426. @smallexample
  4427. @group
  4428. 1: [merge, secsqr] 1: [a/x + b/x := (a + b)/x, ... ]
  4429. . .
  4430. ' [merge,sinsqr] @key{RET} =
  4431. @end group
  4432. @end smallexample
  4433. @noindent
  4434. @smallexample
  4435. @group
  4436. 1: 2 sec(x)^2 / tan(x)^2 - 2 / tan(x)^2 1: 2
  4437. . .
  4438. s t trig @key{RET} r 1 a r trig @key{RET}
  4439. @end group
  4440. @end smallexample
  4441. @c [fix-ref Nested Formulas with Rewrite Rules]
  4442. Calc tries all the rules you give against all parts of the formula,
  4443. repeating until no further change is possible. (The exact order in
  4444. which things are tried is rather complex, but for simple rules like
  4445. the ones we've used here the order doesn't really matter.
  4446. @xref{Nested Formulas with Rewrite Rules}.)
  4447. Calc actually repeats only up to 100 times, just in case your rule set
  4448. has gotten into an infinite loop. You can give a numeric prefix argument
  4449. to @kbd{a r} to specify any limit. In particular, @kbd{M-1 a r} does
  4450. only one rewrite at a time.
  4451. @smallexample
  4452. @group
  4453. 1: (2 sec(x)^2 - 2) / tan(x)^2 1: 2
  4454. . .
  4455. r 1 M-1 a r trig @key{RET} M-1 a r trig @key{RET}
  4456. @end group
  4457. @end smallexample
  4458. You can type @kbd{M-0 a r} if you want no limit at all on the number
  4459. of rewrites that occur.
  4460. Rewrite rules can also be @dfn{conditional}. Simply follow the rule
  4461. with a @samp{::} symbol and the desired condition. For example,
  4462. @smallexample
  4463. @group
  4464. 1: sin(x + 2 pi) + sin(x + 3 pi) + sin(x + 4 pi)
  4465. .
  4466. ' sin(x+2pi) + sin(x+3pi) + sin(x+4pi) @key{RET}
  4467. @end group
  4468. @end smallexample
  4469. @noindent
  4470. @smallexample
  4471. @group
  4472. 1: sin(x + 3 pi) + 2 sin(x)
  4473. .
  4474. a r sin(a + k pi) := sin(a) :: k % 2 = 0 @key{RET}
  4475. @end group
  4476. @end smallexample
  4477. @noindent
  4478. (Recall, @samp{k % 2} is the remainder from dividing @samp{k} by 2,
  4479. which will be zero only when @samp{k} is an even integer.)
  4480. An interesting point is that the variable @samp{pi} was matched
  4481. literally rather than acting as a meta-variable.
  4482. This is because it is a special-constant variable. The special
  4483. constants @samp{e}, @samp{i}, @samp{phi}, and so on also match literally.
  4484. A common error with rewrite
  4485. rules is to write, say, @samp{f(a,b,c,d,e) := g(a+b+c+d+e)}, expecting
  4486. to match any @samp{f} with five arguments but in fact matching
  4487. only when the fifth argument is literally @samp{e}!
  4488. @cindex Fibonacci numbers
  4489. @ignore
  4490. @starindex
  4491. @end ignore
  4492. @tindex fib
  4493. Rewrite rules provide an interesting way to define your own functions.
  4494. Suppose we want to define @samp{fib(n)} to produce the @var{n}th
  4495. Fibonacci number. The first two Fibonacci numbers are each 1;
  4496. later numbers are formed by summing the two preceding numbers in
  4497. the sequence. This is easy to express in a set of three rules:
  4498. @smallexample
  4499. @group
  4500. ' [fib(1) := 1, fib(2) := 1, fib(n) := fib(n-1) + fib(n-2)] @key{RET} s t fib
  4501. 1: fib(7) 1: 13
  4502. . .
  4503. ' fib(7) @key{RET} a r fib @key{RET}
  4504. @end group
  4505. @end smallexample
  4506. One thing that is guaranteed about the order that rewrites are tried
  4507. is that, for any given subformula, earlier rules in the rule set will
  4508. be tried for that subformula before later ones. So even though the
  4509. first and third rules both match @samp{fib(1)}, we know the first will
  4510. be used preferentially.
  4511. This rule set has one dangerous bug: Suppose we apply it to the
  4512. formula @samp{fib(x)}? (Don't actually try this.) The third rule
  4513. will match @samp{fib(x)} and replace it with @w{@samp{fib(x-1) + fib(x-2)}}.
  4514. Each of these will then be replaced to get @samp{fib(x-2) + 2 fib(x-3) +
  4515. fib(x-4)}, and so on, expanding forever. What we really want is to apply
  4516. the third rule only when @samp{n} is an integer greater than two. Type
  4517. @w{@kbd{s e fib @key{RET}}}, then edit the third rule to:
  4518. @smallexample
  4519. fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2
  4520. @end smallexample
  4521. @noindent
  4522. Now:
  4523. @smallexample
  4524. @group
  4525. 1: fib(6) + fib(x) + fib(0) 1: fib(x) + fib(0) + 8
  4526. . .
  4527. ' fib(6)+fib(x)+fib(0) @key{RET} a r fib @key{RET}
  4528. @end group
  4529. @end smallexample
  4530. @noindent
  4531. We've created a new function, @code{fib}, and a new command,
  4532. @w{@kbd{a r fib @key{RET}}}, which means ``evaluate all @code{fib} calls in
  4533. this formula.'' To make things easier still, we can tell Calc to
  4534. apply these rules automatically by storing them in the special
  4535. variable @code{EvalRules}.
  4536. @smallexample
  4537. @group
  4538. 1: [fib(1) := ...] . 1: [8, 13]
  4539. . .
  4540. s r fib @key{RET} s t EvalRules @key{RET} ' [fib(6), fib(7)] @key{RET}
  4541. @end group
  4542. @end smallexample
  4543. It turns out that this rule set has the problem that it does far
  4544. more work than it needs to when @samp{n} is large. Consider the
  4545. first few steps of the computation of @samp{fib(6)}:
  4546. @smallexample
  4547. @group
  4548. fib(6) =
  4549. fib(5) + fib(4) =
  4550. fib(4) + fib(3) + fib(3) + fib(2) =
  4551. fib(3) + fib(2) + fib(2) + fib(1) + fib(2) + fib(1) + 1 = ...
  4552. @end group
  4553. @end smallexample
  4554. @noindent
  4555. Note that @samp{fib(3)} appears three times here. Unless Calc's
  4556. algebraic simplifier notices the multiple @samp{fib(3)}s and combines
  4557. them (and, as it happens, it doesn't), this rule set does lots of
  4558. needless recomputation. To cure the problem, type @code{s e EvalRules}
  4559. to edit the rules (or just @kbd{s E}, a shorthand command for editing
  4560. @code{EvalRules}) and add another condition:
  4561. @smallexample
  4562. fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2 :: remember
  4563. @end smallexample
  4564. @noindent
  4565. If a @samp{:: remember} condition appears anywhere in a rule, then if
  4566. that rule succeeds Calc will add another rule that describes that match
  4567. to the front of the rule set. (Remembering works in any rule set, but
  4568. for technical reasons it is most effective in @code{EvalRules}.) For
  4569. example, if the rule rewrites @samp{fib(7)} to something that evaluates
  4570. to 13, then the rule @samp{fib(7) := 13} will be added to the rule set.
  4571. Type @kbd{' fib(8) @key{RET}} to compute the eighth Fibonacci number, then
  4572. type @kbd{s E} again to see what has happened to the rule set.
  4573. With the @code{remember} feature, our rule set can now compute
  4574. @samp{fib(@var{n})} in just @var{n} steps. In the process it builds
  4575. up a table of all Fibonacci numbers up to @var{n}. After we have
  4576. computed the result for a particular @var{n}, we can get it back
  4577. (and the results for all smaller @var{n}) later in just one step.
  4578. All Calc operations will run somewhat slower whenever @code{EvalRules}
  4579. contains any rules. You should type @kbd{s u EvalRules @key{RET}} now to
  4580. un-store the variable.
  4581. (@bullet{}) @strong{Exercise 2.} Sometimes it is possible to reformulate
  4582. a problem to reduce the amount of recursion necessary to solve it.
  4583. Create a rule that, in about @var{n} simple steps and without recourse
  4584. to the @code{remember} option, replaces @samp{fib(@var{n}, 1, 1)} with
  4585. @samp{fib(1, @var{x}, @var{y})} where @var{x} and @var{y} are the
  4586. @var{n}th and @var{n+1}st Fibonacci numbers, respectively. This rule is
  4587. rather clunky to use, so add a couple more rules to make the ``user
  4588. interface'' the same as for our first version: enter @samp{fib(@var{n})},
  4589. get back a plain number. @xref{Rewrites Answer 2, 2}. (@bullet{})
  4590. There are many more things that rewrites can do. For example, there
  4591. are @samp{&&&} and @samp{|||} pattern operators that create ``and''
  4592. and ``or'' combinations of rules. As one really simple example, we
  4593. could combine our first two Fibonacci rules thusly:
  4594. @example
  4595. [fib(1 ||| 2) := 1, fib(n) := ... ]
  4596. @end example
  4597. @noindent
  4598. That means ``@code{fib} of something matching either 1 or 2 rewrites
  4599. to 1.''
  4600. You can also make meta-variables optional by enclosing them in @code{opt}.
  4601. For example, the pattern @samp{a + b x} matches @samp{2 + 3 x} but not
  4602. @samp{2 + x} or @samp{3 x} or @samp{x}. The pattern @samp{opt(a) + opt(b) x}
  4603. matches all of these forms, filling in a default of zero for @samp{a}
  4604. and one for @samp{b}.
  4605. (@bullet{}) @strong{Exercise 3.} Your friend Joe had @samp{2 + 3 x}
  4606. on the stack and tried to use the rule
  4607. @samp{opt(a) + opt(b) x := f(a, b, x)}. What happened?
  4608. @xref{Rewrites Answer 3, 3}. (@bullet{})
  4609. (@bullet{}) @strong{Exercise 4.} Starting with a positive integer @expr{a},
  4610. divide @expr{a} by two if it is even, otherwise compute @expr{3 a + 1}.
  4611. Now repeat this step over and over. A famous unproved conjecture
  4612. is that for any starting @expr{a}, the sequence always eventually
  4613. reaches 1. Given the formula @samp{seq(@var{a}, 0)}, write a set of
  4614. rules that convert this into @samp{seq(1, @var{n})} where @var{n}
  4615. is the number of steps it took the sequence to reach the value 1.
  4616. Now enhance the rules to accept @samp{seq(@var{a})} as a starting
  4617. configuration, and to stop with just the number @var{n} by itself.
  4618. Now make the result be a vector of values in the sequence, from @var{a}
  4619. to 1. (The formula @samp{@var{x}|@var{y}} appends the vectors @var{x}
  4620. and @var{y}.) For example, rewriting @samp{seq(6)} should yield the
  4621. vector @expr{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
  4622. @xref{Rewrites Answer 4, 4}. (@bullet{})
  4623. (@bullet{}) @strong{Exercise 5.} Define, using rewrite rules, a function
  4624. @samp{nterms(@var{x})} that returns the number of terms in the sum
  4625. @var{x}, or 1 if @var{x} is not a sum. (A @dfn{sum} for our purposes
  4626. is one or more non-sum terms separated by @samp{+} or @samp{-} signs,
  4627. so that @expr{2 - 3 (x + y) + x y} is a sum of three terms.)
  4628. @xref{Rewrites Answer 5, 5}. (@bullet{})
  4629. (@bullet{}) @strong{Exercise 6.} A Taylor series for a function is an
  4630. infinite series that exactly equals the value of that function at
  4631. values of @expr{x} near zero.
  4632. @ifnottex
  4633. @example
  4634. cos(x) = 1 - x^2 / 2! + x^4 / 4! - x^6 / 6! + ...
  4635. @end example
  4636. @end ifnottex
  4637. @tex
  4638. \beforedisplay
  4639. $$ \cos x = 1 - {x^2 \over 2!} + {x^4 \over 4!} - {x^6 \over 6!} + \cdots $$
  4640. \afterdisplay
  4641. @end tex
  4642. The @kbd{a t} command produces a @dfn{truncated Taylor series} which
  4643. is obtained by dropping all the terms higher than, say, @expr{x^2}.
  4644. Calc represents the truncated Taylor series as a polynomial in @expr{x}.
  4645. Mathematicians often write a truncated series using a ``big-O'' notation
  4646. that records what was the lowest term that was truncated.
  4647. @ifnottex
  4648. @example
  4649. cos(x) = 1 - x^2 / 2! + O(x^3)
  4650. @end example
  4651. @end ifnottex
  4652. @tex
  4653. \beforedisplay
  4654. $$ \cos x = 1 - {x^2 \over 2!} + O(x^3) $$
  4655. \afterdisplay
  4656. @end tex
  4657. @noindent
  4658. The meaning of @expr{O(x^3)} is ``a quantity which is negligibly small
  4659. if @expr{x^3} is considered negligibly small as @expr{x} goes to zero.''
  4660. The exercise is to create rewrite rules that simplify sums and products of
  4661. power series represented as @samp{@var{polynomial} + O(@var{var}^@var{n})}.
  4662. For example, given @samp{1 - x^2 / 2 + O(x^3)} and @samp{x - x^3 / 6 + O(x^4)}
  4663. on the stack, we want to be able to type @kbd{*} and get the result
  4664. @samp{x - 2:3 x^3 + O(x^4)}. Don't worry if the terms of the sum are
  4665. rearranged. (This one is rather tricky; the solution at the end of
  4666. this chapter uses 6 rewrite rules. Hint: The @samp{constant(x)}
  4667. condition tests whether @samp{x} is a number.) @xref{Rewrites Answer
  4668. 6, 6}. (@bullet{})
  4669. Just for kicks, try adding the rule @code{2+3 := 6} to @code{EvalRules}.
  4670. What happens? (Be sure to remove this rule afterward, or you might get
  4671. a nasty surprise when you use Calc to balance your checkbook!)
  4672. @xref{Rewrite Rules}, for the whole story on rewrite rules.
  4673. @node Programming Tutorial, Answers to Exercises, Algebra Tutorial, Tutorial
  4674. @section Programming Tutorial
  4675. @noindent
  4676. The Calculator is written entirely in Emacs Lisp, a highly extensible
  4677. language. If you know Lisp, you can program the Calculator to do
  4678. anything you like. Rewrite rules also work as a powerful programming
  4679. system. But Lisp and rewrite rules take a while to master, and often
  4680. all you want to do is define a new function or repeat a command a few
  4681. times. Calc has features that allow you to do these things easily.
  4682. One very limited form of programming is defining your own functions.
  4683. Calc's @kbd{Z F} command allows you to define a function name and
  4684. key sequence to correspond to any formula. Programming commands use
  4685. the shift-@kbd{Z} prefix; the user commands they create use the lower
  4686. case @kbd{z} prefix.
  4687. @smallexample
  4688. @group
  4689. 1: x + x^2 / 2 + x^3 / 6 + 1 1: x + x^2 / 2 + x^3 / 6 + 1
  4690. . .
  4691. ' 1 + x + x^2/2! + x^3/3! @key{RET} Z F e myexp @key{RET} @key{RET} @key{RET} y
  4692. @end group
  4693. @end smallexample
  4694. This polynomial is a Taylor series approximation to @samp{exp(x)}.
  4695. The @kbd{Z F} command asks a number of questions. The above answers
  4696. say that the key sequence for our function should be @kbd{z e}; the
  4697. @kbd{M-x} equivalent should be @code{calc-myexp}; the name of the
  4698. function in algebraic formulas should also be @code{myexp}; the
  4699. default argument list @samp{(x)} is acceptable; and finally @kbd{y}
  4700. answers the question ``leave it in symbolic form for non-constant
  4701. arguments?''
  4702. @smallexample
  4703. @group
  4704. 1: 1.3495 2: 1.3495 3: 1.3495
  4705. . 1: 1.34986 2: 1.34986
  4706. . 1: myexp(a + 1)
  4707. .
  4708. .3 z e .3 E ' a+1 @key{RET} z e
  4709. @end group
  4710. @end smallexample
  4711. @noindent
  4712. First we call our new @code{exp} approximation with 0.3 as an
  4713. argument, and compare it with the true @code{exp} function. Then
  4714. we note that, as requested, if we try to give @kbd{z e} an
  4715. argument that isn't a plain number, it leaves the @code{myexp}
  4716. function call in symbolic form. If we had answered @kbd{n} to the
  4717. final question, @samp{myexp(a + 1)} would have evaluated by plugging
  4718. in @samp{a + 1} for @samp{x} in the defining formula.
  4719. @cindex Sine integral Si(x)
  4720. @ignore
  4721. @starindex
  4722. @end ignore
  4723. @tindex Si
  4724. (@bullet{}) @strong{Exercise 1.} The ``sine integral'' function
  4725. @texline @math{{\rm Si}(x)}
  4726. @infoline @expr{Si(x)}
  4727. is defined as the integral of @samp{sin(t)/t} for
  4728. @expr{t = 0} to @expr{x} in radians. (It was invented because this
  4729. integral has no solution in terms of basic functions; if you give it
  4730. to Calc's @kbd{a i} command, it will ponder it for a long time and then
  4731. give up.) We can use the numerical integration command, however,
  4732. which in algebraic notation is written like @samp{ninteg(f(t), t, 0, x)}
  4733. with any integrand @samp{f(t)}. Define a @kbd{z s} command and
  4734. @code{Si} function that implement this. You will need to edit the
  4735. default argument list a bit. As a test, @samp{Si(1)} should return
  4736. 0.946083. (If you don't get this answer, you might want to check that
  4737. Calc is in Radians mode. Also, @code{ninteg} will run a lot faster if
  4738. you reduce the precision to, say, six digits beforehand.)
  4739. @xref{Programming Answer 1, 1}. (@bullet{})
  4740. The simplest way to do real ``programming'' of Emacs is to define a
  4741. @dfn{keyboard macro}. A keyboard macro is simply a sequence of
  4742. keystrokes which Emacs has stored away and can play back on demand.
  4743. For example, if you find yourself typing @kbd{H a S x @key{RET}} often,
  4744. you may wish to program a keyboard macro to type this for you.
  4745. @smallexample
  4746. @group
  4747. 1: y = sqrt(x) 1: x = y^2
  4748. . .
  4749. ' y=sqrt(x) @key{RET} C-x ( H a S x @key{RET} C-x )
  4750. 1: y = cos(x) 1: x = s1 arccos(y) + 2 n1 pi
  4751. . .
  4752. ' y=cos(x) @key{RET} X
  4753. @end group
  4754. @end smallexample
  4755. @noindent
  4756. When you type @kbd{C-x (}, Emacs begins recording. But it is also
  4757. still ready to execute your keystrokes, so you're really ``training''
  4758. Emacs by walking it through the procedure once. When you type
  4759. @w{@kbd{C-x )}}, the macro is recorded. You can now type @kbd{X} to
  4760. re-execute the same keystrokes.
  4761. You can give a name to your macro by typing @kbd{Z K}.
  4762. @smallexample
  4763. @group
  4764. 1: . 1: y = x^4 1: x = s2 sqrt(s1 sqrt(y))
  4765. . .
  4766. Z K x @key{RET} ' y=x^4 @key{RET} z x
  4767. @end group
  4768. @end smallexample
  4769. @noindent
  4770. Notice that we use shift-@kbd{Z} to define the command, and lower-case
  4771. @kbd{z} to call it up.
  4772. Keyboard macros can call other macros.
  4773. @smallexample
  4774. @group
  4775. 1: abs(x) 1: x = s1 y 1: 2 / x 1: x = 2 / y
  4776. . . . .
  4777. ' abs(x) @key{RET} C-x ( ' y @key{RET} a = z x C-x ) ' 2/x @key{RET} X
  4778. @end group
  4779. @end smallexample
  4780. (@bullet{}) @strong{Exercise 2.} Define a keyboard macro to negate
  4781. the item in level 3 of the stack, without disturbing the rest of
  4782. the stack. @xref{Programming Answer 2, 2}. (@bullet{})
  4783. (@bullet{}) @strong{Exercise 3.} Define keyboard macros to compute
  4784. the following functions:
  4785. @enumerate
  4786. @item
  4787. Compute
  4788. @texline @math{\displaystyle{\sin x \over x}},
  4789. @infoline @expr{sin(x) / x},
  4790. where @expr{x} is the number on the top of the stack.
  4791. @item
  4792. Compute the base-@expr{b} logarithm, just like the @kbd{B} key except
  4793. the arguments are taken in the opposite order.
  4794. @item
  4795. Produce a vector of integers from 1 to the integer on the top of
  4796. the stack.
  4797. @end enumerate
  4798. @noindent
  4799. @xref{Programming Answer 3, 3}. (@bullet{})
  4800. (@bullet{}) @strong{Exercise 4.} Define a keyboard macro to compute
  4801. the average (mean) value of a list of numbers.
  4802. @xref{Programming Answer 4, 4}. (@bullet{})
  4803. In many programs, some of the steps must execute several times.
  4804. Calc has @dfn{looping} commands that allow this. Loops are useful
  4805. inside keyboard macros, but actually work at any time.
  4806. @smallexample
  4807. @group
  4808. 1: x^6 2: x^6 1: 360 x^2
  4809. . 1: 4 .
  4810. .
  4811. ' x^6 @key{RET} 4 Z < a d x @key{RET} Z >
  4812. @end group
  4813. @end smallexample
  4814. @noindent
  4815. Here we have computed the fourth derivative of @expr{x^6} by
  4816. enclosing a derivative command in a ``repeat loop'' structure.
  4817. This structure pops a repeat count from the stack, then
  4818. executes the body of the loop that many times.
  4819. If you make a mistake while entering the body of the loop,
  4820. type @w{@kbd{Z C-g}} to cancel the loop command.
  4821. @cindex Fibonacci numbers
  4822. Here's another example:
  4823. @smallexample
  4824. @group
  4825. 3: 1 2: 10946
  4826. 2: 1 1: 17711
  4827. 1: 20 .
  4828. .
  4829. 1 @key{RET} @key{RET} 20 Z < @key{TAB} C-j + Z >
  4830. @end group
  4831. @end smallexample
  4832. @noindent
  4833. The numbers in levels 2 and 1 should be the 21st and 22nd Fibonacci
  4834. numbers, respectively. (To see what's going on, try a few repetitions
  4835. of the loop body by hand; @kbd{C-j}, also on the Line-Feed or @key{LFD}
  4836. key if you have one, makes a copy of the number in level 2.)
  4837. @cindex Golden ratio
  4838. @cindex Phi, golden ratio
  4839. A fascinating property of the Fibonacci numbers is that the @expr{n}th
  4840. Fibonacci number can be found directly by computing
  4841. @texline @math{\phi^n / \sqrt{5}}
  4842. @infoline @expr{phi^n / sqrt(5)}
  4843. and then rounding to the nearest integer, where
  4844. @texline @math{\phi} (``phi''),
  4845. @infoline @expr{phi},
  4846. the ``golden ratio,'' is
  4847. @texline @math{(1 + \sqrt{5}) / 2}.
  4848. @infoline @expr{(1 + sqrt(5)) / 2}.
  4849. (For convenience, this constant is available from the @code{phi}
  4850. variable, or the @kbd{I H P} command.)
  4851. @smallexample
  4852. @group
  4853. 1: 1.61803 1: 24476.0000409 1: 10945.9999817 1: 10946
  4854. . . . .
  4855. I H P 21 ^ 5 Q / R
  4856. @end group
  4857. @end smallexample
  4858. @cindex Continued fractions
  4859. (@bullet{}) @strong{Exercise 5.} The @dfn{continued fraction}
  4860. representation of
  4861. @texline @math{\phi}
  4862. @infoline @expr{phi}
  4863. is
  4864. @texline @math{1 + 1/(1 + 1/(1 + 1/( \ldots )))}.
  4865. @infoline @expr{1 + 1/(1 + 1/(1 + 1/( ...@: )))}.
  4866. We can compute an approximate value by carrying this however far
  4867. and then replacing the innermost
  4868. @texline @math{1/( \ldots )}
  4869. @infoline @expr{1/( ...@: )}
  4870. by 1. Approximate
  4871. @texline @math{\phi}
  4872. @infoline @expr{phi}
  4873. using a twenty-term continued fraction.
  4874. @xref{Programming Answer 5, 5}. (@bullet{})
  4875. (@bullet{}) @strong{Exercise 6.} Linear recurrences like the one for
  4876. Fibonacci numbers can be expressed in terms of matrices. Given a
  4877. vector @w{@expr{[a, b]}} determine a matrix which, when multiplied by this
  4878. vector, produces the vector @expr{[b, c]}, where @expr{a}, @expr{b} and
  4879. @expr{c} are three successive Fibonacci numbers. Now write a program
  4880. that, given an integer @expr{n}, computes the @expr{n}th Fibonacci number
  4881. using matrix arithmetic. @xref{Programming Answer 6, 6}. (@bullet{})
  4882. @cindex Harmonic numbers
  4883. A more sophisticated kind of loop is the @dfn{for} loop. Suppose
  4884. we wish to compute the 20th ``harmonic'' number, which is equal to
  4885. the sum of the reciprocals of the integers from 1 to 20.
  4886. @smallexample
  4887. @group
  4888. 3: 0 1: 3.597739
  4889. 2: 1 .
  4890. 1: 20
  4891. .
  4892. 0 @key{RET} 1 @key{RET} 20 Z ( & + 1 Z )
  4893. @end group
  4894. @end smallexample
  4895. @noindent
  4896. The ``for'' loop pops two numbers, the lower and upper limits, then
  4897. repeats the body of the loop as an internal counter increases from
  4898. the lower limit to the upper one. Just before executing the loop
  4899. body, it pushes the current loop counter. When the loop body
  4900. finishes, it pops the ``step,'' i.e., the amount by which to
  4901. increment the loop counter. As you can see, our loop always
  4902. uses a step of one.
  4903. This harmonic number function uses the stack to hold the running
  4904. total as well as for the various loop housekeeping functions. If
  4905. you find this disorienting, you can sum in a variable instead:
  4906. @smallexample
  4907. @group
  4908. 1: 0 2: 1 . 1: 3.597739
  4909. . 1: 20 .
  4910. .
  4911. 0 t 7 1 @key{RET} 20 Z ( & s + 7 1 Z ) r 7
  4912. @end group
  4913. @end smallexample
  4914. @noindent
  4915. The @kbd{s +} command adds the top-of-stack into the value in a
  4916. variable (and removes that value from the stack).
  4917. It's worth noting that many jobs that call for a ``for'' loop can
  4918. also be done more easily by Calc's high-level operations. Two
  4919. other ways to compute harmonic numbers are to use vector mapping
  4920. and reduction (@kbd{v x 20}, then @w{@kbd{V M &}}, then @kbd{V R +}),
  4921. or to use the summation command @kbd{a +}. Both of these are
  4922. probably easier than using loops. However, there are some
  4923. situations where loops really are the way to go:
  4924. (@bullet{}) @strong{Exercise 7.} Use a ``for'' loop to find the first
  4925. harmonic number which is greater than 4.0.
  4926. @xref{Programming Answer 7, 7}. (@bullet{})
  4927. Of course, if we're going to be using variables in our programs,
  4928. we have to worry about the programs clobbering values that the
  4929. caller was keeping in those same variables. This is easy to
  4930. fix, though:
  4931. @smallexample
  4932. @group
  4933. . 1: 0.6667 1: 0.6667 3: 0.6667
  4934. . . 2: 3.597739
  4935. 1: 0.6667
  4936. .
  4937. Z ` p 4 @key{RET} 2 @key{RET} 3 / s 7 s s a @key{RET} Z ' r 7 s r a @key{RET}
  4938. @end group
  4939. @end smallexample
  4940. @noindent
  4941. When we type @kbd{Z `} (that's a grave accent), Calc saves
  4942. its mode settings and the contents of the ten ``quick variables''
  4943. for later reference. When we type @kbd{Z '} (that's an apostrophe
  4944. now), Calc restores those saved values. Thus the @kbd{p 4} and
  4945. @kbd{s 7} commands have no effect outside this sequence. Wrapping
  4946. this around the body of a keyboard macro ensures that it doesn't
  4947. interfere with what the user of the macro was doing. Notice that
  4948. the contents of the stack, and the values of named variables,
  4949. survive past the @kbd{Z '} command.
  4950. @cindex Bernoulli numbers, approximate
  4951. The @dfn{Bernoulli numbers} are a sequence with the interesting
  4952. property that all of the odd Bernoulli numbers are zero, and the
  4953. even ones, while difficult to compute, can be roughly approximated
  4954. by the formula
  4955. @texline @math{\displaystyle{2 n! \over (2 \pi)^n}}.
  4956. @infoline @expr{2 n!@: / (2 pi)^n}.
  4957. Let's write a keyboard macro to compute (approximate) Bernoulli numbers.
  4958. (Calc has a command, @kbd{k b}, to compute exact Bernoulli numbers, but
  4959. this command is very slow for large @expr{n} since the higher Bernoulli
  4960. numbers are very large fractions.)
  4961. @smallexample
  4962. @group
  4963. 1: 10 1: 0.0756823
  4964. . .
  4965. 10 C-x ( @key{RET} 2 % Z [ @key{DEL} 0 Z : ' 2 $! / (2 pi)^$ @key{RET} = Z ] C-x )
  4966. @end group
  4967. @end smallexample
  4968. @noindent
  4969. You can read @kbd{Z [} as ``then,'' @kbd{Z :} as ``else,'' and
  4970. @kbd{Z ]} as ``end-if.'' There is no need for an explicit ``if''
  4971. command. For the purposes of @w{@kbd{Z [}}, the condition is ``true''
  4972. if the value it pops from the stack is a nonzero number, or ``false''
  4973. if it pops zero or something that is not a number (like a formula).
  4974. Here we take our integer argument modulo 2; this will be nonzero
  4975. if we're asking for an odd Bernoulli number.
  4976. The actual tenth Bernoulli number is @expr{5/66}.
  4977. @smallexample
  4978. @group
  4979. 3: 0.0756823 1: 0 1: 0.25305 1: 0 1: 1.16659
  4980. 2: 5:66 . . . .
  4981. 1: 0.0757575
  4982. .
  4983. 10 k b @key{RET} c f M-0 @key{DEL} 11 X @key{DEL} 12 X @key{DEL} 13 X @key{DEL} 14 X
  4984. @end group
  4985. @end smallexample
  4986. Just to exercise loops a bit more, let's compute a table of even
  4987. Bernoulli numbers.
  4988. @smallexample
  4989. @group
  4990. 3: [] 1: [0.10132, 0.03079, 0.02340, 0.033197, ...]
  4991. 2: 2 .
  4992. 1: 30
  4993. .
  4994. [ ] 2 @key{RET} 30 Z ( X | 2 Z )
  4995. @end group
  4996. @end smallexample
  4997. @noindent
  4998. The vertical-bar @kbd{|} is the vector-concatenation command. When
  4999. we execute it, the list we are building will be in stack level 2
  5000. (initially this is an empty list), and the next Bernoulli number
  5001. will be in level 1. The effect is to append the Bernoulli number
  5002. onto the end of the list. (To create a table of exact fractional
  5003. Bernoulli numbers, just replace @kbd{X} with @kbd{k b} in the above
  5004. sequence of keystrokes.)
  5005. With loops and conditionals, you can program essentially anything
  5006. in Calc. One other command that makes looping easier is @kbd{Z /},
  5007. which takes a condition from the stack and breaks out of the enclosing
  5008. loop if the condition is true (non-zero). You can use this to make
  5009. ``while'' and ``until'' style loops.
  5010. If you make a mistake when entering a keyboard macro, you can edit
  5011. it using @kbd{Z E}. First, you must attach it to a key with @kbd{Z K}.
  5012. One technique is to enter a throwaway dummy definition for the macro,
  5013. then enter the real one in the edit command.
  5014. @smallexample
  5015. @group
  5016. 1: 3 1: 3 Calc Macro Edit Mode.
  5017. . . Original keys: 1 <return> 2 +
  5018. 1 ;; calc digits
  5019. RET ;; calc-enter
  5020. 2 ;; calc digits
  5021. + ;; calc-plus
  5022. C-x ( 1 @key{RET} 2 + C-x ) Z K h @key{RET} Z E h
  5023. @end group
  5024. @end smallexample
  5025. @noindent
  5026. A keyboard macro is stored as a pure keystroke sequence. The
  5027. @file{edmacro} package (invoked by @kbd{Z E}) scans along the
  5028. macro and tries to decode it back into human-readable steps.
  5029. Descriptions of the keystrokes are given as comments, which begin with
  5030. @samp{;;}, and which are ignored when the edited macro is saved.
  5031. Spaces and line breaks are also ignored when the edited macro is saved.
  5032. To enter a space into the macro, type @code{SPC}. All the special
  5033. characters @code{RET}, @code{LFD}, @code{TAB}, @code{SPC}, @code{DEL},
  5034. and @code{NUL} must be written in all uppercase, as must the prefixes
  5035. @code{C-} and @code{M-}.
  5036. Let's edit in a new definition, for computing harmonic numbers.
  5037. First, erase the four lines of the old definition. Then, type
  5038. in the new definition (or use Emacs @kbd{M-w} and @kbd{C-y} commands
  5039. to copy it from this page of the Info file; you can of course skip
  5040. typing the comments, which begin with @samp{;;}).
  5041. @smallexample
  5042. Z` ;; calc-kbd-push (Save local values)
  5043. 0 ;; calc digits (Push a zero onto the stack)
  5044. st ;; calc-store-into (Store it in the following variable)
  5045. 1 ;; calc quick variable (Quick variable q1)
  5046. 1 ;; calc digits (Initial value for the loop)
  5047. TAB ;; calc-roll-down (Swap initial and final)
  5048. Z( ;; calc-kbd-for (Begin the "for" loop)
  5049. & ;; calc-inv (Take the reciprocal)
  5050. s+ ;; calc-store-plus (Add to the following variable)
  5051. 1 ;; calc quick variable (Quick variable q1)
  5052. 1 ;; calc digits (The loop step is 1)
  5053. Z) ;; calc-kbd-end-for (End the "for" loop)
  5054. sr ;; calc-recall (Recall the final accumulated value)
  5055. 1 ;; calc quick variable (Quick variable q1)
  5056. Z' ;; calc-kbd-pop (Restore values)
  5057. @end smallexample
  5058. @noindent
  5059. Press @kbd{C-c C-c} to finish editing and return to the Calculator.
  5060. @smallexample
  5061. @group
  5062. 1: 20 1: 3.597739
  5063. . .
  5064. 20 z h
  5065. @end group
  5066. @end smallexample
  5067. The @file{edmacro} package defines a handy @code{read-kbd-macro} command
  5068. which reads the current region of the current buffer as a sequence of
  5069. keystroke names, and defines that sequence on the @kbd{X}
  5070. (and @kbd{C-x e}) key. Because this is so useful, Calc puts this
  5071. command on the @kbd{C-x * m} key. Try reading in this macro in the
  5072. following form: Press @kbd{C-@@} (or @kbd{C-@key{SPC}}) at
  5073. one end of the text below, then type @kbd{C-x * m} at the other.
  5074. @example
  5075. @group
  5076. Z ` 0 t 1
  5077. 1 TAB
  5078. Z ( & s + 1 1 Z )
  5079. r 1
  5080. Z '
  5081. @end group
  5082. @end example
  5083. (@bullet{}) @strong{Exercise 8.} A general algorithm for solving
  5084. equations numerically is @dfn{Newton's Method}. Given the equation
  5085. @expr{f(x) = 0} for any function @expr{f}, and an initial guess
  5086. @expr{x_0} which is reasonably close to the desired solution, apply
  5087. this formula over and over:
  5088. @ifnottex
  5089. @example
  5090. new_x = x - f(x)/f'(x)
  5091. @end example
  5092. @end ifnottex
  5093. @tex
  5094. \beforedisplay
  5095. $$ x_{\rm new} = x - {f(x) \over f^{\prime}(x)} $$
  5096. \afterdisplay
  5097. @end tex
  5098. @noindent
  5099. where @expr{f'(x)} is the derivative of @expr{f}. The @expr{x}
  5100. values will quickly converge to a solution, i.e., eventually
  5101. @texline @math{x_{\rm new}}
  5102. @infoline @expr{new_x}
  5103. and @expr{x} will be equal to within the limits
  5104. of the current precision. Write a program which takes a formula
  5105. involving the variable @expr{x}, and an initial guess @expr{x_0},
  5106. on the stack, and produces a value of @expr{x} for which the formula
  5107. is zero. Use it to find a solution of
  5108. @texline @math{\sin(\cos x) = 0.5}
  5109. @infoline @expr{sin(cos(x)) = 0.5}
  5110. near @expr{x = 4.5}. (Use angles measured in radians.) Note that
  5111. the built-in @w{@kbd{a R}} (@code{calc-find-root}) command uses Newton's
  5112. method when it is able. @xref{Programming Answer 8, 8}. (@bullet{})
  5113. @cindex Digamma function
  5114. @cindex Gamma constant, Euler's
  5115. @cindex Euler's gamma constant
  5116. (@bullet{}) @strong{Exercise 9.} The @dfn{digamma} function
  5117. @texline @math{\psi(z) (``psi'')}
  5118. @infoline @expr{psi(z)}
  5119. is defined as the derivative of
  5120. @texline @math{\ln \Gamma(z)}.
  5121. @infoline @expr{ln(gamma(z))}.
  5122. For large values of @expr{z}, it can be approximated by the infinite sum
  5123. @ifnottex
  5124. @example
  5125. psi(z) ~= ln(z) - 1/2z - sum(bern(2 n) / 2 n z^(2 n), n, 1, inf)
  5126. @end example
  5127. @end ifnottex
  5128. @tex
  5129. \beforedisplay
  5130. $$ \psi(z) \approx \ln z - {1\over2z} -
  5131. \sum_{n=1}^\infty {\code{bern}(2 n) \over 2 n z^{2n}}
  5132. $$
  5133. \afterdisplay
  5134. @end tex
  5135. @noindent
  5136. where
  5137. @texline @math{\sum}
  5138. @infoline @expr{sum}
  5139. represents the sum over @expr{n} from 1 to infinity
  5140. (or to some limit high enough to give the desired accuracy), and
  5141. the @code{bern} function produces (exact) Bernoulli numbers.
  5142. While this sum is not guaranteed to converge, in practice it is safe.
  5143. An interesting mathematical constant is Euler's gamma, which is equal
  5144. to about 0.5772. One way to compute it is by the formula,
  5145. @texline @math{\gamma = -\psi(1)}.
  5146. @infoline @expr{gamma = -psi(1)}.
  5147. Unfortunately, 1 isn't a large enough argument
  5148. for the above formula to work (5 is a much safer value for @expr{z}).
  5149. Fortunately, we can compute
  5150. @texline @math{\psi(1)}
  5151. @infoline @expr{psi(1)}
  5152. from
  5153. @texline @math{\psi(5)}
  5154. @infoline @expr{psi(5)}
  5155. using the recurrence
  5156. @texline @math{\psi(z+1) = \psi(z) + {1 \over z}}.
  5157. @infoline @expr{psi(z+1) = psi(z) + 1/z}.
  5158. Your task: Develop a program to compute
  5159. @texline @math{\psi(z)};
  5160. @infoline @expr{psi(z)};
  5161. it should ``pump up'' @expr{z}
  5162. if necessary to be greater than 5, then use the above summation
  5163. formula. Use looping commands to compute the sum. Use your function
  5164. to compute
  5165. @texline @math{\gamma}
  5166. @infoline @expr{gamma}
  5167. to twelve decimal places. (Calc has a built-in command
  5168. for Euler's constant, @kbd{I P}, which you can use to check your answer.)
  5169. @xref{Programming Answer 9, 9}. (@bullet{})
  5170. @cindex Polynomial, list of coefficients
  5171. (@bullet{}) @strong{Exercise 10.} Given a polynomial in @expr{x} and
  5172. a number @expr{m} on the stack, where the polynomial is of degree
  5173. @expr{m} or less (i.e., does not have any terms higher than @expr{x^m}),
  5174. write a program to convert the polynomial into a list-of-coefficients
  5175. notation. For example, @expr{5 x^4 + (x + 1)^2} with @expr{m = 6}
  5176. should produce the list @expr{[1, 2, 1, 0, 5, 0, 0]}. Also develop
  5177. a way to convert from this form back to the standard algebraic form.
  5178. @xref{Programming Answer 10, 10}. (@bullet{})
  5179. @cindex Recursion
  5180. (@bullet{}) @strong{Exercise 11.} The @dfn{Stirling numbers of the
  5181. first kind} are defined by the recurrences,
  5182. @ifnottex
  5183. @example
  5184. s(n,n) = 1 for n >= 0,
  5185. s(n,0) = 0 for n > 0,
  5186. s(n+1,m) = s(n,m-1) - n s(n,m) for n >= m >= 1.
  5187. @end example
  5188. @end ifnottex
  5189. @tex
  5190. \beforedisplay
  5191. $$ \eqalign{ s(n,n) &= 1 \qquad \hbox{for } n \ge 0, \cr
  5192. s(n,0) &= 0 \qquad \hbox{for } n > 0, \cr
  5193. s(n+1,m) &= s(n,m-1) - n \, s(n,m) \qquad
  5194. \hbox{for } n \ge m \ge 1.}
  5195. $$
  5196. \afterdisplay
  5197. \vskip5pt
  5198. (These numbers are also sometimes written $\displaystyle{n \brack m}$.)
  5199. @end tex
  5200. This can be implemented using a @dfn{recursive} program in Calc; the
  5201. program must invoke itself in order to calculate the two righthand
  5202. terms in the general formula. Since it always invokes itself with
  5203. ``simpler'' arguments, it's easy to see that it must eventually finish
  5204. the computation. Recursion is a little difficult with Emacs keyboard
  5205. macros since the macro is executed before its definition is complete.
  5206. So here's the recommended strategy: Create a ``dummy macro'' and assign
  5207. it to a key with, e.g., @kbd{Z K s}. Now enter the true definition,
  5208. using the @kbd{z s} command to call itself recursively, then assign it
  5209. to the same key with @kbd{Z K s}. Now the @kbd{z s} command will run
  5210. the complete recursive program. (Another way is to use @w{@kbd{Z E}}
  5211. or @kbd{C-x * m} (@code{read-kbd-macro}) to read the whole macro at once,
  5212. thus avoiding the ``training'' phase.) The task: Write a program
  5213. that computes Stirling numbers of the first kind, given @expr{n} and
  5214. @expr{m} on the stack. Test it with @emph{small} inputs like
  5215. @expr{s(4,2)}. (There is a built-in command for Stirling numbers,
  5216. @kbd{k s}, which you can use to check your answers.)
  5217. @xref{Programming Answer 11, 11}. (@bullet{})
  5218. The programming commands we've seen in this part of the tutorial
  5219. are low-level, general-purpose operations. Often you will find
  5220. that a higher-level function, such as vector mapping or rewrite
  5221. rules, will do the job much more easily than a detailed, step-by-step
  5222. program can:
  5223. (@bullet{}) @strong{Exercise 12.} Write another program for
  5224. computing Stirling numbers of the first kind, this time using
  5225. rewrite rules. Once again, @expr{n} and @expr{m} should be taken
  5226. from the stack. @xref{Programming Answer 12, 12}. (@bullet{})
  5227. @example
  5228. @end example
  5229. This ends the tutorial section of the Calc manual. Now you know enough
  5230. about Calc to use it effectively for many kinds of calculations. But
  5231. Calc has many features that were not even touched upon in this tutorial.
  5232. @c [not-split]
  5233. The rest of this manual tells the whole story.
  5234. @c [when-split]
  5235. @c Volume II of this manual, the @dfn{Calc Reference}, tells the whole story.
  5236. @page
  5237. @node Answers to Exercises, , Programming Tutorial, Tutorial
  5238. @section Answers to Exercises
  5239. @noindent
  5240. This section includes answers to all the exercises in the Calc tutorial.
  5241. @menu
  5242. * RPN Answer 1:: 1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -
  5243. * RPN Answer 2:: 2*4 + 7*9.5 + 5/4
  5244. * RPN Answer 3:: Operating on levels 2 and 3
  5245. * RPN Answer 4:: Joe's complex problems
  5246. * Algebraic Answer 1:: Simulating Q command
  5247. * Algebraic Answer 2:: Joe's algebraic woes
  5248. * Algebraic Answer 3:: 1 / 0
  5249. * Modes Answer 1:: 3#0.1 = 3#0.0222222?
  5250. * Modes Answer 2:: 16#f.e8fe15
  5251. * Modes Answer 3:: Joe's rounding bug
  5252. * Modes Answer 4:: Why floating point?
  5253. * Arithmetic Answer 1:: Why the \ command?
  5254. * Arithmetic Answer 2:: Tripping up the B command
  5255. * Vector Answer 1:: Normalizing a vector
  5256. * Vector Answer 2:: Average position
  5257. * Matrix Answer 1:: Row and column sums
  5258. * Matrix Answer 2:: Symbolic system of equations
  5259. * Matrix Answer 3:: Over-determined system
  5260. * List Answer 1:: Powers of two
  5261. * List Answer 2:: Least-squares fit with matrices
  5262. * List Answer 3:: Geometric mean
  5263. * List Answer 4:: Divisor function
  5264. * List Answer 5:: Duplicate factors
  5265. * List Answer 6:: Triangular list
  5266. * List Answer 7:: Another triangular list
  5267. * List Answer 8:: Maximum of Bessel function
  5268. * List Answer 9:: Integers the hard way
  5269. * List Answer 10:: All elements equal
  5270. * List Answer 11:: Estimating pi with darts
  5271. * List Answer 12:: Estimating pi with matchsticks
  5272. * List Answer 13:: Hash codes
  5273. * List Answer 14:: Random walk
  5274. * Types Answer 1:: Square root of pi times rational
  5275. * Types Answer 2:: Infinities
  5276. * Types Answer 3:: What can "nan" be?
  5277. * Types Answer 4:: Abbey Road
  5278. * Types Answer 5:: Friday the 13th
  5279. * Types Answer 6:: Leap years
  5280. * Types Answer 7:: Erroneous donut
  5281. * Types Answer 8:: Dividing intervals
  5282. * Types Answer 9:: Squaring intervals
  5283. * Types Answer 10:: Fermat's primality test
  5284. * Types Answer 11:: pi * 10^7 seconds
  5285. * Types Answer 12:: Abbey Road on CD
  5286. * Types Answer 13:: Not quite pi * 10^7 seconds
  5287. * Types Answer 14:: Supercomputers and c
  5288. * Types Answer 15:: Sam the Slug
  5289. * Algebra Answer 1:: Squares and square roots
  5290. * Algebra Answer 2:: Building polynomial from roots
  5291. * Algebra Answer 3:: Integral of x sin(pi x)
  5292. * Algebra Answer 4:: Simpson's rule
  5293. * Rewrites Answer 1:: Multiplying by conjugate
  5294. * Rewrites Answer 2:: Alternative fib rule
  5295. * Rewrites Answer 3:: Rewriting opt(a) + opt(b) x
  5296. * Rewrites Answer 4:: Sequence of integers
  5297. * Rewrites Answer 5:: Number of terms in sum
  5298. * Rewrites Answer 6:: Truncated Taylor series
  5299. * Programming Answer 1:: Fresnel's C(x)
  5300. * Programming Answer 2:: Negate third stack element
  5301. * Programming Answer 3:: Compute sin(x) / x, etc.
  5302. * Programming Answer 4:: Average value of a list
  5303. * Programming Answer 5:: Continued fraction phi
  5304. * Programming Answer 6:: Matrix Fibonacci numbers
  5305. * Programming Answer 7:: Harmonic number greater than 4
  5306. * Programming Answer 8:: Newton's method
  5307. * Programming Answer 9:: Digamma function
  5308. * Programming Answer 10:: Unpacking a polynomial
  5309. * Programming Answer 11:: Recursive Stirling numbers
  5310. * Programming Answer 12:: Stirling numbers with rewrites
  5311. @end menu
  5312. @c The following kludgery prevents the individual answers from
  5313. @c being entered on the table of contents.
  5314. @tex
  5315. \global\let\oldwrite=\write
  5316. \gdef\skipwrite#1#2{\let\write=\oldwrite}
  5317. \global\let\oldchapternofonts=\chapternofonts
  5318. \gdef\chapternofonts{\let\write=\skipwrite\oldchapternofonts}
  5319. @end tex
  5320. @node RPN Answer 1, RPN Answer 2, Answers to Exercises, Answers to Exercises
  5321. @subsection RPN Tutorial Exercise 1
  5322. @noindent
  5323. @kbd{1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -}
  5324. The result is
  5325. @texline @math{1 - (2 \times (3 + 4)) = -13}.
  5326. @infoline @expr{1 - (2 * (3 + 4)) = -13}.
  5327. @node RPN Answer 2, RPN Answer 3, RPN Answer 1, Answers to Exercises
  5328. @subsection RPN Tutorial Exercise 2
  5329. @noindent
  5330. @texline @math{2\times4 + 7\times9.5 + {5\over4} = 75.75}
  5331. @infoline @expr{2*4 + 7*9.5 + 5/4 = 75.75}
  5332. After computing the intermediate term
  5333. @texline @math{2\times4 = 8},
  5334. @infoline @expr{2*4 = 8},
  5335. you can leave that result on the stack while you compute the second
  5336. term. With both of these results waiting on the stack you can then
  5337. compute the final term, then press @kbd{+ +} to add everything up.
  5338. @smallexample
  5339. @group
  5340. 2: 2 1: 8 3: 8 2: 8
  5341. 1: 4 . 2: 7 1: 66.5
  5342. . 1: 9.5 .
  5343. .
  5344. 2 @key{RET} 4 * 7 @key{RET} 9.5 *
  5345. @end group
  5346. @end smallexample
  5347. @noindent
  5348. @smallexample
  5349. @group
  5350. 4: 8 3: 8 2: 8 1: 75.75
  5351. 3: 66.5 2: 66.5 1: 67.75 .
  5352. 2: 5 1: 1.25 .
  5353. 1: 4 .
  5354. .
  5355. 5 @key{RET} 4 / + +
  5356. @end group
  5357. @end smallexample
  5358. Alternatively, you could add the first two terms before going on
  5359. with the third term.
  5360. @smallexample
  5361. @group
  5362. 2: 8 1: 74.5 3: 74.5 2: 74.5 1: 75.75
  5363. 1: 66.5 . 2: 5 1: 1.25 .
  5364. . 1: 4 .
  5365. .
  5366. ... + 5 @key{RET} 4 / +
  5367. @end group
  5368. @end smallexample
  5369. On an old-style RPN calculator this second method would have the
  5370. advantage of using only three stack levels. But since Calc's stack
  5371. can grow arbitrarily large this isn't really an issue. Which method
  5372. you choose is purely a matter of taste.
  5373. @node RPN Answer 3, RPN Answer 4, RPN Answer 2, Answers to Exercises
  5374. @subsection RPN Tutorial Exercise 3
  5375. @noindent
  5376. The @key{TAB} key provides a way to operate on the number in level 2.
  5377. @smallexample
  5378. @group
  5379. 3: 10 3: 10 4: 10 3: 10 3: 10
  5380. 2: 20 2: 30 3: 30 2: 30 2: 21
  5381. 1: 30 1: 20 2: 20 1: 21 1: 30
  5382. . . 1: 1 . .
  5383. .
  5384. @key{TAB} 1 + @key{TAB}
  5385. @end group
  5386. @end smallexample
  5387. Similarly, @kbd{M-@key{TAB}} gives you access to the number in level 3.
  5388. @smallexample
  5389. @group
  5390. 3: 10 3: 21 3: 21 3: 30 3: 11
  5391. 2: 21 2: 30 2: 30 2: 11 2: 21
  5392. 1: 30 1: 10 1: 11 1: 21 1: 30
  5393. . . . . .
  5394. M-@key{TAB} 1 + M-@key{TAB} M-@key{TAB}
  5395. @end group
  5396. @end smallexample
  5397. @node RPN Answer 4, Algebraic Answer 1, RPN Answer 3, Answers to Exercises
  5398. @subsection RPN Tutorial Exercise 4
  5399. @noindent
  5400. Either @kbd{( 2 , 3 )} or @kbd{( 2 @key{SPC} 3 )} would have worked,
  5401. but using both the comma and the space at once yields:
  5402. @smallexample
  5403. @group
  5404. 1: ( ... 2: ( ... 1: (2, ... 2: (2, ... 2: (2, ...
  5405. . 1: 2 . 1: (2, ... 1: (2, 3)
  5406. . . .
  5407. ( 2 , @key{SPC} 3 )
  5408. @end group
  5409. @end smallexample
  5410. Joe probably tried to type @kbd{@key{TAB} @key{DEL}} to swap the
  5411. extra incomplete object to the top of the stack and delete it.
  5412. But a feature of Calc is that @key{DEL} on an incomplete object
  5413. deletes just one component out of that object, so he had to press
  5414. @key{DEL} twice to finish the job.
  5415. @smallexample
  5416. @group
  5417. 2: (2, ... 2: (2, 3) 2: (2, 3) 1: (2, 3)
  5418. 1: (2, 3) 1: (2, ... 1: ( ... .
  5419. . . .
  5420. @key{TAB} @key{DEL} @key{DEL}
  5421. @end group
  5422. @end smallexample
  5423. (As it turns out, deleting the second-to-top stack entry happens often
  5424. enough that Calc provides a special key, @kbd{M-@key{DEL}}, to do just that.
  5425. @kbd{M-@key{DEL}} is just like @kbd{@key{TAB} @key{DEL}}, except that it doesn't exhibit
  5426. the ``feature'' that tripped poor Joe.)
  5427. @node Algebraic Answer 1, Algebraic Answer 2, RPN Answer 4, Answers to Exercises
  5428. @subsection Algebraic Entry Tutorial Exercise 1
  5429. @noindent
  5430. Type @kbd{' sqrt($) @key{RET}}.
  5431. If the @kbd{Q} key is broken, you could use @kbd{' $^0.5 @key{RET}}.
  5432. Or, RPN style, @kbd{0.5 ^}.
  5433. (Actually, @samp{$^1:2}, using the fraction one-half as the power, is
  5434. a closer equivalent, since @samp{9^0.5} yields @expr{3.0} whereas
  5435. @samp{sqrt(9)} and @samp{9^1:2} yield the exact integer @expr{3}.)
  5436. @node Algebraic Answer 2, Algebraic Answer 3, Algebraic Answer 1, Answers to Exercises
  5437. @subsection Algebraic Entry Tutorial Exercise 2
  5438. @noindent
  5439. In the formula @samp{2 x (1+y)}, @samp{x} was interpreted as a function
  5440. name with @samp{1+y} as its argument. Assigning a value to a variable
  5441. has no relation to a function by the same name. Joe needed to use an
  5442. explicit @samp{*} symbol here: @samp{2 x*(1+y)}.
  5443. @node Algebraic Answer 3, Modes Answer 1, Algebraic Answer 2, Answers to Exercises
  5444. @subsection Algebraic Entry Tutorial Exercise 3
  5445. @noindent
  5446. The result from @kbd{1 @key{RET} 0 /} will be the formula @expr{1 / 0}.
  5447. The ``function'' @samp{/} cannot be evaluated when its second argument
  5448. is zero, so it is left in symbolic form. When you now type @kbd{0 *},
  5449. the result will be zero because Calc uses the general rule that ``zero
  5450. times anything is zero.''
  5451. @c [fix-ref Infinities]
  5452. The @kbd{m i} command enables an @dfn{Infinite mode} in which @expr{1 / 0}
  5453. results in a special symbol that represents ``infinity.'' If you
  5454. multiply infinity by zero, Calc uses another special new symbol to
  5455. show that the answer is ``indeterminate.'' @xref{Infinities}, for
  5456. further discussion of infinite and indeterminate values.
  5457. @node Modes Answer 1, Modes Answer 2, Algebraic Answer 3, Answers to Exercises
  5458. @subsection Modes Tutorial Exercise 1
  5459. @noindent
  5460. Calc always stores its numbers in decimal, so even though one-third has
  5461. an exact base-3 representation (@samp{3#0.1}), it is still stored as
  5462. 0.3333333 (chopped off after 12 or however many decimal digits) inside
  5463. the calculator's memory. When this inexact number is converted back
  5464. to base 3 for display, it may still be slightly inexact. When we
  5465. multiply this number by 3, we get 0.999999, also an inexact value.
  5466. When Calc displays a number in base 3, it has to decide how many digits
  5467. to show. If the current precision is 12 (decimal) digits, that corresponds
  5468. to @samp{12 / log10(3) = 25.15} base-3 digits. Because 25.15 is not an
  5469. exact integer, Calc shows only 25 digits, with the result that stored
  5470. numbers carry a little bit of extra information that may not show up on
  5471. the screen. When Joe entered @samp{3#0.2}, the stored number 0.666666
  5472. happened to round to a pleasing value when it lost that last 0.15 of a
  5473. digit, but it was still inexact in Calc's memory. When he divided by 2,
  5474. he still got the dreaded inexact value 0.333333. (Actually, he divided
  5475. 0.666667 by 2 to get 0.333334, which is why he got something a little
  5476. higher than @code{3#0.1} instead of a little lower.)
  5477. If Joe didn't want to be bothered with all this, he could have typed
  5478. @kbd{M-24 d n} to display with one less digit than the default. (If
  5479. you give @kbd{d n} a negative argument, it uses default-minus-that,
  5480. so @kbd{M-- d n} would be an easier way to get the same effect.) Those
  5481. inexact results would still be lurking there, but they would now be
  5482. rounded to nice, natural-looking values for display purposes. (Remember,
  5483. @samp{0.022222} in base 3 is like @samp{0.099999} in base 10; rounding
  5484. off one digit will round the number up to @samp{0.1}.) Depending on the
  5485. nature of your work, this hiding of the inexactness may be a benefit or
  5486. a danger. With the @kbd{d n} command, Calc gives you the choice.
  5487. Incidentally, another consequence of all this is that if you type
  5488. @kbd{M-30 d n} to display more digits than are ``really there,''
  5489. you'll see garbage digits at the end of the number. (In decimal
  5490. display mode, with decimally-stored numbers, these garbage digits are
  5491. always zero so they vanish and you don't notice them.) Because Calc
  5492. rounds off that 0.15 digit, there is the danger that two numbers could
  5493. be slightly different internally but still look the same. If you feel
  5494. uneasy about this, set the @kbd{d n} precision to be a little higher
  5495. than normal; you'll get ugly garbage digits, but you'll always be able
  5496. to tell two distinct numbers apart.
  5497. An interesting side note is that most computers store their
  5498. floating-point numbers in binary, and convert to decimal for display.
  5499. Thus everyday programs have the same problem: Decimal 0.1 cannot be
  5500. represented exactly in binary (try it: @kbd{0.1 d 2}), so @samp{0.1 * 10}
  5501. comes out as an inexact approximation to 1 on some machines (though
  5502. they generally arrange to hide it from you by rounding off one digit as
  5503. we did above). Because Calc works in decimal instead of binary, you can
  5504. be sure that numbers that look exact @emph{are} exact as long as you stay
  5505. in decimal display mode.
  5506. It's not hard to show that any number that can be represented exactly
  5507. in binary, octal, or hexadecimal is also exact in decimal, so the kinds
  5508. of problems we saw in this exercise are likely to be severe only when
  5509. you use a relatively unusual radix like 3.
  5510. @node Modes Answer 2, Modes Answer 3, Modes Answer 1, Answers to Exercises
  5511. @subsection Modes Tutorial Exercise 2
  5512. If the radix is 15 or higher, we can't use the letter @samp{e} to mark
  5513. the exponent because @samp{e} is interpreted as a digit. When Calc
  5514. needs to display scientific notation in a high radix, it writes
  5515. @samp{16#F.E8F*16.^15}. You can enter a number like this as an
  5516. algebraic entry. Also, pressing @kbd{e} without any digits before it
  5517. normally types @kbd{1e}, but in a high radix it types @kbd{16.^} and
  5518. puts you in algebraic entry: @kbd{16#f.e8f @key{RET} e 15 @key{RET} *} is another
  5519. way to enter this number.
  5520. The reason Calc puts a decimal point in the @samp{16.^} is to prevent
  5521. huge integers from being generated if the exponent is large (consider
  5522. @samp{16#1.23*16^1000}, where we compute @samp{16^1000} as a giant
  5523. exact integer and then throw away most of the digits when we multiply
  5524. it by the floating-point @samp{16#1.23}). While this wouldn't normally
  5525. matter for display purposes, it could give you a nasty surprise if you
  5526. copied that number into a file and later moved it back into Calc.
  5527. @node Modes Answer 3, Modes Answer 4, Modes Answer 2, Answers to Exercises
  5528. @subsection Modes Tutorial Exercise 3
  5529. @noindent
  5530. The answer he got was @expr{0.5000000000006399}.
  5531. The problem is not that the square operation is inexact, but that the
  5532. sine of 45 that was already on the stack was accurate to only 12 places.
  5533. Arbitrary-precision calculations still only give answers as good as
  5534. their inputs.
  5535. The real problem is that there is no 12-digit number which, when
  5536. squared, comes out to 0.5 exactly. The @kbd{f [} and @kbd{f ]}
  5537. commands decrease or increase a number by one unit in the last
  5538. place (according to the current precision). They are useful for
  5539. determining facts like this.
  5540. @smallexample
  5541. @group
  5542. 1: 0.707106781187 1: 0.500000000001
  5543. . .
  5544. 45 S 2 ^
  5545. @end group
  5546. @end smallexample
  5547. @noindent
  5548. @smallexample
  5549. @group
  5550. 1: 0.707106781187 1: 0.707106781186 1: 0.499999999999
  5551. . . .
  5552. U @key{DEL} f [ 2 ^
  5553. @end group
  5554. @end smallexample
  5555. A high-precision calculation must be carried out in high precision
  5556. all the way. The only number in the original problem which was known
  5557. exactly was the quantity 45 degrees, so the precision must be raised
  5558. before anything is done after the number 45 has been entered in order
  5559. for the higher precision to be meaningful.
  5560. @node Modes Answer 4, Arithmetic Answer 1, Modes Answer 3, Answers to Exercises
  5561. @subsection Modes Tutorial Exercise 4
  5562. @noindent
  5563. Many calculations involve real-world quantities, like the width and
  5564. height of a piece of wood or the volume of a jar. Such quantities
  5565. can't be measured exactly anyway, and if the data that is input to
  5566. a calculation is inexact, doing exact arithmetic on it is a waste
  5567. of time.
  5568. Fractions become unwieldy after too many calculations have been
  5569. done with them. For example, the sum of the reciprocals of the
  5570. integers from 1 to 10 is 7381:2520. The sum from 1 to 30 is
  5571. 9304682830147:2329089562800. After a point it will take a long
  5572. time to add even one more term to this sum, but a floating-point
  5573. calculation of the sum will not have this problem.
  5574. Also, rational numbers cannot express the results of all calculations.
  5575. There is no fractional form for the square root of two, so if you type
  5576. @w{@kbd{2 Q}}, Calc has no choice but to give you a floating-point answer.
  5577. @node Arithmetic Answer 1, Arithmetic Answer 2, Modes Answer 4, Answers to Exercises
  5578. @subsection Arithmetic Tutorial Exercise 1
  5579. @noindent
  5580. Dividing two integers that are larger than the current precision may
  5581. give a floating-point result that is inaccurate even when rounded
  5582. down to an integer. Consider @expr{123456789 / 2} when the current
  5583. precision is 6 digits. The true answer is @expr{61728394.5}, but
  5584. with a precision of 6 this will be rounded to
  5585. @texline @math{12345700.0/2.0 = 61728500.0}.
  5586. @infoline @expr{12345700.@: / 2.@: = 61728500.}.
  5587. The result, when converted to an integer, will be off by 106.
  5588. Here are two solutions: Raise the precision enough that the
  5589. floating-point round-off error is strictly to the right of the
  5590. decimal point. Or, convert to Fraction mode so that @expr{123456789 / 2}
  5591. produces the exact fraction @expr{123456789:2}, which can be rounded
  5592. down by the @kbd{F} command without ever switching to floating-point
  5593. format.
  5594. @node Arithmetic Answer 2, Vector Answer 1, Arithmetic Answer 1, Answers to Exercises
  5595. @subsection Arithmetic Tutorial Exercise 2
  5596. @noindent
  5597. @kbd{27 @key{RET} 9 B} could give the exact result @expr{3:2}, but it
  5598. does a floating-point calculation instead and produces @expr{1.5}.
  5599. Calc will find an exact result for a logarithm if the result is an integer
  5600. or (when in Fraction mode) the reciprocal of an integer. But there is
  5601. no efficient way to search the space of all possible rational numbers
  5602. for an exact answer, so Calc doesn't try.
  5603. @node Vector Answer 1, Vector Answer 2, Arithmetic Answer 2, Answers to Exercises
  5604. @subsection Vector Tutorial Exercise 1
  5605. @noindent
  5606. Duplicate the vector, compute its length, then divide the vector
  5607. by its length: @kbd{@key{RET} A /}.
  5608. @smallexample
  5609. @group
  5610. 1: [1, 2, 3] 2: [1, 2, 3] 1: [0.27, 0.53, 0.80] 1: 1.
  5611. . 1: 3.74165738677 . .
  5612. .
  5613. r 1 @key{RET} A / A
  5614. @end group
  5615. @end smallexample
  5616. The final @kbd{A} command shows that the normalized vector does
  5617. indeed have unit length.
  5618. @node Vector Answer 2, Matrix Answer 1, Vector Answer 1, Answers to Exercises
  5619. @subsection Vector Tutorial Exercise 2
  5620. @noindent
  5621. The average position is equal to the sum of the products of the
  5622. positions times their corresponding probabilities. This is the
  5623. definition of the dot product operation. So all you need to do
  5624. is to put the two vectors on the stack and press @kbd{*}.
  5625. @node Matrix Answer 1, Matrix Answer 2, Vector Answer 2, Answers to Exercises
  5626. @subsection Matrix Tutorial Exercise 1
  5627. @noindent
  5628. The trick is to multiply by a vector of ones. Use @kbd{r 4 [1 1 1] *} to
  5629. get the row sum. Similarly, use @kbd{[1 1] r 4 *} to get the column sum.
  5630. @node Matrix Answer 2, Matrix Answer 3, Matrix Answer 1, Answers to Exercises
  5631. @subsection Matrix Tutorial Exercise 2
  5632. @ifnottex
  5633. @example
  5634. @group
  5635. x + a y = 6
  5636. x + b y = 10
  5637. @end group
  5638. @end example
  5639. @end ifnottex
  5640. @tex
  5641. \beforedisplay
  5642. $$ \eqalign{ x &+ a y = 6 \cr
  5643. x &+ b y = 10}
  5644. $$
  5645. \afterdisplay
  5646. @end tex
  5647. Just enter the righthand side vector, then divide by the lefthand side
  5648. matrix as usual.
  5649. @smallexample
  5650. @group
  5651. 1: [6, 10] 2: [6, 10] 1: [4 a / (a - b) + 6, 4 / (b - a) ]
  5652. . 1: [ [ 1, a ] .
  5653. [ 1, b ] ]
  5654. .
  5655. ' [6 10] @key{RET} ' [1 a; 1 b] @key{RET} /
  5656. @end group
  5657. @end smallexample
  5658. This can be made more readable using @kbd{d B} to enable Big display
  5659. mode:
  5660. @smallexample
  5661. @group
  5662. 4 a 4
  5663. 1: [----- + 6, -----]
  5664. a - b b - a
  5665. @end group
  5666. @end smallexample
  5667. Type @kbd{d N} to return to Normal display mode afterwards.
  5668. @node Matrix Answer 3, List Answer 1, Matrix Answer 2, Answers to Exercises
  5669. @subsection Matrix Tutorial Exercise 3
  5670. @noindent
  5671. To solve
  5672. @texline @math{A^T A \, X = A^T B},
  5673. @infoline @expr{trn(A) * A * X = trn(A) * B},
  5674. first we compute
  5675. @texline @math{A' = A^T A}
  5676. @infoline @expr{A2 = trn(A) * A}
  5677. and
  5678. @texline @math{B' = A^T B};
  5679. @infoline @expr{B2 = trn(A) * B};
  5680. now, we have a system
  5681. @texline @math{A' X = B'}
  5682. @infoline @expr{A2 * X = B2}
  5683. which we can solve using Calc's @samp{/} command.
  5684. @ifnottex
  5685. @example
  5686. @group
  5687. a + 2b + 3c = 6
  5688. 4a + 5b + 6c = 2
  5689. 7a + 6b = 3
  5690. 2a + 4b + 6c = 11
  5691. @end group
  5692. @end example
  5693. @end ifnottex
  5694. @tex
  5695. \beforedisplayh
  5696. $$ \openup1\jot \tabskip=0pt plus1fil
  5697. \halign to\displaywidth{\tabskip=0pt
  5698. $\hfil#$&$\hfil{}#{}$&
  5699. $\hfil#$&$\hfil{}#{}$&
  5700. $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
  5701. a&+&2b&+&3c&=6 \cr
  5702. 4a&+&5b&+&6c&=2 \cr
  5703. 7a&+&6b& & &=3 \cr
  5704. 2a&+&4b&+&6c&=11 \cr}
  5705. $$
  5706. \afterdisplayh
  5707. @end tex
  5708. The first step is to enter the coefficient matrix. We'll store it in
  5709. quick variable number 7 for later reference. Next, we compute the
  5710. @texline @math{B'}
  5711. @infoline @expr{B2}
  5712. vector.
  5713. @smallexample
  5714. @group
  5715. 1: [ [ 1, 2, 3 ] 2: [ [ 1, 4, 7, 2 ] 1: [57, 84, 96]
  5716. [ 4, 5, 6 ] [ 2, 5, 6, 4 ] .
  5717. [ 7, 6, 0 ] [ 3, 6, 0, 6 ] ]
  5718. [ 2, 4, 6 ] ] 1: [6, 2, 3, 11]
  5719. . .
  5720. ' [1 2 3; 4 5 6; 7 6 0; 2 4 6] @key{RET} s 7 v t [6 2 3 11] *
  5721. @end group
  5722. @end smallexample
  5723. @noindent
  5724. Now we compute the matrix
  5725. @texline @math{A'}
  5726. @infoline @expr{A2}
  5727. and divide.
  5728. @smallexample
  5729. @group
  5730. 2: [57, 84, 96] 1: [-11.64, 14.08, -3.64]
  5731. 1: [ [ 70, 72, 39 ] .
  5732. [ 72, 81, 60 ]
  5733. [ 39, 60, 81 ] ]
  5734. .
  5735. r 7 v t r 7 * /
  5736. @end group
  5737. @end smallexample
  5738. @noindent
  5739. (The actual computed answer will be slightly inexact due to
  5740. round-off error.)
  5741. Notice that the answers are similar to those for the
  5742. @texline @math{3\times3}
  5743. @infoline 3x3
  5744. system solved in the text. That's because the fourth equation that was
  5745. added to the system is almost identical to the first one multiplied
  5746. by two. (If it were identical, we would have gotten the exact same
  5747. answer since the
  5748. @texline @math{4\times3}
  5749. @infoline 4x3
  5750. system would be equivalent to the original
  5751. @texline @math{3\times3}
  5752. @infoline 3x3
  5753. system.)
  5754. Since the first and fourth equations aren't quite equivalent, they
  5755. can't both be satisfied at once. Let's plug our answers back into
  5756. the original system of equations to see how well they match.
  5757. @smallexample
  5758. @group
  5759. 2: [-11.64, 14.08, -3.64] 1: [5.6, 2., 3., 11.2]
  5760. 1: [ [ 1, 2, 3 ] .
  5761. [ 4, 5, 6 ]
  5762. [ 7, 6, 0 ]
  5763. [ 2, 4, 6 ] ]
  5764. .
  5765. r 7 @key{TAB} *
  5766. @end group
  5767. @end smallexample
  5768. @noindent
  5769. This is reasonably close to our original @expr{B} vector,
  5770. @expr{[6, 2, 3, 11]}.
  5771. @node List Answer 1, List Answer 2, Matrix Answer 3, Answers to Exercises
  5772. @subsection List Tutorial Exercise 1
  5773. @noindent
  5774. We can use @kbd{v x} to build a vector of integers. This needs to be
  5775. adjusted to get the range of integers we desire. Mapping @samp{-}
  5776. across the vector will accomplish this, although it turns out the
  5777. plain @samp{-} key will work just as well.
  5778. @smallexample
  5779. @group
  5780. 2: 2 2: 2
  5781. 1: [1, 2, 3, 4, 5, 6, 7, 8, 9] 1: [-4, -3, -2, -1, 0, 1, 2, 3, 4]
  5782. . .
  5783. 2 v x 9 @key{RET} 5 V M - or 5 -
  5784. @end group
  5785. @end smallexample
  5786. @noindent
  5787. Now we use @kbd{V M ^} to map the exponentiation operator across the
  5788. vector.
  5789. @smallexample
  5790. @group
  5791. 1: [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16]
  5792. .
  5793. V M ^
  5794. @end group
  5795. @end smallexample
  5796. @node List Answer 2, List Answer 3, List Answer 1, Answers to Exercises
  5797. @subsection List Tutorial Exercise 2
  5798. @noindent
  5799. Given @expr{x} and @expr{y} vectors in quick variables 1 and 2 as before,
  5800. the first job is to form the matrix that describes the problem.
  5801. @ifnottex
  5802. @example
  5803. m*x + b*1 = y
  5804. @end example
  5805. @end ifnottex
  5806. @tex
  5807. \beforedisplay
  5808. $$ m \times x + b \times 1 = y $$
  5809. \afterdisplay
  5810. @end tex
  5811. Thus we want a
  5812. @texline @math{19\times2}
  5813. @infoline 19x2
  5814. matrix with our @expr{x} vector as one column and
  5815. ones as the other column. So, first we build the column of ones, then
  5816. we combine the two columns to form our @expr{A} matrix.
  5817. @smallexample
  5818. @group
  5819. 2: [1.34, 1.41, 1.49, ... ] 1: [ [ 1.34, 1 ]
  5820. 1: [1, 1, 1, ...] [ 1.41, 1 ]
  5821. . [ 1.49, 1 ]
  5822. @dots{}
  5823. r 1 1 v b 19 @key{RET} M-2 v p v t s 3
  5824. @end group
  5825. @end smallexample
  5826. @noindent
  5827. Now we compute
  5828. @texline @math{A^T y}
  5829. @infoline @expr{trn(A) * y}
  5830. and
  5831. @texline @math{A^T A}
  5832. @infoline @expr{trn(A) * A}
  5833. and divide.
  5834. @smallexample
  5835. @group
  5836. 1: [33.36554, 13.613] 2: [33.36554, 13.613]
  5837. . 1: [ [ 98.0003, 41.63 ]
  5838. [ 41.63, 19 ] ]
  5839. .
  5840. v t r 2 * r 3 v t r 3 *
  5841. @end group
  5842. @end smallexample
  5843. @noindent
  5844. (Hey, those numbers look familiar!)
  5845. @smallexample
  5846. @group
  5847. 1: [0.52141679, -0.425978]
  5848. .
  5849. /
  5850. @end group
  5851. @end smallexample
  5852. Since we were solving equations of the form
  5853. @texline @math{m \times x + b \times 1 = y},
  5854. @infoline @expr{m*x + b*1 = y},
  5855. these numbers should be @expr{m} and @expr{b}, respectively. Sure
  5856. enough, they agree exactly with the result computed using @kbd{V M} and
  5857. @kbd{V R}!
  5858. The moral of this story: @kbd{V M} and @kbd{V R} will probably solve
  5859. your problem, but there is often an easier way using the higher-level
  5860. arithmetic functions!
  5861. @c [fix-ref Curve Fitting]
  5862. In fact, there is a built-in @kbd{a F} command that does least-squares
  5863. fits. @xref{Curve Fitting}.
  5864. @node List Answer 3, List Answer 4, List Answer 2, Answers to Exercises
  5865. @subsection List Tutorial Exercise 3
  5866. @noindent
  5867. Move to one end of the list and press @kbd{C-@@} (or @kbd{C-@key{SPC}} or
  5868. whatever) to set the mark, then move to the other end of the list
  5869. and type @w{@kbd{C-x * g}}.
  5870. @smallexample
  5871. @group
  5872. 1: [2.3, 6, 22, 15.1, 7, 15, 14, 7.5, 2.5]
  5873. .
  5874. @end group
  5875. @end smallexample
  5876. To make things interesting, let's assume we don't know at a glance
  5877. how many numbers are in this list. Then we could type:
  5878. @smallexample
  5879. @group
  5880. 2: [2.3, 6, 22, ... ] 2: [2.3, 6, 22, ... ]
  5881. 1: [2.3, 6, 22, ... ] 1: 126356422.5
  5882. . .
  5883. @key{RET} V R *
  5884. @end group
  5885. @end smallexample
  5886. @noindent
  5887. @smallexample
  5888. @group
  5889. 2: 126356422.5 2: 126356422.5 1: 7.94652913734
  5890. 1: [2.3, 6, 22, ... ] 1: 9 .
  5891. . .
  5892. @key{TAB} v l I ^
  5893. @end group
  5894. @end smallexample
  5895. @noindent
  5896. (The @kbd{I ^} command computes the @var{n}th root of a number.
  5897. You could also type @kbd{& ^} to take the reciprocal of 9 and
  5898. then raise the number to that power.)
  5899. @node List Answer 4, List Answer 5, List Answer 3, Answers to Exercises
  5900. @subsection List Tutorial Exercise 4
  5901. @noindent
  5902. A number @expr{j} is a divisor of @expr{n} if
  5903. @texline @math{n \mathbin{\hbox{\code{\%}}} j = 0}.
  5904. @infoline @samp{n % j = 0}.
  5905. The first step is to get a vector that identifies the divisors.
  5906. @smallexample
  5907. @group
  5908. 2: 30 2: [0, 0, 0, 2, ...] 1: [1, 1, 1, 0, ...]
  5909. 1: [1, 2, 3, 4, ...] 1: 0 .
  5910. . .
  5911. 30 @key{RET} v x 30 @key{RET} s 1 V M % 0 V M a = s 2
  5912. @end group
  5913. @end smallexample
  5914. @noindent
  5915. This vector has 1's marking divisors of 30 and 0's marking non-divisors.
  5916. The zeroth divisor function is just the total number of divisors.
  5917. The first divisor function is the sum of the divisors.
  5918. @smallexample
  5919. @group
  5920. 1: 8 3: 8 2: 8 2: 8
  5921. 2: [1, 2, 3, 4, ...] 1: [1, 2, 3, 0, ...] 1: 72
  5922. 1: [1, 1, 1, 0, ...] . .
  5923. .
  5924. V R + r 1 r 2 V M * V R +
  5925. @end group
  5926. @end smallexample
  5927. @noindent
  5928. Once again, the last two steps just compute a dot product for which
  5929. a simple @kbd{*} would have worked equally well.
  5930. @node List Answer 5, List Answer 6, List Answer 4, Answers to Exercises
  5931. @subsection List Tutorial Exercise 5
  5932. @noindent
  5933. The obvious first step is to obtain the list of factors with @kbd{k f}.
  5934. This list will always be in sorted order, so if there are duplicates
  5935. they will be right next to each other. A suitable method is to compare
  5936. the list with a copy of itself shifted over by one.
  5937. @smallexample
  5938. @group
  5939. 1: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19, 0]
  5940. . 1: [3, 7, 7, 7, 19, 0] 1: [0, 3, 7, 7, 7, 19]
  5941. . .
  5942. 19551 k f @key{RET} 0 | @key{TAB} 0 @key{TAB} |
  5943. @end group
  5944. @end smallexample
  5945. @noindent
  5946. @smallexample
  5947. @group
  5948. 1: [0, 0, 1, 1, 0, 0] 1: 2 1: 0
  5949. . . .
  5950. V M a = V R + 0 a =
  5951. @end group
  5952. @end smallexample
  5953. @noindent
  5954. Note that we have to arrange for both vectors to have the same length
  5955. so that the mapping operation works; no prime factor will ever be
  5956. zero, so adding zeros on the left and right is safe. From then on
  5957. the job is pretty straightforward.
  5958. Incidentally, Calc provides the @dfn{Möbius μ}
  5959. function which is zero if and only if its argument is square-free. It
  5960. would be a much more convenient way to do the above test in practice.
  5961. @node List Answer 6, List Answer 7, List Answer 5, Answers to Exercises
  5962. @subsection List Tutorial Exercise 6
  5963. @noindent
  5964. First use @kbd{v x 6 @key{RET}} to get a list of integers, then @kbd{V M v x}
  5965. to get a list of lists of integers!
  5966. @node List Answer 7, List Answer 8, List Answer 6, Answers to Exercises
  5967. @subsection List Tutorial Exercise 7
  5968. @noindent
  5969. Here's one solution. First, compute the triangular list from the previous
  5970. exercise and type @kbd{1 -} to subtract one from all the elements.
  5971. @smallexample
  5972. @group
  5973. 1: [ [0],
  5974. [0, 1],
  5975. [0, 1, 2],
  5976. @dots{}
  5977. 1 -
  5978. @end group
  5979. @end smallexample
  5980. The numbers down the lefthand edge of the list we desire are called
  5981. the ``triangular numbers'' (now you know why!). The @expr{n}th
  5982. triangular number is the sum of the integers from 1 to @expr{n}, and
  5983. can be computed directly by the formula
  5984. @texline @math{n (n+1) \over 2}.
  5985. @infoline @expr{n * (n+1) / 2}.
  5986. @smallexample
  5987. @group
  5988. 2: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
  5989. 1: [0, 1, 2, 3, 4, 5] 1: [0, 1, 3, 6, 10, 15]
  5990. . .
  5991. v x 6 @key{RET} 1 - V M ' $ ($+1)/2 @key{RET}
  5992. @end group
  5993. @end smallexample
  5994. @noindent
  5995. Adding this list to the above list of lists produces the desired
  5996. result:
  5997. @smallexample
  5998. @group
  5999. 1: [ [0],
  6000. [1, 2],
  6001. [3, 4, 5],
  6002. [6, 7, 8, 9],
  6003. [10, 11, 12, 13, 14],
  6004. [15, 16, 17, 18, 19, 20] ]
  6005. .
  6006. V M +
  6007. @end group
  6008. @end smallexample
  6009. If we did not know the formula for triangular numbers, we could have
  6010. computed them using a @kbd{V U +} command. We could also have
  6011. gotten them the hard way by mapping a reduction across the original
  6012. triangular list.
  6013. @smallexample
  6014. @group
  6015. 2: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
  6016. 1: [ [0], [0, 1], ... ] 1: [0, 1, 3, 6, 10, 15]
  6017. . .
  6018. @key{RET} V M V R +
  6019. @end group
  6020. @end smallexample
  6021. @noindent
  6022. (This means ``map a @kbd{V R +} command across the vector,'' and
  6023. since each element of the main vector is itself a small vector,
  6024. @kbd{V R +} computes the sum of its elements.)
  6025. @node List Answer 8, List Answer 9, List Answer 7, Answers to Exercises
  6026. @subsection List Tutorial Exercise 8
  6027. @noindent
  6028. The first step is to build a list of values of @expr{x}.
  6029. @smallexample
  6030. @group
  6031. 1: [1, 2, 3, ..., 21] 1: [0, 1, 2, ..., 20] 1: [0, 0.25, 0.5, ..., 5]
  6032. . . .
  6033. v x 21 @key{RET} 1 - 4 / s 1
  6034. @end group
  6035. @end smallexample
  6036. Next, we compute the Bessel function values.
  6037. @smallexample
  6038. @group
  6039. 1: [0., 0.124, 0.242, ..., -0.328]
  6040. .
  6041. V M ' besJ(1,$) @key{RET}
  6042. @end group
  6043. @end smallexample
  6044. @noindent
  6045. (Another way to do this would be @kbd{1 @key{TAB} V M f j}.)
  6046. A way to isolate the maximum value is to compute the maximum using
  6047. @kbd{V R X}, then compare all the Bessel values with that maximum.
  6048. @smallexample
  6049. @group
  6050. 2: [0., 0.124, 0.242, ... ] 1: [0, 0, 0, ... ] 2: [0, 0, 0, ... ]
  6051. 1: 0.5801562 . 1: 1
  6052. . .
  6053. @key{RET} V R X V M a = @key{RET} V R + @key{DEL}
  6054. @end group
  6055. @end smallexample
  6056. @noindent
  6057. It's a good idea to verify, as in the last step above, that only
  6058. one value is equal to the maximum. (After all, a plot of
  6059. @texline @math{\sin x}
  6060. @infoline @expr{sin(x)}
  6061. might have many points all equal to the maximum value, 1.)
  6062. The vector we have now has a single 1 in the position that indicates
  6063. the maximum value of @expr{x}. Now it is a simple matter to convert
  6064. this back into the corresponding value itself.
  6065. @smallexample
  6066. @group
  6067. 2: [0, 0, 0, ... ] 1: [0, 0., 0., ... ] 1: 1.75
  6068. 1: [0, 0.25, 0.5, ... ] . .
  6069. .
  6070. r 1 V M * V R +
  6071. @end group
  6072. @end smallexample
  6073. If @kbd{a =} had produced more than one @expr{1} value, this method
  6074. would have given the sum of all maximum @expr{x} values; not very
  6075. useful! In this case we could have used @kbd{v m} (@code{calc-mask-vector})
  6076. instead. This command deletes all elements of a ``data'' vector that
  6077. correspond to zeros in a ``mask'' vector, leaving us with, in this
  6078. example, a vector of maximum @expr{x} values.
  6079. The built-in @kbd{a X} command maximizes a function using more
  6080. efficient methods. Just for illustration, let's use @kbd{a X}
  6081. to maximize @samp{besJ(1,x)} over this same interval.
  6082. @smallexample
  6083. @group
  6084. 2: besJ(1, x) 1: [1.84115, 0.581865]
  6085. 1: [0 .. 5] .
  6086. .
  6087. ' besJ(1,x), [0..5] @key{RET} a X x @key{RET}
  6088. @end group
  6089. @end smallexample
  6090. @noindent
  6091. The output from @kbd{a X} is a vector containing the value of @expr{x}
  6092. that maximizes the function, and the function's value at that maximum.
  6093. As you can see, our simple search got quite close to the right answer.
  6094. @node List Answer 9, List Answer 10, List Answer 8, Answers to Exercises
  6095. @subsection List Tutorial Exercise 9
  6096. @noindent
  6097. Step one is to convert our integer into vector notation.
  6098. @smallexample
  6099. @group
  6100. 1: 25129925999 3: 25129925999
  6101. . 2: 10
  6102. 1: [11, 10, 9, ..., 1, 0]
  6103. .
  6104. 25129925999 @key{RET} 10 @key{RET} 12 @key{RET} v x 12 @key{RET} -
  6105. @end group
  6106. @end smallexample
  6107. @noindent
  6108. @smallexample
  6109. @group
  6110. 1: 25129925999 1: [0, 2, 25, 251, 2512, ... ]
  6111. 2: [100000000000, ... ] .
  6112. .
  6113. V M ^ s 1 V M \
  6114. @end group
  6115. @end smallexample
  6116. @noindent
  6117. (Recall, the @kbd{\} command computes an integer quotient.)
  6118. @smallexample
  6119. @group
  6120. 1: [0, 2, 5, 1, 2, 9, 9, 2, 5, 9, 9, 9]
  6121. .
  6122. 10 V M % s 2
  6123. @end group
  6124. @end smallexample
  6125. Next we must increment this number. This involves adding one to
  6126. the last digit, plus handling carries. There is a carry to the
  6127. left out of a digit if that digit is a nine and all the digits to
  6128. the right of it are nines.
  6129. @smallexample
  6130. @group
  6131. 1: [0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1] 1: [1, 1, 1, 0, 0, 1, ... ]
  6132. . .
  6133. 9 V M a = v v
  6134. @end group
  6135. @end smallexample
  6136. @noindent
  6137. @smallexample
  6138. @group
  6139. 1: [1, 1, 1, 0, 0, 0, ... ] 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
  6140. . .
  6141. V U * v v 1 |
  6142. @end group
  6143. @end smallexample
  6144. @noindent
  6145. Accumulating @kbd{*} across a vector of ones and zeros will preserve
  6146. only the initial run of ones. These are the carries into all digits
  6147. except the rightmost digit. Concatenating a one on the right takes
  6148. care of aligning the carries properly, and also adding one to the
  6149. rightmost digit.
  6150. @smallexample
  6151. @group
  6152. 2: [0, 0, 0, 0, ... ] 1: [0, 0, 2, 5, 1, 2, 9, 9, 2, 6, 0, 0, 0]
  6153. 1: [0, 0, 2, 5, ... ] .
  6154. .
  6155. 0 r 2 | V M + 10 V M %
  6156. @end group
  6157. @end smallexample
  6158. @noindent
  6159. Here we have concatenated 0 to the @emph{left} of the original number;
  6160. this takes care of shifting the carries by one with respect to the
  6161. digits that generated them.
  6162. Finally, we must convert this list back into an integer.
  6163. @smallexample
  6164. @group
  6165. 3: [0, 0, 2, 5, ... ] 2: [0, 0, 2, 5, ... ]
  6166. 2: 1000000000000 1: [1000000000000, 100000000000, ... ]
  6167. 1: [100000000000, ... ] .
  6168. .
  6169. 10 @key{RET} 12 ^ r 1 |
  6170. @end group
  6171. @end smallexample
  6172. @noindent
  6173. @smallexample
  6174. @group
  6175. 1: [0, 0, 20000000000, 5000000000, ... ] 1: 25129926000
  6176. . .
  6177. V M * V R +
  6178. @end group
  6179. @end smallexample
  6180. @noindent
  6181. Another way to do this final step would be to reduce the formula
  6182. @w{@samp{10 $$ + $}} across the vector of digits.
  6183. @smallexample
  6184. @group
  6185. 1: [0, 0, 2, 5, ... ] 1: 25129926000
  6186. . .
  6187. V R ' 10 $$ + $ @key{RET}
  6188. @end group
  6189. @end smallexample
  6190. @node List Answer 10, List Answer 11, List Answer 9, Answers to Exercises
  6191. @subsection List Tutorial Exercise 10
  6192. @noindent
  6193. For the list @expr{[a, b, c, d]}, the result is @expr{((a = b) = c) = d},
  6194. which will compare @expr{a} and @expr{b} to produce a 1 or 0, which is
  6195. then compared with @expr{c} to produce another 1 or 0, which is then
  6196. compared with @expr{d}. This is not at all what Joe wanted.
  6197. Here's a more correct method:
  6198. @smallexample
  6199. @group
  6200. 1: [7, 7, 7, 8, 7] 2: [7, 7, 7, 8, 7]
  6201. . 1: 7
  6202. .
  6203. ' [7,7,7,8,7] @key{RET} @key{RET} v r 1 @key{RET}
  6204. @end group
  6205. @end smallexample
  6206. @noindent
  6207. @smallexample
  6208. @group
  6209. 1: [1, 1, 1, 0, 1] 1: 0
  6210. . .
  6211. V M a = V R *
  6212. @end group
  6213. @end smallexample
  6214. @node List Answer 11, List Answer 12, List Answer 10, Answers to Exercises
  6215. @subsection List Tutorial Exercise 11
  6216. @noindent
  6217. The circle of unit radius consists of those points @expr{(x,y)} for which
  6218. @expr{x^2 + y^2 < 1}. We start by generating a vector of @expr{x^2}
  6219. and a vector of @expr{y^2}.
  6220. We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
  6221. commands.
  6222. @smallexample
  6223. @group
  6224. 2: [2., 2., ..., 2.] 2: [2., 2., ..., 2.]
  6225. 1: [2., 2., ..., 2.] 1: [1.16, 1.98, ..., 0.81]
  6226. . .
  6227. v . t . 2. v b 100 @key{RET} @key{RET} V M k r
  6228. @end group
  6229. @end smallexample
  6230. @noindent
  6231. @smallexample
  6232. @group
  6233. 2: [2., 2., ..., 2.] 1: [0.026, 0.96, ..., 0.036]
  6234. 1: [0.026, 0.96, ..., 0.036] 2: [0.53, 0.81, ..., 0.094]
  6235. . .
  6236. 1 - 2 V M ^ @key{TAB} V M k r 1 - 2 V M ^
  6237. @end group
  6238. @end smallexample
  6239. Now we sum the @expr{x^2} and @expr{y^2} values, compare with 1 to
  6240. get a vector of 1/0 truth values, then sum the truth values.
  6241. @smallexample
  6242. @group
  6243. 1: [0.56, 1.78, ..., 0.13] 1: [1, 0, ..., 1] 1: 84
  6244. . . .
  6245. + 1 V M a < V R +
  6246. @end group
  6247. @end smallexample
  6248. @noindent
  6249. The ratio @expr{84/100} should approximate the ratio @cpiover{4}.
  6250. @smallexample
  6251. @group
  6252. 1: 0.84 1: 3.36 2: 3.36 1: 1.0695
  6253. . . 1: 3.14159 .
  6254. 100 / 4 * P /
  6255. @end group
  6256. @end smallexample
  6257. @noindent
  6258. Our estimate, 3.36, is off by about 7%. We could get a better estimate
  6259. by taking more points (say, 1000), but it's clear that this method is
  6260. not very efficient!
  6261. (Naturally, since this example uses random numbers your own answer
  6262. will be slightly different from the one shown here!)
  6263. If you typed @kbd{v .} and @kbd{t .} before, type them again to
  6264. return to full-sized display of vectors.
  6265. @node List Answer 12, List Answer 13, List Answer 11, Answers to Exercises
  6266. @subsection List Tutorial Exercise 12
  6267. @noindent
  6268. This problem can be made a lot easier by taking advantage of some
  6269. symmetries. First of all, after some thought it's clear that the
  6270. @expr{y} axis can be ignored altogether. Just pick a random @expr{x}
  6271. component for one end of the match, pick a random direction
  6272. @texline @math{\theta},
  6273. @infoline @expr{theta},
  6274. and see if @expr{x} and
  6275. @texline @math{x + \cos \theta}
  6276. @infoline @expr{x + cos(theta)}
  6277. (which is the @expr{x} coordinate of the other endpoint) cross a line.
  6278. The lines are at integer coordinates, so this happens when the two
  6279. numbers surround an integer.
  6280. Since the two endpoints are equivalent, we may as well choose the leftmost
  6281. of the two endpoints as @expr{x}. Then @expr{theta} is an angle pointing
  6282. to the right, in the range -90 to 90 degrees. (We could use radians, but
  6283. it would feel like cheating to refer to @cpiover{2} radians while trying
  6284. to estimate @cpi{}!)
  6285. In fact, since the field of lines is infinite we can choose the
  6286. coordinates 0 and 1 for the lines on either side of the leftmost
  6287. endpoint. The rightmost endpoint will be between 0 and 1 if the
  6288. match does not cross a line, or between 1 and 2 if it does. So:
  6289. Pick random @expr{x} and
  6290. @texline @math{\theta},
  6291. @infoline @expr{theta},
  6292. compute
  6293. @texline @math{x + \cos \theta},
  6294. @infoline @expr{x + cos(theta)},
  6295. and count how many of the results are greater than one. Simple!
  6296. We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
  6297. commands.
  6298. @smallexample
  6299. @group
  6300. 1: [0.52, 0.71, ..., 0.72] 2: [0.52, 0.71, ..., 0.72]
  6301. . 1: [78.4, 64.5, ..., -42.9]
  6302. .
  6303. v . t . 1. v b 100 @key{RET} V M k r 180. v b 100 @key{RET} V M k r 90 -
  6304. @end group
  6305. @end smallexample
  6306. @noindent
  6307. (The next step may be slow, depending on the speed of your computer.)
  6308. @smallexample
  6309. @group
  6310. 2: [0.52, 0.71, ..., 0.72] 1: [0.72, 1.14, ..., 1.45]
  6311. 1: [0.20, 0.43, ..., 0.73] .
  6312. .
  6313. m d V M C +
  6314. @end group
  6315. @end smallexample
  6316. @noindent
  6317. @smallexample
  6318. @group
  6319. 1: [0, 1, ..., 1] 1: 0.64 1: 3.125
  6320. . . .
  6321. 1 V M a > V R + 100 / 2 @key{TAB} /
  6322. @end group
  6323. @end smallexample
  6324. Let's try the third method, too. We'll use random integers up to
  6325. one million. The @kbd{k r} command with an integer argument picks
  6326. a random integer.
  6327. @smallexample
  6328. @group
  6329. 2: [1000000, 1000000, ..., 1000000] 2: [78489, 527587, ..., 814975]
  6330. 1: [1000000, 1000000, ..., 1000000] 1: [324014, 358783, ..., 955450]
  6331. . .
  6332. 1000000 v b 100 @key{RET} @key{RET} V M k r @key{TAB} V M k r
  6333. @end group
  6334. @end smallexample
  6335. @noindent
  6336. @smallexample
  6337. @group
  6338. 1: [1, 1, ..., 25] 1: [1, 1, ..., 0] 1: 0.56
  6339. . . .
  6340. V M k g 1 V M a = V R + 100 /
  6341. @end group
  6342. @end smallexample
  6343. @noindent
  6344. @smallexample
  6345. @group
  6346. 1: 10.714 1: 3.273
  6347. . .
  6348. 6 @key{TAB} / Q
  6349. @end group
  6350. @end smallexample
  6351. For a proof of this property of the GCD function, see section 4.5.2,
  6352. exercise 10, of Knuth's @emph{Art of Computer Programming}, volume II.
  6353. If you typed @kbd{v .} and @kbd{t .} before, type them again to
  6354. return to full-sized display of vectors.
  6355. @node List Answer 13, List Answer 14, List Answer 12, Answers to Exercises
  6356. @subsection List Tutorial Exercise 13
  6357. @noindent
  6358. First, we put the string on the stack as a vector of ASCII codes.
  6359. @smallexample
  6360. @group
  6361. 1: [84, 101, 115, ..., 51]
  6362. .
  6363. "Testing, 1, 2, 3 @key{RET}
  6364. @end group
  6365. @end smallexample
  6366. @noindent
  6367. Note that the @kbd{"} key, like @kbd{$}, initiates algebraic entry so
  6368. there was no need to type an apostrophe. Also, Calc didn't mind that
  6369. we omitted the closing @kbd{"}. (The same goes for all closing delimiters
  6370. like @kbd{)} and @kbd{]} at the end of a formula.
  6371. We'll show two different approaches here. In the first, we note that
  6372. if the input vector is @expr{[a, b, c, d]}, then the hash code is
  6373. @expr{3 (3 (3a + b) + c) + d = 27a + 9b + 3c + d}. In other words,
  6374. it's a sum of descending powers of three times the ASCII codes.
  6375. @smallexample
  6376. @group
  6377. 2: [84, 101, 115, ..., 51] 2: [84, 101, 115, ..., 51]
  6378. 1: 16 1: [15, 14, 13, ..., 0]
  6379. . .
  6380. @key{RET} v l v x 16 @key{RET} -
  6381. @end group
  6382. @end smallexample
  6383. @noindent
  6384. @smallexample
  6385. @group
  6386. 2: [84, 101, 115, ..., 51] 1: 1960915098 1: 121
  6387. 1: [14348907, ..., 1] . .
  6388. .
  6389. 3 @key{TAB} V M ^ * 511 %
  6390. @end group
  6391. @end smallexample
  6392. @noindent
  6393. Once again, @kbd{*} elegantly summarizes most of the computation.
  6394. But there's an even more elegant approach: Reduce the formula
  6395. @kbd{3 $$ + $} across the vector. Recall that this represents a
  6396. function of two arguments that computes its first argument times three
  6397. plus its second argument.
  6398. @smallexample
  6399. @group
  6400. 1: [84, 101, 115, ..., 51] 1: 1960915098
  6401. . .
  6402. "Testing, 1, 2, 3 @key{RET} V R ' 3$$+$ @key{RET}
  6403. @end group
  6404. @end smallexample
  6405. @noindent
  6406. If you did the decimal arithmetic exercise, this will be familiar.
  6407. Basically, we're turning a base-3 vector of digits into an integer,
  6408. except that our ``digits'' are much larger than real digits.
  6409. Instead of typing @kbd{511 %} again to reduce the result, we can be
  6410. cleverer still and notice that rather than computing a huge integer
  6411. and taking the modulo at the end, we can take the modulo at each step
  6412. without affecting the result. While this means there are more
  6413. arithmetic operations, the numbers we operate on remain small so
  6414. the operations are faster.
  6415. @smallexample
  6416. @group
  6417. 1: [84, 101, 115, ..., 51] 1: 121
  6418. . .
  6419. "Testing, 1, 2, 3 @key{RET} V R ' (3$$+$)%511 @key{RET}
  6420. @end group
  6421. @end smallexample
  6422. Why does this work? Think about a two-step computation:
  6423. @w{@expr{3 (3a + b) + c}}. Taking a result modulo 511 basically means
  6424. subtracting off enough 511's to put the result in the desired range.
  6425. So the result when we take the modulo after every step is,
  6426. @ifnottex
  6427. @example
  6428. 3 (3 a + b - 511 m) + c - 511 n
  6429. @end example
  6430. @end ifnottex
  6431. @tex
  6432. \beforedisplay
  6433. $$ 3 (3 a + b - 511 m) + c - 511 n $$
  6434. \afterdisplay
  6435. @end tex
  6436. @noindent
  6437. for some suitable integers @expr{m} and @expr{n}. Expanding out by
  6438. the distributive law yields
  6439. @ifnottex
  6440. @example
  6441. 9 a + 3 b + c - 511*3 m - 511 n
  6442. @end example
  6443. @end ifnottex
  6444. @tex
  6445. \beforedisplay
  6446. $$ 9 a + 3 b + c - 511\times3 m - 511 n $$
  6447. \afterdisplay
  6448. @end tex
  6449. @noindent
  6450. The @expr{m} term in the latter formula is redundant because any
  6451. contribution it makes could just as easily be made by the @expr{n}
  6452. term. So we can take it out to get an equivalent formula with
  6453. @expr{n' = 3m + n},
  6454. @ifnottex
  6455. @example
  6456. 9 a + 3 b + c - 511 n'
  6457. @end example
  6458. @end ifnottex
  6459. @tex
  6460. \beforedisplay
  6461. $$ 9 a + 3 b + c - 511 n^{\prime} $$
  6462. \afterdisplay
  6463. @end tex
  6464. @noindent
  6465. which is just the formula for taking the modulo only at the end of
  6466. the calculation. Therefore the two methods are essentially the same.
  6467. Later in the tutorial we will encounter @dfn{modulo forms}, which
  6468. basically automate the idea of reducing every intermediate result
  6469. modulo some value @var{m}.
  6470. @node List Answer 14, Types Answer 1, List Answer 13, Answers to Exercises
  6471. @subsection List Tutorial Exercise 14
  6472. We want to use @kbd{H V U} to nest a function which adds a random
  6473. step to an @expr{(x,y)} coordinate. The function is a bit long, but
  6474. otherwise the problem is quite straightforward.
  6475. @smallexample
  6476. @group
  6477. 2: [0, 0] 1: [ [ 0, 0 ]
  6478. 1: 50 [ 0.4288, -0.1695 ]
  6479. . [ -0.4787, -0.9027 ]
  6480. ...
  6481. [0,0] 50 H V U ' <# + [random(2.0)-1, random(2.0)-1]> @key{RET}
  6482. @end group
  6483. @end smallexample
  6484. Just as the text recommended, we used @samp{< >} nameless function
  6485. notation to keep the two @code{random} calls from being evaluated
  6486. before nesting even begins.
  6487. We now have a vector of @expr{[x, y]} sub-vectors, which by Calc's
  6488. rules acts like a matrix. We can transpose this matrix and unpack
  6489. to get a pair of vectors, @expr{x} and @expr{y}, suitable for graphing.
  6490. @smallexample
  6491. @group
  6492. 2: [ 0, 0.4288, -0.4787, ... ]
  6493. 1: [ 0, -0.1696, -0.9027, ... ]
  6494. .
  6495. v t v u g f
  6496. @end group
  6497. @end smallexample
  6498. Incidentally, because the @expr{x} and @expr{y} are completely
  6499. independent in this case, we could have done two separate commands
  6500. to create our @expr{x} and @expr{y} vectors of numbers directly.
  6501. To make a random walk of unit steps, we note that @code{sincos} of
  6502. a random direction exactly gives us an @expr{[x, y]} step of unit
  6503. length; in fact, the new nesting function is even briefer, though
  6504. we might want to lower the precision a bit for it.
  6505. @smallexample
  6506. @group
  6507. 2: [0, 0] 1: [ [ 0, 0 ]
  6508. 1: 50 [ 0.1318, 0.9912 ]
  6509. . [ -0.5965, 0.3061 ]
  6510. ...
  6511. [0,0] 50 m d p 6 @key{RET} H V U ' <# + sincos(random(360.0))> @key{RET}
  6512. @end group
  6513. @end smallexample
  6514. Another @kbd{v t v u g f} sequence will graph this new random walk.
  6515. An interesting twist on these random walk functions would be to use
  6516. complex numbers instead of 2-vectors to represent points on the plane.
  6517. In the first example, we'd use something like @samp{random + random*(0,1)},
  6518. and in the second we could use polar complex numbers with random phase
  6519. angles. (This exercise was first suggested in this form by Randal
  6520. Schwartz.)
  6521. @node Types Answer 1, Types Answer 2, List Answer 14, Answers to Exercises
  6522. @subsection Types Tutorial Exercise 1
  6523. @noindent
  6524. If the number is the square root of @cpi{} times a rational number,
  6525. then its square, divided by @cpi{}, should be a rational number.
  6526. @smallexample
  6527. @group
  6528. 1: 1.26508260337 1: 0.509433962268 1: 2486645810:4881193627
  6529. . . .
  6530. 2 ^ P / c F
  6531. @end group
  6532. @end smallexample
  6533. @noindent
  6534. Technically speaking this is a rational number, but not one that is
  6535. likely to have arisen in the original problem. More likely, it just
  6536. happens to be the fraction which most closely represents some
  6537. irrational number to within 12 digits.
  6538. But perhaps our result was not quite exact. Let's reduce the
  6539. precision slightly and try again:
  6540. @smallexample
  6541. @group
  6542. 1: 0.509433962268 1: 27:53
  6543. . .
  6544. U p 10 @key{RET} c F
  6545. @end group
  6546. @end smallexample
  6547. @noindent
  6548. Aha! It's unlikely that an irrational number would equal a fraction
  6549. this simple to within ten digits, so our original number was probably
  6550. @texline @math{\sqrt{27 \pi / 53}}.
  6551. @infoline @expr{sqrt(27 pi / 53)}.
  6552. Notice that we didn't need to re-round the number when we reduced the
  6553. precision. Remember, arithmetic operations always round their inputs
  6554. to the current precision before they begin.
  6555. @node Types Answer 2, Types Answer 3, Types Answer 1, Answers to Exercises
  6556. @subsection Types Tutorial Exercise 2
  6557. @noindent
  6558. @samp{inf / inf = nan}. Perhaps @samp{1} is the ``obvious'' answer.
  6559. But if @w{@samp{17 inf = inf}}, then @samp{17 inf / inf = inf / inf = 17}, too.
  6560. @samp{exp(inf) = inf}. It's tempting to say that the exponential
  6561. of infinity must be ``bigger'' than ``regular'' infinity, but as
  6562. far as Calc is concerned all infinities are the same size.
  6563. In other words, as @expr{x} goes to infinity, @expr{e^x} also goes
  6564. to infinity, but the fact the @expr{e^x} grows much faster than
  6565. @expr{x} is not relevant here.
  6566. @samp{exp(-inf) = 0}. Here we have a finite answer even though
  6567. the input is infinite.
  6568. @samp{sqrt(-inf) = (0, 1) inf}. Remember that @expr{(0, 1)}
  6569. represents the imaginary number @expr{i}. Here's a derivation:
  6570. @samp{sqrt(-inf) = @w{sqrt((-1) * inf)} = sqrt(-1) * sqrt(inf)}.
  6571. The first part is, by definition, @expr{i}; the second is @code{inf}
  6572. because, once again, all infinities are the same size.
  6573. @samp{sqrt(uinf) = uinf}. In fact, we do know something about the
  6574. direction because @code{sqrt} is defined to return a value in the
  6575. right half of the complex plane. But Calc has no notation for this,
  6576. so it settles for the conservative answer @code{uinf}.
  6577. @samp{abs(uinf) = inf}. No matter which direction @expr{x} points,
  6578. @samp{abs(x)} always points along the positive real axis.
  6579. @samp{ln(0) = -inf}. Here we have an infinite answer to a finite
  6580. input. As in the @expr{1 / 0} case, Calc will only use infinities
  6581. here if you have turned on Infinite mode. Otherwise, it will
  6582. treat @samp{ln(0)} as an error.
  6583. @node Types Answer 3, Types Answer 4, Types Answer 2, Answers to Exercises
  6584. @subsection Types Tutorial Exercise 3
  6585. @noindent
  6586. We can make @samp{inf - inf} be any real number we like, say,
  6587. @expr{a}, just by claiming that we added @expr{a} to the first
  6588. infinity but not to the second. This is just as true for complex
  6589. values of @expr{a}, so @code{nan} can stand for a complex number.
  6590. (And, similarly, @code{uinf} can stand for an infinity that points
  6591. in any direction in the complex plane, such as @samp{(0, 1) inf}).
  6592. In fact, we can multiply the first @code{inf} by two. Surely
  6593. @w{@samp{2 inf - inf = inf}}, but also @samp{2 inf - inf = inf - inf = nan}.
  6594. So @code{nan} can even stand for infinity. Obviously it's just
  6595. as easy to make it stand for minus infinity as for plus infinity.
  6596. The moral of this story is that ``infinity'' is a slippery fish
  6597. indeed, and Calc tries to handle it by having a very simple model
  6598. for infinities (only the direction counts, not the ``size''); but
  6599. Calc is careful to write @code{nan} any time this simple model is
  6600. unable to tell what the true answer is.
  6601. @node Types Answer 4, Types Answer 5, Types Answer 3, Answers to Exercises
  6602. @subsection Types Tutorial Exercise 4
  6603. @smallexample
  6604. @group
  6605. 2: 0@@ 47' 26" 1: 0@@ 2' 47.411765"
  6606. 1: 17 .
  6607. .
  6608. 0@@ 47' 26" @key{RET} 17 /
  6609. @end group
  6610. @end smallexample
  6611. @noindent
  6612. The average song length is two minutes and 47.4 seconds.
  6613. @smallexample
  6614. @group
  6615. 2: 0@@ 2' 47.411765" 1: 0@@ 3' 7.411765" 1: 0@@ 53' 6.000005"
  6616. 1: 0@@ 0' 20" . .
  6617. .
  6618. 20" + 17 *
  6619. @end group
  6620. @end smallexample
  6621. @noindent
  6622. The album would be 53 minutes and 6 seconds long.
  6623. @node Types Answer 5, Types Answer 6, Types Answer 4, Answers to Exercises
  6624. @subsection Types Tutorial Exercise 5
  6625. @noindent
  6626. Let's suppose it's January 14, 1991. The easiest thing to do is
  6627. to keep trying 13ths of months until Calc reports a Friday.
  6628. We can do this by manually entering dates, or by using @kbd{t I}:
  6629. @smallexample
  6630. @group
  6631. 1: <Wed Feb 13, 1991> 1: <Wed Mar 13, 1991> 1: <Sat Apr 13, 1991>
  6632. . . .
  6633. ' <2/13> @key{RET} @key{DEL} ' <3/13> @key{RET} t I
  6634. @end group
  6635. @end smallexample
  6636. @noindent
  6637. (Calc assumes the current year if you don't say otherwise.)
  6638. This is getting tedious---we can keep advancing the date by typing
  6639. @kbd{t I} over and over again, but let's automate the job by using
  6640. vector mapping. The @kbd{t I} command actually takes a second
  6641. ``how-many-months'' argument, which defaults to one. This
  6642. argument is exactly what we want to map over:
  6643. @smallexample
  6644. @group
  6645. 2: <Sat Apr 13, 1991> 1: [<Mon May 13, 1991>, <Thu Jun 13, 1991>,
  6646. 1: [1, 2, 3, 4, 5, 6] <Sat Jul 13, 1991>, <Tue Aug 13, 1991>,
  6647. . <Fri Sep 13, 1991>, <Sun Oct 13, 1991>]
  6648. .
  6649. v x 6 @key{RET} V M t I
  6650. @end group
  6651. @end smallexample
  6652. @noindent
  6653. Et voilà, September 13, 1991 is a Friday.
  6654. @smallexample
  6655. @group
  6656. 1: 242
  6657. .
  6658. ' <sep 13> - <jan 14> @key{RET}
  6659. @end group
  6660. @end smallexample
  6661. @noindent
  6662. And the answer to our original question: 242 days to go.
  6663. @node Types Answer 6, Types Answer 7, Types Answer 5, Answers to Exercises
  6664. @subsection Types Tutorial Exercise 6
  6665. @noindent
  6666. The full rule for leap years is that they occur in every year divisible
  6667. by four, except that they don't occur in years divisible by 100, except
  6668. that they @emph{do} in years divisible by 400. We could work out the
  6669. answer by carefully counting the years divisible by four and the
  6670. exceptions, but there is a much simpler way that works even if we
  6671. don't know the leap year rule.
  6672. Let's assume the present year is 1991. Years have 365 days, except
  6673. that leap years (whenever they occur) have 366 days. So let's count
  6674. the number of days between now and then, and compare that to the
  6675. number of years times 365. The number of extra days we find must be
  6676. equal to the number of leap years there were.
  6677. @smallexample
  6678. @group
  6679. 1: <Mon Jan 1, 10001> 2: <Mon Jan 1, 10001> 1: 2925593
  6680. . 1: <Tue Jan 1, 1991> .
  6681. .
  6682. ' <jan 1 10001> @key{RET} ' <jan 1 1991> @key{RET} -
  6683. @end group
  6684. @end smallexample
  6685. @noindent
  6686. @smallexample
  6687. @group
  6688. 3: 2925593 2: 2925593 2: 2925593 1: 1943
  6689. 2: 10001 1: 8010 1: 2923650 .
  6690. 1: 1991 . .
  6691. .
  6692. 10001 @key{RET} 1991 - 365 * -
  6693. @end group
  6694. @end smallexample
  6695. @c [fix-ref Date Forms]
  6696. @noindent
  6697. There will be 1943 leap years before the year 10001. (Assuming,
  6698. of course, that the algorithm for computing leap years remains
  6699. unchanged for that long. @xref{Date Forms}, for some interesting
  6700. background information in that regard.)
  6701. @node Types Answer 7, Types Answer 8, Types Answer 6, Answers to Exercises
  6702. @subsection Types Tutorial Exercise 7
  6703. @noindent
  6704. The relative errors must be converted to absolute errors so that
  6705. @samp{+/-} notation may be used.
  6706. @smallexample
  6707. @group
  6708. 1: 1. 2: 1.
  6709. . 1: 0.2
  6710. .
  6711. 20 @key{RET} .05 * 4 @key{RET} .05 *
  6712. @end group
  6713. @end smallexample
  6714. Now we simply chug through the formula.
  6715. @smallexample
  6716. @group
  6717. 1: 19.7392088022 1: 394.78 +/- 19.739 1: 6316.5 +/- 706.21
  6718. . . .
  6719. 2 P 2 ^ * 20 p 1 * 4 p .2 @key{RET} 2 ^ *
  6720. @end group
  6721. @end smallexample
  6722. It turns out the @kbd{v u} command will unpack an error form as
  6723. well as a vector. This saves us some retyping of numbers.
  6724. @smallexample
  6725. @group
  6726. 3: 6316.5 +/- 706.21 2: 6316.5 +/- 706.21
  6727. 2: 6316.5 1: 0.1118
  6728. 1: 706.21 .
  6729. .
  6730. @key{RET} v u @key{TAB} /
  6731. @end group
  6732. @end smallexample
  6733. @noindent
  6734. Thus the volume is 6316 cubic centimeters, within about 11 percent.
  6735. @node Types Answer 8, Types Answer 9, Types Answer 7, Answers to Exercises
  6736. @subsection Types Tutorial Exercise 8
  6737. @noindent
  6738. The first answer is pretty simple: @samp{1 / (0 .. 10) = (0.1 .. inf)}.
  6739. Since a number in the interval @samp{(0 .. 10)} can get arbitrarily
  6740. close to zero, its reciprocal can get arbitrarily large, so the answer
  6741. is an interval that effectively means, ``any number greater than 0.1''
  6742. but with no upper bound.
  6743. The second answer, similarly, is @samp{1 / (-10 .. 0) = (-inf .. -0.1)}.
  6744. Calc normally treats division by zero as an error, so that the formula
  6745. @w{@samp{1 / 0}} is left unsimplified. Our third problem,
  6746. @w{@samp{1 / [0 .. 10]}}, also (potentially) divides by zero because zero
  6747. is now a member of the interval. So Calc leaves this one unevaluated, too.
  6748. If you turn on Infinite mode by pressing @kbd{m i}, you will
  6749. instead get the answer @samp{[0.1 .. inf]}, which includes infinity
  6750. as a possible value.
  6751. The fourth calculation, @samp{1 / (-10 .. 10)}, has the same problem.
  6752. Zero is buried inside the interval, but it's still a possible value.
  6753. It's not hard to see that the actual result of @samp{1 / (-10 .. 10)}
  6754. will be either greater than @mathit{0.1}, or less than @mathit{-0.1}. Thus
  6755. the interval goes from minus infinity to plus infinity, with a ``hole''
  6756. in it from @mathit{-0.1} to @mathit{0.1}. Calc doesn't have any way to
  6757. represent this, so it just reports @samp{[-inf .. inf]} as the answer.
  6758. It may be disappointing to hear ``the answer lies somewhere between
  6759. minus infinity and plus infinity, inclusive,'' but that's the best
  6760. that interval arithmetic can do in this case.
  6761. @node Types Answer 9, Types Answer 10, Types Answer 8, Answers to Exercises
  6762. @subsection Types Tutorial Exercise 9
  6763. @smallexample
  6764. @group
  6765. 1: [-3 .. 3] 2: [-3 .. 3] 2: [0 .. 9]
  6766. . 1: [0 .. 9] 1: [-9 .. 9]
  6767. . .
  6768. [ 3 n .. 3 ] @key{RET} 2 ^ @key{TAB} @key{RET} *
  6769. @end group
  6770. @end smallexample
  6771. @noindent
  6772. In the first case the result says, ``if a number is between @mathit{-3} and
  6773. 3, its square is between 0 and 9.'' The second case says, ``the product
  6774. of two numbers each between @mathit{-3} and 3 is between @mathit{-9} and 9.''
  6775. An interval form is not a number; it is a symbol that can stand for
  6776. many different numbers. Two identical-looking interval forms can stand
  6777. for different numbers.
  6778. The same issue arises when you try to square an error form.
  6779. @node Types Answer 10, Types Answer 11, Types Answer 9, Answers to Exercises
  6780. @subsection Types Tutorial Exercise 10
  6781. @noindent
  6782. Testing the first number, we might arbitrarily choose 17 for @expr{x}.
  6783. @smallexample
  6784. @group
  6785. 1: 17 mod 811749613 2: 17 mod 811749613 1: 533694123 mod 811749613
  6786. . 811749612 .
  6787. .
  6788. 17 M 811749613 @key{RET} 811749612 ^
  6789. @end group
  6790. @end smallexample
  6791. @noindent
  6792. Since 533694123 is (considerably) different from 1, the number 811749613
  6793. must not be prime.
  6794. It's awkward to type the number in twice as we did above. There are
  6795. various ways to avoid this, and algebraic entry is one. In fact, using
  6796. a vector mapping operation we can perform several tests at once. Let's
  6797. use this method to test the second number.
  6798. @smallexample
  6799. @group
  6800. 2: [17, 42, 100000] 1: [1 mod 15485863, 1 mod ... ]
  6801. 1: 15485863 .
  6802. .
  6803. [17 42 100000] 15485863 @key{RET} V M ' ($$ mod $)^($-1) @key{RET}
  6804. @end group
  6805. @end smallexample
  6806. @noindent
  6807. The result is three ones (modulo @expr{n}), so it's very probable that
  6808. 15485863 is prime. (In fact, this number is the millionth prime.)
  6809. Note that the functions @samp{($$^($-1)) mod $} or @samp{$$^($-1) % $}
  6810. would have been hopelessly inefficient, since they would have calculated
  6811. the power using full integer arithmetic.
  6812. Calc has a @kbd{k p} command that does primality testing. For small
  6813. numbers it does an exact test; for large numbers it uses a variant
  6814. of the Fermat test we used here. You can use @kbd{k p} repeatedly
  6815. to prove that a large integer is prime with any desired probability.
  6816. @node Types Answer 11, Types Answer 12, Types Answer 10, Answers to Exercises
  6817. @subsection Types Tutorial Exercise 11
  6818. @noindent
  6819. There are several ways to insert a calculated number into an HMS form.
  6820. One way to convert a number of seconds to an HMS form is simply to
  6821. multiply the number by an HMS form representing one second:
  6822. @smallexample
  6823. @group
  6824. 1: 31415926.5359 2: 31415926.5359 1: 8726@@ 38' 46.5359"
  6825. . 1: 0@@ 0' 1" .
  6826. .
  6827. P 1e7 * 0@@ 0' 1" *
  6828. @end group
  6829. @end smallexample
  6830. @noindent
  6831. @smallexample
  6832. @group
  6833. 2: 8726@@ 38' 46.5359" 1: 6@@ 6' 2.5359" mod 24@@ 0' 0"
  6834. 1: 15@@ 27' 16" mod 24@@ 0' 0" .
  6835. .
  6836. x time @key{RET} +
  6837. @end group
  6838. @end smallexample
  6839. @noindent
  6840. It will be just after six in the morning.
  6841. The algebraic @code{hms} function can also be used to build an
  6842. HMS form:
  6843. @smallexample
  6844. @group
  6845. 1: hms(0, 0, 10000000. pi) 1: 8726@@ 38' 46.5359"
  6846. . .
  6847. ' hms(0, 0, 1e7 pi) @key{RET} =
  6848. @end group
  6849. @end smallexample
  6850. @noindent
  6851. The @kbd{=} key is necessary to evaluate the symbol @samp{pi} to
  6852. the actual number 3.14159...
  6853. @node Types Answer 12, Types Answer 13, Types Answer 11, Answers to Exercises
  6854. @subsection Types Tutorial Exercise 12
  6855. @noindent
  6856. As we recall, there are 17 songs of about 2 minutes and 47 seconds
  6857. each.
  6858. @smallexample
  6859. @group
  6860. 2: 0@@ 2' 47" 1: [0@@ 3' 7" .. 0@@ 3' 47"]
  6861. 1: [0@@ 0' 20" .. 0@@ 1' 0"] .
  6862. .
  6863. [ 0@@ 20" .. 0@@ 1' ] +
  6864. @end group
  6865. @end smallexample
  6866. @noindent
  6867. @smallexample
  6868. @group
  6869. 1: [0@@ 52' 59." .. 1@@ 4' 19."]
  6870. .
  6871. 17 *
  6872. @end group
  6873. @end smallexample
  6874. @noindent
  6875. No matter how long it is, the album will fit nicely on one CD.
  6876. @node Types Answer 13, Types Answer 14, Types Answer 12, Answers to Exercises
  6877. @subsection Types Tutorial Exercise 13
  6878. @noindent
  6879. Type @kbd{' 1 yr @key{RET} u c s @key{RET}}. The answer is 31557600 seconds.
  6880. @node Types Answer 14, Types Answer 15, Types Answer 13, Answers to Exercises
  6881. @subsection Types Tutorial Exercise 14
  6882. @noindent
  6883. How long will it take for a signal to get from one end of the computer
  6884. to the other?
  6885. @smallexample
  6886. @group
  6887. 1: m / c 1: 3.3356 ns
  6888. . .
  6889. ' 1 m / c @key{RET} u c ns @key{RET}
  6890. @end group
  6891. @end smallexample
  6892. @noindent
  6893. (Recall, @samp{c} is a ``unit'' corresponding to the speed of light.)
  6894. @smallexample
  6895. @group
  6896. 1: 3.3356 ns 1: 0.81356
  6897. 2: 4.1 ns .
  6898. .
  6899. ' 4.1 ns @key{RET} /
  6900. @end group
  6901. @end smallexample
  6902. @noindent
  6903. Thus a signal could take up to 81 percent of a clock cycle just to
  6904. go from one place to another inside the computer, assuming the signal
  6905. could actually attain the full speed of light. Pretty tight!
  6906. @node Types Answer 15, Algebra Answer 1, Types Answer 14, Answers to Exercises
  6907. @subsection Types Tutorial Exercise 15
  6908. @noindent
  6909. The speed limit is 55 miles per hour on most highways. We want to
  6910. find the ratio of Sam's speed to the US speed limit.
  6911. @smallexample
  6912. @group
  6913. 1: 55 mph 2: 55 mph 3: 11 hr mph / yd
  6914. . 1: 5 yd / hr .
  6915. .
  6916. ' 55 mph @key{RET} ' 5 yd/hr @key{RET} /
  6917. @end group
  6918. @end smallexample
  6919. The @kbd{u s} command cancels out these units to get a plain
  6920. number. Now we take the logarithm base two to find the final
  6921. answer, assuming that each successive pill doubles his speed.
  6922. @smallexample
  6923. @group
  6924. 1: 19360. 2: 19360. 1: 14.24
  6925. . 1: 2 .
  6926. .
  6927. u s 2 B
  6928. @end group
  6929. @end smallexample
  6930. @noindent
  6931. Thus Sam can take up to 14 pills without a worry.
  6932. @node Algebra Answer 1, Algebra Answer 2, Types Answer 15, Answers to Exercises
  6933. @subsection Algebra Tutorial Exercise 1
  6934. @noindent
  6935. @c [fix-ref Declarations]
  6936. The result @samp{sqrt(x)^2} is simplified back to @expr{x} by the
  6937. Calculator, but @samp{sqrt(x^2)} is not. (Consider what happens
  6938. if @w{@expr{x = -4}}.) If @expr{x} is real, this formula could be
  6939. simplified to @samp{abs(x)}, but for general complex arguments even
  6940. that is not safe. (@xref{Declarations}, for a way to tell Calc
  6941. that @expr{x} is known to be real.)
  6942. @node Algebra Answer 2, Algebra Answer 3, Algebra Answer 1, Answers to Exercises
  6943. @subsection Algebra Tutorial Exercise 2
  6944. @noindent
  6945. Suppose our roots are @expr{[a, b, c]}. We want a polynomial which
  6946. is zero when @expr{x} is any of these values. The trivial polynomial
  6947. @expr{x-a} is zero when @expr{x=a}, so the product @expr{(x-a)(x-b)(x-c)}
  6948. will do the job. We can use @kbd{a c x} to write this in a more
  6949. familiar form.
  6950. @smallexample
  6951. @group
  6952. 1: 34 x - 24 x^3 1: [1.19023, -1.19023, 0]
  6953. . .
  6954. r 2 a P x @key{RET}
  6955. @end group
  6956. @end smallexample
  6957. @noindent
  6958. @smallexample
  6959. @group
  6960. 1: [x - 1.19023, x + 1.19023, x] 1: x*(x + 1.19023) (x - 1.19023)
  6961. . .
  6962. V M ' x-$ @key{RET} V R *
  6963. @end group
  6964. @end smallexample
  6965. @noindent
  6966. @smallexample
  6967. @group
  6968. 1: x^3 - 1.41666 x 1: 34 x - 24 x^3
  6969. . .
  6970. a c x @key{RET} 24 n * a x
  6971. @end group
  6972. @end smallexample
  6973. @noindent
  6974. Sure enough, our answer (multiplied by a suitable constant) is the
  6975. same as the original polynomial.
  6976. @node Algebra Answer 3, Algebra Answer 4, Algebra Answer 2, Answers to Exercises
  6977. @subsection Algebra Tutorial Exercise 3
  6978. @smallexample
  6979. @group
  6980. 1: x sin(pi x) 1: sin(pi x) / pi^2 - x cos(pi x) / pi
  6981. . .
  6982. ' x sin(pi x) @key{RET} m r a i x @key{RET}
  6983. @end group
  6984. @end smallexample
  6985. @noindent
  6986. @smallexample
  6987. @group
  6988. 1: [y, 1]
  6989. 2: sin(pi x) / pi^2 - x cos(pi x) / pi
  6990. .
  6991. ' [y,1] @key{RET} @key{TAB}
  6992. @end group
  6993. @end smallexample
  6994. @noindent
  6995. @smallexample
  6996. @group
  6997. 1: [sin(pi y) / pi^2 - y cos(pi y) / pi, 1 / pi]
  6998. .
  6999. V M $ @key{RET}
  7000. @end group
  7001. @end smallexample
  7002. @noindent
  7003. @smallexample
  7004. @group
  7005. 1: sin(pi y) / pi^2 - y cos(pi y) / pi - 1 / pi
  7006. .
  7007. V R -
  7008. @end group
  7009. @end smallexample
  7010. @noindent
  7011. @smallexample
  7012. @group
  7013. 1: sin(3.14159 y) / 9.8696 - y cos(3.14159 y) / 3.14159 - 0.3183
  7014. .
  7015. =
  7016. @end group
  7017. @end smallexample
  7018. @noindent
  7019. @smallexample
  7020. @group
  7021. 1: [0., -0.95493, 0.63662, -1.5915, 1.2732]
  7022. .
  7023. v x 5 @key{RET} @key{TAB} V M $ @key{RET}
  7024. @end group
  7025. @end smallexample
  7026. @node Algebra Answer 4, Rewrites Answer 1, Algebra Answer 3, Answers to Exercises
  7027. @subsection Algebra Tutorial Exercise 4
  7028. @noindent
  7029. The hard part is that @kbd{V R +} is no longer sufficient to add up all
  7030. the contributions from the slices, since the slices have varying
  7031. coefficients. So first we must come up with a vector of these
  7032. coefficients. Here's one way:
  7033. @smallexample
  7034. @group
  7035. 2: -1 2: 3 1: [4, 2, ..., 4]
  7036. 1: [1, 2, ..., 9] 1: [-1, 1, ..., -1] .
  7037. . .
  7038. 1 n v x 9 @key{RET} V M ^ 3 @key{TAB} -
  7039. @end group
  7040. @end smallexample
  7041. @noindent
  7042. @smallexample
  7043. @group
  7044. 1: [4, 2, ..., 4, 1] 1: [1, 4, 2, ..., 4, 1]
  7045. . .
  7046. 1 | 1 @key{TAB} |
  7047. @end group
  7048. @end smallexample
  7049. @noindent
  7050. Now we compute the function values. Note that for this method we need
  7051. eleven values, including both endpoints of the desired interval.
  7052. @smallexample
  7053. @group
  7054. 2: [1, 4, 2, ..., 4, 1]
  7055. 1: [1, 1.1, 1.2, ... , 1.8, 1.9, 2.]
  7056. .
  7057. 11 @key{RET} 1 @key{RET} .1 @key{RET} C-u v x
  7058. @end group
  7059. @end smallexample
  7060. @noindent
  7061. @smallexample
  7062. @group
  7063. 2: [1, 4, 2, ..., 4, 1]
  7064. 1: [0., 0.084941, 0.16993, ... ]
  7065. .
  7066. ' sin(x) ln(x) @key{RET} m r p 5 @key{RET} V M $ @key{RET}
  7067. @end group
  7068. @end smallexample
  7069. @noindent
  7070. Once again this calls for @kbd{V M * V R +}; a simple @kbd{*} does the
  7071. same thing.
  7072. @smallexample
  7073. @group
  7074. 1: 11.22 1: 1.122 1: 0.374
  7075. . . .
  7076. * .1 * 3 /
  7077. @end group
  7078. @end smallexample
  7079. @noindent
  7080. Wow! That's even better than the result from the Taylor series method.
  7081. @node Rewrites Answer 1, Rewrites Answer 2, Algebra Answer 4, Answers to Exercises
  7082. @subsection Rewrites Tutorial Exercise 1
  7083. @noindent
  7084. We'll use Big mode to make the formulas more readable.
  7085. @smallexample
  7086. @group
  7087. ___
  7088. V 2 + 2
  7089. 1: (2 + sqrt(2)) / (1 + sqrt(2)) 1: ---------
  7090. . ___
  7091. V 2 + 1
  7092. .
  7093. ' (2+sqrt(2)) / (1+sqrt(2)) @key{RET} d B
  7094. @end group
  7095. @end smallexample
  7096. @noindent
  7097. Multiplying by the conjugate helps because @expr{(a+b) (a-b) = a^2 - b^2}.
  7098. @smallexample
  7099. @group
  7100. ___ ___
  7101. 1: (2 + V 2 ) (V 2 - 1)
  7102. .
  7103. a r a/(b+c) := a*(b-c) / (b^2-c^2) @key{RET}
  7104. @end group
  7105. @end smallexample
  7106. @noindent
  7107. @smallexample
  7108. @group
  7109. ___
  7110. 1: V 2
  7111. .
  7112. a r a*(b+c) := a*b + a*c
  7113. @end group
  7114. @end smallexample
  7115. @noindent
  7116. (We could have used @kbd{a x} instead of a rewrite rule for the
  7117. second step.)
  7118. The multiply-by-conjugate rule turns out to be useful in many
  7119. different circumstances, such as when the denominator involves
  7120. sines and cosines or the imaginary constant @code{i}.
  7121. @node Rewrites Answer 2, Rewrites Answer 3, Rewrites Answer 1, Answers to Exercises
  7122. @subsection Rewrites Tutorial Exercise 2
  7123. @noindent
  7124. Here is the rule set:
  7125. @smallexample
  7126. @group
  7127. [ fib(n) := fib(n, 1, 1) :: integer(n) :: n >= 1,
  7128. fib(1, x, y) := x,
  7129. fib(n, x, y) := fib(n-1, y, x+y) ]
  7130. @end group
  7131. @end smallexample
  7132. @noindent
  7133. The first rule turns a one-argument @code{fib} that people like to write
  7134. into a three-argument @code{fib} that makes computation easier. The
  7135. second rule converts back from three-argument form once the computation
  7136. is done. The third rule does the computation itself. It basically
  7137. says that if @expr{x} and @expr{y} are two consecutive Fibonacci numbers,
  7138. then @expr{y} and @expr{x+y} are the next (overlapping) pair of Fibonacci
  7139. numbers.
  7140. Notice that because the number @expr{n} was ``validated'' by the
  7141. conditions on the first rule, there is no need to put conditions on
  7142. the other rules because the rule set would never get that far unless
  7143. the input were valid. That further speeds computation, since no
  7144. extra conditions need to be checked at every step.
  7145. Actually, a user with a nasty sense of humor could enter a bad
  7146. three-argument @code{fib} call directly, say, @samp{fib(0, 1, 1)},
  7147. which would get the rules into an infinite loop. One thing that would
  7148. help keep this from happening by accident would be to use something like
  7149. @samp{ZzFib} instead of @code{fib} as the name of the three-argument
  7150. function.
  7151. @node Rewrites Answer 3, Rewrites Answer 4, Rewrites Answer 2, Answers to Exercises
  7152. @subsection Rewrites Tutorial Exercise 3
  7153. @noindent
  7154. He got an infinite loop. First, Calc did as expected and rewrote
  7155. @w{@samp{2 + 3 x}} to @samp{f(2, 3, x)}. Then it looked for ways to
  7156. apply the rule again, and found that @samp{f(2, 3, x)} looks like
  7157. @samp{a + b x} with @w{@samp{a = 0}} and @samp{b = 1}, so it rewrote to
  7158. @samp{f(0, 1, f(2, 3, x))}. It then wrapped another @samp{f(0, 1, ...)}
  7159. around that, and so on, ad infinitum. Joe should have used @kbd{M-1 a r}
  7160. to make sure the rule applied only once.
  7161. (Actually, even the first step didn't work as he expected. What Calc
  7162. really gives for @kbd{M-1 a r} in this situation is @samp{f(3 x, 1, 2)},
  7163. treating 2 as the ``variable,'' and @samp{3 x} as a constant being added
  7164. to it. While this may seem odd, it's just as valid a solution as the
  7165. ``obvious'' one. One way to fix this would be to add the condition
  7166. @samp{:: variable(x)} to the rule, to make sure the thing that matches
  7167. @samp{x} is indeed a variable, or to change @samp{x} to @samp{quote(x)}
  7168. on the lefthand side, so that the rule matches the actual variable
  7169. @samp{x} rather than letting @samp{x} stand for something else.)
  7170. @node Rewrites Answer 4, Rewrites Answer 5, Rewrites Answer 3, Answers to Exercises
  7171. @subsection Rewrites Tutorial Exercise 4
  7172. @noindent
  7173. @ignore
  7174. @starindex
  7175. @end ignore
  7176. @tindex seq
  7177. Here is a suitable set of rules to solve the first part of the problem:
  7178. @smallexample
  7179. @group
  7180. [ seq(n, c) := seq(n/2, c+1) :: n%2 = 0,
  7181. seq(n, c) := seq(3n+1, c+1) :: n%2 = 1 :: n > 1 ]
  7182. @end group
  7183. @end smallexample
  7184. Given the initial formula @samp{seq(6, 0)}, application of these
  7185. rules produces the following sequence of formulas:
  7186. @example
  7187. seq( 3, 1)
  7188. seq(10, 2)
  7189. seq( 5, 3)
  7190. seq(16, 4)
  7191. seq( 8, 5)
  7192. seq( 4, 6)
  7193. seq( 2, 7)
  7194. seq( 1, 8)
  7195. @end example
  7196. @noindent
  7197. whereupon neither of the rules match, and rewriting stops.
  7198. We can pretty this up a bit with a couple more rules:
  7199. @smallexample
  7200. @group
  7201. [ seq(n) := seq(n, 0),
  7202. seq(1, c) := c,
  7203. ... ]
  7204. @end group
  7205. @end smallexample
  7206. @noindent
  7207. Now, given @samp{seq(6)} as the starting configuration, we get 8
  7208. as the result.
  7209. The change to return a vector is quite simple:
  7210. @smallexample
  7211. @group
  7212. [ seq(n) := seq(n, []) :: integer(n) :: n > 0,
  7213. seq(1, v) := v | 1,
  7214. seq(n, v) := seq(n/2, v | n) :: n%2 = 0,
  7215. seq(n, v) := seq(3n+1, v | n) :: n%2 = 1 ]
  7216. @end group
  7217. @end smallexample
  7218. @noindent
  7219. Given @samp{seq(6)}, the result is @samp{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
  7220. Notice that the @expr{n > 1} guard is no longer necessary on the last
  7221. rule since the @expr{n = 1} case is now detected by another rule.
  7222. But a guard has been added to the initial rule to make sure the
  7223. initial value is suitable before the computation begins.
  7224. While still a good idea, this guard is not as vitally important as it
  7225. was for the @code{fib} function, since calling, say, @samp{seq(x, [])}
  7226. will not get into an infinite loop. Calc will not be able to prove
  7227. the symbol @samp{x} is either even or odd, so none of the rules will
  7228. apply and the rewrites will stop right away.
  7229. @node Rewrites Answer 5, Rewrites Answer 6, Rewrites Answer 4, Answers to Exercises
  7230. @subsection Rewrites Tutorial Exercise 5
  7231. @noindent
  7232. @ignore
  7233. @starindex
  7234. @end ignore
  7235. @tindex nterms
  7236. If @expr{x} is the sum @expr{a + b}, then `@tfn{nterms(}@var{x}@tfn{)}' must
  7237. be `@tfn{nterms(}@var{a}@tfn{)}' plus `@tfn{nterms(}@var{b}@tfn{)}'. If @expr{x}
  7238. is not a sum, then `@tfn{nterms(}@var{x}@tfn{)}' = 1.
  7239. @smallexample
  7240. @group
  7241. [ nterms(a + b) := nterms(a) + nterms(b),
  7242. nterms(x) := 1 ]
  7243. @end group
  7244. @end smallexample
  7245. @noindent
  7246. Here we have taken advantage of the fact that earlier rules always
  7247. match before later rules; @samp{nterms(x)} will only be tried if we
  7248. already know that @samp{x} is not a sum.
  7249. @node Rewrites Answer 6, Programming Answer 1, Rewrites Answer 5, Answers to Exercises
  7250. @subsection Rewrites Tutorial Exercise 6
  7251. @noindent
  7252. Here is a rule set that will do the job:
  7253. @smallexample
  7254. @group
  7255. [ a*(b + c) := a*b + a*c,
  7256. opt(a) O(x^n) + opt(b) O(x^m) := O(x^n) :: n <= m
  7257. :: constant(a) :: constant(b),
  7258. opt(a) O(x^n) + opt(b) x^m := O(x^n) :: n <= m
  7259. :: constant(a) :: constant(b),
  7260. a O(x^n) := O(x^n) :: constant(a),
  7261. x^opt(m) O(x^n) := O(x^(n+m)),
  7262. O(x^n) O(x^m) := O(x^(n+m)) ]
  7263. @end group
  7264. @end smallexample
  7265. If we really want the @kbd{+} and @kbd{*} keys to operate naturally
  7266. on power series, we should put these rules in @code{EvalRules}. For
  7267. testing purposes, it is better to put them in a different variable,
  7268. say, @code{O}, first.
  7269. The first rule just expands products of sums so that the rest of the
  7270. rules can assume they have an expanded-out polynomial to work with.
  7271. Note that this rule does not mention @samp{O} at all, so it will
  7272. apply to any product-of-sum it encounters---this rule may surprise
  7273. you if you put it into @code{EvalRules}!
  7274. In the second rule, the sum of two O's is changed to the smaller O@.
  7275. The optional constant coefficients are there mostly so that
  7276. @samp{O(x^2) - O(x^3)} and @samp{O(x^3) - O(x^2)} are handled
  7277. as well as @samp{O(x^2) + O(x^3)}.
  7278. The third rule absorbs higher powers of @samp{x} into O's.
  7279. The fourth rule says that a constant times a negligible quantity
  7280. is still negligible. (This rule will also match @samp{O(x^3) / 4},
  7281. with @samp{a = 1/4}.)
  7282. The fifth rule rewrites, for example, @samp{x^2 O(x^3)} to @samp{O(x^5)}.
  7283. (It is easy to see that if one of these forms is negligible, the other
  7284. is, too.) Notice the @samp{x^opt(m)} to pick up terms like
  7285. @w{@samp{x O(x^3)}}. Optional powers will match @samp{x} as @samp{x^1}
  7286. but not 1 as @samp{x^0}. This turns out to be exactly what we want here.
  7287. The sixth rule is the corresponding rule for products of two O's.
  7288. Another way to solve this problem would be to create a new ``data type''
  7289. that represents truncated power series. We might represent these as
  7290. function calls @samp{series(@var{coefs}, @var{x})} where @var{coefs} is
  7291. a vector of coefficients for @expr{x^0}, @expr{x^1}, @expr{x^2}, and so
  7292. on. Rules would exist for sums and products of such @code{series}
  7293. objects, and as an optional convenience could also know how to combine a
  7294. @code{series} object with a normal polynomial. (With this, and with a
  7295. rule that rewrites @samp{O(x^n)} to the equivalent @code{series} form,
  7296. you could still enter power series in exactly the same notation as
  7297. before.) Operations on such objects would probably be more efficient,
  7298. although the objects would be a bit harder to read.
  7299. @c [fix-ref Compositions]
  7300. Some other symbolic math programs provide a power series data type
  7301. similar to this. Mathematica, for example, has an object that looks
  7302. like @samp{PowerSeries[@var{x}, @var{x0}, @var{coefs}, @var{nmin},
  7303. @var{nmax}, @var{den}]}, where @var{x0} is the point about which the
  7304. power series is taken (we've been assuming this was always zero),
  7305. and @var{nmin}, @var{nmax}, and @var{den} allow pseudo-power-series
  7306. with fractional or negative powers. Also, the @code{PowerSeries}
  7307. objects have a special display format that makes them look like
  7308. @samp{2 x^2 + O(x^4)} when they are printed out. (@xref{Compositions},
  7309. for a way to do this in Calc, although for something as involved as
  7310. this it would probably be better to write the formatting routine
  7311. in Lisp.)
  7312. @node Programming Answer 1, Programming Answer 2, Rewrites Answer 6, Answers to Exercises
  7313. @subsection Programming Tutorial Exercise 1
  7314. @noindent
  7315. Just enter the formula @samp{ninteg(sin(t)/t, t, 0, x)}, type
  7316. @kbd{Z F}, and answer the questions. Since this formula contains two
  7317. variables, the default argument list will be @samp{(t x)}. We want to
  7318. change this to @samp{(x)} since @expr{t} is really a dummy variable
  7319. to be used within @code{ninteg}.
  7320. The exact keystrokes are @kbd{Z F s Si @key{RET} @key{RET} C-b C-b @key{DEL} @key{DEL} @key{RET} y}.
  7321. (The @kbd{C-b C-b @key{DEL} @key{DEL}} are what fix the argument list.)
  7322. @node Programming Answer 2, Programming Answer 3, Programming Answer 1, Answers to Exercises
  7323. @subsection Programming Tutorial Exercise 2
  7324. @noindent
  7325. One way is to move the number to the top of the stack, operate on
  7326. it, then move it back: @kbd{C-x ( M-@key{TAB} n M-@key{TAB} M-@key{TAB} C-x )}.
  7327. Another way is to negate the top three stack entries, then negate
  7328. again the top two stack entries: @kbd{C-x ( M-3 n M-2 n C-x )}.
  7329. Finally, it turns out that a negative prefix argument causes a
  7330. command like @kbd{n} to operate on the specified stack entry only,
  7331. which is just what we want: @kbd{C-x ( M-- 3 n C-x )}.
  7332. Just for kicks, let's also do it algebraically:
  7333. @w{@kbd{C-x ( ' -$$$, $$, $ @key{RET} C-x )}}.
  7334. @node Programming Answer 3, Programming Answer 4, Programming Answer 2, Answers to Exercises
  7335. @subsection Programming Tutorial Exercise 3
  7336. @noindent
  7337. Each of these functions can be computed using the stack, or using
  7338. algebraic entry, whichever way you prefer:
  7339. @noindent
  7340. Computing
  7341. @texline @math{\displaystyle{\sin x \over x}}:
  7342. @infoline @expr{sin(x) / x}:
  7343. Using the stack: @kbd{C-x ( @key{RET} S @key{TAB} / C-x )}.
  7344. Using algebraic entry: @kbd{C-x ( ' sin($)/$ @key{RET} C-x )}.
  7345. @noindent
  7346. Computing the logarithm:
  7347. Using the stack: @kbd{C-x ( @key{TAB} B C-x )}
  7348. Using algebraic entry: @kbd{C-x ( ' log($,$$) @key{RET} C-x )}.
  7349. @noindent
  7350. Computing the vector of integers:
  7351. Using the stack: @kbd{C-x ( 1 @key{RET} 1 C-u v x C-x )}. (Recall that
  7352. @kbd{C-u v x} takes the vector size, starting value, and increment
  7353. from the stack.)
  7354. Alternatively: @kbd{C-x ( ~ v x C-x )}. (The @kbd{~} key pops a
  7355. number from the stack and uses it as the prefix argument for the
  7356. next command.)
  7357. Using algebraic entry: @kbd{C-x ( ' index($) @key{RET} C-x )}.
  7358. @node Programming Answer 4, Programming Answer 5, Programming Answer 3, Answers to Exercises
  7359. @subsection Programming Tutorial Exercise 4
  7360. @noindent
  7361. Here's one way: @kbd{C-x ( @key{RET} V R + @key{TAB} v l / C-x )}.
  7362. @node Programming Answer 5, Programming Answer 6, Programming Answer 4, Answers to Exercises
  7363. @subsection Programming Tutorial Exercise 5
  7364. @smallexample
  7365. @group
  7366. 2: 1 1: 1.61803398502 2: 1.61803398502
  7367. 1: 20 . 1: 1.61803398875
  7368. . .
  7369. 1 @key{RET} 20 Z < & 1 + Z > I H P
  7370. @end group
  7371. @end smallexample
  7372. @noindent
  7373. This answer is quite accurate.
  7374. @node Programming Answer 6, Programming Answer 7, Programming Answer 5, Answers to Exercises
  7375. @subsection Programming Tutorial Exercise 6
  7376. @noindent
  7377. Here is the matrix:
  7378. @example
  7379. [ [ 0, 1 ] * [a, b] = [b, a + b]
  7380. [ 1, 1 ] ]
  7381. @end example
  7382. @noindent
  7383. Thus @samp{[0, 1; 1, 1]^n * [1, 1]} computes Fibonacci numbers @expr{n+1}
  7384. and @expr{n+2}. Here's one program that does the job:
  7385. @example
  7386. C-x ( ' [0, 1; 1, 1] ^ ($-1) * [1, 1] @key{RET} v u @key{DEL} C-x )
  7387. @end example
  7388. @noindent
  7389. This program is quite efficient because Calc knows how to raise a
  7390. matrix (or other value) to the power @expr{n} in only
  7391. @texline @math{\log_2 n}
  7392. @infoline @expr{log(n,2)}
  7393. steps. For example, this program can compute the 1000th Fibonacci
  7394. number (a 209-digit integer!)@: in about 10 steps; even though the
  7395. @kbd{Z < ... Z >} solution had much simpler steps, it would have
  7396. required so many steps that it would not have been practical.
  7397. @node Programming Answer 7, Programming Answer 8, Programming Answer 6, Answers to Exercises
  7398. @subsection Programming Tutorial Exercise 7
  7399. @noindent
  7400. The trick here is to compute the harmonic numbers differently, so that
  7401. the loop counter itself accumulates the sum of reciprocals. We use
  7402. a separate variable to hold the integer counter.
  7403. @smallexample
  7404. @group
  7405. 1: 1 2: 1 1: .
  7406. . 1: 4
  7407. .
  7408. 1 t 1 1 @key{RET} 4 Z ( t 2 r 1 1 + s 1 & Z )
  7409. @end group
  7410. @end smallexample
  7411. @noindent
  7412. The body of the loop goes as follows: First save the harmonic sum
  7413. so far in variable 2. Then delete it from the stack; the for loop
  7414. itself will take care of remembering it for us. Next, recall the
  7415. count from variable 1, add one to it, and feed its reciprocal to
  7416. the for loop to use as the step value. The for loop will increase
  7417. the ``loop counter'' by that amount and keep going until the
  7418. loop counter exceeds 4.
  7419. @smallexample
  7420. @group
  7421. 2: 31 3: 31
  7422. 1: 3.99498713092 2: 3.99498713092
  7423. . 1: 4.02724519544
  7424. .
  7425. r 1 r 2 @key{RET} 31 & +
  7426. @end group
  7427. @end smallexample
  7428. Thus we find that the 30th harmonic number is 3.99, and the 31st
  7429. harmonic number is 4.02.
  7430. @node Programming Answer 8, Programming Answer 9, Programming Answer 7, Answers to Exercises
  7431. @subsection Programming Tutorial Exercise 8
  7432. @noindent
  7433. The first step is to compute the derivative @expr{f'(x)} and thus
  7434. the formula
  7435. @texline @math{\displaystyle{x - {f(x) \over f'(x)}}}.
  7436. @infoline @expr{x - f(x)/f'(x)}.
  7437. (Because this definition is long, it will be repeated in concise form
  7438. below. You can use @w{@kbd{C-x * m}} to load it from there. While you are
  7439. entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
  7440. keystrokes without executing them. In the following diagrams we'll
  7441. pretend Calc actually executed the keystrokes as you typed them,
  7442. just for purposes of illustration.)
  7443. @smallexample
  7444. @group
  7445. 2: sin(cos(x)) - 0.5 3: 4.5
  7446. 1: 4.5 2: sin(cos(x)) - 0.5
  7447. . 1: -(sin(x) cos(cos(x)))
  7448. .
  7449. ' sin(cos(x))-0.5 @key{RET} 4.5 m r C-x ( Z ` @key{TAB} @key{RET} a d x @key{RET}
  7450. @end group
  7451. @end smallexample
  7452. @noindent
  7453. @smallexample
  7454. @group
  7455. 2: 4.5
  7456. 1: x + (sin(cos(x)) - 0.5) / sin(x) cos(cos(x))
  7457. .
  7458. / ' x @key{RET} @key{TAB} - t 1
  7459. @end group
  7460. @end smallexample
  7461. Now, we enter the loop. We'll use a repeat loop with a 20-repetition
  7462. limit just in case the method fails to converge for some reason.
  7463. (Normally, the @w{@kbd{Z /}} command will stop the loop before all 20
  7464. repetitions are done.)
  7465. @smallexample
  7466. @group
  7467. 1: 4.5 3: 4.5 2: 4.5
  7468. . 2: x + (sin(cos(x)) ... 1: 5.24196456928
  7469. 1: 4.5 .
  7470. .
  7471. 20 Z < @key{RET} r 1 @key{TAB} s l x @key{RET}
  7472. @end group
  7473. @end smallexample
  7474. This is the new guess for @expr{x}. Now we compare it with the
  7475. old one to see if we've converged.
  7476. @smallexample
  7477. @group
  7478. 3: 5.24196 2: 5.24196 1: 5.24196 1: 5.26345856348
  7479. 2: 5.24196 1: 0 . .
  7480. 1: 4.5 .
  7481. .
  7482. @key{RET} M-@key{TAB} a = Z / Z > Z ' C-x )
  7483. @end group
  7484. @end smallexample
  7485. The loop converges in just a few steps to this value. To check
  7486. the result, we can simply substitute it back into the equation.
  7487. @smallexample
  7488. @group
  7489. 2: 5.26345856348
  7490. 1: 0.499999999997
  7491. .
  7492. @key{RET} ' sin(cos($)) @key{RET}
  7493. @end group
  7494. @end smallexample
  7495. Let's test the new definition again:
  7496. @smallexample
  7497. @group
  7498. 2: x^2 - 9 1: 3.
  7499. 1: 1 .
  7500. .
  7501. ' x^2-9 @key{RET} 1 X
  7502. @end group
  7503. @end smallexample
  7504. Once again, here's the full Newton's Method definition:
  7505. @example
  7506. @group
  7507. C-x ( Z ` @key{TAB} @key{RET} a d x @key{RET} / ' x @key{RET} @key{TAB} - t 1
  7508. 20 Z < @key{RET} r 1 @key{TAB} s l x @key{RET}
  7509. @key{RET} M-@key{TAB} a = Z /
  7510. Z >
  7511. Z '
  7512. C-x )
  7513. @end group
  7514. @end example
  7515. @c [fix-ref Nesting and Fixed Points]
  7516. It turns out that Calc has a built-in command for applying a formula
  7517. repeatedly until it converges to a number. @xref{Nesting and Fixed Points},
  7518. to see how to use it.
  7519. @c [fix-ref Root Finding]
  7520. Also, of course, @kbd{a R} is a built-in command that uses Newton's
  7521. method (among others) to look for numerical solutions to any equation.
  7522. @xref{Root Finding}.
  7523. @node Programming Answer 9, Programming Answer 10, Programming Answer 8, Answers to Exercises
  7524. @subsection Programming Tutorial Exercise 9
  7525. @noindent
  7526. The first step is to adjust @expr{z} to be greater than 5. A simple
  7527. ``for'' loop will do the job here. If @expr{z} is less than 5, we
  7528. reduce the problem using
  7529. @texline @math{\psi(z) = \psi(z+1) - 1/z}.
  7530. @infoline @expr{psi(z) = psi(z+1) - 1/z}. We go
  7531. on to compute
  7532. @texline @math{\psi(z+1)},
  7533. @infoline @expr{psi(z+1)},
  7534. and remember to add back a factor of @expr{-1/z} when we're done. This
  7535. step is repeated until @expr{z > 5}.
  7536. (Because this definition is long, it will be repeated in concise form
  7537. below. You can use @w{@kbd{C-x * m}} to load it from there. While you are
  7538. entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
  7539. keystrokes without executing them. In the following diagrams we'll
  7540. pretend Calc actually executed the keystrokes as you typed them,
  7541. just for purposes of illustration.)
  7542. @smallexample
  7543. @group
  7544. 1: 1. 1: 1.
  7545. . .
  7546. 1.0 @key{RET} C-x ( Z ` s 1 0 t 2
  7547. @end group
  7548. @end smallexample
  7549. Here, variable 1 holds @expr{z} and variable 2 holds the adjustment
  7550. factor. If @expr{z < 5}, we use a loop to increase it.
  7551. (By the way, we started with @samp{1.0} instead of the integer 1 because
  7552. otherwise the calculation below will try to do exact fractional arithmetic,
  7553. and will never converge because fractions compare equal only if they
  7554. are exactly equal, not just equal to within the current precision.)
  7555. @smallexample
  7556. @group
  7557. 3: 1. 2: 1. 1: 6.
  7558. 2: 1. 1: 1 .
  7559. 1: 5 .
  7560. .
  7561. @key{RET} 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
  7562. @end group
  7563. @end smallexample
  7564. Now we compute the initial part of the sum:
  7565. @texline @math{\ln z - {1 \over 2z}}
  7566. @infoline @expr{ln(z) - 1/2z}
  7567. minus the adjustment factor.
  7568. @smallexample
  7569. @group
  7570. 2: 1.79175946923 2: 1.7084261359 1: -0.57490719743
  7571. 1: 0.0833333333333 1: 2.28333333333 .
  7572. . .
  7573. L r 1 2 * & - r 2 -
  7574. @end group
  7575. @end smallexample
  7576. Now we evaluate the series. We'll use another ``for'' loop counting
  7577. up the value of @expr{2 n}. (Calc does have a summation command,
  7578. @kbd{a +}, but we'll use loops just to get more practice with them.)
  7579. @smallexample
  7580. @group
  7581. 3: -0.5749 3: -0.5749 4: -0.5749 2: -0.5749
  7582. 2: 2 2: 1:6 3: 1:6 1: 2.3148e-3
  7583. 1: 40 1: 2 2: 2 .
  7584. . . 1: 36.
  7585. .
  7586. 2 @key{RET} 40 Z ( @key{RET} k b @key{TAB} @key{RET} r 1 @key{TAB} ^ * /
  7587. @end group
  7588. @end smallexample
  7589. @noindent
  7590. @smallexample
  7591. @group
  7592. 3: -0.5749 3: -0.5772 2: -0.5772 1: -0.577215664892
  7593. 2: -0.5749 2: -0.5772 1: 0 .
  7594. 1: 2.3148e-3 1: -0.5749 .
  7595. . .
  7596. @key{TAB} @key{RET} M-@key{TAB} - @key{RET} M-@key{TAB} a = Z / 2 Z ) Z ' C-x )
  7597. @end group
  7598. @end smallexample
  7599. This is the value of
  7600. @texline @math{-\gamma},
  7601. @infoline @expr{- gamma},
  7602. with a slight bit of roundoff error. To get a full 12 digits, let's use
  7603. a higher precision:
  7604. @smallexample
  7605. @group
  7606. 2: -0.577215664892 2: -0.577215664892
  7607. 1: 1. 1: -0.577215664901532
  7608. 1. @key{RET} p 16 @key{RET} X
  7609. @end group
  7610. @end smallexample
  7611. Here's the complete sequence of keystrokes:
  7612. @example
  7613. @group
  7614. C-x ( Z ` s 1 0 t 2
  7615. @key{RET} 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
  7616. L r 1 2 * & - r 2 -
  7617. 2 @key{RET} 40 Z ( @key{RET} k b @key{TAB} @key{RET} r 1 @key{TAB} ^ * /
  7618. @key{TAB} @key{RET} M-@key{TAB} - @key{RET} M-@key{TAB} a = Z /
  7619. 2 Z )
  7620. Z '
  7621. C-x )
  7622. @end group
  7623. @end example
  7624. @node Programming Answer 10, Programming Answer 11, Programming Answer 9, Answers to Exercises
  7625. @subsection Programming Tutorial Exercise 10
  7626. @noindent
  7627. Taking the derivative of a term of the form @expr{x^n} will produce
  7628. a term like
  7629. @texline @math{n x^{n-1}}.
  7630. @infoline @expr{n x^(n-1)}.
  7631. Taking the derivative of a constant
  7632. produces zero. From this it is easy to see that the @expr{n}th
  7633. derivative of a polynomial, evaluated at @expr{x = 0}, will equal the
  7634. coefficient on the @expr{x^n} term times @expr{n!}.
  7635. (Because this definition is long, it will be repeated in concise form
  7636. below. You can use @w{@kbd{C-x * m}} to load it from there. While you are
  7637. entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
  7638. keystrokes without executing them. In the following diagrams we'll
  7639. pretend Calc actually executed the keystrokes as you typed them,
  7640. just for purposes of illustration.)
  7641. @smallexample
  7642. @group
  7643. 2: 5 x^4 + (x + 1)^2 3: 5 x^4 + (x + 1)^2
  7644. 1: 6 2: 0
  7645. . 1: 6
  7646. .
  7647. ' 5 x^4 + (x+1)^2 @key{RET} 6 C-x ( Z ` [ ] t 1 0 @key{TAB}
  7648. @end group
  7649. @end smallexample
  7650. @noindent
  7651. Variable 1 will accumulate the vector of coefficients.
  7652. @smallexample
  7653. @group
  7654. 2: 0 3: 0 2: 5 x^4 + ...
  7655. 1: 5 x^4 + ... 2: 5 x^4 + ... 1: 1
  7656. . 1: 1 .
  7657. .
  7658. Z ( @key{TAB} @key{RET} 0 s l x @key{RET} M-@key{TAB} ! / s | 1
  7659. @end group
  7660. @end smallexample
  7661. @noindent
  7662. Note that @kbd{s | 1} appends the top-of-stack value to the vector
  7663. in a variable; it is completely analogous to @kbd{s + 1}. We could
  7664. have written instead, @kbd{r 1 @key{TAB} | t 1}.
  7665. @smallexample
  7666. @group
  7667. 1: 20 x^3 + 2 x + 2 1: 0 1: [1, 2, 1, 0, 5, 0, 0]
  7668. . . .
  7669. a d x @key{RET} 1 Z ) @key{DEL} r 1 Z ' C-x )
  7670. @end group
  7671. @end smallexample
  7672. To convert back, a simple method is just to map the coefficients
  7673. against a table of powers of @expr{x}.
  7674. @smallexample
  7675. @group
  7676. 2: [1, 2, 1, 0, 5, 0, 0] 2: [1, 2, 1, 0, 5, 0, 0]
  7677. 1: 6 1: [0, 1, 2, 3, 4, 5, 6]
  7678. . .
  7679. 6 @key{RET} 1 + 0 @key{RET} 1 C-u v x
  7680. @end group
  7681. @end smallexample
  7682. @noindent
  7683. @smallexample
  7684. @group
  7685. 2: [1, 2, 1, 0, 5, 0, 0] 2: 1 + 2 x + x^2 + 5 x^4
  7686. 1: [1, x, x^2, x^3, ... ] .
  7687. .
  7688. ' x @key{RET} @key{TAB} V M ^ *
  7689. @end group
  7690. @end smallexample
  7691. Once again, here are the whole polynomial to/from vector programs:
  7692. @example
  7693. @group
  7694. C-x ( Z ` [ ] t 1 0 @key{TAB}
  7695. Z ( @key{TAB} @key{RET} 0 s l x @key{RET} M-@key{TAB} ! / s | 1
  7696. a d x @key{RET}
  7697. 1 Z ) r 1
  7698. Z '
  7699. C-x )
  7700. C-x ( 1 + 0 @key{RET} 1 C-u v x ' x @key{RET} @key{TAB} V M ^ * C-x )
  7701. @end group
  7702. @end example
  7703. @node Programming Answer 11, Programming Answer 12, Programming Answer 10, Answers to Exercises
  7704. @subsection Programming Tutorial Exercise 11
  7705. @noindent
  7706. First we define a dummy program to go on the @kbd{z s} key. The true
  7707. @w{@kbd{z s}} key is supposed to take two numbers from the stack and
  7708. return one number, so @key{DEL} as a dummy definition will make
  7709. sure the stack comes out right.
  7710. @smallexample
  7711. @group
  7712. 2: 4 1: 4 2: 4
  7713. 1: 2 . 1: 2
  7714. . .
  7715. 4 @key{RET} 2 C-x ( @key{DEL} C-x ) Z K s @key{RET} 2
  7716. @end group
  7717. @end smallexample
  7718. The last step replaces the 2 that was eaten during the creation
  7719. of the dummy @kbd{z s} command. Now we move on to the real
  7720. definition. The recurrence needs to be rewritten slightly,
  7721. to the form @expr{s(n,m) = s(n-1,m-1) - (n-1) s(n-1,m)}.
  7722. (Because this definition is long, it will be repeated in concise form
  7723. below. You can use @kbd{C-x * m} to load it from there.)
  7724. @smallexample
  7725. @group
  7726. 2: 4 4: 4 3: 4 2: 4
  7727. 1: 2 3: 2 2: 2 1: 2
  7728. . 2: 4 1: 0 .
  7729. 1: 2 .
  7730. .
  7731. C-x ( M-2 @key{RET} a = Z [ @key{DEL} @key{DEL} 1 Z :
  7732. @end group
  7733. @end smallexample
  7734. @noindent
  7735. @smallexample
  7736. @group
  7737. 4: 4 2: 4 2: 3 4: 3 4: 3 3: 3
  7738. 3: 2 1: 2 1: 2 3: 2 3: 2 2: 2
  7739. 2: 2 . . 2: 3 2: 3 1: 3
  7740. 1: 0 1: 2 1: 1 .
  7741. . . .
  7742. @key{RET} 0 a = Z [ @key{DEL} @key{DEL} 0 Z : @key{TAB} 1 - @key{TAB} M-2 @key{RET} 1 - z s
  7743. @end group
  7744. @end smallexample
  7745. @noindent
  7746. (Note that the value 3 that our dummy @kbd{z s} produces is not correct;
  7747. it is merely a placeholder that will do just as well for now.)
  7748. @smallexample
  7749. @group
  7750. 3: 3 4: 3 3: 3 2: 3 1: -6
  7751. 2: 3 3: 3 2: 3 1: 9 .
  7752. 1: 2 2: 3 1: 3 .
  7753. . 1: 2 .
  7754. .
  7755. M-@key{TAB} M-@key{TAB} @key{TAB} @key{RET} M-@key{TAB} z s * -
  7756. @end group
  7757. @end smallexample
  7758. @noindent
  7759. @smallexample
  7760. @group
  7761. 1: -6 2: 4 1: 11 2: 11
  7762. . 1: 2 . 1: 11
  7763. . .
  7764. Z ] Z ] C-x ) Z K s @key{RET} @key{DEL} 4 @key{RET} 2 z s M-@key{RET} k s
  7765. @end group
  7766. @end smallexample
  7767. Even though the result that we got during the definition was highly
  7768. bogus, once the definition is complete the @kbd{z s} command gets
  7769. the right answers.
  7770. Here's the full program once again:
  7771. @example
  7772. @group
  7773. C-x ( M-2 @key{RET} a =
  7774. Z [ @key{DEL} @key{DEL} 1
  7775. Z : @key{RET} 0 a =
  7776. Z [ @key{DEL} @key{DEL} 0
  7777. Z : @key{TAB} 1 - @key{TAB} M-2 @key{RET} 1 - z s
  7778. M-@key{TAB} M-@key{TAB} @key{TAB} @key{RET} M-@key{TAB} z s * -
  7779. Z ]
  7780. Z ]
  7781. C-x )
  7782. @end group
  7783. @end example
  7784. You can read this definition using @kbd{C-x * m} (@code{read-kbd-macro})
  7785. followed by @kbd{Z K s}, without having to make a dummy definition
  7786. first, because @code{read-kbd-macro} doesn't need to execute the
  7787. definition as it reads it in. For this reason, @code{C-x * m} is often
  7788. the easiest way to create recursive programs in Calc.
  7789. @node Programming Answer 12, , Programming Answer 11, Answers to Exercises
  7790. @subsection Programming Tutorial Exercise 12
  7791. @noindent
  7792. This turns out to be a much easier way to solve the problem. Let's
  7793. denote Stirling numbers as calls of the function @samp{s}.
  7794. First, we store the rewrite rules corresponding to the definition of
  7795. Stirling numbers in a convenient variable:
  7796. @smallexample
  7797. s e StirlingRules @key{RET}
  7798. [ s(n,n) := 1 :: n >= 0,
  7799. s(n,0) := 0 :: n > 0,
  7800. s(n,m) := s(n-1,m-1) - (n-1) s(n-1,m) :: n >= m :: m >= 1 ]
  7801. C-c C-c
  7802. @end smallexample
  7803. Now, it's just a matter of applying the rules:
  7804. @smallexample
  7805. @group
  7806. 2: 4 1: s(4, 2) 1: 11
  7807. 1: 2 . .
  7808. .
  7809. 4 @key{RET} 2 C-x ( ' s($$,$) @key{RET} a r StirlingRules @key{RET} C-x )
  7810. @end group
  7811. @end smallexample
  7812. As in the case of the @code{fib} rules, it would be useful to put these
  7813. rules in @code{EvalRules} and to add a @samp{:: remember} condition to
  7814. the last rule.
  7815. @c This ends the table-of-contents kludge from above:
  7816. @tex
  7817. \global\let\chapternofonts=\oldchapternofonts
  7818. @end tex
  7819. @c [reference]
  7820. @node Introduction, Data Types, Tutorial, Top
  7821. @chapter Introduction
  7822. @noindent
  7823. This chapter is the beginning of the Calc reference manual.
  7824. It covers basic concepts such as the stack, algebraic and
  7825. numeric entry, undo, numeric prefix arguments, etc.
  7826. @c [when-split]
  7827. @c (Chapter 2, the Tutorial, has been printed in a separate volume.)
  7828. @menu
  7829. * Basic Commands::
  7830. * Help Commands::
  7831. * Stack Basics::
  7832. * Numeric Entry::
  7833. * Algebraic Entry::
  7834. * Quick Calculator::
  7835. * Prefix Arguments::
  7836. * Undo::
  7837. * Error Messages::
  7838. * Multiple Calculators::
  7839. * Troubleshooting Commands::
  7840. @end menu
  7841. @node Basic Commands, Help Commands, Introduction, Introduction
  7842. @section Basic Commands
  7843. @noindent
  7844. @pindex calc
  7845. @pindex calc-mode
  7846. @cindex Starting the Calculator
  7847. @cindex Running the Calculator
  7848. To start the Calculator in its standard interface, type @kbd{M-x calc}.
  7849. By default this creates a pair of small windows, @file{*Calculator*}
  7850. and @file{*Calc Trail*}. The former displays the contents of the
  7851. Calculator stack and is manipulated exclusively through Calc commands.
  7852. It is possible (though not usually necessary) to create several Calc
  7853. mode buffers each of which has an independent stack, undo list, and
  7854. mode settings. There is exactly one Calc Trail buffer; it records a
  7855. list of the results of all calculations that have been done. The
  7856. Calc Trail buffer uses a variant of Calc mode, so Calculator commands
  7857. still work when the trail buffer's window is selected. It is possible
  7858. to turn the trail window off, but the @file{*Calc Trail*} buffer itself
  7859. still exists and is updated silently. @xref{Trail Commands}.
  7860. @kindex C-x * c
  7861. @kindex C-x * *
  7862. @ignore
  7863. @mindex @null
  7864. @end ignore
  7865. In most installations, the @kbd{C-x * c} key sequence is a more
  7866. convenient way to start the Calculator. Also, @kbd{C-x * *}
  7867. is a synonym for @kbd{C-x * c} unless you last used Calc
  7868. in its Keypad mode.
  7869. @kindex x
  7870. @kindex M-x
  7871. @pindex calc-execute-extended-command
  7872. Most Calc commands use one or two keystrokes. Lower- and upper-case
  7873. letters are distinct. Commands may also be entered in full @kbd{M-x} form;
  7874. for some commands this is the only form. As a convenience, the @kbd{x}
  7875. key (@code{calc-execute-extended-command})
  7876. is like @kbd{M-x} except that it enters the initial string @samp{calc-}
  7877. for you. For example, the following key sequences are equivalent:
  7878. @kbd{S}, @kbd{M-x calc-sin @key{RET}}, @kbd{x sin @key{RET}}.
  7879. Although Calc is designed to be used from the keyboard, some of
  7880. Calc's more common commands are available from a menu. In the menu, the
  7881. arguments to the functions are given by referring to their stack level
  7882. numbers.
  7883. @cindex Extensions module
  7884. @cindex @file{calc-ext} module
  7885. The Calculator exists in many parts. When you type @kbd{C-x * c}, the
  7886. Emacs ``auto-load'' mechanism will bring in only the first part, which
  7887. contains the basic arithmetic functions. The other parts will be
  7888. auto-loaded the first time you use the more advanced commands like trig
  7889. functions or matrix operations. This is done to improve the response time
  7890. of the Calculator in the common case when all you need to do is a
  7891. little arithmetic. If for some reason the Calculator fails to load an
  7892. extension module automatically, you can force it to load all the
  7893. extensions by using the @kbd{C-x * L} (@code{calc-load-everything})
  7894. command. @xref{Mode Settings}.
  7895. If you type @kbd{M-x calc} or @kbd{C-x * c} with any numeric prefix argument,
  7896. the Calculator is loaded if necessary, but it is not actually started.
  7897. If the argument is positive, the @file{calc-ext} extensions are also
  7898. loaded if necessary. User-written Lisp code that wishes to make use
  7899. of Calc's arithmetic routines can use @samp{(calc 0)} or @samp{(calc 1)}
  7900. to auto-load the Calculator.
  7901. @kindex C-x * b
  7902. @pindex full-calc
  7903. If you type @kbd{C-x * b}, then next time you use @kbd{C-x * c} you
  7904. will get a Calculator that uses the full height of the Emacs screen.
  7905. When full-screen mode is on, @kbd{C-x * c} runs the @code{full-calc}
  7906. command instead of @code{calc}. From the Unix shell you can type
  7907. @samp{emacs -f full-calc} to start a new Emacs specifically for use
  7908. as a calculator. When Calc is started from the Emacs command line
  7909. like this, Calc's normal ``quit'' commands actually quit Emacs itself.
  7910. @kindex C-x * o
  7911. @pindex calc-other-window
  7912. The @kbd{C-x * o} command is like @kbd{C-x * c} except that the Calc
  7913. window is not actually selected. If you are already in the Calc
  7914. window, @kbd{C-x * o} switches you out of it. (The regular Emacs
  7915. @kbd{C-x o} command would also work for this, but it has a
  7916. tendency to drop you into the Calc Trail window instead, which
  7917. @kbd{C-x * o} takes care not to do.)
  7918. @ignore
  7919. @mindex C-x * q
  7920. @end ignore
  7921. For one quick calculation, you can type @kbd{C-x * q} (@code{quick-calc})
  7922. which prompts you for a formula (like @samp{2+3/4}). The result is
  7923. displayed at the bottom of the Emacs screen without ever creating
  7924. any special Calculator windows. @xref{Quick Calculator}.
  7925. @ignore
  7926. @mindex C-x * k
  7927. @end ignore
  7928. Finally, if you are using the X window system you may want to try
  7929. @kbd{C-x * k} (@code{calc-keypad}) which runs Calc with a
  7930. ``calculator keypad'' picture as well as a stack display. Click on
  7931. the keys with the mouse to operate the calculator. @xref{Keypad Mode}.
  7932. @kindex q
  7933. @pindex calc-quit
  7934. @cindex Quitting the Calculator
  7935. @cindex Exiting the Calculator
  7936. The @kbd{q} key (@code{calc-quit}) exits Calc mode and closes the
  7937. Calculator's window(s). It does not delete the Calculator buffers.
  7938. If you type @kbd{M-x calc} again, the Calculator will reappear with the
  7939. contents of the stack intact. Typing @kbd{C-x * c} or @kbd{C-x * *}
  7940. again from inside the Calculator buffer is equivalent to executing
  7941. @code{calc-quit}; you can think of @kbd{C-x * *} as toggling the
  7942. Calculator on and off.
  7943. @kindex C-x * x
  7944. The @kbd{C-x * x} command also turns the Calculator off, no matter which
  7945. user interface (standard, Keypad, or Embedded) is currently active.
  7946. It also cancels @code{calc-edit} mode if used from there.
  7947. @kindex d @key{SPC}
  7948. @pindex calc-refresh
  7949. @cindex Refreshing a garbled display
  7950. @cindex Garbled displays, refreshing
  7951. The @kbd{d @key{SPC}} key sequence (@code{calc-refresh}) redraws the contents
  7952. of the Calculator buffer from memory. Use this if the contents of the
  7953. buffer have been damaged somehow.
  7954. @ignore
  7955. @mindex o
  7956. @end ignore
  7957. The @kbd{o} key (@code{calc-realign}) moves the cursor back to its
  7958. ``home'' position at the bottom of the Calculator buffer.
  7959. @kindex <
  7960. @kindex >
  7961. @pindex calc-scroll-left
  7962. @pindex calc-scroll-right
  7963. @cindex Horizontal scrolling
  7964. @cindex Scrolling
  7965. @cindex Wide text, scrolling
  7966. The @kbd{<} and @kbd{>} keys are bound to @code{calc-scroll-left} and
  7967. @code{calc-scroll-right}. These are just like the normal horizontal
  7968. scrolling commands except that they scroll one half-screen at a time by
  7969. default. (Calc formats its output to fit within the bounds of the
  7970. window whenever it can.)
  7971. @kindex @{
  7972. @kindex @}
  7973. @pindex calc-scroll-down
  7974. @pindex calc-scroll-up
  7975. @cindex Vertical scrolling
  7976. The @kbd{@{} and @kbd{@}} keys are bound to @code{calc-scroll-down}
  7977. and @code{calc-scroll-up}. They scroll up or down by one-half the
  7978. height of the Calc window.
  7979. @kindex C-x * 0
  7980. @pindex calc-reset
  7981. The @kbd{C-x * 0} command (@code{calc-reset}; that's @kbd{C-x *} followed
  7982. by a zero) resets the Calculator to its initial state. This clears
  7983. the stack, resets all the modes to their initial values (the values
  7984. that were saved with @kbd{m m} (@code{calc-save-modes})), clears the
  7985. caches (@pxref{Caches}), and so on. (It does @emph{not} erase the
  7986. values of any variables.) With an argument of 0, Calc will be reset to
  7987. its default state; namely, the modes will be given their default values.
  7988. With a positive prefix argument, @kbd{C-x * 0} preserves the contents of
  7989. the stack but resets everything else to its initial state; with a
  7990. negative prefix argument, @kbd{C-x * 0} preserves the contents of the
  7991. stack but resets everything else to its default state.
  7992. @node Help Commands, Stack Basics, Basic Commands, Introduction
  7993. @section Help Commands
  7994. @noindent
  7995. @cindex Help commands
  7996. @kindex ?
  7997. @kindex a ?
  7998. @kindex b ?
  7999. @kindex c ?
  8000. @kindex d ?
  8001. @kindex f ?
  8002. @kindex g ?
  8003. @kindex j ?
  8004. @kindex k ?
  8005. @kindex m ?
  8006. @kindex r ?
  8007. @kindex s ?
  8008. @kindex t ?
  8009. @kindex u ?
  8010. @kindex v ?
  8011. @kindex V ?
  8012. @kindex z ?
  8013. @kindex Z ?
  8014. @pindex calc-help
  8015. The @kbd{?} key (@code{calc-help}) displays a series of brief help messages.
  8016. Some keys (such as @kbd{b} and @kbd{d}) are prefix keys, like Emacs's
  8017. @key{ESC} and @kbd{C-x} prefixes. You can type
  8018. @kbd{?} after a prefix to see a list of commands beginning with that
  8019. prefix. (If the message includes @samp{[MORE]}, press @kbd{?} again
  8020. to see additional commands for that prefix.)
  8021. @kindex h h
  8022. @pindex calc-full-help
  8023. The @kbd{h h} (@code{calc-full-help}) command displays all the @kbd{?}
  8024. responses at once. When printed, this makes a nice, compact (three pages)
  8025. summary of Calc keystrokes.
  8026. In general, the @kbd{h} key prefix introduces various commands that
  8027. provide help within Calc. Many of the @kbd{h} key functions are
  8028. Calc-specific analogues to the @kbd{C-h} functions for Emacs help.
  8029. @kindex h i
  8030. @kindex C-x * i
  8031. @kindex i
  8032. @pindex calc-info
  8033. The @kbd{h i} (@code{calc-info}) command runs the Emacs Info system
  8034. to read this manual on-line. This is basically the same as typing
  8035. @kbd{C-h i} (the regular way to run the Info system), then, if Info
  8036. is not already in the Calc manual, selecting the beginning of the
  8037. manual. The @kbd{C-x * i} command is another way to read the Calc
  8038. manual; it is different from @kbd{h i} in that it works any time,
  8039. not just inside Calc. The plain @kbd{i} key is also equivalent to
  8040. @kbd{h i}, though this key is obsolete and may be replaced with a
  8041. different command in a future version of Calc.
  8042. @kindex h t
  8043. @kindex C-x * t
  8044. @pindex calc-tutorial
  8045. The @kbd{h t} (@code{calc-tutorial}) command runs the Info system on
  8046. the Tutorial section of the Calc manual. It is like @kbd{h i},
  8047. except that it selects the starting node of the tutorial rather
  8048. than the beginning of the whole manual. (It actually selects the
  8049. node ``Interactive Tutorial'' which tells a few things about
  8050. using the Info system before going on to the actual tutorial.)
  8051. The @kbd{C-x * t} key is equivalent to @kbd{h t} (but it works at
  8052. all times).
  8053. @kindex h s
  8054. @kindex C-x * s
  8055. @pindex calc-info-summary
  8056. The @kbd{h s} (@code{calc-info-summary}) command runs the Info system
  8057. on the Summary node of the Calc manual. @xref{Summary}. The @kbd{C-x * s}
  8058. key is equivalent to @kbd{h s}.
  8059. @kindex h k
  8060. @pindex calc-describe-key
  8061. The @kbd{h k} (@code{calc-describe-key}) command looks up a key
  8062. sequence in the Calc manual. For example, @kbd{h k H a S} looks
  8063. up the documentation on the @kbd{H a S} (@code{calc-solve-for})
  8064. command. This works by looking up the textual description of
  8065. the key(s) in the Key Index of the manual, then jumping to the
  8066. node indicated by the index.
  8067. Most Calc commands do not have traditional Emacs documentation
  8068. strings, since the @kbd{h k} command is both more convenient and
  8069. more instructive. This means the regular Emacs @kbd{C-h k}
  8070. (@code{describe-key}) command will not be useful for Calc keystrokes.
  8071. @kindex h c
  8072. @pindex calc-describe-key-briefly
  8073. The @kbd{h c} (@code{calc-describe-key-briefly}) command reads a
  8074. key sequence and displays a brief one-line description of it at
  8075. the bottom of the screen. It looks for the key sequence in the
  8076. Summary node of the Calc manual; if it doesn't find the sequence
  8077. there, it acts just like its regular Emacs counterpart @kbd{C-h c}
  8078. (@code{describe-key-briefly}). For example, @kbd{h c H a S}
  8079. gives the description:
  8080. @smallexample
  8081. H a S runs calc-solve-for: a `H a S' v => fsolve(a,v) (?=notes)
  8082. @end smallexample
  8083. @noindent
  8084. which means the command @kbd{H a S} or @kbd{H M-x calc-solve-for}
  8085. takes a value @expr{a} from the stack, prompts for a value @expr{v},
  8086. then applies the algebraic function @code{fsolve} to these values.
  8087. The @samp{?=notes} message means you can now type @kbd{?} to see
  8088. additional notes from the summary that apply to this command.
  8089. @kindex h f
  8090. @pindex calc-describe-function
  8091. The @kbd{h f} (@code{calc-describe-function}) command looks up an
  8092. algebraic function or a command name in the Calc manual. Enter an
  8093. algebraic function name to look up that function in the Function
  8094. Index or enter a command name beginning with @samp{calc-} to look it
  8095. up in the Command Index. This command will also look up operator
  8096. symbols that can appear in algebraic formulas, like @samp{%} and
  8097. @samp{=>}.
  8098. @kindex h v
  8099. @pindex calc-describe-variable
  8100. The @kbd{h v} (@code{calc-describe-variable}) command looks up a
  8101. variable in the Calc manual. Enter a variable name like @code{pi} or
  8102. @code{PlotRejects}.
  8103. @kindex h b
  8104. @pindex describe-bindings
  8105. The @kbd{h b} (@code{calc-describe-bindings}) command is just like
  8106. @kbd{C-h b}, except that only local (Calc-related) key bindings are
  8107. listed.
  8108. @kindex h n
  8109. The @kbd{h n} or @kbd{h C-n} (@code{calc-view-news}) command displays
  8110. the ``news'' or change history of Emacs, and jumps to the most recent
  8111. portion concerning Calc (if present). For older history, see the file
  8112. @file{etc/CALC-NEWS} in the Emacs distribution.
  8113. @kindex h C-c
  8114. @kindex h C-d
  8115. @kindex h C-w
  8116. The @kbd{h C-c}, @kbd{h C-d}, and @kbd{h C-w} keys display copying,
  8117. distribution, and warranty information about Calc. These work by
  8118. pulling up the appropriate parts of the ``Copying'' or ``Reporting
  8119. Bugs'' sections of the manual.
  8120. @node Stack Basics, Numeric Entry, Help Commands, Introduction
  8121. @section Stack Basics
  8122. @noindent
  8123. @cindex Stack basics
  8124. @c [fix-tut RPN Calculations and the Stack]
  8125. Calc uses RPN notation. If you are not familiar with RPN, @pxref{RPN
  8126. Tutorial}.
  8127. To add the numbers 1 and 2 in Calc you would type the keys:
  8128. @kbd{1 @key{RET} 2 +}.
  8129. (@key{RET} corresponds to the @key{ENTER} key on most calculators.)
  8130. The first three keystrokes ``push'' the numbers 1 and 2 onto the stack. The
  8131. @kbd{+} key always ``pops'' the top two numbers from the stack, adds them,
  8132. and pushes the result (3) back onto the stack. This number is ready for
  8133. further calculations: @kbd{5 -} pushes 5 onto the stack, then pops the
  8134. 3 and 5, subtracts them, and pushes the result (@mathit{-2}).
  8135. Note that the ``top'' of the stack actually appears at the @emph{bottom}
  8136. of the buffer. A line containing a single @samp{.} character signifies
  8137. the end of the buffer; Calculator commands operate on the number(s)
  8138. directly above this line. The @kbd{d t} (@code{calc-truncate-stack})
  8139. command allows you to move the @samp{.} marker up and down in the stack;
  8140. @pxref{Truncating the Stack}.
  8141. @kindex d l
  8142. @pindex calc-line-numbering
  8143. Stack elements are numbered consecutively, with number 1 being the top of
  8144. the stack. These line numbers are ordinarily displayed on the lefthand side
  8145. of the window. The @kbd{d l} (@code{calc-line-numbering}) command controls
  8146. whether these numbers appear. (Line numbers may be turned off since they
  8147. slow the Calculator down a bit and also clutter the display.)
  8148. @kindex o
  8149. @pindex calc-realign
  8150. The unshifted letter @kbd{o} (@code{calc-realign}) command repositions
  8151. the cursor to its top-of-stack ``home'' position. It also undoes any
  8152. horizontal scrolling in the window. If you give it a numeric prefix
  8153. argument, it instead moves the cursor to the specified stack element.
  8154. The @key{RET} (or equivalent @key{SPC}) key is only required to separate
  8155. two consecutive numbers.
  8156. (After all, if you typed @kbd{1 2} by themselves the Calculator
  8157. would enter the number 12.) If you press @key{RET} or @key{SPC} @emph{not}
  8158. right after typing a number, the key duplicates the number on the top of
  8159. the stack. @kbd{@key{RET} *} is thus a handy way to square a number.
  8160. The @key{DEL} key pops and throws away the top number on the stack.
  8161. The @key{TAB} key swaps the top two objects on the stack.
  8162. @xref{Stack and Trail}, for descriptions of these and other stack-related
  8163. commands.
  8164. @node Numeric Entry, Algebraic Entry, Stack Basics, Introduction
  8165. @section Numeric Entry
  8166. @noindent
  8167. @kindex 0-9
  8168. @kindex .
  8169. @kindex e
  8170. @cindex Numeric entry
  8171. @cindex Entering numbers
  8172. Pressing a digit or other numeric key begins numeric entry using the
  8173. minibuffer. The number is pushed on the stack when you press the @key{RET}
  8174. or @key{SPC} keys. If you press any other non-numeric key, the number is
  8175. pushed onto the stack and the appropriate operation is performed. If
  8176. you press a numeric key which is not valid, the key is ignored.
  8177. @cindex Minus signs
  8178. @cindex Negative numbers, entering
  8179. @kindex _
  8180. There are three different concepts corresponding to the word ``minus,''
  8181. typified by @expr{a-b} (subtraction), @expr{-x}
  8182. (change-sign), and @expr{-5} (negative number). Calc uses three
  8183. different keys for these operations, respectively:
  8184. @kbd{-}, @kbd{n}, and @kbd{_} (the underscore). The @kbd{-} key subtracts
  8185. the two numbers on the top of the stack. The @kbd{n} key changes the sign
  8186. of the number on the top of the stack or the number currently being entered.
  8187. The @kbd{_} key begins entry of a negative number or changes the sign of
  8188. the number currently being entered. The following sequences all enter the
  8189. number @mathit{-5} onto the stack: @kbd{0 @key{RET} 5 -}, @kbd{5 n @key{RET}},
  8190. @kbd{5 @key{RET} n}, @kbd{_ 5 @key{RET}}, @kbd{5 _ @key{RET}}.
  8191. Some other keys are active during numeric entry, such as @kbd{#} for
  8192. non-decimal numbers, @kbd{:} for fractions, and @kbd{@@} for HMS forms.
  8193. These notations are described later in this manual with the corresponding
  8194. data types. @xref{Data Types}.
  8195. During numeric entry, the only editing key available is @key{DEL}.
  8196. @node Algebraic Entry, Quick Calculator, Numeric Entry, Introduction
  8197. @section Algebraic Entry
  8198. @noindent
  8199. @kindex '
  8200. @pindex calc-algebraic-entry
  8201. @cindex Algebraic notation
  8202. @cindex Formulas, entering
  8203. The @kbd{'} (@code{calc-algebraic-entry}) command can be used to enter
  8204. calculations in algebraic form. This is accomplished by typing the
  8205. apostrophe key, ', followed by the expression in standard format:
  8206. @example
  8207. ' 2+3*4 @key{RET}.
  8208. @end example
  8209. @noindent
  8210. This will compute
  8211. @texline @math{2+(3\times4) = 14}
  8212. @infoline @expr{2+(3*4) = 14}
  8213. and push it on the stack. If you wish you can
  8214. ignore the RPN aspect of Calc altogether and simply enter algebraic
  8215. expressions in this way. You may want to use @key{DEL} every so often to
  8216. clear previous results off the stack.
  8217. You can press the apostrophe key during normal numeric entry to switch
  8218. the half-entered number into Algebraic entry mode. One reason to do
  8219. this would be to fix a typo, as the full Emacs cursor motion and editing
  8220. keys are available during algebraic entry but not during numeric entry.
  8221. In the same vein, during either numeric or algebraic entry you can
  8222. press @kbd{`} (grave accent) to switch to @code{calc-edit} mode, where
  8223. you complete your half-finished entry in a separate buffer.
  8224. @xref{Editing Stack Entries}.
  8225. @kindex m a
  8226. @pindex calc-algebraic-mode
  8227. @cindex Algebraic Mode
  8228. If you prefer algebraic entry, you can use the command @kbd{m a}
  8229. (@code{calc-algebraic-mode}) to set Algebraic mode. In this mode,
  8230. digits and other keys that would normally start numeric entry instead
  8231. start full algebraic entry; as long as your formula begins with a digit
  8232. you can omit the apostrophe. Open parentheses and square brackets also
  8233. begin algebraic entry. You can still do RPN calculations in this mode,
  8234. but you will have to press @key{RET} to terminate every number:
  8235. @kbd{2 @key{RET} 3 @key{RET} * 4 @key{RET} +} would accomplish the same
  8236. thing as @kbd{2*3+4 @key{RET}}.
  8237. @cindex Incomplete Algebraic Mode
  8238. If you give a numeric prefix argument like @kbd{C-u} to the @kbd{m a}
  8239. command, it enables Incomplete Algebraic mode; this is like regular
  8240. Algebraic mode except that it applies to the @kbd{(} and @kbd{[} keys
  8241. only. Numeric keys still begin a numeric entry in this mode.
  8242. @kindex m t
  8243. @pindex calc-total-algebraic-mode
  8244. @cindex Total Algebraic Mode
  8245. The @kbd{m t} (@code{calc-total-algebraic-mode}) gives you an even
  8246. stronger algebraic-entry mode, in which @emph{all} regular letter and
  8247. punctuation keys begin algebraic entry. Use this if you prefer typing
  8248. @w{@kbd{sqrt( )}} instead of @kbd{Q}, @w{@kbd{factor( )}} instead of
  8249. @kbd{a f}, and so on. To type regular Calc commands when you are in
  8250. Total Algebraic mode, hold down the @key{META} key. Thus @kbd{M-q}
  8251. is the command to quit Calc, @kbd{M-p} sets the precision, and
  8252. @kbd{M-m t} (or @kbd{M-m M-t}, if you prefer) turns Total Algebraic
  8253. mode back off again. Meta keys also terminate algebraic entry, so
  8254. that @kbd{2+3 M-S} is equivalent to @kbd{2+3 @key{RET} M-S}. The symbol
  8255. @samp{Alg*} will appear in the mode line whenever you are in this mode.
  8256. Pressing @kbd{'} (the apostrophe) a second time re-enters the previous
  8257. algebraic formula. You can then use the normal Emacs editing keys to
  8258. modify this formula to your liking before pressing @key{RET}.
  8259. @kindex $
  8260. @cindex Formulas, referring to stack
  8261. Within a formula entered from the keyboard, the symbol @kbd{$}
  8262. represents the number on the top of the stack. If an entered formula
  8263. contains any @kbd{$} characters, the Calculator replaces the top of
  8264. stack with that formula rather than simply pushing the formula onto the
  8265. stack. Thus, @kbd{' 1+2 @key{RET}} pushes 3 on the stack, and @kbd{$*2
  8266. @key{RET}} replaces it with 6. Note that the @kbd{$} key always
  8267. initiates algebraic entry; the @kbd{'} is unnecessary if @kbd{$} is the
  8268. first character in the new formula.
  8269. Higher stack elements can be accessed from an entered formula with the
  8270. symbols @kbd{$$}, @kbd{$$$}, and so on. The number of stack elements
  8271. removed (to be replaced by the entered values) equals the number of dollar
  8272. signs in the longest such symbol in the formula. For example, @samp{$$+$$$}
  8273. adds the second and third stack elements, replacing the top three elements
  8274. with the answer. (All information about the top stack element is thus lost
  8275. since no single @samp{$} appears in this formula.)
  8276. A slightly different way to refer to stack elements is with a dollar
  8277. sign followed by a number: @samp{$1}, @samp{$2}, and so on are much
  8278. like @samp{$}, @samp{$$}, etc., except that stack entries referred
  8279. to numerically are not replaced by the algebraic entry. That is, while
  8280. @samp{$+1} replaces 5 on the stack with 6, @samp{$1+1} leaves the 5
  8281. on the stack and pushes an additional 6.
  8282. If a sequence of formulas are entered separated by commas, each formula
  8283. is pushed onto the stack in turn. For example, @samp{1,2,3} pushes
  8284. those three numbers onto the stack (leaving the 3 at the top), and
  8285. @samp{$+1,$-1} replaces a 5 on the stack with 4 followed by 6. Also,
  8286. @samp{$,$$} exchanges the top two elements of the stack, just like the
  8287. @key{TAB} key.
  8288. You can finish an algebraic entry with @kbd{M-=} or @kbd{M-@key{RET}} instead
  8289. of @key{RET}. This uses @kbd{=} to evaluate the variables in each
  8290. formula that goes onto the stack. (Thus @kbd{' pi @key{RET}} pushes
  8291. the variable @samp{pi}, but @kbd{' pi M-@key{RET}} pushes 3.1415.)
  8292. If you finish your algebraic entry by pressing @key{LFD} (or @kbd{C-j})
  8293. instead of @key{RET}, Calc disables simplification
  8294. (as if by @kbd{m O}; @pxref{Simplification Modes}) while the entry
  8295. is being pushed on the stack. Thus @kbd{' 1+2 @key{RET}} pushes 3
  8296. on the stack, but @kbd{' 1+2 @key{LFD}} pushes the formula @expr{1+2};
  8297. you might then press @kbd{=} when it is time to evaluate this formula.
  8298. @node Quick Calculator, Prefix Arguments, Algebraic Entry, Introduction
  8299. @section ``Quick Calculator'' Mode
  8300. @noindent
  8301. @kindex C-x * q
  8302. @pindex quick-calc
  8303. @cindex Quick Calculator
  8304. There is another way to invoke the Calculator if all you need to do
  8305. is make one or two quick calculations. Type @kbd{C-x * q} (or
  8306. @kbd{M-x quick-calc}), then type any formula as an algebraic entry.
  8307. The Calculator will compute the result and display it in the echo
  8308. area, without ever actually putting up a Calc window.
  8309. You can use the @kbd{$} character in a Quick Calculator formula to
  8310. refer to the previous Quick Calculator result. Older results are
  8311. not retained; the Quick Calculator has no effect on the full
  8312. Calculator's stack or trail. If you compute a result and then
  8313. forget what it was, just run @code{C-x * q} again and enter
  8314. @samp{$} as the formula.
  8315. If this is the first time you have used the Calculator in this Emacs
  8316. session, the @kbd{C-x * q} command will create the @file{*Calculator*}
  8317. buffer and perform all the usual initializations; it simply will
  8318. refrain from putting that buffer up in a new window. The Quick
  8319. Calculator refers to the @file{*Calculator*} buffer for all mode
  8320. settings. Thus, for example, to set the precision that the Quick
  8321. Calculator uses, simply run the full Calculator momentarily and use
  8322. the regular @kbd{p} command.
  8323. If you use @code{C-x * q} from inside the Calculator buffer, the
  8324. effect is the same as pressing the apostrophe key (algebraic entry).
  8325. The result of a Quick calculation is placed in the Emacs ``kill ring''
  8326. as well as being displayed. A subsequent @kbd{C-y} command will
  8327. yank the result into the editing buffer. You can also use this
  8328. to yank the result into the next @kbd{C-x * q} input line as a more
  8329. explicit alternative to @kbd{$} notation, or to yank the result
  8330. into the Calculator stack after typing @kbd{C-x * c}.
  8331. If you give a prefix argument to @kbd{C-x * q} or finish your formula
  8332. by typing @key{LFD} (or @kbd{C-j}) instead of @key{RET}, the result is
  8333. inserted immediately into the current buffer rather than going into
  8334. the kill ring.
  8335. Quick Calculator results are actually evaluated as if by the @kbd{=}
  8336. key (which replaces variable names by their stored values, if any).
  8337. If the formula you enter is an assignment to a variable using the
  8338. @samp{:=} operator, say, @samp{foo := 2 + 3} or @samp{foo := foo + 1},
  8339. then the result of the evaluation is stored in that Calc variable.
  8340. @xref{Store and Recall}.
  8341. If the result is an integer and the current display radix is decimal,
  8342. the number will also be displayed in hex, octal and binary formats. If
  8343. the integer is in the range from 1 to 126, it will also be displayed as
  8344. an ASCII character.
  8345. For example, the quoted character @samp{"x"} produces the vector
  8346. result @samp{[120]} (because 120 is the ASCII code of the lower-case
  8347. ``x''; @pxref{Strings}). Since this is a vector, not an integer, it
  8348. is displayed only according to the current mode settings. But
  8349. running Quick Calc again and entering @samp{120} will produce the
  8350. result @samp{120 (16#78, 8#170, x)} which shows the number in its
  8351. decimal, hexadecimal, octal, and ASCII forms.
  8352. Please note that the Quick Calculator is not any faster at loading
  8353. or computing the answer than the full Calculator; the name ``quick''
  8354. merely refers to the fact that it's much less hassle to use for
  8355. small calculations.
  8356. @node Prefix Arguments, Undo, Quick Calculator, Introduction
  8357. @section Numeric Prefix Arguments
  8358. @noindent
  8359. Many Calculator commands use numeric prefix arguments. Some, such as
  8360. @kbd{d s} (@code{calc-sci-notation}), set a parameter to the value of
  8361. the prefix argument or use a default if you don't use a prefix.
  8362. Others (like @kbd{d f} (@code{calc-fix-notation})) require an argument
  8363. and prompt for a number if you don't give one as a prefix.
  8364. As a rule, stack-manipulation commands accept a numeric prefix argument
  8365. which is interpreted as an index into the stack. A positive argument
  8366. operates on the top @var{n} stack entries; a negative argument operates
  8367. on the @var{n}th stack entry in isolation; and a zero argument operates
  8368. on the entire stack.
  8369. Most commands that perform computations (such as the arithmetic and
  8370. scientific functions) accept a numeric prefix argument that allows the
  8371. operation to be applied across many stack elements. For unary operations
  8372. (that is, functions of one argument like absolute value or complex
  8373. conjugate), a positive prefix argument applies that function to the top
  8374. @var{n} stack entries simultaneously, and a negative argument applies it
  8375. to the @var{n}th stack entry only. For binary operations (functions of
  8376. two arguments like addition, GCD, and vector concatenation), a positive
  8377. prefix argument ``reduces'' the function across the top @var{n}
  8378. stack elements (for example, @kbd{C-u 5 +} sums the top 5 stack entries;
  8379. @pxref{Reducing and Mapping}), and a negative argument maps the next-to-top
  8380. @var{n} stack elements with the top stack element as a second argument
  8381. (for example, @kbd{7 c-u -5 +} adds 7 to the top 5 stack elements).
  8382. This feature is not available for operations which use the numeric prefix
  8383. argument for some other purpose.
  8384. Numeric prefixes are specified the same way as always in Emacs: Press
  8385. a sequence of @key{META}-digits, or press @key{ESC} followed by digits,
  8386. or press @kbd{C-u} followed by digits. Some commands treat plain
  8387. @kbd{C-u} (without any actual digits) specially.
  8388. @kindex ~
  8389. @pindex calc-num-prefix
  8390. You can type @kbd{~} (@code{calc-num-prefix}) to pop an integer from the
  8391. top of the stack and enter it as the numeric prefix for the next command.
  8392. For example, @kbd{C-u 16 p} sets the precision to 16 digits; an alternate
  8393. (silly) way to do this would be @kbd{2 @key{RET} 4 ^ ~ p}, i.e., compute 2
  8394. to the fourth power and set the precision to that value.
  8395. Conversely, if you have typed a numeric prefix argument the @kbd{~} key
  8396. pushes it onto the stack in the form of an integer.
  8397. @node Undo, Error Messages, Prefix Arguments, Introduction
  8398. @section Undoing Mistakes
  8399. @noindent
  8400. @kindex U
  8401. @kindex C-_
  8402. @pindex calc-undo
  8403. @cindex Mistakes, undoing
  8404. @cindex Undoing mistakes
  8405. @cindex Errors, undoing
  8406. The shift-@kbd{U} key (@code{calc-undo}) undoes the most recent operation.
  8407. If that operation added or dropped objects from the stack, those objects
  8408. are removed or restored. If it was a ``store'' operation, you are
  8409. queried whether or not to restore the variable to its original value.
  8410. The @kbd{U} key may be pressed any number of times to undo successively
  8411. farther back in time; with a numeric prefix argument it undoes a
  8412. specified number of operations. When the Calculator is quit, as with
  8413. the @kbd{q} (@code{calc-quit}) command, the undo history will be
  8414. truncated to the length of the customizable variable
  8415. @code{calc-undo-length} (@pxref{Customizing Calc}), which by default
  8416. is @expr{100}. (Recall that @kbd{C-x * c} is synonymous with
  8417. @code{calc-quit} while inside the Calculator; this also truncates the
  8418. undo history.)
  8419. Currently the mode-setting commands (like @code{calc-precision}) are not
  8420. undoable. You can undo past a point where you changed a mode, but you
  8421. will need to reset the mode yourself.
  8422. @kindex D
  8423. @pindex calc-redo
  8424. @cindex Redoing after an Undo
  8425. The shift-@kbd{D} key (@code{calc-redo}) redoes an operation that was
  8426. mistakenly undone. Pressing @kbd{U} with a negative prefix argument is
  8427. equivalent to executing @code{calc-redo}. You can redo any number of
  8428. times, up to the number of recent consecutive undo commands. Redo
  8429. information is cleared whenever you give any command that adds new undo
  8430. information, i.e., if you undo, then enter a number on the stack or make
  8431. any other change, then it will be too late to redo.
  8432. @kindex M-@key{RET}
  8433. @pindex calc-last-args
  8434. @cindex Last-arguments feature
  8435. @cindex Arguments, restoring
  8436. The @kbd{M-@key{RET}} key (@code{calc-last-args}) is like undo in that
  8437. it restores the arguments of the most recent command onto the stack;
  8438. however, it does not remove the result of that command. Given a numeric
  8439. prefix argument, this command applies to the @expr{n}th most recent
  8440. command which removed items from the stack; it pushes those items back
  8441. onto the stack.
  8442. The @kbd{K} (@code{calc-keep-args}) command provides a related function
  8443. to @kbd{M-@key{RET}}. @xref{Stack and Trail}.
  8444. It is also possible to recall previous results or inputs using the trail.
  8445. @xref{Trail Commands}.
  8446. The standard Emacs @kbd{C-_} undo key is recognized as a synonym for @kbd{U}.
  8447. @node Error Messages, Multiple Calculators, Undo, Introduction
  8448. @section Error Messages
  8449. @noindent
  8450. @kindex w
  8451. @pindex calc-why
  8452. @cindex Errors, messages
  8453. @cindex Why did an error occur?
  8454. Many situations that would produce an error message in other calculators
  8455. simply create unsimplified formulas in the Emacs Calculator. For example,
  8456. @kbd{1 @key{RET} 0 /} pushes the formula @expr{1 / 0}; @w{@kbd{0 L}} pushes
  8457. the formula @samp{ln(0)}. Floating-point overflow and underflow are also
  8458. reasons for this to happen.
  8459. When a function call must be left in symbolic form, Calc usually
  8460. produces a message explaining why. Messages that are probably
  8461. surprising or indicative of user errors are displayed automatically.
  8462. Other messages are simply kept in Calc's memory and are displayed only
  8463. if you type @kbd{w} (@code{calc-why}). You can also press @kbd{w} if
  8464. the same computation results in several messages. (The first message
  8465. will end with @samp{[w=more]} in this case.)
  8466. @kindex d w
  8467. @pindex calc-auto-why
  8468. The @kbd{d w} (@code{calc-auto-why}) command controls when error messages
  8469. are displayed automatically. (Calc effectively presses @kbd{w} for you
  8470. after your computation finishes.) By default, this occurs only for
  8471. ``important'' messages. The other possible modes are to report
  8472. @emph{all} messages automatically, or to report none automatically (so
  8473. that you must always press @kbd{w} yourself to see the messages).
  8474. @node Multiple Calculators, Troubleshooting Commands, Error Messages, Introduction
  8475. @section Multiple Calculators
  8476. @noindent
  8477. @pindex another-calc
  8478. It is possible to have any number of Calc mode buffers at once.
  8479. Usually this is done by executing @kbd{M-x another-calc}, which
  8480. is similar to @kbd{C-x * c} except that if a @file{*Calculator*}
  8481. buffer already exists, a new, independent one with a name of the
  8482. form @file{*Calculator*<@var{n}>} is created. You can also use the
  8483. command @code{calc-mode} to put any buffer into Calculator mode, but
  8484. this would ordinarily never be done.
  8485. The @kbd{q} (@code{calc-quit}) command does not destroy a Calculator buffer;
  8486. it only closes its window. Use @kbd{M-x kill-buffer} to destroy a
  8487. Calculator buffer.
  8488. Each Calculator buffer keeps its own stack, undo list, and mode settings
  8489. such as precision, angular mode, and display formats. In Emacs terms,
  8490. variables such as @code{calc-stack} are buffer-local variables. The
  8491. global default values of these variables are used only when a new
  8492. Calculator buffer is created. The @code{calc-quit} command saves
  8493. the stack and mode settings of the buffer being quit as the new defaults.
  8494. There is only one trail buffer, @file{*Calc Trail*}, used by all
  8495. Calculator buffers.
  8496. @node Troubleshooting Commands, , Multiple Calculators, Introduction
  8497. @section Troubleshooting Commands
  8498. @noindent
  8499. This section describes commands you can use in case a computation
  8500. incorrectly fails or gives the wrong answer.
  8501. @xref{Reporting Bugs}, if you find a problem that appears to be due
  8502. to a bug or deficiency in Calc.
  8503. @menu
  8504. * Autoloading Problems::
  8505. * Recursion Depth::
  8506. * Caches::
  8507. * Debugging Calc::
  8508. @end menu
  8509. @node Autoloading Problems, Recursion Depth, Troubleshooting Commands, Troubleshooting Commands
  8510. @subsection Autoloading Problems
  8511. @noindent
  8512. The Calc program is split into many component files; components are
  8513. loaded automatically as you use various commands that require them.
  8514. Occasionally Calc may lose track of when a certain component is
  8515. necessary; typically this means you will type a command and it won't
  8516. work because some function you've never heard of was undefined.
  8517. @kindex C-x * L
  8518. @pindex calc-load-everything
  8519. If this happens, the easiest workaround is to type @kbd{C-x * L}
  8520. (@code{calc-load-everything}) to force all the parts of Calc to be
  8521. loaded right away. This will cause Emacs to take up a lot more
  8522. memory than it would otherwise, but it's guaranteed to fix the problem.
  8523. @node Recursion Depth, Caches, Autoloading Problems, Troubleshooting Commands
  8524. @subsection Recursion Depth
  8525. @noindent
  8526. @kindex M
  8527. @kindex I M
  8528. @pindex calc-more-recursion-depth
  8529. @pindex calc-less-recursion-depth
  8530. @cindex Recursion depth
  8531. @cindex ``Computation got stuck'' message
  8532. @cindex @code{max-lisp-eval-depth}
  8533. @cindex @code{max-specpdl-size}
  8534. Calc uses recursion in many of its calculations. Emacs Lisp keeps a
  8535. variable @code{max-lisp-eval-depth} which limits the amount of recursion
  8536. possible in an attempt to recover from program bugs. If a calculation
  8537. ever halts incorrectly with the message ``Computation got stuck or
  8538. ran too long,'' use the @kbd{M} command (@code{calc-more-recursion-depth})
  8539. to increase this limit. (Of course, this will not help if the
  8540. calculation really did get stuck due to some problem inside Calc.)
  8541. The limit is always increased (multiplied) by a factor of two. There
  8542. is also an @kbd{I M} (@code{calc-less-recursion-depth}) command which
  8543. decreases this limit by a factor of two, down to a minimum value of 200.
  8544. The default value is 1000.
  8545. These commands also double or halve @code{max-specpdl-size}, another
  8546. internal Lisp recursion limit. The minimum value for this limit is 600.
  8547. @node Caches, Debugging Calc, Recursion Depth, Troubleshooting Commands
  8548. @subsection Caches
  8549. @noindent
  8550. @cindex Caches
  8551. @cindex Flushing caches
  8552. Calc saves certain values after they have been computed once. For
  8553. example, the @kbd{P} (@code{calc-pi}) command initially ``knows'' the
  8554. constant @cpi{} to about 20 decimal places; if the current precision
  8555. is greater than this, it will recompute @cpi{} using a series
  8556. approximation. This value will not need to be recomputed ever again
  8557. unless you raise the precision still further. Many operations such as
  8558. logarithms and sines make use of similarly cached values such as
  8559. @cpiover{4} and
  8560. @texline @math{\ln 2}.
  8561. @infoline @expr{ln(2)}.
  8562. The visible effect of caching is that
  8563. high-precision computations may seem to do extra work the first time.
  8564. Other things cached include powers of two (for the binary arithmetic
  8565. functions), matrix inverses and determinants, symbolic integrals, and
  8566. data points computed by the graphing commands.
  8567. @pindex calc-flush-caches
  8568. If you suspect a Calculator cache has become corrupt, you can use the
  8569. @code{calc-flush-caches} command to reset all caches to the empty state.
  8570. (This should only be necessary in the event of bugs in the Calculator.)
  8571. The @kbd{C-x * 0} (with the zero key) command also resets caches along
  8572. with all other aspects of the Calculator's state.
  8573. @node Debugging Calc, , Caches, Troubleshooting Commands
  8574. @subsection Debugging Calc
  8575. @noindent
  8576. A few commands exist to help in the debugging of Calc commands.
  8577. @xref{Programming}, to see the various ways that you can write
  8578. your own Calc commands.
  8579. @kindex Z T
  8580. @pindex calc-timing
  8581. The @kbd{Z T} (@code{calc-timing}) command turns on and off a mode
  8582. in which the timing of slow commands is reported in the Trail.
  8583. Any Calc command that takes two seconds or longer writes a line
  8584. to the Trail showing how many seconds it took. This value is
  8585. accurate only to within one second.
  8586. All steps of executing a command are included; in particular, time
  8587. taken to format the result for display in the stack and trail is
  8588. counted. Some prompts also count time taken waiting for them to
  8589. be answered, while others do not; this depends on the exact
  8590. implementation of the command. For best results, if you are timing
  8591. a sequence that includes prompts or multiple commands, define a
  8592. keyboard macro to run the whole sequence at once. Calc's @kbd{X}
  8593. command (@pxref{Keyboard Macros}) will then report the time taken
  8594. to execute the whole macro.
  8595. Another advantage of the @kbd{X} command is that while it is
  8596. executing, the stack and trail are not updated from step to step.
  8597. So if you expect the output of your test sequence to leave a result
  8598. that may take a long time to format and you don't wish to count
  8599. this formatting time, end your sequence with a @key{DEL} keystroke
  8600. to clear the result from the stack. When you run the sequence with
  8601. @kbd{X}, Calc will never bother to format the large result.
  8602. Another thing @kbd{Z T} does is to increase the Emacs variable
  8603. @code{gc-cons-threshold} to a much higher value (two million; the
  8604. usual default in Calc is 250,000) for the duration of each command.
  8605. This generally prevents garbage collection during the timing of
  8606. the command, though it may cause your Emacs process to grow
  8607. abnormally large. (Garbage collection time is a major unpredictable
  8608. factor in the timing of Emacs operations.)
  8609. Another command that is useful when debugging your own Lisp
  8610. extensions to Calc is @kbd{M-x calc-pass-errors}, which disables
  8611. the error handler that changes the ``@code{max-lisp-eval-depth}
  8612. exceeded'' message to the much more friendly ``Computation got
  8613. stuck or ran too long.'' This handler interferes with the Emacs
  8614. Lisp debugger's @code{debug-on-error} mode. Errors are reported
  8615. in the handler itself rather than at the true location of the
  8616. error. After you have executed @code{calc-pass-errors}, Lisp
  8617. errors will be reported correctly but the user-friendly message
  8618. will be lost.
  8619. @node Data Types, Stack and Trail, Introduction, Top
  8620. @chapter Data Types
  8621. @noindent
  8622. This chapter discusses the various types of objects that can be placed
  8623. on the Calculator stack, how they are displayed, and how they are
  8624. entered. (@xref{Data Type Formats}, for information on how these data
  8625. types are represented as underlying Lisp objects.)
  8626. Integers, fractions, and floats are various ways of describing real
  8627. numbers. HMS forms also for many purposes act as real numbers. These
  8628. types can be combined to form complex numbers, modulo forms, error forms,
  8629. or interval forms. (But these last four types cannot be combined
  8630. arbitrarily: error forms may not contain modulo forms, for example.)
  8631. Finally, all these types of numbers may be combined into vectors,
  8632. matrices, or algebraic formulas.
  8633. @menu
  8634. * Integers:: The most basic data type.
  8635. * Fractions:: This and above are called @dfn{rationals}.
  8636. * Floats:: This and above are called @dfn{reals}.
  8637. * Complex Numbers:: This and above are called @dfn{numbers}.
  8638. * Infinities::
  8639. * Vectors and Matrices::
  8640. * Strings::
  8641. * HMS Forms::
  8642. * Date Forms::
  8643. * Modulo Forms::
  8644. * Error Forms::
  8645. * Interval Forms::
  8646. * Incomplete Objects::
  8647. * Variables::
  8648. * Formulas::
  8649. @end menu
  8650. @node Integers, Fractions, Data Types, Data Types
  8651. @section Integers
  8652. @noindent
  8653. @cindex Integers
  8654. The Calculator stores integers to arbitrary precision. Addition,
  8655. subtraction, and multiplication of integers always yields an exact
  8656. integer result. (If the result of a division or exponentiation of
  8657. integers is not an integer, it is expressed in fractional or
  8658. floating-point form according to the current Fraction mode.
  8659. @xref{Fraction Mode}.)
  8660. A decimal integer is represented as an optional sign followed by a
  8661. sequence of digits. Grouping (@pxref{Grouping Digits}) can be used to
  8662. insert a comma at every third digit for display purposes, but you
  8663. must not type commas during the entry of numbers.
  8664. @kindex #
  8665. A non-decimal integer is represented as an optional sign, a radix
  8666. between 2 and 36, a @samp{#} symbol, and one or more digits. For radix 11
  8667. and above, the letters A through Z (upper- or lower-case) count as
  8668. digits and do not terminate numeric entry mode. @xref{Radix Modes}, for how
  8669. to set the default radix for display of integers. Numbers of any radix
  8670. may be entered at any time. If you press @kbd{#} at the beginning of a
  8671. number, the current display radix is used.
  8672. @node Fractions, Floats, Integers, Data Types
  8673. @section Fractions
  8674. @noindent
  8675. @cindex Fractions
  8676. A @dfn{fraction} is a ratio of two integers. Fractions are traditionally
  8677. written ``2/3'' but Calc uses the notation @samp{2:3}. (The @kbd{/} key
  8678. performs RPN division; the following two sequences push the number
  8679. @samp{2:3} on the stack: @kbd{2 :@: 3 @key{RET}}, or @kbd{2 @key{RET} 3 /}
  8680. assuming Fraction mode has been enabled.)
  8681. When the Calculator produces a fractional result it always reduces it to
  8682. simplest form, which may in fact be an integer.
  8683. Fractions may also be entered in a three-part form, where @samp{2:3:4}
  8684. represents two-and-three-quarters. @xref{Fraction Formats}, for fraction
  8685. display formats.
  8686. Non-decimal fractions are entered and displayed as
  8687. @samp{@var{radix}#@var{num}:@var{denom}} (or in the analogous three-part
  8688. form). The numerator and denominator always use the same radix.
  8689. @node Floats, Complex Numbers, Fractions, Data Types
  8690. @section Floats
  8691. @noindent
  8692. @cindex Floating-point numbers
  8693. A floating-point number or @dfn{float} is a number stored in scientific
  8694. notation. The number of significant digits in the fractional part is
  8695. governed by the current floating precision (@pxref{Precision}). The
  8696. range of acceptable values is from
  8697. @texline @math{10^{-3999999}}
  8698. @infoline @expr{10^-3999999}
  8699. (inclusive) to
  8700. @texline @math{10^{4000000}}
  8701. @infoline @expr{10^4000000}
  8702. (exclusive), plus the corresponding negative values and zero.
  8703. Calculations that would exceed the allowable range of values (such
  8704. as @samp{exp(exp(20))}) are left in symbolic form by Calc. The
  8705. messages ``floating-point overflow'' or ``floating-point underflow''
  8706. indicate that during the calculation a number would have been produced
  8707. that was too large or too close to zero, respectively, to be represented
  8708. by Calc. This does not necessarily mean the final result would have
  8709. overflowed, just that an overflow occurred while computing the result.
  8710. (In fact, it could report an underflow even though the final result
  8711. would have overflowed!)
  8712. If a rational number and a float are mixed in a calculation, the result
  8713. will in general be expressed as a float. Commands that require an integer
  8714. value (such as @kbd{k g} [@code{gcd}]) will also accept integer-valued
  8715. floats, i.e., floating-point numbers with nothing after the decimal point.
  8716. Floats are identified by the presence of a decimal point and/or an
  8717. exponent. In general a float consists of an optional sign, digits
  8718. including an optional decimal point, and an optional exponent consisting
  8719. of an @samp{e}, an optional sign, and up to seven exponent digits.
  8720. For example, @samp{23.5e-2} is 23.5 times ten to the minus-second power,
  8721. or 0.235.
  8722. Floating-point numbers are normally displayed in decimal notation with
  8723. all significant figures shown. Exceedingly large or small numbers are
  8724. displayed in scientific notation. Various other display options are
  8725. available. @xref{Float Formats}.
  8726. @cindex Accuracy of calculations
  8727. Floating-point numbers are stored in decimal, not binary. The result
  8728. of each operation is rounded to the nearest value representable in the
  8729. number of significant digits specified by the current precision,
  8730. rounding away from zero in the case of a tie. Thus (in the default
  8731. display mode) what you see is exactly what you get. Some operations such
  8732. as square roots and transcendental functions are performed with several
  8733. digits of extra precision and then rounded down, in an effort to make the
  8734. final result accurate to the full requested precision. However,
  8735. accuracy is not rigorously guaranteed. If you suspect the validity of a
  8736. result, try doing the same calculation in a higher precision. The
  8737. Calculator's arithmetic is not intended to be IEEE-conformant in any
  8738. way.
  8739. While floats are always @emph{stored} in decimal, they can be entered
  8740. and displayed in any radix just like integers and fractions. Since a
  8741. float that is entered in a radix other that 10 will be converted to
  8742. decimal, the number that Calc stores may not be exactly the number that
  8743. was entered, it will be the closest decimal approximation given the
  8744. current precision. The notation @samp{@var{radix}#@var{ddd}.@var{ddd}}
  8745. is a floating-point number whose digits are in the specified radix.
  8746. Note that the @samp{.} is more aptly referred to as a ``radix point''
  8747. than as a decimal point in this case. The number @samp{8#123.4567} is
  8748. defined as @samp{8#1234567 * 8^-4}. If the radix is 14 or less, you can
  8749. use @samp{e} notation to write a non-decimal number in scientific
  8750. notation. The exponent is written in decimal, and is considered to be a
  8751. power of the radix: @samp{8#1234567e-4}. If the radix is 15 or above,
  8752. the letter @samp{e} is a digit, so scientific notation must be written
  8753. out, e.g., @samp{16#123.4567*16^2}. The first two exercises of the
  8754. Modes Tutorial explore some of the properties of non-decimal floats.
  8755. @node Complex Numbers, Infinities, Floats, Data Types
  8756. @section Complex Numbers
  8757. @noindent
  8758. @cindex Complex numbers
  8759. There are two supported formats for complex numbers: rectangular and
  8760. polar. The default format is rectangular, displayed in the form
  8761. @samp{(@var{real},@var{imag})} where @var{real} is the real part and
  8762. @var{imag} is the imaginary part, each of which may be any real number.
  8763. Rectangular complex numbers can also be displayed in @samp{@var{a}+@var{b}i}
  8764. notation; @pxref{Complex Formats}.
  8765. Polar complex numbers are displayed in the form
  8766. @texline `@tfn{(}@var{r}@tfn{;}@math{\theta}@tfn{)}'
  8767. @infoline `@tfn{(}@var{r}@tfn{;}@var{theta}@tfn{)}'
  8768. where @var{r} is the nonnegative magnitude and
  8769. @texline @math{\theta}
  8770. @infoline @var{theta}
  8771. is the argument or phase angle. The range of
  8772. @texline @math{\theta}
  8773. @infoline @var{theta}
  8774. depends on the current angular mode (@pxref{Angular Modes}); it is
  8775. generally between @mathit{-180} and @mathit{+180} degrees or the equivalent range
  8776. in radians.
  8777. Complex numbers are entered in stages using incomplete objects.
  8778. @xref{Incomplete Objects}.
  8779. Operations on rectangular complex numbers yield rectangular complex
  8780. results, and similarly for polar complex numbers. Where the two types
  8781. are mixed, or where new complex numbers arise (as for the square root of
  8782. a negative real), the current @dfn{Polar mode} is used to determine the
  8783. type. @xref{Polar Mode}.
  8784. A complex result in which the imaginary part is zero (or the phase angle
  8785. is 0 or 180 degrees or @cpi{} radians) is automatically converted to a real
  8786. number.
  8787. @node Infinities, Vectors and Matrices, Complex Numbers, Data Types
  8788. @section Infinities
  8789. @noindent
  8790. @cindex Infinity
  8791. @cindex @code{inf} variable
  8792. @cindex @code{uinf} variable
  8793. @cindex @code{nan} variable
  8794. @vindex inf
  8795. @vindex uinf
  8796. @vindex nan
  8797. The word @code{inf} represents the mathematical concept of @dfn{infinity}.
  8798. Calc actually has three slightly different infinity-like values:
  8799. @code{inf}, @code{uinf}, and @code{nan}. These are just regular
  8800. variable names (@pxref{Variables}); you should avoid using these
  8801. names for your own variables because Calc gives them special
  8802. treatment. Infinities, like all variable names, are normally
  8803. entered using algebraic entry.
  8804. Mathematically speaking, it is not rigorously correct to treat
  8805. ``infinity'' as if it were a number, but mathematicians often do
  8806. so informally. When they say that @samp{1 / inf = 0}, what they
  8807. really mean is that @expr{1 / x}, as @expr{x} becomes larger and
  8808. larger, becomes arbitrarily close to zero. So you can imagine
  8809. that if @expr{x} got ``all the way to infinity,'' then @expr{1 / x}
  8810. would go all the way to zero. Similarly, when they say that
  8811. @samp{exp(inf) = inf}, they mean that
  8812. @texline @math{e^x}
  8813. @infoline @expr{exp(x)}
  8814. grows without bound as @expr{x} grows. The symbol @samp{-inf} likewise
  8815. stands for an infinitely negative real value; for example, we say that
  8816. @samp{exp(-inf) = 0}. You can have an infinity pointing in any
  8817. direction on the complex plane: @samp{sqrt(-inf) = i inf}.
  8818. The same concept of limits can be used to define @expr{1 / 0}. We
  8819. really want the value that @expr{1 / x} approaches as @expr{x}
  8820. approaches zero. But if all we have is @expr{1 / 0}, we can't
  8821. tell which direction @expr{x} was coming from. If @expr{x} was
  8822. positive and decreasing toward zero, then we should say that
  8823. @samp{1 / 0 = inf}. But if @expr{x} was negative and increasing
  8824. toward zero, the answer is @samp{1 / 0 = -inf}. In fact, @expr{x}
  8825. could be an imaginary number, giving the answer @samp{i inf} or
  8826. @samp{-i inf}. Calc uses the special symbol @samp{uinf} to mean
  8827. @dfn{undirected infinity}, i.e., a value which is infinitely
  8828. large but with an unknown sign (or direction on the complex plane).
  8829. Calc actually has three modes that say how infinities are handled.
  8830. Normally, infinities never arise from calculations that didn't
  8831. already have them. Thus, @expr{1 / 0} is treated simply as an
  8832. error and left unevaluated. The @kbd{m i} (@code{calc-infinite-mode})
  8833. command (@pxref{Infinite Mode}) enables a mode in which
  8834. @expr{1 / 0} evaluates to @code{uinf} instead. There is also
  8835. an alternative type of infinite mode which says to treat zeros
  8836. as if they were positive, so that @samp{1 / 0 = inf}. While this
  8837. is less mathematically correct, it may be the answer you want in
  8838. some cases.
  8839. Since all infinities are ``as large'' as all others, Calc simplifies,
  8840. e.g., @samp{5 inf} to @samp{inf}. Another example is
  8841. @samp{5 - inf = -inf}, where the @samp{-inf} is so large that
  8842. adding a finite number like five to it does not affect it.
  8843. Note that @samp{a - inf} also results in @samp{-inf}; Calc assumes
  8844. that variables like @code{a} always stand for finite quantities.
  8845. Just to show that infinities really are all the same size,
  8846. note that @samp{sqrt(inf) = inf^2 = exp(inf) = inf} in Calc's
  8847. notation.
  8848. It's not so easy to define certain formulas like @samp{0 * inf} and
  8849. @samp{inf / inf}. Depending on where these zeros and infinities
  8850. came from, the answer could be literally anything. The latter
  8851. formula could be the limit of @expr{x / x} (giving a result of one),
  8852. or @expr{2 x / x} (giving two), or @expr{x^2 / x} (giving @code{inf}),
  8853. or @expr{x / x^2} (giving zero). Calc uses the symbol @code{nan}
  8854. to represent such an @dfn{indeterminate} value. (The name ``nan''
  8855. comes from analogy with the ``NAN'' concept of IEEE standard
  8856. arithmetic; it stands for ``Not A Number.'' This is somewhat of a
  8857. misnomer, since @code{nan} @emph{does} stand for some number or
  8858. infinity, it's just that @emph{which} number it stands for
  8859. cannot be determined.) In Calc's notation, @samp{0 * inf = nan}
  8860. and @samp{inf / inf = nan}. A few other common indeterminate
  8861. expressions are @samp{inf - inf} and @samp{inf ^ 0}. Also,
  8862. @samp{0 / 0 = nan} if you have turned on Infinite mode
  8863. (as described above).
  8864. Infinities are especially useful as parts of @dfn{intervals}.
  8865. @xref{Interval Forms}.
  8866. @node Vectors and Matrices, Strings, Infinities, Data Types
  8867. @section Vectors and Matrices
  8868. @noindent
  8869. @cindex Vectors
  8870. @cindex Plain vectors
  8871. @cindex Matrices
  8872. The @dfn{vector} data type is flexible and general. A vector is simply a
  8873. list of zero or more data objects. When these objects are numbers, the
  8874. whole is a vector in the mathematical sense. When these objects are
  8875. themselves vectors of equal (nonzero) length, the whole is a @dfn{matrix}.
  8876. A vector which is not a matrix is referred to here as a @dfn{plain vector}.
  8877. A vector is displayed as a list of values separated by commas and enclosed
  8878. in square brackets: @samp{[1, 2, 3]}. Thus the following is a 2 row by
  8879. 3 column matrix: @samp{[[1, 2, 3], [4, 5, 6]]}. Vectors, like complex
  8880. numbers, are entered as incomplete objects. @xref{Incomplete Objects}.
  8881. During algebraic entry, vectors are entered all at once in the usual
  8882. brackets-and-commas form. Matrices may be entered algebraically as nested
  8883. vectors, or using the shortcut notation @w{@samp{[1, 2, 3; 4, 5, 6]}},
  8884. with rows separated by semicolons. The commas may usually be omitted
  8885. when entering vectors: @samp{[1 2 3]}. Curly braces may be used in
  8886. place of brackets: @samp{@{1, 2, 3@}}, but the commas are required in
  8887. this case.
  8888. Traditional vector and matrix arithmetic is also supported;
  8889. @pxref{Basic Arithmetic} and @pxref{Matrix Functions}.
  8890. Many other operations are applied to vectors element-wise. For example,
  8891. the complex conjugate of a vector is a vector of the complex conjugates
  8892. of its elements.
  8893. @ignore
  8894. @starindex
  8895. @end ignore
  8896. @tindex vec
  8897. Algebraic functions for building vectors include @samp{vec(a, b, c)}
  8898. to build @samp{[a, b, c]}, @samp{cvec(a, n, m)} to build an
  8899. @texline @math{n\times m}
  8900. @infoline @var{n}x@var{m}
  8901. matrix of @samp{a}s, and @samp{index(n)} to build a vector of integers
  8902. from 1 to @samp{n}.
  8903. @node Strings, HMS Forms, Vectors and Matrices, Data Types
  8904. @section Strings
  8905. @noindent
  8906. @kindex "
  8907. @cindex Strings
  8908. @cindex Character strings
  8909. Character strings are not a special data type in the Calculator.
  8910. Rather, a string is represented simply as a vector all of whose
  8911. elements are integers in the range 0 to 255 (ASCII codes). You can
  8912. enter a string at any time by pressing the @kbd{"} key. Quotation
  8913. marks and backslashes are written @samp{\"} and @samp{\\}, respectively,
  8914. inside strings. Other notations introduced by backslashes are:
  8915. @example
  8916. @group
  8917. \a 7 \^@@ 0
  8918. \b 8 \^a-z 1-26
  8919. \e 27 \^[ 27
  8920. \f 12 \^\\ 28
  8921. \n 10 \^] 29
  8922. \r 13 \^^ 30
  8923. \t 9 \^_ 31
  8924. \^? 127
  8925. @end group
  8926. @end example
  8927. @noindent
  8928. Finally, a backslash followed by three octal digits produces any
  8929. character from its ASCII code.
  8930. @kindex d "
  8931. @pindex calc-display-strings
  8932. Strings are normally displayed in vector-of-integers form. The
  8933. @w{@kbd{d "}} (@code{calc-display-strings}) command toggles a mode in
  8934. which any vectors of small integers are displayed as quoted strings
  8935. instead.
  8936. The backslash notations shown above are also used for displaying
  8937. strings. Characters 128 and above are not translated by Calc; unless
  8938. you have an Emacs modified for 8-bit fonts, these will show up in
  8939. backslash-octal-digits notation. For characters below 32, and
  8940. for character 127, Calc uses the backslash-letter combination if
  8941. there is one, or otherwise uses a @samp{\^} sequence.
  8942. The only Calc feature that uses strings is @dfn{compositions};
  8943. @pxref{Compositions}. Strings also provide a convenient
  8944. way to do conversions between ASCII characters and integers.
  8945. @ignore
  8946. @starindex
  8947. @end ignore
  8948. @tindex string
  8949. There is a @code{string} function which provides a different display
  8950. format for strings. Basically, @samp{string(@var{s})}, where @var{s}
  8951. is a vector of integers in the proper range, is displayed as the
  8952. corresponding string of characters with no surrounding quotation
  8953. marks or other modifications. Thus @samp{string("ABC")} (or
  8954. @samp{string([65 66 67])}) will look like @samp{ABC} on the stack.
  8955. This happens regardless of whether @w{@kbd{d "}} has been used. The
  8956. only way to turn it off is to use @kbd{d U} (unformatted language
  8957. mode) which will display @samp{string("ABC")} instead.
  8958. Control characters are displayed somewhat differently by @code{string}.
  8959. Characters below 32, and character 127, are shown using @samp{^} notation
  8960. (same as shown above, but without the backslash). The quote and
  8961. backslash characters are left alone, as are characters 128 and above.
  8962. @ignore
  8963. @starindex
  8964. @end ignore
  8965. @tindex bstring
  8966. The @code{bstring} function is just like @code{string} except that
  8967. the resulting string is breakable across multiple lines if it doesn't
  8968. fit all on one line. Potential break points occur at every space
  8969. character in the string.
  8970. @node HMS Forms, Date Forms, Strings, Data Types
  8971. @section HMS Forms
  8972. @noindent
  8973. @cindex Hours-minutes-seconds forms
  8974. @cindex Degrees-minutes-seconds forms
  8975. @dfn{HMS} stands for Hours-Minutes-Seconds; when used as an angular
  8976. argument, the interpretation is Degrees-Minutes-Seconds. All functions
  8977. that operate on angles accept HMS forms. These are interpreted as
  8978. degrees regardless of the current angular mode. It is also possible to
  8979. use HMS as the angular mode so that calculated angles are expressed in
  8980. degrees, minutes, and seconds.
  8981. @kindex @@
  8982. @ignore
  8983. @mindex @null
  8984. @end ignore
  8985. @kindex ' (HMS forms)
  8986. @ignore
  8987. @mindex @null
  8988. @end ignore
  8989. @kindex " (HMS forms)
  8990. @ignore
  8991. @mindex @null
  8992. @end ignore
  8993. @kindex h (HMS forms)
  8994. @ignore
  8995. @mindex @null
  8996. @end ignore
  8997. @kindex o (HMS forms)
  8998. @ignore
  8999. @mindex @null
  9000. @end ignore
  9001. @kindex m (HMS forms)
  9002. @ignore
  9003. @mindex @null
  9004. @end ignore
  9005. @kindex s (HMS forms)
  9006. The default format for HMS values is
  9007. @samp{@var{hours}@@ @var{mins}' @var{secs}"}. During entry, the letters
  9008. @samp{h} (for ``hours'') or
  9009. @samp{o} (approximating the ``degrees'' symbol) are accepted as well as
  9010. @samp{@@}, @samp{m} is accepted in place of @samp{'}, and @samp{s} is
  9011. accepted in place of @samp{"}.
  9012. The @var{hours} value is an integer (or integer-valued float).
  9013. The @var{mins} value is an integer or integer-valued float between 0 and 59.
  9014. The @var{secs} value is a real number between 0 (inclusive) and 60
  9015. (exclusive). A positive HMS form is interpreted as @var{hours} +
  9016. @var{mins}/60 + @var{secs}/3600. A negative HMS form is interpreted
  9017. as @mathit{- @var{hours}} @mathit{-} @var{mins}/60 @mathit{-} @var{secs}/3600.
  9018. Display format for HMS forms is quite flexible. @xref{HMS Formats}.
  9019. HMS forms can be added and subtracted. When they are added to numbers,
  9020. the numbers are interpreted according to the current angular mode. HMS
  9021. forms can also be multiplied and divided by real numbers. Dividing
  9022. two HMS forms produces a real-valued ratio of the two angles.
  9023. @pindex calc-time
  9024. @cindex Time of day
  9025. Just for kicks, @kbd{M-x calc-time} pushes the current time of day on
  9026. the stack as an HMS form.
  9027. @node Date Forms, Modulo Forms, HMS Forms, Data Types
  9028. @section Date Forms
  9029. @noindent
  9030. @cindex Date forms
  9031. A @dfn{date form} represents a date and possibly an associated time.
  9032. Simple date arithmetic is supported: Adding a number to a date
  9033. produces a new date shifted by that many days; adding an HMS form to
  9034. a date shifts it by that many hours. Subtracting two date forms
  9035. computes the number of days between them (represented as a simple
  9036. number). Many other operations, such as multiplying two date forms,
  9037. are nonsensical and are not allowed by Calc.
  9038. Date forms are entered and displayed enclosed in @samp{< >} brackets.
  9039. The default format is, e.g., @samp{<Wed Jan 9, 1991>} for dates,
  9040. or @samp{<3:32:20pm Wed Jan 9, 1991>} for dates with times.
  9041. Input is flexible; date forms can be entered in any of the usual
  9042. notations for dates and times. @xref{Date Formats}.
  9043. Date forms are stored internally as numbers, specifically the number
  9044. of days since midnight on the morning of December 31 of the year 1 BC@.
  9045. If the internal number is an integer, the form represents a date only;
  9046. if the internal number is a fraction or float, the form represents
  9047. a date and time. For example, @samp{<6:00am Thu Jan 10, 1991>}
  9048. is represented by the number 726842.25. The standard precision of
  9049. 12 decimal digits is enough to ensure that a (reasonable) date and
  9050. time can be stored without roundoff error.
  9051. If the current precision is greater than 12, date forms will keep
  9052. additional digits in the seconds position. For example, if the
  9053. precision is 15, the seconds will keep three digits after the
  9054. decimal point. Decreasing the precision below 12 may cause the
  9055. time part of a date form to become inaccurate. This can also happen
  9056. if astronomically high years are used, though this will not be an
  9057. issue in everyday (or even everymillennium) use. Note that date
  9058. forms without times are stored as exact integers, so roundoff is
  9059. never an issue for them.
  9060. You can use the @kbd{v p} (@code{calc-pack}) and @kbd{v u}
  9061. (@code{calc-unpack}) commands to get at the numerical representation
  9062. of a date form. @xref{Packing and Unpacking}.
  9063. Date forms can go arbitrarily far into the future or past. Negative
  9064. year numbers represent years BC@. There is no ``year 0''; the day
  9065. before @samp{<Mon Jan 1, +1>} is @samp{<Sun Dec 31, -1>}. These are
  9066. days 1 and 0 respectively in Calc's internal numbering scheme. The
  9067. Gregorian calendar is used for all dates, including dates before the
  9068. Gregorian calendar was invented (although that can be configured; see
  9069. below). Thus Calc's use of the day number @mathit{-10000} to
  9070. represent August 15, 28 BC should be taken with a grain of salt.
  9071. @cindex Julian calendar
  9072. @cindex Gregorian calendar
  9073. Some historical background: The Julian calendar was created by
  9074. Julius Caesar in the year 46 BC as an attempt to fix the confusion
  9075. caused by the irregular Roman calendar that was used before that time.
  9076. The Julian calendar introduced an extra day in all years divisible by
  9077. four. After some initial confusion, the calendar was adopted around
  9078. the year we call 8 AD@. Some centuries later it became
  9079. apparent that the Julian year of 365.25 days was itself not quite
  9080. right. In 1582 Pope Gregory XIII introduced the Gregorian calendar,
  9081. which added the new rule that years divisible by 100, but not by 400,
  9082. were not to be considered leap years despite being divisible by four.
  9083. Many countries delayed adoption of the Gregorian calendar
  9084. because of religious differences. For example, Great Britain and the
  9085. British colonies switched to the Gregorian calendar in September
  9086. 1752, when the Julian calendar was eleven days behind the
  9087. Gregorian calendar. That year in Britain, the day after September 2
  9088. was September 14. To take another example, Russia did not adopt the
  9089. Gregorian calendar until 1918, and that year in Russia the day after
  9090. January 31 was February 14. Calc's reckoning therefore matches English
  9091. practice starting in 1752 and Russian practice starting in 1918, but
  9092. disagrees with earlier dates in both countries.
  9093. When the Julian calendar was introduced, it had January 1 as the first
  9094. day of the year. By the Middle Ages, many European countries
  9095. had changed the beginning of a new year to a different date, often to
  9096. a religious festival. Almost all countries reverted to using January 1
  9097. as the beginning of the year by the time they adopted the Gregorian
  9098. calendar.
  9099. Some calendars attempt to mimic the historical situation by using the
  9100. Gregorian calendar for recent dates and the Julian calendar for older
  9101. dates. The @code{cal} program in most Unix implementations does this,
  9102. for example. While January 1 wasn't always the beginning of a calendar
  9103. year, these hybrid calendars still use January 1 as the beginning of
  9104. the year even for older dates. The customizable variable
  9105. @code{calc-gregorian-switch} (@pxref{Customizing Calc}) can be set to
  9106. have Calc's date forms switch from the Julian to Gregorian calendar at
  9107. any specified date.
  9108. Today's timekeepers introduce an occasional ``leap second''.
  9109. These do not occur regularly and Calc does not take these minor
  9110. effects into account. (If it did, it would have to report a
  9111. non-integer number of days between, say,
  9112. @samp{<12:00am Mon Jan 1, 1900>} and
  9113. @samp{<12:00am Sat Jan 1, 2000>}.)
  9114. @cindex Julian day counting
  9115. Another day counting system in common use is, confusingly, also called
  9116. ``Julian.'' Julian days go from noon to noon. The Julian day number
  9117. is the numbers of days since 12:00 noon (GMT) on November 24, 4714 BC
  9118. in the Gregorian calendar (i.e., January 1, 4713 BC in the Julian
  9119. calendar). In Calc's scheme (in GMT) the Julian day origin is
  9120. @mathit{-1721422.5}, because Calc starts at midnight instead of noon.
  9121. Thus to convert a Calc date code obtained by unpacking a
  9122. date form into a Julian day number, simply add 1721422.5 after
  9123. compensating for the time zone difference. The built-in @kbd{t J}
  9124. command performs this conversion for you.
  9125. The Julian day number is based on the Julian cycle, which was invented
  9126. in 1583 by Joseph Justus Scaliger. Scaliger named it the Julian cycle
  9127. since it involves the Julian calendar, but some have suggested that
  9128. Scaliger named it in honor of his father, Julius Caesar Scaliger. The
  9129. Julian cycle is based on three other cycles: the indiction cycle, the
  9130. Metonic cycle, and the solar cycle. The indiction cycle is a 15 year
  9131. cycle originally used by the Romans for tax purposes but later used to
  9132. date medieval documents. The Metonic cycle is a 19 year cycle; 19
  9133. years is close to being a common multiple of a solar year and a lunar
  9134. month, and so every 19 years the phases of the moon will occur on the
  9135. same days of the year. The solar cycle is a 28 year cycle; the Julian
  9136. calendar repeats itself every 28 years. The smallest time period
  9137. which contains multiples of all three cycles is the least common
  9138. multiple of 15 years, 19 years and 28 years, which (since they're
  9139. pairwise relatively prime) is
  9140. @texline @math{15\times 19\times 28 = 7980} years.
  9141. @infoline 15*19*28 = 7980 years.
  9142. This is the length of a Julian cycle. Working backwards, the previous
  9143. year in which all three cycles began was 4713 BC, and so Scaliger
  9144. chose that year as the beginning of a Julian cycle. Since at the time
  9145. there were no historical records from before 4713 BC, using this year
  9146. as a starting point had the advantage of avoiding negative year
  9147. numbers. In 1849, the astronomer John Herschel (son of William
  9148. Herschel) suggested using the number of days since the beginning of
  9149. the Julian cycle as an astronomical dating system; this idea was taken
  9150. up by other astronomers. (At the time, noon was the start of the
  9151. astronomical day. Herschel originally suggested counting the days
  9152. since Jan 1, 4713 BC at noon Alexandria time; this was later amended to
  9153. noon GMT@.) Julian day numbering is largely used in astronomy.
  9154. @cindex Unix time format
  9155. The Unix operating system measures time as an integer number of
  9156. seconds since midnight, Jan 1, 1970. To convert a Calc date
  9157. value into a Unix time stamp, first subtract 719163 (the code
  9158. for @samp{<Jan 1, 1970>}), then multiply by 86400 (the number of
  9159. seconds in a day) and press @kbd{R} to round to the nearest
  9160. integer. If you have a date form, you can simply subtract the
  9161. day @samp{<Jan 1, 1970>} instead of unpacking and subtracting
  9162. 719163. Likewise, divide by 86400 and add @samp{<Jan 1, 1970>}
  9163. to convert from Unix time to a Calc date form. (Note that
  9164. Unix normally maintains the time in the GMT time zone; you may
  9165. need to subtract five hours to get New York time, or eight hours
  9166. for California time. The same is usually true of Julian day
  9167. counts.) The built-in @kbd{t U} command performs these
  9168. conversions.
  9169. @node Modulo Forms, Error Forms, Date Forms, Data Types
  9170. @section Modulo Forms
  9171. @noindent
  9172. @cindex Modulo forms
  9173. A @dfn{modulo form} is a real number which is taken modulo (i.e., within
  9174. an integer multiple of) some value @var{M}. Arithmetic modulo @var{M}
  9175. often arises in number theory. Modulo forms are written
  9176. `@var{a} @tfn{mod} @var{M}',
  9177. where @var{a} and @var{M} are real numbers or HMS forms, and
  9178. @texline @math{0 \le a < M}.
  9179. @infoline @expr{0 <= a < @var{M}}.
  9180. In many applications @expr{a} and @expr{M} will be
  9181. integers but this is not required.
  9182. @ignore
  9183. @mindex M
  9184. @end ignore
  9185. @kindex M (modulo forms)
  9186. @ignore
  9187. @mindex mod
  9188. @end ignore
  9189. @tindex mod (operator)
  9190. To create a modulo form during numeric entry, press the shift-@kbd{M}
  9191. key to enter the word @samp{mod}. As a special convenience, pressing
  9192. shift-@kbd{M} a second time automatically enters the value of @expr{M}
  9193. that was most recently used before. During algebraic entry, either
  9194. type @samp{mod} by hand or press @kbd{M-m} (that's @kbd{@key{META}-m}).
  9195. Once again, pressing this a second time enters the current modulo.
  9196. Modulo forms are not to be confused with the modulo operator @samp{%}.
  9197. The expression @samp{27 % 10} means to compute 27 modulo 10 to produce
  9198. the result 7. Further computations treat this 7 as just a regular integer.
  9199. The expression @samp{27 mod 10} produces the result @samp{7 mod 10};
  9200. further computations with this value are again reduced modulo 10 so that
  9201. the result always lies in the desired range.
  9202. When two modulo forms with identical @expr{M}'s are added or multiplied,
  9203. the Calculator simply adds or multiplies the values, then reduces modulo
  9204. @expr{M}. If one argument is a modulo form and the other a plain number,
  9205. the plain number is treated like a compatible modulo form. It is also
  9206. possible to raise modulo forms to powers; the result is the value raised
  9207. to the power, then reduced modulo @expr{M}. (When all values involved
  9208. are integers, this calculation is done much more efficiently than
  9209. actually computing the power and then reducing.)
  9210. @cindex Modulo division
  9211. Two modulo forms `@var{a} @tfn{mod} @var{M}' and `@var{b} @tfn{mod} @var{M}'
  9212. can be divided if @expr{a}, @expr{b}, and @expr{M} are all
  9213. integers. The result is the modulo form which, when multiplied by
  9214. `@var{b} @tfn{mod} @var{M}', produces `@var{a} @tfn{mod} @var{M}'. If
  9215. there is no solution to this equation (which can happen only when
  9216. @expr{M} is non-prime), or if any of the arguments are non-integers, the
  9217. division is left in symbolic form. Other operations, such as square
  9218. roots, are not yet supported for modulo forms. (Note that, although
  9219. @w{`@tfn{(}@var{a} @tfn{mod} @var{M}@tfn{)^.5}'} will compute a ``modulo square root''
  9220. in the sense of reducing
  9221. @texline @math{\sqrt a}
  9222. @infoline @expr{sqrt(a)}
  9223. modulo @expr{M}, this is not a useful definition from the
  9224. number-theoretical point of view.)
  9225. It is possible to mix HMS forms and modulo forms. For example, an
  9226. HMS form modulo 24 could be used to manipulate clock times; an HMS
  9227. form modulo 360 would be suitable for angles. Making the modulo @expr{M}
  9228. also be an HMS form eliminates troubles that would arise if the angular
  9229. mode were inadvertently set to Radians, in which case
  9230. @w{@samp{2@@ 0' 0" mod 24}} would be interpreted as two degrees modulo
  9231. 24 radians!
  9232. Modulo forms cannot have variables or formulas for components. If you
  9233. enter the formula @samp{(x + 2) mod 5}, Calc propagates the modulus
  9234. to each of the coefficients: @samp{(1 mod 5) x + (2 mod 5)}.
  9235. You can use @kbd{v p} and @kbd{%} to modify modulo forms.
  9236. @xref{Packing and Unpacking}. @xref{Basic Arithmetic}.
  9237. @ignore
  9238. @starindex
  9239. @end ignore
  9240. @tindex makemod
  9241. The algebraic function @samp{makemod(a, m)} builds the modulo form
  9242. @w{@samp{a mod m}}.
  9243. @node Error Forms, Interval Forms, Modulo Forms, Data Types
  9244. @section Error Forms
  9245. @noindent
  9246. @cindex Error forms
  9247. @cindex Standard deviations
  9248. An @dfn{error form} is a number with an associated standard
  9249. deviation, as in @samp{2.3 +/- 0.12}. The notation
  9250. @texline `@var{x} @tfn{+/-} @math{\sigma}'
  9251. @infoline `@var{x} @tfn{+/-} sigma'
  9252. stands for an uncertain value which follows
  9253. a normal or Gaussian distribution of mean @expr{x} and standard
  9254. deviation or ``error''
  9255. @texline @math{\sigma}.
  9256. @infoline @expr{sigma}.
  9257. Both the mean and the error can be either numbers or
  9258. formulas. Generally these are real numbers but the mean may also be
  9259. complex. If the error is negative or complex, it is changed to its
  9260. absolute value. An error form with zero error is converted to a
  9261. regular number by the Calculator.
  9262. All arithmetic and transcendental functions accept error forms as input.
  9263. Operations on the mean-value part work just like operations on regular
  9264. numbers. The error part for any function @expr{f(x)} (such as
  9265. @texline @math{\sin x}
  9266. @infoline @expr{sin(x)})
  9267. is defined by the error of @expr{x} times the derivative of @expr{f}
  9268. evaluated at the mean value of @expr{x}. For a two-argument function
  9269. @expr{f(x,y)} (such as addition) the error is the square root of the sum
  9270. of the squares of the errors due to @expr{x} and @expr{y}.
  9271. @tex
  9272. $$ \eqalign{
  9273. f(x \hbox{\code{ +/- }} \sigma)
  9274. &= f(x) \hbox{\code{ +/- }} \sigma \left| {df(x) \over dx} \right| \cr
  9275. f(x \hbox{\code{ +/- }} \sigma_x, y \hbox{\code{ +/- }} \sigma_y)
  9276. &= f(x,y) \hbox{\code{ +/- }}
  9277. \sqrt{\left(\sigma_x \left| {\partial f(x,y) \over \partial x}
  9278. \right| \right)^2
  9279. +\left(\sigma_y \left| {\partial f(x,y) \over \partial y}
  9280. \right| \right)^2 } \cr
  9281. } $$
  9282. @end tex
  9283. Note that this
  9284. definition assumes the errors in @expr{x} and @expr{y} are uncorrelated.
  9285. A side effect of this definition is that @samp{(2 +/- 1) * (2 +/- 1)}
  9286. is not the same as @samp{(2 +/- 1)^2}; the former represents the product
  9287. of two independent values which happen to have the same probability
  9288. distributions, and the latter is the product of one random value with itself.
  9289. The former will produce an answer with less error, since on the average
  9290. the two independent errors can be expected to cancel out.
  9291. Consult a good text on error analysis for a discussion of the proper use
  9292. of standard deviations. Actual errors often are neither Gaussian-distributed
  9293. nor uncorrelated, and the above formulas are valid only when errors
  9294. are small. As an example, the error arising from
  9295. @texline `@tfn{sin(}@var{x} @tfn{+/-} @math{\sigma}@tfn{)}'
  9296. @infoline `@tfn{sin(}@var{x} @tfn{+/-} @var{sigma}@tfn{)}'
  9297. is
  9298. @texline `@math{\sigma} @tfn{abs(cos(}@var{x}@tfn{))}'.
  9299. @infoline `@var{sigma} @tfn{abs(cos(}@var{x}@tfn{))}'.
  9300. When @expr{x} is close to zero,
  9301. @texline @math{\cos x}
  9302. @infoline @expr{cos(x)}
  9303. is close to one so the error in the sine is close to
  9304. @texline @math{\sigma};
  9305. @infoline @expr{sigma};
  9306. this makes sense, since
  9307. @texline @math{\sin x}
  9308. @infoline @expr{sin(x)}
  9309. is approximately @expr{x} near zero, so a given error in @expr{x} will
  9310. produce about the same error in the sine. Likewise, near 90 degrees
  9311. @texline @math{\cos x}
  9312. @infoline @expr{cos(x)}
  9313. is nearly zero and so the computed error is
  9314. small: The sine curve is nearly flat in that region, so an error in @expr{x}
  9315. has relatively little effect on the value of
  9316. @texline @math{\sin x}.
  9317. @infoline @expr{sin(x)}.
  9318. However, consider @samp{sin(90 +/- 1000)}. The cosine of 90 is zero, so
  9319. Calc will report zero error! We get an obviously wrong result because
  9320. we have violated the small-error approximation underlying the error
  9321. analysis. If the error in @expr{x} had been small, the error in
  9322. @texline @math{\sin x}
  9323. @infoline @expr{sin(x)}
  9324. would indeed have been negligible.
  9325. @ignore
  9326. @mindex p
  9327. @end ignore
  9328. @kindex p (error forms)
  9329. @tindex +/-
  9330. To enter an error form during regular numeric entry, use the @kbd{p}
  9331. (``plus-or-minus'') key to type the @samp{+/-} symbol. (If you try actually
  9332. typing @samp{+/-} the @kbd{+} key will be interpreted as the Calculator's
  9333. @kbd{+} command!) Within an algebraic formula, you can press @kbd{M-+} to
  9334. type the @samp{+/-} symbol, or type it out by hand.
  9335. Error forms and complex numbers can be mixed; the formulas shown above
  9336. are used for complex numbers, too; note that if the error part evaluates
  9337. to a complex number its absolute value (or the square root of the sum of
  9338. the squares of the absolute values of the two error contributions) is
  9339. used. Mathematically, this corresponds to a radially symmetric Gaussian
  9340. distribution of numbers on the complex plane. However, note that Calc
  9341. considers an error form with real components to represent a real number,
  9342. not a complex distribution around a real mean.
  9343. Error forms may also be composed of HMS forms. For best results, both
  9344. the mean and the error should be HMS forms if either one is.
  9345. @ignore
  9346. @starindex
  9347. @end ignore
  9348. @tindex sdev
  9349. The algebraic function @samp{sdev(a, b)} builds the error form @samp{a +/- b}.
  9350. @node Interval Forms, Incomplete Objects, Error Forms, Data Types
  9351. @section Interval Forms
  9352. @noindent
  9353. @cindex Interval forms
  9354. An @dfn{interval} is a subset of consecutive real numbers. For example,
  9355. the interval @samp{[2 ..@: 4]} represents all the numbers from 2 to 4,
  9356. inclusive. If you multiply it by the interval @samp{[0.5 ..@: 2]} you
  9357. obtain @samp{[1 ..@: 8]}. This calculation represents the fact that if
  9358. you multiply some number in the range @samp{[2 ..@: 4]} by some other
  9359. number in the range @samp{[0.5 ..@: 2]}, your result will lie in the range
  9360. from 1 to 8. Interval arithmetic is used to get a worst-case estimate
  9361. of the possible range of values a computation will produce, given the
  9362. set of possible values of the input.
  9363. @ifnottex
  9364. Calc supports several varieties of intervals, including @dfn{closed}
  9365. intervals of the type shown above, @dfn{open} intervals such as
  9366. @samp{(2 ..@: 4)}, which represents the range of numbers from 2 to 4
  9367. @emph{exclusive}, and @dfn{semi-open} intervals in which one end
  9368. uses a round parenthesis and the other a square bracket. In mathematical
  9369. terms,
  9370. @samp{[2 ..@: 4]} means @expr{2 <= x <= 4}, whereas
  9371. @samp{[2 ..@: 4)} represents @expr{2 <= x < 4},
  9372. @samp{(2 ..@: 4]} represents @expr{2 < x <= 4}, and
  9373. @samp{(2 ..@: 4)} represents @expr{2 < x < 4}.
  9374. @end ifnottex
  9375. @tex
  9376. Calc supports several varieties of intervals, including \dfn{closed}
  9377. intervals of the type shown above, \dfn{open} intervals such as
  9378. \samp{(2 ..\: 4)}, which represents the range of numbers from 2 to 4
  9379. \emph{exclusive}, and \dfn{semi-open} intervals in which one end
  9380. uses a round parenthesis and the other a square bracket. In mathematical
  9381. terms,
  9382. $$ \eqalign{
  9383. [2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 \le x \le 4 \cr
  9384. [2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 \le x < 4 \cr
  9385. (2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 < x \le 4 \cr
  9386. (2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 < x < 4 \cr
  9387. } $$
  9388. @end tex
  9389. The lower and upper limits of an interval must be either real numbers
  9390. (or HMS or date forms), or symbolic expressions which are assumed to be
  9391. real-valued, or @samp{-inf} and @samp{inf}. In general the lower limit
  9392. must be less than the upper limit. A closed interval containing only
  9393. one value, @samp{[3 ..@: 3]}, is converted to a plain number (3)
  9394. automatically. An interval containing no values at all (such as
  9395. @samp{[3 ..@: 2]} or @samp{[2 ..@: 2)}) can be represented but is not
  9396. guaranteed to behave well when used in arithmetic. Note that the
  9397. interval @samp{[3 .. inf)} represents all real numbers greater than
  9398. or equal to 3, and @samp{(-inf .. inf)} represents all real numbers.
  9399. In fact, @samp{[-inf .. inf]} represents all real numbers including
  9400. the real infinities.
  9401. Intervals are entered in the notation shown here, either as algebraic
  9402. formulas, or using incomplete forms. (@xref{Incomplete Objects}.)
  9403. In algebraic formulas, multiple periods in a row are collected from
  9404. left to right, so that @samp{1...1e2} is interpreted as @samp{1.0 ..@: 1e2}
  9405. rather than @samp{1 ..@: 0.1e2}. Add spaces or zeros if you want to
  9406. get the other interpretation. If you omit the lower or upper limit,
  9407. a default of @samp{-inf} or @samp{inf} (respectively) is furnished.
  9408. Infinite mode also affects operations on intervals
  9409. (@pxref{Infinities}). Calc will always introduce an open infinity,
  9410. as in @samp{1 / (0 .. 2] = [0.5 .. inf)}. But closed infinities,
  9411. @w{@samp{1 / [0 .. 2] = [0.5 .. inf]}}, arise only in Infinite mode;
  9412. otherwise they are left unevaluated. Note that the ``direction'' of
  9413. a zero is not an issue in this case since the zero is always assumed
  9414. to be continuous with the rest of the interval. For intervals that
  9415. contain zero inside them Calc is forced to give the result,
  9416. @samp{1 / (-2 .. 2) = [-inf .. inf]}.
  9417. While it may seem that intervals and error forms are similar, they are
  9418. based on entirely different concepts of inexact quantities. An error
  9419. form
  9420. @texline `@var{x} @tfn{+/-} @math{\sigma}'
  9421. @infoline `@var{x} @tfn{+/-} @var{sigma}'
  9422. means a variable is random, and its value could
  9423. be anything but is ``probably'' within one
  9424. @texline @math{\sigma}
  9425. @infoline @var{sigma}
  9426. of the mean value @expr{x}. An interval
  9427. `@tfn{[}@var{a} @tfn{..@:} @var{b}@tfn{]}' means a
  9428. variable's value is unknown, but guaranteed to lie in the specified
  9429. range. Error forms are statistical or ``average case'' approximations;
  9430. interval arithmetic tends to produce ``worst case'' bounds on an
  9431. answer.
  9432. Intervals may not contain complex numbers, but they may contain
  9433. HMS forms or date forms.
  9434. @xref{Set Operations}, for commands that interpret interval forms
  9435. as subsets of the set of real numbers.
  9436. @ignore
  9437. @starindex
  9438. @end ignore
  9439. @tindex intv
  9440. The algebraic function @samp{intv(n, a, b)} builds an interval form
  9441. from @samp{a} to @samp{b}; @samp{n} is an integer code which must
  9442. be 0 for @samp{(..)}, 1 for @samp{(..]}, 2 for @samp{[..)}, or
  9443. 3 for @samp{[..]}.
  9444. Please note that in fully rigorous interval arithmetic, care would be
  9445. taken to make sure that the computation of the lower bound rounds toward
  9446. minus infinity, while upper bound computations round toward plus
  9447. infinity. Calc's arithmetic always uses a round-to-nearest mode,
  9448. which means that roundoff errors could creep into an interval
  9449. calculation to produce intervals slightly smaller than they ought to
  9450. be. For example, entering @samp{[1..2]} and pressing @kbd{Q 2 ^}
  9451. should yield the interval @samp{[1..2]} again, but in fact it yields the
  9452. (slightly too small) interval @samp{[1..1.9999999]} due to roundoff
  9453. error.
  9454. @node Incomplete Objects, Variables, Interval Forms, Data Types
  9455. @section Incomplete Objects
  9456. @noindent
  9457. @ignore
  9458. @mindex [ ]
  9459. @end ignore
  9460. @kindex [
  9461. @ignore
  9462. @mindex ( )
  9463. @end ignore
  9464. @kindex (
  9465. @kindex ,
  9466. @ignore
  9467. @mindex @null
  9468. @end ignore
  9469. @kindex ]
  9470. @ignore
  9471. @mindex @null
  9472. @end ignore
  9473. @kindex )
  9474. @cindex Incomplete vectors
  9475. @cindex Incomplete complex numbers
  9476. @cindex Incomplete interval forms
  9477. When @kbd{(} or @kbd{[} is typed to begin entering a complex number or
  9478. vector, respectively, the effect is to push an @dfn{incomplete} complex
  9479. number or vector onto the stack. The @kbd{,} key adds the value(s) at
  9480. the top of the stack onto the current incomplete object. The @kbd{)}
  9481. and @kbd{]} keys ``close'' the incomplete object after adding any values
  9482. on the top of the stack in front of the incomplete object.
  9483. As a result, the sequence of keystrokes @kbd{[ 2 , 3 @key{RET} 2 * , 9 ]}
  9484. pushes the vector @samp{[2, 6, 9]} onto the stack. Likewise, @kbd{( 1 , 2 Q )}
  9485. pushes the complex number @samp{(1, 1.414)} (approximately).
  9486. If several values lie on the stack in front of the incomplete object,
  9487. all are collected and appended to the object. Thus the @kbd{,} key
  9488. is redundant: @kbd{[ 2 @key{RET} 3 @key{RET} 2 * 9 ]}. Some people
  9489. prefer the equivalent @key{SPC} key to @key{RET}.
  9490. As a special case, typing @kbd{,} immediately after @kbd{(}, @kbd{[}, or
  9491. @kbd{,} adds a zero or duplicates the preceding value in the list being
  9492. formed. Typing @key{DEL} during incomplete entry removes the last item
  9493. from the list.
  9494. @kindex ;
  9495. The @kbd{;} key is used in the same way as @kbd{,} to create polar complex
  9496. numbers: @kbd{( 1 ; 2 )}. When entering a vector, @kbd{;} is useful for
  9497. creating a matrix. In particular, @kbd{[ [ 1 , 2 ; 3 , 4 ; 5 , 6 ] ]} is
  9498. equivalent to @kbd{[ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ]}.
  9499. @kindex ..
  9500. @pindex calc-dots
  9501. Incomplete entry is also used to enter intervals. For example,
  9502. @kbd{[ 2 ..@: 4 )} enters a semi-open interval. Note that when you type
  9503. the first period, it will be interpreted as a decimal point, but when
  9504. you type a second period immediately afterward, it is re-interpreted as
  9505. part of the interval symbol. Typing @kbd{..} corresponds to executing
  9506. the @code{calc-dots} command.
  9507. If you find incomplete entry distracting, you may wish to enter vectors
  9508. and complex numbers as algebraic formulas by pressing the apostrophe key.
  9509. @node Variables, Formulas, Incomplete Objects, Data Types
  9510. @section Variables
  9511. @noindent
  9512. @cindex Variables, in formulas
  9513. A @dfn{variable} is somewhere between a storage register on a conventional
  9514. calculator, and a variable in a programming language. (In fact, a Calc
  9515. variable is really just an Emacs Lisp variable that contains a Calc number
  9516. or formula.) A variable's name is normally composed of letters and digits.
  9517. Calc also allows apostrophes and @code{#} signs in variable names.
  9518. (The Calc variable @code{foo} corresponds to the Emacs Lisp variable
  9519. @code{var-foo}, but unless you access the variable from within Emacs
  9520. Lisp, you don't need to worry about it. Variable names in algebraic
  9521. formulas implicitly have @samp{var-} prefixed to their names. The
  9522. @samp{#} character in variable names used in algebraic formulas
  9523. corresponds to a dash @samp{-} in the Lisp variable name. If the name
  9524. contains any dashes, the prefix @samp{var-} is @emph{not} automatically
  9525. added. Thus the two formulas @samp{foo + 1} and @samp{var#foo + 1} both
  9526. refer to the same variable.)
  9527. In a command that takes a variable name, you can either type the full
  9528. name of a variable, or type a single digit to use one of the special
  9529. convenience variables @code{q0} through @code{q9}. For example,
  9530. @kbd{3 s s 2} stores the number 3 in variable @code{q2}, and
  9531. @w{@kbd{3 s s foo @key{RET}}} stores that number in variable
  9532. @code{foo}.
  9533. To push a variable itself (as opposed to the variable's value) on the
  9534. stack, enter its name as an algebraic expression using the apostrophe
  9535. (@key{'}) key.
  9536. @kindex =
  9537. @pindex calc-evaluate
  9538. @cindex Evaluation of variables in a formula
  9539. @cindex Variables, evaluation
  9540. @cindex Formulas, evaluation
  9541. The @kbd{=} (@code{calc-evaluate}) key ``evaluates'' a formula by
  9542. replacing all variables in the formula which have been given values by a
  9543. @code{calc-store} or @code{calc-let} command by their stored values.
  9544. Other variables are left alone. Thus a variable that has not been
  9545. stored acts like an abstract variable in algebra; a variable that has
  9546. been stored acts more like a register in a traditional calculator.
  9547. With a positive numeric prefix argument, @kbd{=} evaluates the top
  9548. @var{n} stack entries; with a negative argument, @kbd{=} evaluates
  9549. the @var{n}th stack entry.
  9550. @cindex @code{e} variable
  9551. @cindex @code{pi} variable
  9552. @cindex @code{i} variable
  9553. @cindex @code{phi} variable
  9554. @cindex @code{gamma} variable
  9555. @vindex e
  9556. @vindex pi
  9557. @vindex i
  9558. @vindex phi
  9559. @vindex gamma
  9560. A few variables are called @dfn{special constants}. Their names are
  9561. @samp{e}, @samp{pi}, @samp{i}, @samp{phi}, and @samp{gamma}.
  9562. (@xref{Scientific Functions}.) When they are evaluated with @kbd{=},
  9563. their values are calculated if necessary according to the current precision
  9564. or complex polar mode. If you wish to use these symbols for other purposes,
  9565. simply undefine or redefine them using @code{calc-store}.
  9566. The variables @samp{inf}, @samp{uinf}, and @samp{nan} stand for
  9567. infinite or indeterminate values. It's best not to use them as
  9568. regular variables, since Calc uses special algebraic rules when
  9569. it manipulates them. Calc displays a warning message if you store
  9570. a value into any of these special variables.
  9571. @xref{Store and Recall}, for a discussion of commands dealing with variables.
  9572. @node Formulas, , Variables, Data Types
  9573. @section Formulas
  9574. @noindent
  9575. @cindex Formulas
  9576. @cindex Expressions
  9577. @cindex Operators in formulas
  9578. @cindex Precedence of operators
  9579. When you press the apostrophe key you may enter any expression or formula
  9580. in algebraic form. (Calc uses the terms ``expression'' and ``formula''
  9581. interchangeably.) An expression is built up of numbers, variable names,
  9582. and function calls, combined with various arithmetic operators.
  9583. Parentheses may
  9584. be used to indicate grouping. Spaces are ignored within formulas, except
  9585. that spaces are not permitted within variable names or numbers.
  9586. Arithmetic operators, in order from highest to lowest precedence, and
  9587. with their equivalent function names, are:
  9588. @samp{_} [@code{subscr}] (subscripts);
  9589. postfix @samp{%} [@code{percent}] (as in @samp{25% = 0.25});
  9590. prefix @samp{!} [@code{lnot}] (logical ``not,'' as in @samp{!x});
  9591. @samp{+/-} [@code{sdev}] (the standard deviation symbol) and
  9592. @samp{mod} [@code{makemod}] (the symbol for modulo forms);
  9593. postfix @samp{!} [@code{fact}] (factorial, as in @samp{n!})
  9594. and postfix @samp{!!} [@code{dfact}] (double factorial);
  9595. @samp{^} [@code{pow}] (raised-to-the-power-of);
  9596. prefix @samp{+} and @samp{-} [@code{neg}] (as in @samp{-x});
  9597. @samp{*} [@code{mul}];
  9598. @samp{/} [@code{div}], @samp{%} [@code{mod}] (modulo), and
  9599. @samp{\} [@code{idiv}] (integer division);
  9600. infix @samp{+} [@code{add}] and @samp{-} [@code{sub}] (as in @samp{x-y});
  9601. @samp{|} [@code{vconcat}] (vector concatenation);
  9602. relations @samp{=} [@code{eq}], @samp{!=} [@code{neq}], @samp{<} [@code{lt}],
  9603. @samp{>} [@code{gt}], @samp{<=} [@code{leq}], and @samp{>=} [@code{geq}];
  9604. @samp{&&} [@code{land}] (logical ``and'');
  9605. @samp{||} [@code{lor}] (logical ``or'');
  9606. the C-style ``if'' operator @samp{a?b:c} [@code{if}];
  9607. @samp{!!!} [@code{pnot}] (rewrite pattern ``not'');
  9608. @samp{&&&} [@code{pand}] (rewrite pattern ``and'');
  9609. @samp{|||} [@code{por}] (rewrite pattern ``or'');
  9610. @samp{:=} [@code{assign}] (for assignments and rewrite rules);
  9611. @samp{::} [@code{condition}] (rewrite pattern condition);
  9612. @samp{=>} [@code{evalto}].
  9613. Note that, unlike in usual computer notation, multiplication binds more
  9614. strongly than division: @samp{a*b/c*d} is equivalent to
  9615. @texline @math{a b \over c d}.
  9616. @infoline @expr{(a*b)/(c*d)}.
  9617. @cindex Multiplication, implicit
  9618. @cindex Implicit multiplication
  9619. The multiplication sign @samp{*} may be omitted in many cases. In particular,
  9620. if the righthand side is a number, variable name, or parenthesized
  9621. expression, the @samp{*} may be omitted. Implicit multiplication has the
  9622. same precedence as the explicit @samp{*} operator. The one exception to
  9623. the rule is that a variable name followed by a parenthesized expression,
  9624. as in @samp{f(x)},
  9625. is interpreted as a function call, not an implicit @samp{*}. In many
  9626. cases you must use a space if you omit the @samp{*}: @samp{2a} is the
  9627. same as @samp{2*a}, and @samp{a b} is the same as @samp{a*b}, but @samp{ab}
  9628. is a variable called @code{ab}, @emph{not} the product of @samp{a} and
  9629. @samp{b}! Also note that @samp{f (x)} is still a function call.
  9630. @cindex Implicit comma in vectors
  9631. The rules are slightly different for vectors written with square brackets.
  9632. In vectors, the space character is interpreted (like the comma) as a
  9633. separator of elements of the vector. Thus @w{@samp{[ 2a b+c d ]}} is
  9634. equivalent to @samp{[2*a, b+c, d]}, whereas @samp{2a b+c d} is equivalent
  9635. to @samp{2*a*b + c*d}.
  9636. Note that spaces around the brackets, and around explicit commas, are
  9637. ignored. To force spaces to be interpreted as multiplication you can
  9638. enclose a formula in parentheses as in @samp{[(a b) 2(c d)]}, which is
  9639. interpreted as @samp{[a*b, 2*c*d]}. An implicit comma is also inserted
  9640. between @samp{][}, as in the matrix @samp{[[1 2][3 4]]}.
  9641. Vectors that contain commas (not embedded within nested parentheses or
  9642. brackets) do not treat spaces specially: @samp{[a b, 2 c d]} is a vector
  9643. of two elements. Also, if it would be an error to treat spaces as
  9644. separators, but not otherwise, then Calc will ignore spaces:
  9645. @w{@samp{[a - b]}} is a vector of one element, but @w{@samp{[a -b]}} is
  9646. a vector of two elements. Finally, vectors entered with curly braces
  9647. instead of square brackets do not give spaces any special treatment.
  9648. When Calc displays a vector that does not contain any commas, it will
  9649. insert parentheses if necessary to make the meaning clear:
  9650. @w{@samp{[(a b)]}}.
  9651. The expression @samp{5%-2} is ambiguous; is this five-percent minus two,
  9652. or five modulo minus-two? Calc always interprets the leftmost symbol as
  9653. an infix operator preferentially (modulo, in this case), so you would
  9654. need to write @samp{(5%)-2} to get the former interpretation.
  9655. @cindex Function call notation
  9656. A function call is, e.g., @samp{sin(1+x)}. (The Calc algebraic function
  9657. @code{foo} corresponds to the Emacs Lisp function @code{calcFunc-foo},
  9658. but unless you access the function from within Emacs Lisp, you don't
  9659. need to worry about it.) Most mathematical Calculator commands like
  9660. @code{calc-sin} have function equivalents like @code{sin}.
  9661. If no Lisp function is defined for a function called by a formula, the
  9662. call is left as it is during algebraic manipulation: @samp{f(x+y)} is
  9663. left alone. Beware that many innocent-looking short names like @code{in}
  9664. and @code{re} have predefined meanings which could surprise you; however,
  9665. single letters or single letters followed by digits are always safe to
  9666. use for your own function names. @xref{Function Index}.
  9667. In the documentation for particular commands, the notation @kbd{H S}
  9668. (@code{calc-sinh}) [@code{sinh}] means that the key sequence @kbd{H S}, the
  9669. command @kbd{M-x calc-sinh}, and the algebraic function @code{sinh(x)} all
  9670. represent the same operation.
  9671. Commands that interpret (``parse'') text as algebraic formulas include
  9672. algebraic entry (@kbd{'}), editing commands like @kbd{`} which parse
  9673. the contents of the editing buffer when you finish, the @kbd{C-x * g}
  9674. and @w{@kbd{C-x * r}} commands, the @kbd{C-y} command, the X window system
  9675. ``paste'' mouse operation, and Embedded mode. All of these operations
  9676. use the same rules for parsing formulas; in particular, language modes
  9677. (@pxref{Language Modes}) affect them all in the same way.
  9678. When you read a large amount of text into the Calculator (say a vector
  9679. which represents a big set of rewrite rules; @pxref{Rewrite Rules}),
  9680. you may wish to include comments in the text. Calc's formula parser
  9681. ignores the symbol @samp{%%} and anything following it on a line:
  9682. @example
  9683. [ a + b, %% the sum of "a" and "b"
  9684. c + d,
  9685. %% last line is coming up:
  9686. e + f ]
  9687. @end example
  9688. @noindent
  9689. This is parsed exactly the same as @samp{[ a + b, c + d, e + f ]}.
  9690. @xref{Syntax Tables}, for a way to create your own operators and other
  9691. input notations. @xref{Compositions}, for a way to create new display
  9692. formats.
  9693. @xref{Algebra}, for commands for manipulating formulas symbolically.
  9694. @node Stack and Trail, Mode Settings, Data Types, Top
  9695. @chapter Stack and Trail Commands
  9696. @noindent
  9697. This chapter describes the Calc commands for manipulating objects on the
  9698. stack and in the trail buffer. (These commands operate on objects of any
  9699. type, such as numbers, vectors, formulas, and incomplete objects.)
  9700. @menu
  9701. * Stack Manipulation::
  9702. * Editing Stack Entries::
  9703. * Trail Commands::
  9704. * Keep Arguments::
  9705. @end menu
  9706. @node Stack Manipulation, Editing Stack Entries, Stack and Trail, Stack and Trail
  9707. @section Stack Manipulation Commands
  9708. @noindent
  9709. @kindex @key{RET}
  9710. @kindex @key{SPC}
  9711. @pindex calc-enter
  9712. @cindex Duplicating stack entries
  9713. To duplicate the top object on the stack, press @key{RET} or @key{SPC}
  9714. (two equivalent keys for the @code{calc-enter} command).
  9715. Given a positive numeric prefix argument, these commands duplicate
  9716. several elements at the top of the stack.
  9717. Given a negative argument,
  9718. these commands duplicate the specified element of the stack.
  9719. Given an argument of zero, they duplicate the entire stack.
  9720. For example, with @samp{10 20 30} on the stack,
  9721. @key{RET} creates @samp{10 20 30 30},
  9722. @kbd{C-u 2 @key{RET}} creates @samp{10 20 30 20 30},
  9723. @kbd{C-u - 2 @key{RET}} creates @samp{10 20 30 20}, and
  9724. @kbd{C-u 0 @key{RET}} creates @samp{10 20 30 10 20 30}.
  9725. @kindex @key{LFD}
  9726. @pindex calc-over
  9727. The @key{LFD} (@code{calc-over}) command (on a key marked Line-Feed if you
  9728. have it, else on @kbd{C-j}) is like @code{calc-enter}
  9729. except that the sign of the numeric prefix argument is interpreted
  9730. oppositely. Also, with no prefix argument the default argument is 2.
  9731. Thus with @samp{10 20 30} on the stack, @key{LFD} and @kbd{C-u 2 @key{LFD}}
  9732. are both equivalent to @kbd{C-u - 2 @key{RET}}, producing
  9733. @samp{10 20 30 20}.
  9734. @kindex @key{DEL}
  9735. @kindex C-d
  9736. @pindex calc-pop
  9737. @cindex Removing stack entries
  9738. @cindex Deleting stack entries
  9739. To remove the top element from the stack, press @key{DEL} (@code{calc-pop}).
  9740. The @kbd{C-d} key is a synonym for @key{DEL}.
  9741. (If the top element is an incomplete object with at least one element, the
  9742. last element is removed from it.) Given a positive numeric prefix argument,
  9743. several elements are removed. Given a negative argument, the specified
  9744. element of the stack is deleted. Given an argument of zero, the entire
  9745. stack is emptied.
  9746. For example, with @samp{10 20 30} on the stack,
  9747. @key{DEL} leaves @samp{10 20},
  9748. @kbd{C-u 2 @key{DEL}} leaves @samp{10},
  9749. @kbd{C-u - 2 @key{DEL}} leaves @samp{10 30}, and
  9750. @kbd{C-u 0 @key{DEL}} leaves an empty stack.
  9751. @kindex M-@key{DEL}
  9752. @pindex calc-pop-above
  9753. The @kbd{M-@key{DEL}} (@code{calc-pop-above}) command is to @key{DEL} what
  9754. @key{LFD} is to @key{RET}: It interprets the sign of the numeric
  9755. prefix argument in the opposite way, and the default argument is 2.
  9756. Thus @kbd{M-@key{DEL}} by itself removes the second-from-top stack element,
  9757. leaving the first, third, fourth, and so on; @kbd{M-3 M-@key{DEL}} deletes
  9758. the third stack element.
  9759. The above commands do not depend on the location of the cursor.
  9760. If the customizable variable @code{calc-context-sensitive-enter} is
  9761. non-@code{nil} (@pxref{Customizing Calc}), these commands will become
  9762. context sensitive. For example, instead of duplicating the top of the stack,
  9763. @key{RET} will copy the element at the cursor to the top of the
  9764. stack. With a positive numeric prefix, a copy of the element at the
  9765. cursor and the appropriate number of preceding elements will be placed
  9766. at the top of the stack. A negative prefix will still duplicate the
  9767. specified element of the stack regardless of the cursor position.
  9768. Similarly, @key{DEL} will remove the corresponding elements from the
  9769. stack.
  9770. @kindex @key{TAB}
  9771. @pindex calc-roll-down
  9772. To exchange the top two elements of the stack, press @key{TAB}
  9773. (@code{calc-roll-down}). Given a positive numeric prefix argument, the
  9774. specified number of elements at the top of the stack are rotated downward.
  9775. Given a negative argument, the entire stack is rotated downward the specified
  9776. number of times. Given an argument of zero, the entire stack is reversed
  9777. top-for-bottom.
  9778. For example, with @samp{10 20 30 40 50} on the stack,
  9779. @key{TAB} creates @samp{10 20 30 50 40},
  9780. @kbd{C-u 3 @key{TAB}} creates @samp{10 20 50 30 40},
  9781. @kbd{C-u - 2 @key{TAB}} creates @samp{40 50 10 20 30}, and
  9782. @kbd{C-u 0 @key{TAB}} creates @samp{50 40 30 20 10}.
  9783. @kindex M-@key{TAB}
  9784. @pindex calc-roll-up
  9785. The command @kbd{M-@key{TAB}} (@code{calc-roll-up}) is analogous to @key{TAB}
  9786. except that it rotates upward instead of downward. Also, the default
  9787. with no prefix argument is to rotate the top 3 elements.
  9788. For example, with @samp{10 20 30 40 50} on the stack,
  9789. @kbd{M-@key{TAB}} creates @samp{10 20 40 50 30},
  9790. @kbd{C-u 4 M-@key{TAB}} creates @samp{10 30 40 50 20},
  9791. @kbd{C-u - 2 M-@key{TAB}} creates @samp{30 40 50 10 20}, and
  9792. @kbd{C-u 0 M-@key{TAB}} creates @samp{50 40 30 20 10}.
  9793. A good way to view the operation of @key{TAB} and @kbd{M-@key{TAB}} is in
  9794. terms of moving a particular element to a new position in the stack.
  9795. With a positive argument @var{n}, @key{TAB} moves the top stack
  9796. element down to level @var{n}, making room for it by pulling all the
  9797. intervening stack elements toward the top. @kbd{M-@key{TAB}} moves the
  9798. element at level @var{n} up to the top. (Compare with @key{LFD},
  9799. which copies instead of moving the element in level @var{n}.)
  9800. With a negative argument @mathit{-@var{n}}, @key{TAB} rotates the stack
  9801. to move the object in level @var{n} to the deepest place in the
  9802. stack, and the object in level @mathit{@var{n}+1} to the top. @kbd{M-@key{TAB}}
  9803. rotates the deepest stack element to be in level @var{n}, also
  9804. putting the top stack element in level @mathit{@var{n}+1}.
  9805. @xref{Selecting Subformulas}, for a way to apply these commands to
  9806. any portion of a vector or formula on the stack.
  9807. @kindex C-xC-t
  9808. @pindex calc-transpose-lines
  9809. @cindex Moving stack entries
  9810. The command @kbd{C-x C-t} (@code{calc-transpose-lines}) will transpose
  9811. the stack object determined by the point with the stack object at the
  9812. next higher level. For example, with @samp{10 20 30 40 50} on the
  9813. stack and the point on the line containing @samp{30}, @kbd{C-x C-t}
  9814. creates @samp{10 20 40 30 50}. More generally, @kbd{C-x C-t} acts on
  9815. the stack objects determined by the current point (and mark) similar
  9816. to how the text-mode command @code{transpose-lines} acts on
  9817. lines. With argument @var{n}, @kbd{C-x C-t} will move the stack object
  9818. at the level above the current point and move it past N other objects;
  9819. for example, with @samp{10 20 30 40 50} on the stack and the point on
  9820. the line containing @samp{30}, @kbd{C-u 2 C-x C-t} creates
  9821. @samp{10 40 20 30 50}. With an argument of 0, @kbd{C-x C-t} will switch
  9822. the stack objects at the levels determined by the point and the mark.
  9823. @node Editing Stack Entries, Trail Commands, Stack Manipulation, Stack and Trail
  9824. @section Editing Stack Entries
  9825. @noindent
  9826. @kindex `
  9827. @pindex calc-edit
  9828. @pindex calc-edit-finish
  9829. @cindex Editing the stack with Emacs
  9830. The @kbd{`} (@code{calc-edit}) command creates a temporary buffer
  9831. (@file{*Calc Edit*}) for editing the top-of-stack value using regular
  9832. Emacs commands. Note that @kbd{`} is a grave accent, not an apostrophe.
  9833. With a numeric prefix argument, it edits the specified number of stack
  9834. entries at once. (An argument of zero edits the entire stack; a
  9835. negative argument edits one specific stack entry.)
  9836. When you are done editing, press @kbd{C-c C-c} to finish and return
  9837. to Calc. The @key{RET} and @key{LFD} keys also work to finish most
  9838. sorts of editing, though in some cases Calc leaves @key{RET} with its
  9839. usual meaning (``insert a newline'') if it's a situation where you
  9840. might want to insert new lines into the editing buffer.
  9841. When you finish editing, the Calculator parses the lines of text in
  9842. the @file{*Calc Edit*} buffer as numbers or formulas, replaces the
  9843. original stack elements in the original buffer with these new values,
  9844. then kills the @file{*Calc Edit*} buffer. The original Calculator buffer
  9845. continues to exist during editing, but for best results you should be
  9846. careful not to change it until you have finished the edit. You can
  9847. also cancel the edit by killing the buffer with @kbd{C-x k}.
  9848. The formula is normally reevaluated as it is put onto the stack.
  9849. For example, editing @samp{a + 2} to @samp{3 + 2} and pressing
  9850. @kbd{C-c C-c} will push 5 on the stack. If you use @key{LFD} to
  9851. finish, Calc will put the result on the stack without evaluating it.
  9852. If you give a prefix argument to @kbd{C-c C-c},
  9853. Calc will not kill the @file{*Calc Edit*} buffer. You can switch
  9854. back to that buffer and continue editing if you wish. However, you
  9855. should understand that if you initiated the edit with @kbd{`}, the
  9856. @kbd{C-c C-c} operation will be programmed to replace the top of the
  9857. stack with the new edited value, and it will do this even if you have
  9858. rearranged the stack in the meanwhile. This is not so much of a problem
  9859. with other editing commands, though, such as @kbd{s e}
  9860. (@code{calc-edit-variable}; @pxref{Operations on Variables}).
  9861. If the @code{calc-edit} command involves more than one stack entry,
  9862. each line of the @file{*Calc Edit*} buffer is interpreted as a
  9863. separate formula. Otherwise, the entire buffer is interpreted as
  9864. one formula, with line breaks ignored. (You can use @kbd{C-o} or
  9865. @kbd{C-q C-j} to insert a newline in the buffer without pressing @key{RET}.)
  9866. The @kbd{`} key also works during numeric or algebraic entry. The
  9867. text entered so far is moved to the @file{*Calc Edit*} buffer for
  9868. more extensive editing than is convenient in the minibuffer.
  9869. @node Trail Commands, Keep Arguments, Editing Stack Entries, Stack and Trail
  9870. @section Trail Commands
  9871. @noindent
  9872. @cindex Trail buffer
  9873. The commands for manipulating the Calc Trail buffer are two-key sequences
  9874. beginning with the @kbd{t} prefix.
  9875. @kindex t d
  9876. @pindex calc-trail-display
  9877. The @kbd{t d} (@code{calc-trail-display}) command turns display of the
  9878. trail on and off. Normally the trail display is toggled on if it was off,
  9879. off if it was on. With a numeric prefix of zero, this command always
  9880. turns the trail off; with a prefix of one, it always turns the trail on.
  9881. The other trail-manipulation commands described here automatically turn
  9882. the trail on. Note that when the trail is off values are still recorded
  9883. there; they are simply not displayed. To set Emacs to turn the trail
  9884. off by default, type @kbd{t d} and then save the mode settings with
  9885. @kbd{m m} (@code{calc-save-modes}).
  9886. @kindex t i
  9887. @pindex calc-trail-in
  9888. @kindex t o
  9889. @pindex calc-trail-out
  9890. The @kbd{t i} (@code{calc-trail-in}) and @kbd{t o}
  9891. (@code{calc-trail-out}) commands switch the cursor into and out of the
  9892. Calc Trail window. In practice they are rarely used, since the commands
  9893. shown below are a more convenient way to move around in the
  9894. trail, and they work ``by remote control'' when the cursor is still
  9895. in the Calculator window.
  9896. @cindex Trail pointer
  9897. There is a @dfn{trail pointer} which selects some entry of the trail at
  9898. any given time. The trail pointer looks like a @samp{>} symbol right
  9899. before the selected number. The following commands operate on the
  9900. trail pointer in various ways.
  9901. @kindex t y
  9902. @pindex calc-trail-yank
  9903. @cindex Retrieving previous results
  9904. The @kbd{t y} (@code{calc-trail-yank}) command reads the selected value in
  9905. the trail and pushes it onto the Calculator stack. It allows you to
  9906. re-use any previously computed value without retyping. With a numeric
  9907. prefix argument @var{n}, it yanks the value @var{n} lines above the current
  9908. trail pointer.
  9909. @kindex t <
  9910. @pindex calc-trail-scroll-left
  9911. @kindex t >
  9912. @pindex calc-trail-scroll-right
  9913. The @kbd{t <} (@code{calc-trail-scroll-left}) and @kbd{t >}
  9914. (@code{calc-trail-scroll-right}) commands horizontally scroll the trail
  9915. window left or right by one half of its width.
  9916. @kindex t n
  9917. @pindex calc-trail-next
  9918. @kindex t p
  9919. @pindex calc-trail-previous
  9920. @kindex t f
  9921. @pindex calc-trail-forward
  9922. @kindex t b
  9923. @pindex calc-trail-backward
  9924. The @kbd{t n} (@code{calc-trail-next}) and @kbd{t p}
  9925. (@code{calc-trail-previous)} commands move the trail pointer down or up
  9926. one line. The @kbd{t f} (@code{calc-trail-forward}) and @kbd{t b}
  9927. (@code{calc-trail-backward}) commands move the trail pointer down or up
  9928. one screenful at a time. All of these commands accept numeric prefix
  9929. arguments to move several lines or screenfuls at a time.
  9930. @kindex t [
  9931. @pindex calc-trail-first
  9932. @kindex t ]
  9933. @pindex calc-trail-last
  9934. @kindex t h
  9935. @pindex calc-trail-here
  9936. The @kbd{t [} (@code{calc-trail-first}) and @kbd{t ]}
  9937. (@code{calc-trail-last}) commands move the trail pointer to the first or
  9938. last line of the trail. The @kbd{t h} (@code{calc-trail-here}) command
  9939. moves the trail pointer to the cursor position; unlike the other trail
  9940. commands, @kbd{t h} works only when Calc Trail is the selected window.
  9941. @kindex t s
  9942. @pindex calc-trail-isearch-forward
  9943. @kindex t r
  9944. @pindex calc-trail-isearch-backward
  9945. @ifnottex
  9946. The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
  9947. (@code{calc-trail-isearch-backward}) commands perform an incremental
  9948. search forward or backward through the trail. You can press @key{RET}
  9949. to terminate the search; the trail pointer moves to the current line.
  9950. If you cancel the search with @kbd{C-g}, the trail pointer stays where
  9951. it was when the search began.
  9952. @end ifnottex
  9953. @tex
  9954. The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
  9955. (@code{calc-trail-isearch-backward}) com\-mands perform an incremental
  9956. search forward or backward through the trail. You can press @key{RET}
  9957. to terminate the search; the trail pointer moves to the current line.
  9958. If you cancel the search with @kbd{C-g}, the trail pointer stays where
  9959. it was when the search began.
  9960. @end tex
  9961. @kindex t m
  9962. @pindex calc-trail-marker
  9963. The @kbd{t m} (@code{calc-trail-marker}) command allows you to enter a
  9964. line of text of your own choosing into the trail. The text is inserted
  9965. after the line containing the trail pointer; this usually means it is
  9966. added to the end of the trail. Trail markers are useful mainly as the
  9967. targets for later incremental searches in the trail.
  9968. @kindex t k
  9969. @pindex calc-trail-kill
  9970. The @kbd{t k} (@code{calc-trail-kill}) command removes the selected line
  9971. from the trail. The line is saved in the Emacs kill ring suitable for
  9972. yanking into another buffer, but it is not easy to yank the text back
  9973. into the trail buffer. With a numeric prefix argument, this command
  9974. kills the @var{n} lines below or above the selected one.
  9975. The @kbd{t .} (@code{calc-full-trail-vectors}) command is described
  9976. elsewhere; @pxref{Vector and Matrix Formats}.
  9977. @node Keep Arguments, , Trail Commands, Stack and Trail
  9978. @section Keep Arguments
  9979. @noindent
  9980. @kindex K
  9981. @pindex calc-keep-args
  9982. The @kbd{K} (@code{calc-keep-args}) command acts like a prefix for
  9983. the following command. It prevents that command from removing its
  9984. arguments from the stack. For example, after @kbd{2 @key{RET} 3 +},
  9985. the stack contains the sole number 5, but after @kbd{2 @key{RET} 3 K +},
  9986. the stack contains the arguments and the result: @samp{2 3 5}.
  9987. With the exception of keyboard macros, this works for all commands that
  9988. take arguments off the stack. (To avoid potentially unpleasant behavior,
  9989. a @kbd{K} prefix before a keyboard macro will be ignored. A @kbd{K}
  9990. prefix called @emph{within} the keyboard macro will still take effect.)
  9991. As another example, @kbd{K a s} simplifies a formula, pushing the
  9992. simplified version of the formula onto the stack after the original
  9993. formula (rather than replacing the original formula). Note that you
  9994. could get the same effect by typing @kbd{@key{RET} a s}, copying the
  9995. formula and then simplifying the copy. One difference is that for a very
  9996. large formula the time taken to format the intermediate copy in
  9997. @kbd{@key{RET} a s} could be noticeable; @kbd{K a s} would avoid this
  9998. extra work.
  9999. Even stack manipulation commands are affected. @key{TAB} works by
  10000. popping two values and pushing them back in the opposite order,
  10001. so @kbd{2 @key{RET} 3 K @key{TAB}} produces @samp{2 3 3 2}.
  10002. A few Calc commands provide other ways of doing the same thing.
  10003. For example, @kbd{' sin($)} replaces the number on the stack with
  10004. its sine using algebraic entry; to push the sine and keep the
  10005. original argument you could use either @kbd{' sin($1)} or
  10006. @kbd{K ' sin($)}. @xref{Algebraic Entry}. Also, the @kbd{s s}
  10007. command is effectively the same as @kbd{K s t}. @xref{Storing Variables}.
  10008. If you execute a command and then decide you really wanted to keep
  10009. the argument, you can press @kbd{M-@key{RET}} (@code{calc-last-args}).
  10010. This command pushes the last arguments that were popped by any command
  10011. onto the stack. Note that the order of things on the stack will be
  10012. different than with @kbd{K}: @kbd{2 @key{RET} 3 + M-@key{RET}} leaves
  10013. @samp{5 2 3} on the stack instead of @samp{2 3 5}. @xref{Undo}.
  10014. @node Mode Settings, Arithmetic, Stack and Trail, Top
  10015. @chapter Mode Settings
  10016. @noindent
  10017. This chapter describes commands that set modes in the Calculator.
  10018. They do not affect the contents of the stack, although they may change
  10019. the @emph{appearance} or @emph{interpretation} of the stack's contents.
  10020. @menu
  10021. * General Mode Commands::
  10022. * Precision::
  10023. * Inverse and Hyperbolic::
  10024. * Calculation Modes::
  10025. * Simplification Modes::
  10026. * Declarations::
  10027. * Display Modes::
  10028. * Language Modes::
  10029. * Modes Variable::
  10030. * Calc Mode Line::
  10031. @end menu
  10032. @node General Mode Commands, Precision, Mode Settings, Mode Settings
  10033. @section General Mode Commands
  10034. @noindent
  10035. @kindex m m
  10036. @pindex calc-save-modes
  10037. @cindex Continuous memory
  10038. @cindex Saving mode settings
  10039. @cindex Permanent mode settings
  10040. @cindex Calc init file, mode settings
  10041. You can save all of the current mode settings in your Calc init file
  10042. (the file given by the variable @code{calc-settings-file}, typically
  10043. @file{~/.emacs.d/calc.el}) with the @kbd{m m} (@code{calc-save-modes})
  10044. command. This will cause Emacs to reestablish these modes each time
  10045. it starts up. The modes saved in the file include everything
  10046. controlled by the @kbd{m} and @kbd{d} prefix keys, the current
  10047. precision and binary word size, whether or not the trail is displayed,
  10048. the current height of the Calc window, and more. The current
  10049. interface (used when you type @kbd{C-x * *}) is also saved. If there
  10050. were already saved mode settings in the file, they are replaced.
  10051. Otherwise, the new mode information is appended to the end of the
  10052. file.
  10053. @kindex m R
  10054. @pindex calc-mode-record-mode
  10055. The @kbd{m R} (@code{calc-mode-record-mode}) command tells Calc to
  10056. record all the mode settings (as if by pressing @kbd{m m}) every
  10057. time a mode setting changes. If the modes are saved this way, then this
  10058. ``automatic mode recording'' mode is also saved.
  10059. Type @kbd{m R} again to disable this method of recording the mode
  10060. settings. To turn it off permanently, the @kbd{m m} command will also be
  10061. necessary. (If Embedded mode is enabled, other options for recording
  10062. the modes are available; @pxref{Mode Settings in Embedded Mode}.)
  10063. @kindex m F
  10064. @pindex calc-settings-file-name
  10065. The @kbd{m F} (@code{calc-settings-file-name}) command allows you to
  10066. choose a different file than the current value of @code{calc-settings-file}
  10067. for @kbd{m m}, @kbd{Z P}, and similar commands to save permanent information.
  10068. You are prompted for a file name. All Calc modes are then reset to
  10069. their default values, then settings from the file you named are loaded
  10070. if this file exists, and this file becomes the one that Calc will
  10071. use in the future for commands like @kbd{m m}. The default settings
  10072. file name is @file{~/.emacs.d/calc.el}. You can see the current file name by
  10073. giving a blank response to the @kbd{m F} prompt. See also the
  10074. discussion of the @code{calc-settings-file} variable; @pxref{Customizing Calc}.
  10075. If the file name you give is your user init file (typically
  10076. @file{~/.emacs}), @kbd{m F} will not automatically load the new file. This
  10077. is because your user init file may contain other things you don't want
  10078. to reread. You can give
  10079. a numeric prefix argument of 1 to @kbd{m F} to force it to read the
  10080. file no matter what. Conversely, an argument of @mathit{-1} tells
  10081. @kbd{m F} @emph{not} to read the new file. An argument of 2 or @mathit{-2}
  10082. tells @kbd{m F} not to reset the modes to their defaults beforehand,
  10083. which is useful if you intend your new file to have a variant of the
  10084. modes present in the file you were using before.
  10085. @kindex m x
  10086. @pindex calc-always-load-extensions
  10087. The @kbd{m x} (@code{calc-always-load-extensions}) command enables a mode
  10088. in which the first use of Calc loads the entire program, including all
  10089. extensions modules. Otherwise, the extensions modules will not be loaded
  10090. until the various advanced Calc features are used. Since this mode only
  10091. has effect when Calc is first loaded, @kbd{m x} is usually followed by
  10092. @kbd{m m} to make the mode-setting permanent. To load all of Calc just
  10093. once, rather than always in the future, you can press @kbd{C-x * L}.
  10094. @kindex m S
  10095. @pindex calc-shift-prefix
  10096. The @kbd{m S} (@code{calc-shift-prefix}) command enables a mode in which
  10097. all of Calc's letter prefix keys may be typed shifted as well as unshifted.
  10098. If you are typing, say, @kbd{a S} (@code{calc-solve-for}) quite often
  10099. you might find it easier to turn this mode on so that you can type
  10100. @kbd{A S} instead. When this mode is enabled, the commands that used to
  10101. be on those single shifted letters (e.g., @kbd{A} (@code{calc-abs})) can
  10102. now be invoked by pressing the shifted letter twice: @kbd{A A}. Note
  10103. that the @kbd{v} prefix key always works both shifted and unshifted, and
  10104. the @kbd{z} and @kbd{Z} prefix keys are always distinct. Also, the @kbd{h}
  10105. prefix is not affected by this mode. Press @kbd{m S} again to disable
  10106. shifted-prefix mode.
  10107. @node Precision, Inverse and Hyperbolic, General Mode Commands, Mode Settings
  10108. @section Precision
  10109. @noindent
  10110. @kindex p
  10111. @pindex calc-precision
  10112. @cindex Precision of calculations
  10113. The @kbd{p} (@code{calc-precision}) command controls the precision to
  10114. which floating-point calculations are carried. The precision must be
  10115. at least 3 digits and may be arbitrarily high, within the limits of
  10116. memory and time. This affects only floats: Integer and rational
  10117. calculations are always carried out with as many digits as necessary.
  10118. The @kbd{p} key prompts for the current precision. If you wish you
  10119. can instead give the precision as a numeric prefix argument.
  10120. Many internal calculations are carried to one or two digits higher
  10121. precision than normal. Results are rounded down afterward to the
  10122. current precision. Unless a special display mode has been selected,
  10123. floats are always displayed with their full stored precision, i.e.,
  10124. what you see is what you get. Reducing the current precision does not
  10125. round values already on the stack, but those values will be rounded
  10126. down before being used in any calculation. The @kbd{c 0} through
  10127. @kbd{c 9} commands (@pxref{Conversions}) can be used to round an
  10128. existing value to a new precision.
  10129. @cindex Accuracy of calculations
  10130. It is important to distinguish the concepts of @dfn{precision} and
  10131. @dfn{accuracy}. In the normal usage of these words, the number
  10132. 123.4567 has a precision of 7 digits but an accuracy of 4 digits.
  10133. The precision is the total number of digits not counting leading
  10134. or trailing zeros (regardless of the position of the decimal point).
  10135. The accuracy is simply the number of digits after the decimal point
  10136. (again not counting trailing zeros). In Calc you control the precision,
  10137. not the accuracy of computations. If you were to set the accuracy
  10138. instead, then calculations like @samp{exp(100)} would generate many
  10139. more digits than you would typically need, while @samp{exp(-100)} would
  10140. probably round to zero! In Calc, both these computations give you
  10141. exactly 12 (or the requested number of) significant digits.
  10142. The only Calc features that deal with accuracy instead of precision
  10143. are fixed-point display mode for floats (@kbd{d f}; @pxref{Float Formats}),
  10144. and the rounding functions like @code{floor} and @code{round}
  10145. (@pxref{Integer Truncation}). Also, @kbd{c 0} through @kbd{c 9}
  10146. deal with both precision and accuracy depending on the magnitudes
  10147. of the numbers involved.
  10148. If you need to work with a particular fixed accuracy (say, dollars and
  10149. cents with two digits after the decimal point), one solution is to work
  10150. with integers and an ``implied'' decimal point. For example, $8.99
  10151. divided by 6 would be entered @kbd{899 @key{RET} 6 /}, yielding 149.833
  10152. (actually $1.49833 with our implied decimal point); pressing @kbd{R}
  10153. would round this to 150 cents, i.e., $1.50.
  10154. @xref{Floats}, for still more on floating-point precision and related
  10155. issues.
  10156. @node Inverse and Hyperbolic, Calculation Modes, Precision, Mode Settings
  10157. @section Inverse and Hyperbolic Flags
  10158. @noindent
  10159. @kindex I
  10160. @pindex calc-inverse
  10161. There is no single-key equivalent to the @code{calc-arcsin} function.
  10162. Instead, you must first press @kbd{I} (@code{calc-inverse}) to set
  10163. the @dfn{Inverse Flag}, then press @kbd{S} (@code{calc-sin}).
  10164. The @kbd{I} key actually toggles the Inverse Flag. When this flag
  10165. is set, the word @samp{Inv} appears in the mode line.
  10166. @kindex H
  10167. @pindex calc-hyperbolic
  10168. Likewise, the @kbd{H} key (@code{calc-hyperbolic}) sets or clears the
  10169. Hyperbolic Flag, which transforms @code{calc-sin} into @code{calc-sinh}.
  10170. If both of these flags are set at once, the effect will be
  10171. @code{calc-arcsinh}. (The Hyperbolic flag is also used by some
  10172. non-trigonometric commands; for example @kbd{H L} computes a base-10,
  10173. instead of base-@mathit{e}, logarithm.)
  10174. Command names like @code{calc-arcsin} are provided for completeness, and
  10175. may be executed with @kbd{x} or @kbd{M-x}. Their effect is simply to
  10176. toggle the Inverse and/or Hyperbolic flags and then execute the
  10177. corresponding base command (@code{calc-sin} in this case).
  10178. @kindex O
  10179. @pindex calc-option
  10180. The @kbd{O} key (@code{calc-option}) sets another flag, the
  10181. @dfn{Option Flag}, which also can alter the subsequent Calc command in
  10182. various ways.
  10183. The Inverse, Hyperbolic and Option flags apply only to the next
  10184. Calculator command, after which they are automatically cleared. (They
  10185. are also cleared if the next keystroke is not a Calc command.) Digits
  10186. you type after @kbd{I}, @kbd{H} or @kbd{O} (or @kbd{K}) are treated as
  10187. prefix arguments for the next command, not as numeric entries. The
  10188. same is true of @kbd{C-u}, but not of the minus sign (@kbd{K -} means
  10189. to subtract and keep arguments).
  10190. Another Calc prefix flag, @kbd{K} (keep-arguments), is discussed
  10191. elsewhere. @xref{Keep Arguments}.
  10192. @node Calculation Modes, Simplification Modes, Inverse and Hyperbolic, Mode Settings
  10193. @section Calculation Modes
  10194. @noindent
  10195. The commands in this section are two-key sequences beginning with
  10196. the @kbd{m} prefix. (That's the letter @kbd{m}, not the @key{META} key.)
  10197. The @samp{m a} (@code{calc-algebraic-mode}) command is described elsewhere
  10198. (@pxref{Algebraic Entry}).
  10199. @menu
  10200. * Angular Modes::
  10201. * Polar Mode::
  10202. * Fraction Mode::
  10203. * Infinite Mode::
  10204. * Symbolic Mode::
  10205. * Matrix Mode::
  10206. * Automatic Recomputation::
  10207. * Working Message::
  10208. @end menu
  10209. @node Angular Modes, Polar Mode, Calculation Modes, Calculation Modes
  10210. @subsection Angular Modes
  10211. @noindent
  10212. @cindex Angular mode
  10213. The Calculator supports three notations for angles: radians, degrees,
  10214. and degrees-minutes-seconds. When a number is presented to a function
  10215. like @code{sin} that requires an angle, the current angular mode is
  10216. used to interpret the number as either radians or degrees. If an HMS
  10217. form is presented to @code{sin}, it is always interpreted as
  10218. degrees-minutes-seconds.
  10219. Functions that compute angles produce a number in radians, a number in
  10220. degrees, or an HMS form depending on the current angular mode. If the
  10221. result is a complex number and the current mode is HMS, the number is
  10222. instead expressed in degrees. (Complex-number calculations would
  10223. normally be done in Radians mode, though. Complex numbers are converted
  10224. to degrees by calculating the complex result in radians and then
  10225. multiplying by 180 over @cpi{}.)
  10226. @kindex m r
  10227. @pindex calc-radians-mode
  10228. @kindex m d
  10229. @pindex calc-degrees-mode
  10230. @kindex m h
  10231. @pindex calc-hms-mode
  10232. The @kbd{m r} (@code{calc-radians-mode}), @kbd{m d} (@code{calc-degrees-mode}),
  10233. and @kbd{m h} (@code{calc-hms-mode}) commands control the angular mode.
  10234. The current angular mode is displayed on the Emacs mode line.
  10235. The default angular mode is Degrees.
  10236. @node Polar Mode, Fraction Mode, Angular Modes, Calculation Modes
  10237. @subsection Polar Mode
  10238. @noindent
  10239. @cindex Polar mode
  10240. The Calculator normally ``prefers'' rectangular complex numbers in the
  10241. sense that rectangular form is used when the proper form can not be
  10242. decided from the input. This might happen by multiplying a rectangular
  10243. number by a polar one, by taking the square root of a negative real
  10244. number, or by entering @kbd{( 2 @key{SPC} 3 )}.
  10245. @kindex m p
  10246. @pindex calc-polar-mode
  10247. The @kbd{m p} (@code{calc-polar-mode}) command toggles complex-number
  10248. preference between rectangular and polar forms. In Polar mode, all
  10249. of the above example situations would produce polar complex numbers.
  10250. @node Fraction Mode, Infinite Mode, Polar Mode, Calculation Modes
  10251. @subsection Fraction Mode
  10252. @noindent
  10253. @cindex Fraction mode
  10254. @cindex Division of integers
  10255. Division of two integers normally yields a floating-point number if the
  10256. result cannot be expressed as an integer. In some cases you would
  10257. rather get an exact fractional answer. One way to accomplish this is
  10258. to use the @kbd{:} (@code{calc-fdiv}) [@code{fdiv}] command, which
  10259. divides the two integers on the top of the stack to produce a fraction:
  10260. @kbd{6 @key{RET} 4 :} produces @expr{3:2} even though
  10261. @kbd{6 @key{RET} 4 /} produces @expr{1.5}.
  10262. @kindex m f
  10263. @pindex calc-frac-mode
  10264. To set the Calculator to produce fractional results for normal integer
  10265. divisions, use the @kbd{m f} (@code{calc-frac-mode}) command.
  10266. For example, @expr{8/4} produces @expr{2} in either mode,
  10267. but @expr{6/4} produces @expr{3:2} in Fraction mode, @expr{1.5} in
  10268. Float mode.
  10269. At any time you can use @kbd{c f} (@code{calc-float}) to convert a
  10270. fraction to a float, or @kbd{c F} (@code{calc-fraction}) to convert a
  10271. float to a fraction. @xref{Conversions}.
  10272. @node Infinite Mode, Symbolic Mode, Fraction Mode, Calculation Modes
  10273. @subsection Infinite Mode
  10274. @noindent
  10275. @cindex Infinite mode
  10276. The Calculator normally treats results like @expr{1 / 0} as errors;
  10277. formulas like this are left in unsimplified form. But Calc can be
  10278. put into a mode where such calculations instead produce ``infinite''
  10279. results.
  10280. @kindex m i
  10281. @pindex calc-infinite-mode
  10282. The @kbd{m i} (@code{calc-infinite-mode}) command turns this mode
  10283. on and off. When the mode is off, infinities do not arise except
  10284. in calculations that already had infinities as inputs. (One exception
  10285. is that infinite open intervals like @samp{[0 .. inf)} can be
  10286. generated; however, intervals closed at infinity (@samp{[0 .. inf]})
  10287. will not be generated when Infinite mode is off.)
  10288. With Infinite mode turned on, @samp{1 / 0} will generate @code{uinf},
  10289. an undirected infinity. @xref{Infinities}, for a discussion of the
  10290. difference between @code{inf} and @code{uinf}. Also, @expr{0 / 0}
  10291. evaluates to @code{nan}, the ``indeterminate'' symbol. Various other
  10292. functions can also return infinities in this mode; for example,
  10293. @samp{ln(0) = -inf}, and @samp{gamma(-7) = uinf}. Once again,
  10294. note that @samp{exp(inf) = inf} regardless of Infinite mode because
  10295. this calculation has infinity as an input.
  10296. @cindex Positive Infinite mode
  10297. The @kbd{m i} command with a numeric prefix argument of zero,
  10298. i.e., @kbd{C-u 0 m i}, turns on a Positive Infinite mode in
  10299. which zero is treated as positive instead of being directionless.
  10300. Thus, @samp{1 / 0 = inf} and @samp{-1 / 0 = -inf} in this mode.
  10301. Note that zero never actually has a sign in Calc; there are no
  10302. separate representations for @mathit{+0} and @mathit{-0}. Positive
  10303. Infinite mode merely changes the interpretation given to the
  10304. single symbol, @samp{0}. One consequence of this is that, while
  10305. you might expect @samp{1 / -0 = -inf}, actually @samp{1 / -0}
  10306. is equivalent to @samp{1 / 0}, which is equal to positive @code{inf}.
  10307. @node Symbolic Mode, Matrix Mode, Infinite Mode, Calculation Modes
  10308. @subsection Symbolic Mode
  10309. @noindent
  10310. @cindex Symbolic mode
  10311. @cindex Inexact results
  10312. Calculations are normally performed numerically wherever possible.
  10313. For example, the @code{calc-sqrt} command, or @code{sqrt} function in an
  10314. algebraic expression, produces a numeric answer if the argument is a
  10315. number or a symbolic expression if the argument is an expression:
  10316. @kbd{2 Q} pushes 1.4142 but @kbd{@key{'} x+1 @key{RET} Q} pushes @samp{sqrt(x+1)}.
  10317. @kindex m s
  10318. @pindex calc-symbolic-mode
  10319. In @dfn{Symbolic mode}, controlled by the @kbd{m s} (@code{calc-symbolic-mode})
  10320. command, functions which would produce inexact, irrational results are
  10321. left in symbolic form. Thus @kbd{16 Q} pushes 4, but @kbd{2 Q} pushes
  10322. @samp{sqrt(2)}.
  10323. @kindex N
  10324. @pindex calc-eval-num
  10325. The shift-@kbd{N} (@code{calc-eval-num}) command evaluates numerically
  10326. the expression at the top of the stack, by temporarily disabling
  10327. @code{calc-symbolic-mode} and executing @kbd{=} (@code{calc-evaluate}).
  10328. Given a numeric prefix argument, it also
  10329. sets the floating-point precision to the specified value for the duration
  10330. of the command.
  10331. To evaluate a formula numerically without expanding the variables it
  10332. contains, you can use the key sequence @kbd{m s a v m s} (this uses
  10333. @code{calc-alg-evaluate}, which resimplifies but doesn't evaluate
  10334. variables.)
  10335. @node Matrix Mode, Automatic Recomputation, Symbolic Mode, Calculation Modes
  10336. @subsection Matrix and Scalar Modes
  10337. @noindent
  10338. @cindex Matrix mode
  10339. @cindex Scalar mode
  10340. Calc sometimes makes assumptions during algebraic manipulation that
  10341. are awkward or incorrect when vectors and matrices are involved.
  10342. Calc has two modes, @dfn{Matrix mode} and @dfn{Scalar mode}, which
  10343. modify its behavior around vectors in useful ways.
  10344. @kindex m v
  10345. @pindex calc-matrix-mode
  10346. Press @kbd{m v} (@code{calc-matrix-mode}) once to enter Matrix mode.
  10347. In this mode, all objects are assumed to be matrices unless provably
  10348. otherwise. One major effect is that Calc will no longer consider
  10349. multiplication to be commutative. (Recall that in matrix arithmetic,
  10350. @samp{A*B} is not the same as @samp{B*A}.) This assumption affects
  10351. rewrite rules and algebraic simplification. Another effect of this
  10352. mode is that calculations that would normally produce constants like
  10353. 0 and 1 (e.g., @expr{a - a} and @expr{a / a}, respectively) will now
  10354. produce function calls that represent ``generic'' zero or identity
  10355. matrices: @samp{idn(0)}, @samp{idn(1)}. The @code{idn} function
  10356. @samp{idn(@var{a},@var{n})} returns @var{a} times an @var{n}x@var{n}
  10357. identity matrix; if @var{n} is omitted, it doesn't know what
  10358. dimension to use and so the @code{idn} call remains in symbolic
  10359. form. However, if this generic identity matrix is later combined
  10360. with a matrix whose size is known, it will be converted into
  10361. a true identity matrix of the appropriate size. On the other hand,
  10362. if it is combined with a scalar (as in @samp{idn(1) + 2}), Calc
  10363. will assume it really was a scalar after all and produce, e.g., 3.
  10364. Press @kbd{m v} a second time to get Scalar mode. Here, objects are
  10365. assumed @emph{not} to be vectors or matrices unless provably so.
  10366. For example, normally adding a variable to a vector, as in
  10367. @samp{[x, y, z] + a}, will leave the sum in symbolic form because
  10368. as far as Calc knows, @samp{a} could represent either a number or
  10369. another 3-vector. In Scalar mode, @samp{a} is assumed to be a
  10370. non-vector, and the addition is evaluated to @samp{[x+a, y+a, z+a]}.
  10371. Press @kbd{m v} a third time to return to the normal mode of operation.
  10372. If you press @kbd{m v} with a numeric prefix argument @var{n}, you
  10373. get a special ``dimensioned'' Matrix mode in which matrices of
  10374. unknown size are assumed to be @var{n}x@var{n} square matrices.
  10375. Then, the function call @samp{idn(1)} will expand into an actual
  10376. matrix rather than representing a ``generic'' matrix. Simply typing
  10377. @kbd{C-u m v} will get you a square Matrix mode, in which matrices of
  10378. unknown size are assumed to be square matrices of unspecified size.
  10379. @cindex Declaring scalar variables
  10380. Of course these modes are approximations to the true state of
  10381. affairs, which is probably that some quantities will be matrices
  10382. and others will be scalars. One solution is to ``declare''
  10383. certain variables or functions to be scalar-valued.
  10384. @xref{Declarations}, to see how to make declarations in Calc.
  10385. There is nothing stopping you from declaring a variable to be
  10386. scalar and then storing a matrix in it; however, if you do, the
  10387. results you get from Calc may not be valid. Suppose you let Calc
  10388. get the result @samp{[x+a, y+a, z+a]} shown above, and then stored
  10389. @samp{[1, 2, 3]} in @samp{a}. The result would not be the same as
  10390. for @samp{[x, y, z] + [1, 2, 3]}, but that's because you have broken
  10391. your earlier promise to Calc that @samp{a} would be scalar.
  10392. Another way to mix scalars and matrices is to use selections
  10393. (@pxref{Selecting Subformulas}). Use Matrix mode when operating on
  10394. your formula normally; then, to apply Scalar mode to a certain part
  10395. of the formula without affecting the rest just select that part,
  10396. change into Scalar mode and press @kbd{=} to resimplify the part
  10397. under this mode, then change back to Matrix mode before deselecting.
  10398. @node Automatic Recomputation, Working Message, Matrix Mode, Calculation Modes
  10399. @subsection Automatic Recomputation
  10400. @noindent
  10401. The @dfn{evaluates-to} operator, @samp{=>}, has the special
  10402. property that any @samp{=>} formulas on the stack are recomputed
  10403. whenever variable values or mode settings that might affect them
  10404. are changed. @xref{Evaluates-To Operator}.
  10405. @kindex m C
  10406. @pindex calc-auto-recompute
  10407. The @kbd{m C} (@code{calc-auto-recompute}) command turns this
  10408. automatic recomputation on and off. If you turn it off, Calc will
  10409. not update @samp{=>} operators on the stack (nor those in the
  10410. attached Embedded mode buffer, if there is one). They will not
  10411. be updated unless you explicitly do so by pressing @kbd{=} or until
  10412. you press @kbd{m C} to turn recomputation back on. (While automatic
  10413. recomputation is off, you can think of @kbd{m C m C} as a command
  10414. to update all @samp{=>} operators while leaving recomputation off.)
  10415. To update @samp{=>} operators in an Embedded buffer while
  10416. automatic recomputation is off, use @w{@kbd{C-x * u}}.
  10417. @xref{Embedded Mode}.
  10418. @node Working Message, , Automatic Recomputation, Calculation Modes
  10419. @subsection Working Messages
  10420. @noindent
  10421. @cindex Performance
  10422. @cindex Working messages
  10423. Since the Calculator is written entirely in Emacs Lisp, which is not
  10424. designed for heavy numerical work, many operations are quite slow.
  10425. The Calculator normally displays the message @samp{Working...} in the
  10426. echo area during any command that may be slow. In addition, iterative
  10427. operations such as square roots and trigonometric functions display the
  10428. intermediate result at each step. Both of these types of messages can
  10429. be disabled if you find them distracting.
  10430. @kindex m w
  10431. @pindex calc-working
  10432. Type @kbd{m w} (@code{calc-working}) with a numeric prefix of 0 to
  10433. disable all ``working'' messages. Use a numeric prefix of 1 to enable
  10434. only the plain @samp{Working...} message. Use a numeric prefix of 2 to
  10435. see intermediate results as well. With no numeric prefix this displays
  10436. the current mode.
  10437. While it may seem that the ``working'' messages will slow Calc down
  10438. considerably, experiments have shown that their impact is actually
  10439. quite small. But if your terminal is slow you may find that it helps
  10440. to turn the messages off.
  10441. @node Simplification Modes, Declarations, Calculation Modes, Mode Settings
  10442. @section Simplification Modes
  10443. @noindent
  10444. The current @dfn{simplification mode} controls how numbers and formulas
  10445. are ``normalized'' when being taken from or pushed onto the stack.
  10446. Some normalizations are unavoidable, such as rounding floating-point
  10447. results to the current precision, and reducing fractions to simplest
  10448. form. Others, such as simplifying a formula like @expr{a+a} (or @expr{2+3}),
  10449. are done automatically but can be turned off when necessary.
  10450. When you press a key like @kbd{+} when @expr{2} and @expr{3} are on the
  10451. stack, Calc pops these numbers, normalizes them, creates the formula
  10452. @expr{2+3}, normalizes it, and pushes the result. Of course the standard
  10453. rules for normalizing @expr{2+3} will produce the result @expr{5}.
  10454. Simplification mode commands consist of the lower-case @kbd{m} prefix key
  10455. followed by a shifted letter.
  10456. @kindex m O
  10457. @pindex calc-no-simplify-mode
  10458. The @kbd{m O} (@code{calc-no-simplify-mode}) command turns off all optional
  10459. simplifications. These would leave a formula like @expr{2+3} alone. In
  10460. fact, nothing except simple numbers are ever affected by normalization
  10461. in this mode. Explicit simplification commands, such as @kbd{=} or
  10462. @kbd{a s}, can still be given to simplify any formulas.
  10463. @xref{Algebraic Definitions}, for a sample use of
  10464. No-Simplification mode.
  10465. @kindex m N
  10466. @pindex calc-num-simplify-mode
  10467. The @kbd{m N} (@code{calc-num-simplify-mode}) command turns off simplification
  10468. of any formulas except those for which all arguments are constants. For
  10469. example, @expr{1+2} is simplified to @expr{3}, and @expr{a+(2-2)} is
  10470. simplified to @expr{a+0} but no further, since one argument of the sum
  10471. is not a constant. Unfortunately, @expr{(a+2)-2} is @emph{not} simplified
  10472. because the top-level @samp{-} operator's arguments are not both
  10473. constant numbers (one of them is the formula @expr{a+2}).
  10474. A constant is a number or other numeric object (such as a constant
  10475. error form or modulo form), or a vector all of whose
  10476. elements are constant.
  10477. @kindex m I
  10478. @pindex calc-basic-simplify-mode
  10479. The @kbd{m I} (@code{calc-basic-simplify-mode}) command does some basic
  10480. simplifications for all formulas. This includes many easy and
  10481. fast algebraic simplifications such as @expr{a+0} to @expr{a}, and
  10482. @expr{a + 2 a} to @expr{3 a}, as well as evaluating functions like
  10483. @expr{@tfn{deriv}(x^2, x)} to @expr{2 x}.
  10484. @kindex m B
  10485. @pindex calc-bin-simplify-mode
  10486. The @kbd{m B} (@code{calc-bin-simplify-mode}) mode applies the basic
  10487. simplifications to a result and then, if the result is an integer,
  10488. uses the @kbd{b c} (@code{calc-clip}) command to clip the integer according
  10489. to the current binary word size. @xref{Binary Functions}. Real numbers
  10490. are rounded to the nearest integer and then clipped; other kinds of
  10491. results (after the basic simplifications) are left alone.
  10492. @kindex m A
  10493. @pindex calc-alg-simplify-mode
  10494. The @kbd{m A} (@code{calc-alg-simplify-mode}) mode does standard
  10495. algebraic simplifications. @xref{Algebraic Simplifications}.
  10496. @kindex m E
  10497. @pindex calc-ext-simplify-mode
  10498. The @kbd{m E} (@code{calc-ext-simplify-mode}) mode does ``extended'', or
  10499. ``unsafe'', algebraic simplification. @xref{Unsafe Simplifications}.
  10500. @kindex m U
  10501. @pindex calc-units-simplify-mode
  10502. The @kbd{m U} (@code{calc-units-simplify-mode}) mode does units
  10503. simplification. @xref{Simplification of Units}. These include the
  10504. algebraic simplifications, plus variable names which
  10505. are identifiable as unit names (like @samp{mm} for ``millimeters'')
  10506. are simplified with their unit definitions in mind.
  10507. A common technique is to set the simplification mode down to the lowest
  10508. amount of simplification you will allow to be applied automatically, then
  10509. use manual commands like @kbd{a s} and @kbd{c c} (@code{calc-clean}) to
  10510. perform higher types of simplifications on demand.
  10511. @node Declarations, Display Modes, Simplification Modes, Mode Settings
  10512. @section Declarations
  10513. @noindent
  10514. A @dfn{declaration} is a statement you make that promises you will
  10515. use a certain variable or function in a restricted way. This may
  10516. give Calc the freedom to do things that it couldn't do if it had to
  10517. take the fully general situation into account.
  10518. @menu
  10519. * Declaration Basics::
  10520. * Kinds of Declarations::
  10521. * Functions for Declarations::
  10522. @end menu
  10523. @node Declaration Basics, Kinds of Declarations, Declarations, Declarations
  10524. @subsection Declaration Basics
  10525. @noindent
  10526. @kindex s d
  10527. @pindex calc-declare-variable
  10528. The @kbd{s d} (@code{calc-declare-variable}) command is the easiest
  10529. way to make a declaration for a variable. This command prompts for
  10530. the variable name, then prompts for the declaration. The default
  10531. at the declaration prompt is the previous declaration, if any.
  10532. You can edit this declaration, or press @kbd{C-k} to erase it and
  10533. type a new declaration. (Or, erase it and press @key{RET} to clear
  10534. the declaration, effectively ``undeclaring'' the variable.)
  10535. A declaration is in general a vector of @dfn{type symbols} and
  10536. @dfn{range} values. If there is only one type symbol or range value,
  10537. you can write it directly rather than enclosing it in a vector.
  10538. For example, @kbd{s d foo @key{RET} real @key{RET}} declares @code{foo} to
  10539. be a real number, and @kbd{s d bar @key{RET} [int, const, [1..6]] @key{RET}}
  10540. declares @code{bar} to be a constant integer between 1 and 6.
  10541. (Actually, you can omit the outermost brackets and Calc will
  10542. provide them for you: @kbd{s d bar @key{RET} int, const, [1..6] @key{RET}}.)
  10543. @cindex @code{Decls} variable
  10544. @vindex Decls
  10545. Declarations in Calc are kept in a special variable called @code{Decls}.
  10546. This variable encodes the set of all outstanding declarations in
  10547. the form of a matrix. Each row has two elements: A variable or
  10548. vector of variables declared by that row, and the declaration
  10549. specifier as described above. You can use the @kbd{s D} command to
  10550. edit this variable if you wish to see all the declarations at once.
  10551. @xref{Operations on Variables}, for a description of this command
  10552. and the @kbd{s p} command that allows you to save your declarations
  10553. permanently if you wish.
  10554. Items being declared can also be function calls. The arguments in
  10555. the call are ignored; the effect is to say that this function returns
  10556. values of the declared type for any valid arguments. The @kbd{s d}
  10557. command declares only variables, so if you wish to make a function
  10558. declaration you will have to edit the @code{Decls} matrix yourself.
  10559. For example, the declaration matrix
  10560. @smallexample
  10561. @group
  10562. [ [ foo, real ]
  10563. [ [j, k, n], int ]
  10564. [ f(1,2,3), [0 .. inf) ] ]
  10565. @end group
  10566. @end smallexample
  10567. @noindent
  10568. declares that @code{foo} represents a real number, @code{j}, @code{k}
  10569. and @code{n} represent integers, and the function @code{f} always
  10570. returns a real number in the interval shown.
  10571. @vindex All
  10572. If there is a declaration for the variable @code{All}, then that
  10573. declaration applies to all variables that are not otherwise declared.
  10574. It does not apply to function names. For example, using the row
  10575. @samp{[All, real]} says that all your variables are real unless they
  10576. are explicitly declared without @code{real} in some other row.
  10577. The @kbd{s d} command declares @code{All} if you give a blank
  10578. response to the variable-name prompt.
  10579. @node Kinds of Declarations, Functions for Declarations, Declaration Basics, Declarations
  10580. @subsection Kinds of Declarations
  10581. @noindent
  10582. The type-specifier part of a declaration (that is, the second prompt
  10583. in the @kbd{s d} command) can be a type symbol, an interval, or a
  10584. vector consisting of zero or more type symbols followed by zero or
  10585. more intervals or numbers that represent the set of possible values
  10586. for the variable.
  10587. @smallexample
  10588. @group
  10589. [ [ a, [1, 2, 3, 4, 5] ]
  10590. [ b, [1 .. 5] ]
  10591. [ c, [int, 1 .. 5] ] ]
  10592. @end group
  10593. @end smallexample
  10594. Here @code{a} is declared to contain one of the five integers shown;
  10595. @code{b} is any number in the interval from 1 to 5 (any real number
  10596. since we haven't specified), and @code{c} is any integer in that
  10597. interval. Thus the declarations for @code{a} and @code{c} are
  10598. nearly equivalent (see below).
  10599. The type-specifier can be the empty vector @samp{[]} to say that
  10600. nothing is known about a given variable's value. This is the same
  10601. as not declaring the variable at all except that it overrides any
  10602. @code{All} declaration which would otherwise apply.
  10603. The initial value of @code{Decls} is the empty vector @samp{[]}.
  10604. If @code{Decls} has no stored value or if the value stored in it
  10605. is not valid, it is ignored and there are no declarations as far
  10606. as Calc is concerned. (The @kbd{s d} command will replace such a
  10607. malformed value with a fresh empty matrix, @samp{[]}, before recording
  10608. the new declaration.) Unrecognized type symbols are ignored.
  10609. The following type symbols describe what sorts of numbers will be
  10610. stored in a variable:
  10611. @table @code
  10612. @item int
  10613. Integers.
  10614. @item numint
  10615. Numerical integers. (Integers or integer-valued floats.)
  10616. @item frac
  10617. Fractions. (Rational numbers which are not integers.)
  10618. @item rat
  10619. Rational numbers. (Either integers or fractions.)
  10620. @item float
  10621. Floating-point numbers.
  10622. @item real
  10623. Real numbers. (Integers, fractions, or floats. Actually,
  10624. intervals and error forms with real components also count as
  10625. reals here.)
  10626. @item pos
  10627. Positive real numbers. (Strictly greater than zero.)
  10628. @item nonneg
  10629. Nonnegative real numbers. (Greater than or equal to zero.)
  10630. @item number
  10631. Numbers. (Real or complex.)
  10632. @end table
  10633. Calc uses this information to determine when certain simplifications
  10634. of formulas are safe. For example, @samp{(x^y)^z} cannot be
  10635. simplified to @samp{x^(y z)} in general; for example,
  10636. @samp{((-3)^2)^1:2} is 3, but @samp{(-3)^(2*1:2) = (-3)^1} is @mathit{-3}.
  10637. However, this simplification @emph{is} safe if @code{z} is known
  10638. to be an integer, or if @code{x} is known to be a nonnegative
  10639. real number. If you have given declarations that allow Calc to
  10640. deduce either of these facts, Calc will perform this simplification
  10641. of the formula.
  10642. Calc can apply a certain amount of logic when using declarations.
  10643. For example, @samp{(x^y)^(2n+1)} will be simplified if @code{n}
  10644. has been declared @code{int}; Calc knows that an integer times an
  10645. integer, plus an integer, must always be an integer. (In fact,
  10646. Calc would simplify @samp{(-x)^(2n+1)} to @samp{-(x^(2n+1))} since
  10647. it is able to determine that @samp{2n+1} must be an odd integer.)
  10648. Similarly, @samp{(abs(x)^y)^z} will be simplified to @samp{abs(x)^(y z)}
  10649. because Calc knows that the @code{abs} function always returns a
  10650. nonnegative real. If you had a @code{myabs} function that also had
  10651. this property, you could get Calc to recognize it by adding the row
  10652. @samp{[myabs(), nonneg]} to the @code{Decls} matrix.
  10653. One instance of this simplification is @samp{sqrt(x^2)} (since the
  10654. @code{sqrt} function is effectively a one-half power). Normally
  10655. Calc leaves this formula alone. After the command
  10656. @kbd{s d x @key{RET} real @key{RET}}, however, it can simplify the formula to
  10657. @samp{abs(x)}. And after @kbd{s d x @key{RET} nonneg @key{RET}}, Calc can
  10658. simplify this formula all the way to @samp{x}.
  10659. If there are any intervals or real numbers in the type specifier,
  10660. they comprise the set of possible values that the variable or
  10661. function being declared can have. In particular, the type symbol
  10662. @code{real} is effectively the same as the range @samp{[-inf .. inf]}
  10663. (note that infinity is included in the range of possible values);
  10664. @code{pos} is the same as @samp{(0 .. inf]}, and @code{nonneg} is
  10665. the same as @samp{[0 .. inf]}. Saying @samp{[real, [-5 .. 5]]} is
  10666. redundant because the fact that the variable is real can be
  10667. deduced just from the interval, but @samp{[int, [-5 .. 5]]} and
  10668. @samp{[rat, [-5 .. 5]]} are useful combinations.
  10669. Note that the vector of intervals or numbers is in the same format
  10670. used by Calc's set-manipulation commands. @xref{Set Operations}.
  10671. The type specifier @samp{[1, 2, 3]} is equivalent to
  10672. @samp{[numint, 1, 2, 3]}, @emph{not} to @samp{[int, 1, 2, 3]}.
  10673. In other words, the range of possible values means only that
  10674. the variable's value must be numerically equal to a number in
  10675. that range, but not that it must be equal in type as well.
  10676. Calc's set operations act the same way; @samp{in(2, [1., 2., 3.])}
  10677. and @samp{in(1.5, [1:2, 3:2, 5:2])} both report ``true.''
  10678. If you use a conflicting combination of type specifiers, the
  10679. results are unpredictable. An example is @samp{[pos, [0 .. 5]]},
  10680. where the interval does not lie in the range described by the
  10681. type symbol.
  10682. ``Real'' declarations mostly affect simplifications involving powers
  10683. like the one described above. Another case where they are used
  10684. is in the @kbd{a P} command which returns a list of all roots of a
  10685. polynomial; if the variable has been declared real, only the real
  10686. roots (if any) will be included in the list.
  10687. ``Integer'' declarations are used for simplifications which are valid
  10688. only when certain values are integers (such as @samp{(x^y)^z}
  10689. shown above).
  10690. Calc's algebraic simplifications also make use of declarations when
  10691. simplifying equations and inequalities. They will cancel @code{x}
  10692. from both sides of @samp{a x = b x} only if it is sure @code{x}
  10693. is non-zero, say, because it has a @code{pos} declaration.
  10694. To declare specifically that @code{x} is real and non-zero,
  10695. use @samp{[[-inf .. 0), (0 .. inf]]}. (There is no way in the
  10696. current notation to say that @code{x} is nonzero but not necessarily
  10697. real.) The @kbd{a e} command does ``unsafe'' simplifications,
  10698. including canceling @samp{x} from the equation when @samp{x} is
  10699. not known to be nonzero.
  10700. Another set of type symbols distinguish between scalars and vectors.
  10701. @table @code
  10702. @item scalar
  10703. The value is not a vector.
  10704. @item vector
  10705. The value is a vector.
  10706. @item matrix
  10707. The value is a matrix (a rectangular vector of vectors).
  10708. @item sqmatrix
  10709. The value is a square matrix.
  10710. @end table
  10711. These type symbols can be combined with the other type symbols
  10712. described above; @samp{[int, matrix]} describes an object which
  10713. is a matrix of integers.
  10714. Scalar/vector declarations are used to determine whether certain
  10715. algebraic operations are safe. For example, @samp{[a, b, c] + x}
  10716. is normally not simplified to @samp{[a + x, b + x, c + x]}, but
  10717. it will be if @code{x} has been declared @code{scalar}. On the
  10718. other hand, multiplication is usually assumed to be commutative,
  10719. but the terms in @samp{x y} will never be exchanged if both @code{x}
  10720. and @code{y} are known to be vectors or matrices. (Calc currently
  10721. never distinguishes between @code{vector} and @code{matrix}
  10722. declarations.)
  10723. @xref{Matrix Mode}, for a discussion of Matrix mode and
  10724. Scalar mode, which are similar to declaring @samp{[All, matrix]}
  10725. or @samp{[All, scalar]} but much more convenient.
  10726. One more type symbol that is recognized is used with the @kbd{H a d}
  10727. command for taking total derivatives of a formula. @xref{Calculus}.
  10728. @table @code
  10729. @item const
  10730. The value is a constant with respect to other variables.
  10731. @end table
  10732. Calc does not check the declarations for a variable when you store
  10733. a value in it. However, storing @mathit{-3.5} in a variable that has
  10734. been declared @code{pos}, @code{int}, or @code{matrix} may have
  10735. unexpected effects; Calc may evaluate @samp{sqrt(x^2)} to @expr{3.5}
  10736. if it substitutes the value first, or to @expr{-3.5} if @code{x}
  10737. was declared @code{pos} and the formula @samp{sqrt(x^2)} is
  10738. simplified to @samp{x} before the value is substituted. Before
  10739. using a variable for a new purpose, it is best to use @kbd{s d}
  10740. or @kbd{s D} to check to make sure you don't still have an old
  10741. declaration for the variable that will conflict with its new meaning.
  10742. @node Functions for Declarations, , Kinds of Declarations, Declarations
  10743. @subsection Functions for Declarations
  10744. @noindent
  10745. Calc has a set of functions for accessing the current declarations
  10746. in a convenient manner. These functions return 1 if the argument
  10747. can be shown to have the specified property, or 0 if the argument
  10748. can be shown @emph{not} to have that property; otherwise they are
  10749. left unevaluated. These functions are suitable for use with rewrite
  10750. rules (@pxref{Conditional Rewrite Rules}) or programming constructs
  10751. (@pxref{Conditionals in Macros}). They can be entered only using
  10752. algebraic notation. @xref{Logical Operations}, for functions
  10753. that perform other tests not related to declarations.
  10754. For example, @samp{dint(17)} returns 1 because 17 is an integer, as
  10755. do @samp{dint(n)} and @samp{dint(2 n - 3)} if @code{n} has been declared
  10756. @code{int}, but @samp{dint(2.5)} and @samp{dint(n + 0.5)} return 0.
  10757. Calc consults knowledge of its own built-in functions as well as your
  10758. own declarations: @samp{dint(floor(x))} returns 1.
  10759. @ignore
  10760. @starindex
  10761. @end ignore
  10762. @tindex dint
  10763. @ignore
  10764. @starindex
  10765. @end ignore
  10766. @tindex dnumint
  10767. @ignore
  10768. @starindex
  10769. @end ignore
  10770. @tindex dnatnum
  10771. The @code{dint} function checks if its argument is an integer.
  10772. The @code{dnatnum} function checks if its argument is a natural
  10773. number, i.e., a nonnegative integer. The @code{dnumint} function
  10774. checks if its argument is numerically an integer, i.e., either an
  10775. integer or an integer-valued float. Note that these and the other
  10776. data type functions also accept vectors or matrices composed of
  10777. suitable elements, and that real infinities @samp{inf} and @samp{-inf}
  10778. are considered to be integers for the purposes of these functions.
  10779. @ignore
  10780. @starindex
  10781. @end ignore
  10782. @tindex drat
  10783. The @code{drat} function checks if its argument is rational, i.e.,
  10784. an integer or fraction. Infinities count as rational, but intervals
  10785. and error forms do not.
  10786. @ignore
  10787. @starindex
  10788. @end ignore
  10789. @tindex dreal
  10790. The @code{dreal} function checks if its argument is real. This
  10791. includes integers, fractions, floats, real error forms, and intervals.
  10792. @ignore
  10793. @starindex
  10794. @end ignore
  10795. @tindex dimag
  10796. The @code{dimag} function checks if its argument is imaginary,
  10797. i.e., is mathematically equal to a real number times @expr{i}.
  10798. @ignore
  10799. @starindex
  10800. @end ignore
  10801. @tindex dpos
  10802. @ignore
  10803. @starindex
  10804. @end ignore
  10805. @tindex dneg
  10806. @ignore
  10807. @starindex
  10808. @end ignore
  10809. @tindex dnonneg
  10810. The @code{dpos} function checks for positive (but nonzero) reals.
  10811. The @code{dneg} function checks for negative reals. The @code{dnonneg}
  10812. function checks for nonnegative reals, i.e., reals greater than or
  10813. equal to zero. Note that Calc's algebraic simplifications, which are
  10814. effectively applied to all conditions in rewrite rules, can simplify
  10815. an expression like @expr{x > 0} to 1 or 0 using @code{dpos}.
  10816. So the actual functions @code{dpos}, @code{dneg}, and @code{dnonneg}
  10817. are rarely necessary.
  10818. @ignore
  10819. @starindex
  10820. @end ignore
  10821. @tindex dnonzero
  10822. The @code{dnonzero} function checks that its argument is nonzero.
  10823. This includes all nonzero real or complex numbers, all intervals that
  10824. do not include zero, all nonzero modulo forms, vectors all of whose
  10825. elements are nonzero, and variables or formulas whose values can be
  10826. deduced to be nonzero. It does not include error forms, since they
  10827. represent values which could be anything including zero. (This is
  10828. also the set of objects considered ``true'' in conditional contexts.)
  10829. @ignore
  10830. @starindex
  10831. @end ignore
  10832. @tindex deven
  10833. @ignore
  10834. @starindex
  10835. @end ignore
  10836. @tindex dodd
  10837. The @code{deven} function returns 1 if its argument is known to be
  10838. an even integer (or integer-valued float); it returns 0 if its argument
  10839. is known not to be even (because it is known to be odd or a non-integer).
  10840. Calc's algebraic simplifications use this to simplify a test of the form
  10841. @samp{x % 2 = 0}. There is also an analogous @code{dodd} function.
  10842. @ignore
  10843. @starindex
  10844. @end ignore
  10845. @tindex drange
  10846. The @code{drange} function returns a set (an interval or a vector
  10847. of intervals and/or numbers; @pxref{Set Operations}) that describes
  10848. the set of possible values of its argument. If the argument is
  10849. a variable or a function with a declaration, the range is copied
  10850. from the declaration. Otherwise, the possible signs of the
  10851. expression are determined using a method similar to @code{dpos},
  10852. etc., and a suitable set like @samp{[0 .. inf]} is returned. If
  10853. the expression is not provably real, the @code{drange} function
  10854. remains unevaluated.
  10855. @ignore
  10856. @starindex
  10857. @end ignore
  10858. @tindex dscalar
  10859. The @code{dscalar} function returns 1 if its argument is provably
  10860. scalar, or 0 if its argument is provably non-scalar. It is left
  10861. unevaluated if this cannot be determined. (If Matrix mode or Scalar
  10862. mode is in effect, this function returns 1 or 0, respectively,
  10863. if it has no other information.) When Calc interprets a condition
  10864. (say, in a rewrite rule) it considers an unevaluated formula to be
  10865. ``false.'' Thus, @samp{dscalar(a)} is ``true'' only if @code{a} is
  10866. provably scalar, and @samp{!dscalar(a)} is ``true'' only if @code{a}
  10867. is provably non-scalar; both are ``false'' if there is insufficient
  10868. information to tell.
  10869. @node Display Modes, Language Modes, Declarations, Mode Settings
  10870. @section Display Modes
  10871. @noindent
  10872. The commands in this section are two-key sequences beginning with the
  10873. @kbd{d} prefix. The @kbd{d l} (@code{calc-line-numbering}) and @kbd{d b}
  10874. (@code{calc-line-breaking}) commands are described elsewhere;
  10875. @pxref{Stack Basics} and @pxref{Normal Language Modes}, respectively.
  10876. Display formats for vectors and matrices are also covered elsewhere;
  10877. @pxref{Vector and Matrix Formats}.
  10878. One thing all display modes have in common is their treatment of the
  10879. @kbd{H} prefix. This prefix causes any mode command that would normally
  10880. refresh the stack to leave the stack display alone. The word ``Dirty''
  10881. will appear in the mode line when Calc thinks the stack display may not
  10882. reflect the latest mode settings.
  10883. @kindex d @key{RET}
  10884. @pindex calc-refresh-top
  10885. The @kbd{d @key{RET}} (@code{calc-refresh-top}) command reformats the
  10886. top stack entry according to all the current modes. Positive prefix
  10887. arguments reformat the top @var{n} entries; negative prefix arguments
  10888. reformat the specified entry, and a prefix of zero is equivalent to
  10889. @kbd{d @key{SPC}} (@code{calc-refresh}), which reformats the entire stack.
  10890. For example, @kbd{H d s M-2 d @key{RET}} changes to scientific notation
  10891. but reformats only the top two stack entries in the new mode.
  10892. The @kbd{I} prefix has another effect on the display modes. The mode
  10893. is set only temporarily; the top stack entry is reformatted according
  10894. to that mode, then the original mode setting is restored. In other
  10895. words, @kbd{I d s} is equivalent to @kbd{H d s d @key{RET} H d (@var{old mode})}.
  10896. @menu
  10897. * Radix Modes::
  10898. * Grouping Digits::
  10899. * Float Formats::
  10900. * Complex Formats::
  10901. * Fraction Formats::
  10902. * HMS Formats::
  10903. * Date Formats::
  10904. * Truncating the Stack::
  10905. * Justification::
  10906. * Labels::
  10907. @end menu
  10908. @node Radix Modes, Grouping Digits, Display Modes, Display Modes
  10909. @subsection Radix Modes
  10910. @noindent
  10911. @cindex Radix display
  10912. @cindex Non-decimal numbers
  10913. @cindex Decimal and non-decimal numbers
  10914. Calc normally displays numbers in decimal (@dfn{base-10} or @dfn{radix-10})
  10915. notation. Calc can actually display in any radix from two (binary) to 36.
  10916. When the radix is above 10, the letters @code{A} to @code{Z} are used as
  10917. digits. When entering such a number, letter keys are interpreted as
  10918. potential digits rather than terminating numeric entry mode.
  10919. @kindex d 2
  10920. @kindex d 8
  10921. @kindex d 6
  10922. @kindex d 0
  10923. @cindex Hexadecimal integers
  10924. @cindex Octal integers
  10925. The key sequences @kbd{d 2}, @kbd{d 8}, @kbd{d 6}, and @kbd{d 0} select
  10926. binary, octal, hexadecimal, and decimal as the current display radix,
  10927. respectively. Numbers can always be entered in any radix, though the
  10928. current radix is used as a default if you press @kbd{#} without any initial
  10929. digits. A number entered without a @kbd{#} is @emph{always} interpreted
  10930. as decimal.
  10931. @kindex d r
  10932. @pindex calc-radix
  10933. To set the radix generally, use @kbd{d r} (@code{calc-radix}) and enter
  10934. an integer from 2 to 36. You can specify the radix as a numeric prefix
  10935. argument; otherwise you will be prompted for it.
  10936. @kindex d z
  10937. @pindex calc-leading-zeros
  10938. @cindex Leading zeros
  10939. Integers normally are displayed with however many digits are necessary to
  10940. represent the integer and no more. The @kbd{d z} (@code{calc-leading-zeros})
  10941. command causes integers to be padded out with leading zeros according to the
  10942. current binary word size. (@xref{Binary Functions}, for a discussion of
  10943. word size.) If the absolute value of the word size is @expr{w}, all integers
  10944. are displayed with at least enough digits to represent
  10945. @texline @math{2^w-1}
  10946. @infoline @expr{(2^w)-1}
  10947. in the current radix. (Larger integers will still be displayed in their
  10948. entirety.)
  10949. @cindex Two's complements
  10950. Calc can display @expr{w}-bit integers using two's complement
  10951. notation, although this is most useful with the binary, octal and
  10952. hexadecimal display modes. This option is selected by using the
  10953. @kbd{O} option prefix before setting the display radix, and a negative word
  10954. size might be appropriate (@pxref{Binary Functions}). In two's
  10955. complement notation, the integers in the (nearly) symmetric interval
  10956. from
  10957. @texline @math{-2^{w-1}}
  10958. @infoline @expr{-2^(w-1)}
  10959. to
  10960. @texline @math{2^{w-1}-1}
  10961. @infoline @expr{2^(w-1)-1}
  10962. are represented by the integers from @expr{0} to @expr{2^w-1}:
  10963. the integers from @expr{0} to
  10964. @texline @math{2^{w-1}-1}
  10965. @infoline @expr{2^(w-1)-1}
  10966. are represented by themselves and the integers from
  10967. @texline @math{-2^{w-1}}
  10968. @infoline @expr{-2^(w-1)}
  10969. to @expr{-1} are represented by the integers from
  10970. @texline @math{2^{w-1}}
  10971. @infoline @expr{2^(w-1)}
  10972. to @expr{2^w-1} (the integer @expr{k} is represented by @expr{k+2^w}).
  10973. Calc will display a two's complement integer by the radix (either
  10974. @expr{2}, @expr{8} or @expr{16}), two @kbd{#} symbols, and then its
  10975. representation (including any leading zeros necessary to include all
  10976. @expr{w} bits). In a two's complement display mode, numbers that
  10977. are not displayed in two's complement notation (i.e., that aren't
  10978. integers from
  10979. @texline @math{-2^{w-1}}
  10980. @infoline @expr{-2^(w-1)}
  10981. to
  10982. @c (
  10983. @texline @math{2^{w-1}-1})
  10984. @infoline @expr{2^(w-1)-1})
  10985. will be represented using Calc's usual notation (in the appropriate
  10986. radix).
  10987. @node Grouping Digits, Float Formats, Radix Modes, Display Modes
  10988. @subsection Grouping Digits
  10989. @noindent
  10990. @kindex d g
  10991. @pindex calc-group-digits
  10992. @cindex Grouping digits
  10993. @cindex Digit grouping
  10994. Long numbers can be hard to read if they have too many digits. For
  10995. example, the factorial of 30 is 33 digits long! Press @kbd{d g}
  10996. (@code{calc-group-digits}) to enable @dfn{Grouping} mode, in which digits
  10997. are displayed in clumps of 3 or 4 (depending on the current radix)
  10998. separated by commas.
  10999. The @kbd{d g} command toggles grouping on and off.
  11000. With a numeric prefix of 0, this command displays the current state of
  11001. the grouping flag; with an argument of minus one it disables grouping;
  11002. with a positive argument @expr{N} it enables grouping on every @expr{N}
  11003. digits. For floating-point numbers, grouping normally occurs only
  11004. before the decimal point. A negative prefix argument @expr{-N} enables
  11005. grouping every @expr{N} digits both before and after the decimal point.
  11006. @kindex d ,
  11007. @pindex calc-group-char
  11008. The @kbd{d ,} (@code{calc-group-char}) command allows you to choose any
  11009. character as the grouping separator. The default is the comma character.
  11010. If you find it difficult to read vectors of large integers grouped with
  11011. commas, you may wish to use spaces or some other character instead.
  11012. This command takes the next character you type, whatever it is, and
  11013. uses it as the digit separator. As a special case, @kbd{d , \} selects
  11014. @samp{\,} (@TeX{}'s thin-space symbol) as the digit separator.
  11015. Please note that grouped numbers will not generally be parsed correctly
  11016. if re-read in textual form, say by the use of @kbd{C-x * y} and @kbd{C-x * g}.
  11017. (@xref{Kill and Yank}, for details on these commands.) One exception is
  11018. the @samp{\,} separator, which doesn't interfere with parsing because it
  11019. is ignored by @TeX{} language mode.
  11020. @node Float Formats, Complex Formats, Grouping Digits, Display Modes
  11021. @subsection Float Formats
  11022. @noindent
  11023. Floating-point quantities are normally displayed in standard decimal
  11024. form, with scientific notation used if the exponent is especially high
  11025. or low. All significant digits are normally displayed. The commands
  11026. in this section allow you to choose among several alternative display
  11027. formats for floats.
  11028. @kindex d n
  11029. @pindex calc-normal-notation
  11030. The @kbd{d n} (@code{calc-normal-notation}) command selects the normal
  11031. display format. All significant figures in a number are displayed.
  11032. With a positive numeric prefix, numbers are rounded if necessary to
  11033. that number of significant digits. With a negative numerix prefix,
  11034. the specified number of significant digits less than the current
  11035. precision is used. (Thus @kbd{C-u -2 d n} displays 10 digits if the
  11036. current precision is 12.)
  11037. @kindex d f
  11038. @pindex calc-fix-notation
  11039. The @kbd{d f} (@code{calc-fix-notation}) command selects fixed-point
  11040. notation. The numeric argument is the number of digits after the
  11041. decimal point, zero or more. This format will relax into scientific
  11042. notation if a nonzero number would otherwise have been rounded all the
  11043. way to zero. Specifying a negative number of digits is the same as
  11044. for a positive number, except that small nonzero numbers will be rounded
  11045. to zero rather than switching to scientific notation.
  11046. @kindex d s
  11047. @pindex calc-sci-notation
  11048. @cindex Scientific notation, display of
  11049. The @kbd{d s} (@code{calc-sci-notation}) command selects scientific
  11050. notation. A positive argument sets the number of significant figures
  11051. displayed, of which one will be before and the rest after the decimal
  11052. point. A negative argument works the same as for @kbd{d n} format.
  11053. The default is to display all significant digits.
  11054. @kindex d e
  11055. @pindex calc-eng-notation
  11056. @cindex Engineering notation, display of
  11057. The @kbd{d e} (@code{calc-eng-notation}) command selects engineering
  11058. notation. This is similar to scientific notation except that the
  11059. exponent is rounded down to a multiple of three, with from one to three
  11060. digits before the decimal point. An optional numeric prefix sets the
  11061. number of significant digits to display, as for @kbd{d s}.
  11062. It is important to distinguish between the current @emph{precision} and
  11063. the current @emph{display format}. After the commands @kbd{C-u 10 p}
  11064. and @kbd{C-u 6 d n} the Calculator computes all results to ten
  11065. significant figures but displays only six. (In fact, intermediate
  11066. calculations are often carried to one or two more significant figures,
  11067. but values placed on the stack will be rounded down to ten figures.)
  11068. Numbers are never actually rounded to the display precision for storage,
  11069. except by commands like @kbd{C-k} and @kbd{C-x * y} which operate on the
  11070. actual displayed text in the Calculator buffer.
  11071. @kindex d .
  11072. @pindex calc-point-char
  11073. The @kbd{d .} (@code{calc-point-char}) command selects the character used
  11074. as a decimal point. Normally this is a period; users in some countries
  11075. may wish to change this to a comma. Note that this is only a display
  11076. style; on entry, periods must always be used to denote floating-point
  11077. numbers, and commas to separate elements in a list.
  11078. @node Complex Formats, Fraction Formats, Float Formats, Display Modes
  11079. @subsection Complex Formats
  11080. @noindent
  11081. @kindex d c
  11082. @pindex calc-complex-notation
  11083. There are three supported notations for complex numbers in rectangular
  11084. form. The default is as a pair of real numbers enclosed in parentheses
  11085. and separated by a comma: @samp{(a,b)}. The @kbd{d c}
  11086. (@code{calc-complex-notation}) command selects this style.
  11087. @kindex d i
  11088. @pindex calc-i-notation
  11089. @kindex d j
  11090. @pindex calc-j-notation
  11091. The other notations are @kbd{d i} (@code{calc-i-notation}), in which
  11092. numbers are displayed in @samp{a+bi} form, and @kbd{d j}
  11093. (@code{calc-j-notation}) which displays the form @samp{a+bj} preferred
  11094. in some disciplines.
  11095. @cindex @code{i} variable
  11096. @vindex i
  11097. Complex numbers are normally entered in @samp{(a,b)} format.
  11098. If you enter @samp{2+3i} as an algebraic formula, it will be stored as
  11099. the formula @samp{2 + 3 * i}. However, if you use @kbd{=} to evaluate
  11100. this formula and you have not changed the variable @samp{i}, the @samp{i}
  11101. will be interpreted as @samp{(0,1)} and the formula will be simplified
  11102. to @samp{(2,3)}. Other commands (like @code{calc-sin}) will @emph{not}
  11103. interpret the formula @samp{2 + 3 * i} as a complex number.
  11104. @xref{Variables}, under ``special constants.''
  11105. @node Fraction Formats, HMS Formats, Complex Formats, Display Modes
  11106. @subsection Fraction Formats
  11107. @noindent
  11108. @kindex d o
  11109. @pindex calc-over-notation
  11110. Display of fractional numbers is controlled by the @kbd{d o}
  11111. (@code{calc-over-notation}) command. By default, a number like
  11112. eight thirds is displayed in the form @samp{8:3}. The @kbd{d o} command
  11113. prompts for a one- or two-character format. If you give one character,
  11114. that character is used as the fraction separator. Common separators are
  11115. @samp{:} and @samp{/}. (During input of numbers, the @kbd{:} key must be
  11116. used regardless of the display format; in particular, the @kbd{/} is used
  11117. for RPN-style division, @emph{not} for entering fractions.)
  11118. If you give two characters, fractions use ``integer-plus-fractional-part''
  11119. notation. For example, the format @samp{+/} would display eight thirds
  11120. as @samp{2+2/3}. If two colons are present in a number being entered,
  11121. the number is interpreted in this form (so that the entries @kbd{2:2:3}
  11122. and @kbd{8:3} are equivalent).
  11123. It is also possible to follow the one- or two-character format with
  11124. a number. For example: @samp{:10} or @samp{+/3}. In this case,
  11125. Calc adjusts all fractions that are displayed to have the specified
  11126. denominator, if possible. Otherwise it adjusts the denominator to
  11127. be a multiple of the specified value. For example, in @samp{:6} mode
  11128. the fraction @expr{1:6} will be unaffected, but @expr{2:3} will be
  11129. displayed as @expr{4:6}, @expr{1:2} will be displayed as @expr{3:6},
  11130. and @expr{1:8} will be displayed as @expr{3:24}. Integers are also
  11131. affected by this mode: 3 is displayed as @expr{18:6}. Note that the
  11132. format @samp{:1} writes fractions the same as @samp{:}, but it writes
  11133. integers as @expr{n:1}.
  11134. The fraction format does not affect the way fractions or integers are
  11135. stored, only the way they appear on the screen. The fraction format
  11136. never affects floats.
  11137. @node HMS Formats, Date Formats, Fraction Formats, Display Modes
  11138. @subsection HMS Formats
  11139. @noindent
  11140. @kindex d h
  11141. @pindex calc-hms-notation
  11142. The @kbd{d h} (@code{calc-hms-notation}) command controls the display of
  11143. HMS (hours-minutes-seconds) forms. It prompts for a string which
  11144. consists basically of an ``hours'' marker, optional punctuation, a
  11145. ``minutes'' marker, more optional punctuation, and a ``seconds'' marker.
  11146. Punctuation is zero or more spaces, commas, or semicolons. The hours
  11147. marker is one or more non-punctuation characters. The minutes and
  11148. seconds markers must be single non-punctuation characters.
  11149. The default HMS format is @samp{@@ ' "}, producing HMS values of the form
  11150. @samp{23@@ 30' 15.75"}. The format @samp{deg, ms} would display this same
  11151. value as @samp{23deg, 30m15.75s}. During numeric entry, the @kbd{h} or @kbd{o}
  11152. keys are recognized as synonyms for @kbd{@@} regardless of display format.
  11153. The @kbd{m} and @kbd{s} keys are recognized as synonyms for @kbd{'} and
  11154. @kbd{"}, respectively, but only if an @kbd{@@} (or @kbd{h} or @kbd{o}) has
  11155. already been typed; otherwise, they have their usual meanings
  11156. (@kbd{m-} prefix and @kbd{s-} prefix). Thus, @kbd{5 "}, @kbd{0 @@ 5 "}, and
  11157. @kbd{0 h 5 s} are some of the ways to enter the quantity ``five seconds.''
  11158. The @kbd{'} key is recognized as ``minutes'' only if @kbd{@@} (or @kbd{h} or
  11159. @kbd{o}) has already been pressed; otherwise it means to switch to algebraic
  11160. entry.
  11161. @node Date Formats, Truncating the Stack, HMS Formats, Display Modes
  11162. @subsection Date Formats
  11163. @noindent
  11164. @kindex d d
  11165. @pindex calc-date-notation
  11166. The @kbd{d d} (@code{calc-date-notation}) command controls the display
  11167. of date forms (@pxref{Date Forms}). It prompts for a string which
  11168. contains letters that represent the various parts of a date and time.
  11169. To show which parts should be omitted when the form represents a pure
  11170. date with no time, parts of the string can be enclosed in @samp{< >}
  11171. marks. If you don't include @samp{< >} markers in the format, Calc
  11172. guesses at which parts, if any, should be omitted when formatting
  11173. pure dates.
  11174. The default format is: @samp{<H:mm:SSpp >Www Mmm D, YYYY}.
  11175. An example string in this format is @samp{3:32pm Wed Jan 9, 1991}.
  11176. If you enter a blank format string, this default format is
  11177. reestablished.
  11178. Calc uses @samp{< >} notation for nameless functions as well as for
  11179. dates. @xref{Specifying Operators}. To avoid confusion with nameless
  11180. functions, your date formats should avoid using the @samp{#} character.
  11181. @menu
  11182. * ISO 8601::
  11183. * Date Formatting Codes::
  11184. * Free-Form Dates::
  11185. * Standard Date Formats::
  11186. @end menu
  11187. @node ISO 8601, Date Formatting Codes, Date Formats, Date Formats
  11188. @subsubsection ISO 8601
  11189. @noindent
  11190. @cindex ISO 8601
  11191. The same date can be written down in different formats and Calc tries
  11192. to allow you to choose your preferred format. Some common formats are
  11193. ambiguous, however; for example, 10/11/2012 means October 11,
  11194. 2012 in the United States but it means November 10, 2012 in
  11195. Europe. To help avoid such ambiguities, the International Organization
  11196. for Standardization (ISO) provides the ISO 8601 standard, which
  11197. provides three different but easily distinguishable and unambiguous
  11198. ways to represent a date.
  11199. The ISO 8601 calendar date representation is
  11200. @example
  11201. @var{YYYY}-@var{MM}-@var{DD}
  11202. @end example
  11203. @noindent
  11204. where @var{YYYY} is the four digit year, @var{MM} is the two-digit month
  11205. number (01 for January to 12 for December), and @var{DD} is the
  11206. two-digit day of the month (01 to 31). (Note that @var{YYYY} does not
  11207. correspond to Calc's date formatting code, which will be introduced
  11208. later.) The year, which should be padded with zeros to ensure it has at
  11209. least four digits, is the Gregorian year, except that the year before
  11210. 0001 (1 AD) is the year 0000 (1 BC). The date October 11, 2012 is
  11211. written 2012-10-11 in this representation and November 10, 2012 is
  11212. written 2012-11-10.
  11213. The ISO 8601 ordinal date representation is
  11214. @example
  11215. @var{YYYY}-@var{DDD}
  11216. @end example
  11217. @noindent
  11218. where @var{YYYY} is the year, as above, and @var{DDD} is the day of the year.
  11219. The date December 31, 2011 is written 2011-365 in this representation
  11220. and January 1, 2012 is written 2012-001.
  11221. The ISO 8601 week date representation is
  11222. @example
  11223. @var{YYYY}-W@var{ww}-@var{D}
  11224. @end example
  11225. @noindent
  11226. where @var{YYYY} is the ISO week-numbering year, @var{ww} is the two
  11227. digit week number (preceded by a literal ``W''), and @var{D} is the day
  11228. of the week (1 for Monday through 7 for Sunday). The ISO week-numbering
  11229. year is based on the Gregorian year but can differ slightly. The first
  11230. week of an ISO week-numbering year is the week with the Gregorian year's
  11231. first Thursday in it (equivalently, the week containing January 4);
  11232. any day of that week (Monday through Sunday) is part of the same ISO
  11233. week-numbering year, any day from the previous week is part of the
  11234. previous year. For example, January 4, 2013 is on a Friday, and so
  11235. the first week for the ISO week-numbering year 2013 starts on
  11236. Monday, December 31, 2012. The day December 31, 2012 is then part of the
  11237. Gregorian year 2012 but ISO week-numbering year 2013. In the week
  11238. date representation, this week goes from 2013-W01-1 (December 31,
  11239. 2012) to 2013-W01-7 (January 6, 2013).
  11240. All three ISO 8601 representations arrange the numbers from most
  11241. significant to least significant; as well as being unambiguous
  11242. representations, they are easy to sort since chronological order in
  11243. this formats corresponds to lexicographical order. The hyphens are
  11244. sometimes omitted.
  11245. The ISO 8601 standard uses a 24 hour clock; a particular time is
  11246. represented by @var{hh}:@var{mm}:@var{ss} where @var{hh} is the
  11247. two-digit hour (from 00 to 24), @var{mm} is the two-digit minute (from
  11248. 00 to 59) and @var{ss} is the two-digit second. The seconds or minutes
  11249. and seconds can be omitted, and decimals can be added. If a date with a
  11250. time is represented, they should be separated by a literal ``T'', so noon
  11251. on December 13, 2012 can be represented as 2012-12-13T12:00.
  11252. @node Date Formatting Codes, Free-Form Dates, ISO 8601, Date Formats
  11253. @subsubsection Date Formatting Codes
  11254. @noindent
  11255. When displaying a date, the current date format is used. All
  11256. characters except for letters and @samp{<} and @samp{>} are
  11257. copied literally when dates are formatted. The portion between
  11258. @samp{< >} markers is omitted for pure dates, or included for
  11259. date/time forms. Letters are interpreted according to the table
  11260. below.
  11261. When dates are read in during algebraic entry, Calc first tries to
  11262. match the input string to the current format either with or without
  11263. the time part. The punctuation characters (including spaces) must
  11264. match exactly; letter fields must correspond to suitable text in
  11265. the input. If this doesn't work, Calc checks if the input is a
  11266. simple number; if so, the number is interpreted as a number of days
  11267. since Dec 31, 1 BC@. Otherwise, Calc tries a much more relaxed and
  11268. flexible algorithm which is described in the next section.
  11269. Weekday names are ignored during reading.
  11270. Two-digit year numbers are interpreted as lying in the range
  11271. from 1941 to 2039. Years outside that range are always
  11272. entered and displayed in full. Year numbers with a leading
  11273. @samp{+} sign are always interpreted exactly, allowing the
  11274. entry and display of the years 1 through 99 AD.
  11275. Here is a complete list of the formatting codes for dates:
  11276. @table @asis
  11277. @item Y
  11278. Year: ``91'' for 1991, ``7'' for 2007, ``+23'' for 23 AD.
  11279. @item YY
  11280. Year: ``91'' for 1991, ``07'' for 2007, ``+23'' for 23 AD.
  11281. @item BY
  11282. Year: ``91'' for 1991, `` 7'' for 2007, ``+23'' for 23 AD.
  11283. @item YYY
  11284. Year: ``1991'' for 1991, ``23'' for 23 AD.
  11285. @item YYYY
  11286. Year: ``1991'' for 1991, ``+23'' for 23 AD.
  11287. @item ZYYY
  11288. Year: ``1991'' for 1991, ``0023'' for 23 AD, ``0000'' for 1 BC.
  11289. @item IYYY
  11290. Year: ISO 8601 week-numbering year.
  11291. @item aa
  11292. Year: ``ad'' or blank.
  11293. @item AA
  11294. Year: ``AD'' or blank.
  11295. @item aaa
  11296. Year: ``ad '' or blank. (Note trailing space.)
  11297. @item AAA
  11298. Year: ``AD '' or blank.
  11299. @item aaaa
  11300. Year: ``a.d.@:'' or blank.
  11301. @item AAAA
  11302. Year: ``A.D.'' or blank.
  11303. @item bb
  11304. Year: ``bc'' or blank.
  11305. @item BB
  11306. Year: ``BC'' or blank.
  11307. @item bbb
  11308. Year: `` bc'' or blank. (Note leading space.)
  11309. @item BBB
  11310. Year: `` BC'' or blank.
  11311. @item bbbb
  11312. Year: ``b.c.@:'' or blank.
  11313. @item BBBB
  11314. Year: ``B.C.'' or blank.
  11315. @item M
  11316. Month: ``8'' for August.
  11317. @item MM
  11318. Month: ``08'' for August.
  11319. @item BM
  11320. Month: `` 8'' for August.
  11321. @item MMM
  11322. Month: ``AUG'' for August.
  11323. @item Mmm
  11324. Month: ``Aug'' for August.
  11325. @item mmm
  11326. Month: ``aug'' for August.
  11327. @item MMMM
  11328. Month: ``AUGUST'' for August.
  11329. @item Mmmm
  11330. Month: ``August'' for August.
  11331. @item D
  11332. Day: ``7'' for 7th day of month.
  11333. @item DD
  11334. Day: ``07'' for 7th day of month.
  11335. @item BD
  11336. Day: `` 7'' for 7th day of month.
  11337. @item W
  11338. Weekday: ``0'' for Sunday, ``6'' for Saturday.
  11339. @item w
  11340. Weekday: ``1'' for Monday, ``7'' for Sunday.
  11341. @item WWW
  11342. Weekday: ``SUN'' for Sunday.
  11343. @item Www
  11344. Weekday: ``Sun'' for Sunday.
  11345. @item www
  11346. Weekday: ``sun'' for Sunday.
  11347. @item WWWW
  11348. Weekday: ``SUNDAY'' for Sunday.
  11349. @item Wwww
  11350. Weekday: ``Sunday'' for Sunday.
  11351. @item Iww
  11352. Week number: ISO 8601 week number, ``W01'' for week 1.
  11353. @item d
  11354. Day of year: ``34'' for Feb.@: 3.
  11355. @item ddd
  11356. Day of year: ``034'' for Feb.@: 3.
  11357. @item bdd
  11358. Day of year: `` 34'' for Feb.@: 3.
  11359. @item T
  11360. Letter: Literal ``T''.
  11361. @item h
  11362. Hour: ``5'' for 5 AM; ``17'' for 5 PM.
  11363. @item hh
  11364. Hour: ``05'' for 5 AM; ``17'' for 5 PM.
  11365. @item bh
  11366. Hour: `` 5'' for 5 AM; ``17'' for 5 PM.
  11367. @item H
  11368. Hour: ``5'' for 5 AM and 5 PM.
  11369. @item HH
  11370. Hour: ``05'' for 5 AM and 5 PM.
  11371. @item BH
  11372. Hour: `` 5'' for 5 AM and 5 PM.
  11373. @item p
  11374. AM/PM: ``a'' or ``p''.
  11375. @item P
  11376. AM/PM: ``A'' or ``P''.
  11377. @item pp
  11378. AM/PM: ``am'' or ``pm''.
  11379. @item PP
  11380. AM/PM: ``AM'' or ``PM''.
  11381. @item pppp
  11382. AM/PM: ``a.m.@:'' or ``p.m.''.
  11383. @item PPPP
  11384. AM/PM: ``A.M.'' or ``P.M.''.
  11385. @item m
  11386. Minutes: ``7'' for 7.
  11387. @item mm
  11388. Minutes: ``07'' for 7.
  11389. @item bm
  11390. Minutes: `` 7'' for 7.
  11391. @item s
  11392. Seconds: ``7'' for 7; ``7.23'' for 7.23.
  11393. @item ss
  11394. Seconds: ``07'' for 7; ``07.23'' for 7.23.
  11395. @item bs
  11396. Seconds: `` 7'' for 7; `` 7.23'' for 7.23.
  11397. @item SS
  11398. Optional seconds: ``07'' for 7; blank for 0.
  11399. @item BS
  11400. Optional seconds: `` 7'' for 7; blank for 0.
  11401. @item N
  11402. Numeric date/time: ``726842.25'' for 6:00am Wed Jan 9, 1991.
  11403. @item n
  11404. Numeric date: ``726842'' for any time on Wed Jan 9, 1991.
  11405. @item J
  11406. Julian date/time: ``2448265.75'' for 6:00am Wed Jan 9, 1991.
  11407. @item j
  11408. Julian date: ``2448266'' for any time on Wed Jan 9, 1991.
  11409. @item U
  11410. Unix time: ``663400800'' for 6:00am Wed Jan 9, 1991.
  11411. @item X
  11412. Brackets suppression. An ``X'' at the front of the format
  11413. causes the surrounding @w{@samp{< >}} delimiters to be omitted
  11414. when formatting dates. Note that the brackets are still
  11415. required for algebraic entry.
  11416. @end table
  11417. If ``SS'' or ``BS'' (optional seconds) is preceded by a colon, the
  11418. colon is also omitted if the seconds part is zero.
  11419. If ``bb,'' ``bbb'' or ``bbbb'' or their upper-case equivalents
  11420. appear in the format, then negative year numbers are displayed
  11421. without a minus sign. Note that ``aa'' and ``bb'' are mutually
  11422. exclusive. Some typical usages would be @samp{YYYY AABB};
  11423. @samp{AAAYYYYBBB}; @samp{YYYYBBB}.
  11424. The formats ``YY,'' ``YYYY,'' ``MM,'' ``DD,'' ``ddd,'' ``hh,'' ``HH,''
  11425. ``mm,'' ``ss,'' and ``SS'' actually match any number of digits during
  11426. reading unless several of these codes are strung together with no
  11427. punctuation in between, in which case the input must have exactly as
  11428. many digits as there are letters in the format.
  11429. The ``j,'' ``J,'' and ``U'' formats do not make any time zone
  11430. adjustment. They effectively use @samp{julian(x,0)} and
  11431. @samp{unixtime(x,0)} to make the conversion; @pxref{Date Arithmetic}.
  11432. @node Free-Form Dates, Standard Date Formats, Date Formatting Codes, Date Formats
  11433. @subsubsection Free-Form Dates
  11434. @noindent
  11435. When reading a date form during algebraic entry, Calc falls back
  11436. on the algorithm described here if the input does not exactly
  11437. match the current date format. This algorithm generally
  11438. ``does the right thing'' and you don't have to worry about it,
  11439. but it is described here in full detail for the curious.
  11440. Calc does not distinguish between upper- and lower-case letters
  11441. while interpreting dates.
  11442. First, the time portion, if present, is located somewhere in the
  11443. text and then removed. The remaining text is then interpreted as
  11444. the date.
  11445. A time is of the form @samp{hh:mm:ss}, possibly with the seconds
  11446. part omitted and possibly with an AM/PM indicator added to indicate
  11447. 12-hour time. If the AM/PM is present, the minutes may also be
  11448. omitted. The AM/PM part may be any of the words @samp{am},
  11449. @samp{pm}, @samp{noon}, or @samp{midnight}; each of these may be
  11450. abbreviated to one letter, and the alternate forms @samp{a.m.},
  11451. @samp{p.m.}, and @samp{mid} are also understood. Obviously
  11452. @samp{noon} and @samp{midnight} are allowed only on 12:00:00.
  11453. The words @samp{noon}, @samp{mid}, and @samp{midnight} are also
  11454. recognized with no number attached. Midnight will represent the
  11455. beginning of a day.
  11456. If there is no AM/PM indicator, the time is interpreted in 24-hour
  11457. format.
  11458. When reading the date portion, Calc first checks to see if it is an
  11459. ISO 8601 week-numbering date; if the string contains an integer
  11460. representing the year, a ``W'' followed by two digits for the week
  11461. number, and an integer from 1 to 7 representing the weekday (in that
  11462. order), then all other characters are ignored and this information
  11463. determines the date. Otherwise, all words and numbers are isolated
  11464. from the string; other characters are ignored. All words must be
  11465. either month names or day-of-week names (the latter of which are
  11466. ignored). Names can be written in full or as three-letter
  11467. abbreviations.
  11468. Large numbers, or numbers with @samp{+} or @samp{-} signs,
  11469. are interpreted as years. If one of the other numbers is
  11470. greater than 12, then that must be the day and the remaining
  11471. number in the input is therefore the month. Otherwise, Calc
  11472. assumes the month, day and year are in the same order that they
  11473. appear in the current date format. If the year is omitted, the
  11474. current year is taken from the system clock.
  11475. If there are too many or too few numbers, or any unrecognizable
  11476. words, then the input is rejected.
  11477. If there are any large numbers (of five digits or more) other than
  11478. the year, they are ignored on the assumption that they are something
  11479. like Julian dates that were included along with the traditional
  11480. date components when the date was formatted.
  11481. One of the words @samp{ad}, @samp{a.d.}, @samp{bc}, or @samp{b.c.}
  11482. may optionally be used; the latter two are equivalent to a
  11483. minus sign on the year value.
  11484. If you always enter a four-digit year, and use a name instead
  11485. of a number for the month, there is no danger of ambiguity.
  11486. @node Standard Date Formats, , Free-Form Dates, Date Formats
  11487. @subsubsection Standard Date Formats
  11488. @noindent
  11489. There are actually ten standard date formats, numbered 0 through 9.
  11490. Entering a blank line at the @kbd{d d} command's prompt gives
  11491. you format number 1, Calc's usual format. You can enter any digit
  11492. to select the other formats.
  11493. To create your own standard date formats, give a numeric prefix
  11494. argument from 0 to 9 to the @w{@kbd{d d}} command. The format you
  11495. enter will be recorded as the new standard format of that
  11496. number, as well as becoming the new current date format.
  11497. You can save your formats permanently with the @w{@kbd{m m}}
  11498. command (@pxref{Mode Settings}).
  11499. @table @asis
  11500. @item 0
  11501. @samp{N} (Numerical format)
  11502. @item 1
  11503. @samp{<H:mm:SSpp >Www Mmm D, YYYY} (American format)
  11504. @item 2
  11505. @samp{D Mmm YYYY<, h:mm:SS>} (European format)
  11506. @item 3
  11507. @samp{Www Mmm BD< hh:mm:ss> YYYY} (Unix written date format)
  11508. @item 4
  11509. @samp{M/D/Y< H:mm:SSpp>} (American slashed format)
  11510. @item 5
  11511. @samp{D.M.Y< h:mm:SS>} (European dotted format)
  11512. @item 6
  11513. @samp{M-D-Y< H:mm:SSpp>} (American dashed format)
  11514. @item 7
  11515. @samp{D-M-Y< h:mm:SS>} (European dashed format)
  11516. @item 8
  11517. @samp{j<, h:mm:ss>} (Julian day plus time)
  11518. @item 9
  11519. @samp{YYddd< hh:mm:ss>} (Year-day format)
  11520. @item 10
  11521. @samp{ZYYY-MM-DD Www< hh:mm>} (Org mode format)
  11522. @item 11
  11523. @samp{IYYY-Iww-w<Thh:mm:ss>} (ISO 8601 week numbering format)
  11524. @end table
  11525. @node Truncating the Stack, Justification, Date Formats, Display Modes
  11526. @subsection Truncating the Stack
  11527. @noindent
  11528. @kindex d t
  11529. @pindex calc-truncate-stack
  11530. @cindex Truncating the stack
  11531. @cindex Narrowing the stack
  11532. The @kbd{d t} (@code{calc-truncate-stack}) command moves the @samp{.}@:
  11533. line that marks the top-of-stack up or down in the Calculator buffer.
  11534. The number right above that line is considered to the be at the top of
  11535. the stack. Any numbers below that line are ``hidden'' from all stack
  11536. operations (although still visible to the user). This is similar to the
  11537. Emacs ``narrowing'' feature, except that the values below the @samp{.}
  11538. are @emph{visible}, just temporarily frozen. This feature allows you to
  11539. keep several independent calculations running at once in different parts
  11540. of the stack, or to apply a certain command to an element buried deep in
  11541. the stack.
  11542. Pressing @kbd{d t} by itself moves the @samp{.} to the line the cursor
  11543. is on. Thus, this line and all those below it become hidden. To un-hide
  11544. these lines, move down to the end of the buffer and press @w{@kbd{d t}}.
  11545. With a positive numeric prefix argument @expr{n}, @kbd{d t} hides the
  11546. bottom @expr{n} values in the buffer. With a negative argument, it hides
  11547. all but the top @expr{n} values. With an argument of zero, it hides zero
  11548. values, i.e., moves the @samp{.} all the way down to the bottom.
  11549. @kindex d [
  11550. @pindex calc-truncate-up
  11551. @kindex d ]
  11552. @pindex calc-truncate-down
  11553. The @kbd{d [} (@code{calc-truncate-up}) and @kbd{d ]}
  11554. (@code{calc-truncate-down}) commands move the @samp{.} up or down one
  11555. line at a time (or several lines with a prefix argument).
  11556. @node Justification, Labels, Truncating the Stack, Display Modes
  11557. @subsection Justification
  11558. @noindent
  11559. @kindex d <
  11560. @pindex calc-left-justify
  11561. @kindex d =
  11562. @pindex calc-center-justify
  11563. @kindex d >
  11564. @pindex calc-right-justify
  11565. Values on the stack are normally left-justified in the window. You can
  11566. control this arrangement by typing @kbd{d <} (@code{calc-left-justify}),
  11567. @kbd{d >} (@code{calc-right-justify}), or @kbd{d =}
  11568. (@code{calc-center-justify}). For example, in Right-Justification mode,
  11569. stack entries are displayed flush-right against the right edge of the
  11570. window.
  11571. If you change the width of the Calculator window you may have to type
  11572. @kbd{d @key{SPC}} (@code{calc-refresh}) to re-align right-justified or centered
  11573. text.
  11574. Right-justification is especially useful together with fixed-point
  11575. notation (see @code{d f}; @code{calc-fix-notation}). With these modes
  11576. together, the decimal points on numbers will always line up.
  11577. With a numeric prefix argument, the justification commands give you
  11578. a little extra control over the display. The argument specifies the
  11579. horizontal ``origin'' of a display line. It is also possible to
  11580. specify a maximum line width using the @kbd{d b} command (@pxref{Normal
  11581. Language Modes}). For reference, the precise rules for formatting and
  11582. breaking lines are given below. Notice that the interaction between
  11583. origin and line width is slightly different in each justification
  11584. mode.
  11585. In Left-Justified mode, the line is indented by a number of spaces
  11586. given by the origin (default zero). If the result is longer than the
  11587. maximum line width, if given, or too wide to fit in the Calc window
  11588. otherwise, then it is broken into lines which will fit; each broken
  11589. line is indented to the origin.
  11590. In Right-Justified mode, lines are shifted right so that the rightmost
  11591. character is just before the origin, or just before the current
  11592. window width if no origin was specified. If the line is too long
  11593. for this, then it is broken; the current line width is used, if
  11594. specified, or else the origin is used as a width if that is
  11595. specified, or else the line is broken to fit in the window.
  11596. In Centering mode, the origin is the column number of the center of
  11597. each stack entry. If a line width is specified, lines will not be
  11598. allowed to go past that width; Calc will either indent less or
  11599. break the lines if necessary. If no origin is specified, half the
  11600. line width or Calc window width is used.
  11601. Note that, in each case, if line numbering is enabled the display
  11602. is indented an additional four spaces to make room for the line
  11603. number. The width of the line number is taken into account when
  11604. positioning according to the current Calc window width, but not
  11605. when positioning by explicit origins and widths. In the latter
  11606. case, the display is formatted as specified, and then uniformly
  11607. shifted over four spaces to fit the line numbers.
  11608. @node Labels, , Justification, Display Modes
  11609. @subsection Labels
  11610. @noindent
  11611. @kindex d @{
  11612. @pindex calc-left-label
  11613. The @kbd{d @{} (@code{calc-left-label}) command prompts for a string,
  11614. then displays that string to the left of every stack entry. If the
  11615. entries are left-justified (@pxref{Justification}), then they will
  11616. appear immediately after the label (unless you specified an origin
  11617. greater than the length of the label). If the entries are centered
  11618. or right-justified, the label appears on the far left and does not
  11619. affect the horizontal position of the stack entry.
  11620. Give a blank string (with @kbd{d @{ @key{RET}}) to turn the label off.
  11621. @kindex d @}
  11622. @pindex calc-right-label
  11623. The @kbd{d @}} (@code{calc-right-label}) command similarly adds a
  11624. label on the righthand side. It does not affect positioning of
  11625. the stack entries unless they are right-justified. Also, if both
  11626. a line width and an origin are given in Right-Justified mode, the
  11627. stack entry is justified to the origin and the righthand label is
  11628. justified to the line width.
  11629. One application of labels would be to add equation numbers to
  11630. formulas you are manipulating in Calc and then copying into a
  11631. document (possibly using Embedded mode). The equations would
  11632. typically be centered, and the equation numbers would be on the
  11633. left or right as you prefer.
  11634. @node Language Modes, Modes Variable, Display Modes, Mode Settings
  11635. @section Language Modes
  11636. @noindent
  11637. The commands in this section change Calc to use a different notation for
  11638. entry and display of formulas, corresponding to the conventions of some
  11639. other common language such as Pascal or @LaTeX{}. Objects displayed on the
  11640. stack or yanked from the Calculator to an editing buffer will be formatted
  11641. in the current language; objects entered in algebraic entry or yanked from
  11642. another buffer will be interpreted according to the current language.
  11643. The current language has no effect on things written to or read from the
  11644. trail buffer, nor does it affect numeric entry. Only algebraic entry is
  11645. affected. You can make even algebraic entry ignore the current language
  11646. and use the standard notation by giving a numeric prefix, e.g., @kbd{C-u '}.
  11647. For example, suppose the formula @samp{2*a[1] + atan(a[2])} occurs in a C
  11648. program; elsewhere in the program you need the derivatives of this formula
  11649. with respect to @samp{a[1]} and @samp{a[2]}. First, type @kbd{d C}
  11650. to switch to C notation. Now use @code{C-u C-x * g} to grab the formula
  11651. into the Calculator, @kbd{a d a[1] @key{RET}} to differentiate with respect
  11652. to the first variable, and @kbd{C-x * y} to yank the formula for the derivative
  11653. back into your C program. Press @kbd{U} to undo the differentiation and
  11654. repeat with @kbd{a d a[2] @key{RET}} for the other derivative.
  11655. Without being switched into C mode first, Calc would have misinterpreted
  11656. the brackets in @samp{a[1]} and @samp{a[2]}, would not have known that
  11657. @code{atan} was equivalent to Calc's built-in @code{arctan} function,
  11658. and would have written the formula back with notations (like implicit
  11659. multiplication) which would not have been valid for a C program.
  11660. As another example, suppose you are maintaining a C program and a @LaTeX{}
  11661. document, each of which needs a copy of the same formula. You can grab the
  11662. formula from the program in C mode, switch to @LaTeX{} mode, and yank the
  11663. formula into the document in @LaTeX{} math-mode format.
  11664. Language modes are selected by typing the letter @kbd{d} followed by a
  11665. shifted letter key.
  11666. @menu
  11667. * Normal Language Modes::
  11668. * C FORTRAN Pascal::
  11669. * TeX and LaTeX Language Modes::
  11670. * Eqn Language Mode::
  11671. * Yacas Language Mode::
  11672. * Maxima Language Mode::
  11673. * Giac Language Mode::
  11674. * Mathematica Language Mode::
  11675. * Maple Language Mode::
  11676. * Compositions::
  11677. * Syntax Tables::
  11678. @end menu
  11679. @node Normal Language Modes, C FORTRAN Pascal, Language Modes, Language Modes
  11680. @subsection Normal Language Modes
  11681. @noindent
  11682. @kindex d N
  11683. @pindex calc-normal-language
  11684. The @kbd{d N} (@code{calc-normal-language}) command selects the usual
  11685. notation for Calc formulas, as described in the rest of this manual.
  11686. Matrices are displayed in a multi-line tabular format, but all other
  11687. objects are written in linear form, as they would be typed from the
  11688. keyboard.
  11689. @kindex d O
  11690. @pindex calc-flat-language
  11691. @cindex Matrix display
  11692. The @kbd{d O} (@code{calc-flat-language}) command selects a language
  11693. identical with the normal one, except that matrices are written in
  11694. one-line form along with everything else. In some applications this
  11695. form may be more suitable for yanking data into other buffers.
  11696. @kindex d b
  11697. @pindex calc-line-breaking
  11698. @cindex Line breaking
  11699. @cindex Breaking up long lines
  11700. Even in one-line mode, long formulas or vectors will still be split
  11701. across multiple lines if they exceed the width of the Calculator window.
  11702. The @kbd{d b} (@code{calc-line-breaking}) command turns this line-breaking
  11703. feature on and off. (It works independently of the current language.)
  11704. If you give a numeric prefix argument of five or greater to the @kbd{d b}
  11705. command, that argument will specify the line width used when breaking
  11706. long lines.
  11707. @kindex d B
  11708. @pindex calc-big-language
  11709. The @kbd{d B} (@code{calc-big-language}) command selects a language
  11710. which uses textual approximations to various mathematical notations,
  11711. such as powers, quotients, and square roots:
  11712. @example
  11713. ____________
  11714. | a + 1 2
  11715. | ----- + c
  11716. \| b
  11717. @end example
  11718. @noindent
  11719. in place of @samp{sqrt((a+1)/b + c^2)}.
  11720. Subscripts like @samp{a_i} are displayed as actual subscripts in Big
  11721. mode. Double subscripts, @samp{a_i_j} (@samp{subscr(subscr(a, i), j)})
  11722. are displayed as @samp{a} with subscripts separated by commas:
  11723. @samp{i, j}. They must still be entered in the usual underscore
  11724. notation.
  11725. One slight ambiguity of Big notation is that
  11726. @example
  11727. 3
  11728. - -
  11729. 4
  11730. @end example
  11731. @noindent
  11732. can represent either the negative rational number @expr{-3:4}, or the
  11733. actual expression @samp{-(3/4)}; but the latter formula would normally
  11734. never be displayed because it would immediately be evaluated to
  11735. @expr{-3:4} or @expr{-0.75}, so this ambiguity is not a problem in
  11736. typical use.
  11737. Non-decimal numbers are displayed with subscripts. Thus there is no
  11738. way to tell the difference between @samp{16#C2} and @samp{C2_16},
  11739. though generally you will know which interpretation is correct.
  11740. Logarithms @samp{log(x,b)} and @samp{log10(x)} also use subscripts
  11741. in Big mode.
  11742. In Big mode, stack entries often take up several lines. To aid
  11743. readability, stack entries are separated by a blank line in this mode.
  11744. You may find it useful to expand the Calc window's height using
  11745. @kbd{C-x ^} (@code{enlarge-window}) or to make the Calc window the only
  11746. one on the screen with @kbd{C-x 1} (@code{delete-other-windows}).
  11747. Long lines are currently not rearranged to fit the window width in
  11748. Big mode, so you may need to use the @kbd{<} and @kbd{>} keys
  11749. to scroll across a wide formula. For really big formulas, you may
  11750. even need to use @kbd{@{} and @kbd{@}} to scroll up and down.
  11751. @kindex d U
  11752. @pindex calc-unformatted-language
  11753. The @kbd{d U} (@code{calc-unformatted-language}) command altogether disables
  11754. the use of operator notation in formulas. In this mode, the formula
  11755. shown above would be displayed:
  11756. @example
  11757. sqrt(add(div(add(a, 1), b), pow(c, 2)))
  11758. @end example
  11759. These four modes differ only in display format, not in the format
  11760. expected for algebraic entry. The standard Calc operators work in
  11761. all four modes, and unformatted notation works in any language mode
  11762. (except that Mathematica mode expects square brackets instead of
  11763. parentheses).
  11764. @node C FORTRAN Pascal, TeX and LaTeX Language Modes, Normal Language Modes, Language Modes
  11765. @subsection C, FORTRAN, and Pascal Modes
  11766. @noindent
  11767. @kindex d C
  11768. @pindex calc-c-language
  11769. @cindex C language
  11770. The @kbd{d C} (@code{calc-c-language}) command selects the conventions
  11771. of the C language for display and entry of formulas. This differs from
  11772. the normal language mode in a variety of (mostly minor) ways. In
  11773. particular, C language operators and operator precedences are used in
  11774. place of Calc's usual ones. For example, @samp{a^b} means @samp{xor(a,b)}
  11775. in C mode; a value raised to a power is written as a function call,
  11776. @samp{pow(a,b)}.
  11777. In C mode, vectors and matrices use curly braces instead of brackets.
  11778. Octal and hexadecimal values are written with leading @samp{0} or @samp{0x}
  11779. rather than using the @samp{#} symbol. Array subscripting is
  11780. translated into @code{subscr} calls, so that @samp{a[i]} in C
  11781. mode is the same as @samp{a_i} in Normal mode. Assignments
  11782. turn into the @code{assign} function, which Calc normally displays
  11783. using the @samp{:=} symbol.
  11784. The variables @code{pi} and @code{e} would be displayed @samp{pi}
  11785. and @samp{e} in Normal mode, but in C mode they are displayed as
  11786. @samp{M_PI} and @samp{M_E}, corresponding to the names of constants
  11787. typically provided in the @file{<math.h>} header. Functions whose
  11788. names are different in C are translated automatically for entry and
  11789. display purposes. For example, entering @samp{asin(x)} will push the
  11790. formula @samp{arcsin(x)} onto the stack; this formula will be displayed
  11791. as @samp{asin(x)} as long as C mode is in effect.
  11792. @kindex d P
  11793. @pindex calc-pascal-language
  11794. @cindex Pascal language
  11795. The @kbd{d P} (@code{calc-pascal-language}) command selects Pascal
  11796. conventions. Like C mode, Pascal mode interprets array brackets and uses
  11797. a different table of operators. Hexadecimal numbers are entered and
  11798. displayed with a preceding dollar sign. (Thus the regular meaning of
  11799. @kbd{$2} during algebraic entry does not work in Pascal mode, though
  11800. @kbd{$} (and @kbd{$$}, etc.)@: not followed by digits works the same as
  11801. always.) No special provisions are made for other non-decimal numbers,
  11802. vectors, and so on, since there is no universally accepted standard way
  11803. of handling these in Pascal.
  11804. @kindex d F
  11805. @pindex calc-fortran-language
  11806. @cindex FORTRAN language
  11807. The @kbd{d F} (@code{calc-fortran-language}) command selects FORTRAN
  11808. conventions. Various function names are transformed into FORTRAN
  11809. equivalents. Vectors are written as @samp{/1, 2, 3/}, and may be
  11810. entered this way or using square brackets. Since FORTRAN uses round
  11811. parentheses for both function calls and array subscripts, Calc displays
  11812. both in the same way; @samp{a(i)} is interpreted as a function call
  11813. upon reading, and subscripts must be entered as @samp{subscr(a, i)}.
  11814. If the variable @code{a} has been declared to have type
  11815. @code{vector} or @code{matrix}, however, then @samp{a(i)} will be
  11816. parsed as a subscript. (@xref{Declarations}.) Usually it doesn't
  11817. matter, though; if you enter the subscript expression @samp{a(i)} and
  11818. Calc interprets it as a function call, you'll never know the difference
  11819. unless you switch to another language mode or replace @code{a} with an
  11820. actual vector (or unless @code{a} happens to be the name of a built-in
  11821. function!).
  11822. Underscores are allowed in variable and function names in all of these
  11823. language modes. The underscore here is equivalent to the @samp{#} in
  11824. Normal mode, or to hyphens in the underlying Emacs Lisp variable names.
  11825. FORTRAN and Pascal modes normally do not adjust the case of letters in
  11826. formulas. Most built-in Calc names use lower-case letters. If you use a
  11827. positive numeric prefix argument with @kbd{d P} or @kbd{d F}, these
  11828. modes will use upper-case letters exclusively for display, and will
  11829. convert to lower-case on input. With a negative prefix, these modes
  11830. convert to lower-case for display and input.
  11831. @node TeX and LaTeX Language Modes, Eqn Language Mode, C FORTRAN Pascal, Language Modes
  11832. @subsection @TeX{} and @LaTeX{} Language Modes
  11833. @noindent
  11834. @kindex d T
  11835. @pindex calc-tex-language
  11836. @cindex TeX language
  11837. @kindex d L
  11838. @pindex calc-latex-language
  11839. @cindex LaTeX language
  11840. The @kbd{d T} (@code{calc-tex-language}) command selects the conventions
  11841. of ``math mode'' in Donald Knuth's @TeX{} typesetting language,
  11842. and the @kbd{d L} (@code{calc-latex-language}) command selects the
  11843. conventions of ``math mode'' in @LaTeX{}, a typesetting language that
  11844. uses @TeX{} as its formatting engine. Calc's @LaTeX{} language mode can
  11845. read any formula that the @TeX{} language mode can, although @LaTeX{}
  11846. mode may display it differently.
  11847. Formulas are entered and displayed in the appropriate notation;
  11848. @texline @math{\sin(a/b)}
  11849. @infoline @expr{sin(a/b)}
  11850. will appear as @samp{\sin\left( @{a \over b@} \right)} in @TeX{} mode and
  11851. @samp{\sin\left(\frac@{a@}@{b@}\right)} in @LaTeX{} mode.
  11852. Math formulas are often enclosed by @samp{$ $} signs in @TeX{} and
  11853. @LaTeX{}; these should be omitted when interfacing with Calc. To Calc,
  11854. the @samp{$} sign has the same meaning it always does in algebraic
  11855. formulas (a reference to an existing entry on the stack).
  11856. Complex numbers are displayed as in @samp{3 + 4i}. Fractions and
  11857. quotients are written using @code{\over} in @TeX{} mode (as in
  11858. @code{@{a \over b@}}) and @code{\frac} in @LaTeX{} mode (as in
  11859. @code{\frac@{a@}@{b@}}); binomial coefficients are written with
  11860. @code{\choose} in @TeX{} mode (as in @code{@{a \choose b@}}) and
  11861. @code{\binom} in @LaTeX{} mode (as in @code{\binom@{a@}@{b@}}).
  11862. Interval forms are written with @code{\ldots}, and error forms are
  11863. written with @code{\pm}. Absolute values are written as in
  11864. @samp{|x + 1|}, and the floor and ceiling functions are written with
  11865. @code{\lfloor}, @code{\rfloor}, etc. The words @code{\left} and
  11866. @code{\right} are ignored when reading formulas in @TeX{} and @LaTeX{}
  11867. modes. Both @code{inf} and @code{uinf} are written as @code{\infty};
  11868. when read, @code{\infty} always translates to @code{inf}.
  11869. Function calls are written the usual way, with the function name followed
  11870. by the arguments in parentheses. However, functions for which @TeX{}
  11871. and @LaTeX{} have special names (like @code{\sin}) will use curly braces
  11872. instead of parentheses for very simple arguments. During input, curly
  11873. braces and parentheses work equally well for grouping, but when the
  11874. document is formatted the curly braces will be invisible. Thus the
  11875. printed result is
  11876. @texline @math{\sin{2 x}}
  11877. @infoline @expr{sin 2x}
  11878. but
  11879. @texline @math{\sin(2 + x)}.
  11880. @infoline @expr{sin(2 + x)}.
  11881. The @TeX{} specific unit names (@pxref{Predefined Units}) will not use
  11882. the @samp{tex} prefix; the unit name for a @TeX{} point will be
  11883. @samp{pt} instead of @samp{texpt}, for example.
  11884. Function and variable names not treated specially by @TeX{} and @LaTeX{}
  11885. are simply written out as-is, which will cause them to come out in
  11886. italic letters in the printed document. If you invoke @kbd{d T} or
  11887. @kbd{d L} with a positive numeric prefix argument, names of more than
  11888. one character will instead be enclosed in a protective commands that
  11889. will prevent them from being typeset in the math italics; they will be
  11890. written @samp{\hbox@{@var{name}@}} in @TeX{} mode and
  11891. @samp{\text@{@var{name}@}} in @LaTeX{} mode. The
  11892. @samp{\hbox@{ @}} and @samp{\text@{ @}} notations are ignored during
  11893. reading. If you use a negative prefix argument, such function names are
  11894. written @samp{\@var{name}}, and function names that begin with @code{\} during
  11895. reading have the @code{\} removed. (Note that in this mode, long
  11896. variable names are still written with @code{\hbox} or @code{\text}.
  11897. However, you can always make an actual variable name like @code{\bar} in
  11898. any @TeX{} mode.)
  11899. During reading, text of the form @samp{\matrix@{ ...@: @}} is replaced
  11900. by @samp{[ ...@: ]}. The same also applies to @code{\pmatrix} and
  11901. @code{\bmatrix}. In @LaTeX{} mode this also applies to
  11902. @samp{\begin@{matrix@} ... \end@{matrix@}},
  11903. @samp{\begin@{bmatrix@} ... \end@{bmatrix@}},
  11904. @samp{\begin@{pmatrix@} ... \end@{pmatrix@}}, as well as
  11905. @samp{\begin@{smallmatrix@} ... \end@{smallmatrix@}}.
  11906. The symbol @samp{&} is interpreted as a comma,
  11907. and the symbols @samp{\cr} and @samp{\\} are interpreted as semicolons.
  11908. During output, matrices are displayed in @samp{\matrix@{ a & b \\ c & d@}}
  11909. format in @TeX{} mode and in
  11910. @samp{\begin@{pmatrix@} a & b \\ c & d \end@{pmatrix@}} format in
  11911. @LaTeX{} mode; you may need to edit this afterwards to change to your
  11912. preferred matrix form. If you invoke @kbd{d T} or @kbd{d L} with an
  11913. argument of 2 or -2, then matrices will be displayed in two-dimensional
  11914. form, such as
  11915. @example
  11916. \begin@{pmatrix@}
  11917. a & b \\
  11918. c & d
  11919. \end@{pmatrix@}
  11920. @end example
  11921. @noindent
  11922. This may be convenient for isolated matrices, but could lead to
  11923. expressions being displayed like
  11924. @example
  11925. \begin@{pmatrix@} \times x
  11926. a & b \\
  11927. c & d
  11928. \end@{pmatrix@}
  11929. @end example
  11930. @noindent
  11931. While this wouldn't bother Calc, it is incorrect @LaTeX{}.
  11932. (Similarly for @TeX{}.)
  11933. Accents like @code{\tilde} and @code{\bar} translate into function
  11934. calls internally (@samp{tilde(x)}, @samp{bar(x)}). The @code{\underline}
  11935. sequence is treated as an accent. The @code{\vec} accent corresponds
  11936. to the function name @code{Vec}, because @code{vec} is the name of
  11937. a built-in Calc function. The following table shows the accents
  11938. in Calc, @TeX{}, @LaTeX{} and @dfn{eqn} (described in the next section):
  11939. @ignore
  11940. @iftex
  11941. @begingroup
  11942. @let@calcindexershow=@calcindexernoshow @c Suppress marginal notes
  11943. @let@calcindexersh=@calcindexernoshow
  11944. @end iftex
  11945. @starindex
  11946. @end ignore
  11947. @tindex acute
  11948. @ignore
  11949. @starindex
  11950. @end ignore
  11951. @tindex Acute
  11952. @ignore
  11953. @starindex
  11954. @end ignore
  11955. @tindex bar
  11956. @ignore
  11957. @starindex
  11958. @end ignore
  11959. @tindex Bar
  11960. @ignore
  11961. @starindex
  11962. @end ignore
  11963. @tindex breve
  11964. @ignore
  11965. @starindex
  11966. @end ignore
  11967. @tindex Breve
  11968. @ignore
  11969. @starindex
  11970. @end ignore
  11971. @tindex check
  11972. @ignore
  11973. @starindex
  11974. @end ignore
  11975. @tindex Check
  11976. @ignore
  11977. @starindex
  11978. @end ignore
  11979. @tindex dddot
  11980. @ignore
  11981. @starindex
  11982. @end ignore
  11983. @tindex ddddot
  11984. @ignore
  11985. @starindex
  11986. @end ignore
  11987. @tindex dot
  11988. @ignore
  11989. @starindex
  11990. @end ignore
  11991. @tindex Dot
  11992. @ignore
  11993. @starindex
  11994. @end ignore
  11995. @tindex dotdot
  11996. @ignore
  11997. @starindex
  11998. @end ignore
  11999. @tindex DotDot
  12000. @ignore
  12001. @starindex
  12002. @end ignore
  12003. @tindex dyad
  12004. @ignore
  12005. @starindex
  12006. @end ignore
  12007. @tindex grave
  12008. @ignore
  12009. @starindex
  12010. @end ignore
  12011. @tindex Grave
  12012. @ignore
  12013. @starindex
  12014. @end ignore
  12015. @tindex hat
  12016. @ignore
  12017. @starindex
  12018. @end ignore
  12019. @tindex Hat
  12020. @ignore
  12021. @starindex
  12022. @end ignore
  12023. @tindex Prime
  12024. @ignore
  12025. @starindex
  12026. @end ignore
  12027. @tindex tilde
  12028. @ignore
  12029. @starindex
  12030. @end ignore
  12031. @tindex Tilde
  12032. @ignore
  12033. @starindex
  12034. @end ignore
  12035. @tindex under
  12036. @ignore
  12037. @starindex
  12038. @end ignore
  12039. @tindex Vec
  12040. @ignore
  12041. @starindex
  12042. @end ignore
  12043. @tindex VEC
  12044. @ignore
  12045. @iftex
  12046. @endgroup
  12047. @end iftex
  12048. @end ignore
  12049. @example
  12050. Calc TeX LaTeX eqn
  12051. ---- --- ----- ---
  12052. acute \acute \acute
  12053. Acute \Acute
  12054. bar \bar \bar bar
  12055. Bar \Bar
  12056. breve \breve \breve
  12057. Breve \Breve
  12058. check \check \check
  12059. Check \Check
  12060. dddot \dddot
  12061. ddddot \ddddot
  12062. dot \dot \dot dot
  12063. Dot \Dot
  12064. dotdot \ddot \ddot dotdot
  12065. DotDot \Ddot
  12066. dyad dyad
  12067. grave \grave \grave
  12068. Grave \Grave
  12069. hat \hat \hat hat
  12070. Hat \Hat
  12071. Prime prime
  12072. tilde \tilde \tilde tilde
  12073. Tilde \Tilde
  12074. under \underline \underline under
  12075. Vec \vec \vec vec
  12076. VEC \Vec
  12077. @end example
  12078. The @samp{=>} (evaluates-to) operator appears as a @code{\to} symbol:
  12079. @samp{@{@var{a} \to @var{b}@}}. @TeX{} defines @code{\to} as an
  12080. alias for @code{\rightarrow}. However, if the @samp{=>} is the
  12081. top-level expression being formatted, a slightly different notation
  12082. is used: @samp{\evalto @var{a} \to @var{b}}. The @code{\evalto}
  12083. word is ignored by Calc's input routines, and is undefined in @TeX{}.
  12084. You will typically want to include one of the following definitions
  12085. at the top of a @TeX{} file that uses @code{\evalto}:
  12086. @example
  12087. \def\evalto@{@}
  12088. \def\evalto#1\to@{@}
  12089. @end example
  12090. The first definition formats evaluates-to operators in the usual
  12091. way. The second causes only the @var{b} part to appear in the
  12092. printed document; the @var{a} part and the arrow are hidden.
  12093. Another definition you may wish to use is @samp{\let\to=\Rightarrow}
  12094. which causes @code{\to} to appear more like Calc's @samp{=>} symbol.
  12095. @xref{Evaluates-To Operator}, for a discussion of @code{evalto}.
  12096. The complete set of @TeX{} control sequences that are ignored during
  12097. reading is:
  12098. @example
  12099. \hbox \mbox \text \left \right
  12100. \, \> \: \; \! \quad \qquad \hfil \hfill
  12101. \displaystyle \textstyle \dsize \tsize
  12102. \scriptstyle \scriptscriptstyle \ssize \ssize
  12103. \rm \bf \it \sl \roman \bold \italic \slanted
  12104. \cal \mit \Cal \Bbb \frak \goth
  12105. \evalto
  12106. @end example
  12107. Note that, because these symbols are ignored, reading a @TeX{} or
  12108. @LaTeX{} formula into Calc and writing it back out may lose spacing and
  12109. font information.
  12110. Also, the ``discretionary multiplication sign'' @samp{\*} is read
  12111. the same as @samp{*}.
  12112. @ifnottex
  12113. The @TeX{} version of this manual includes some printed examples at the
  12114. end of this section.
  12115. @end ifnottex
  12116. @iftex
  12117. Here are some examples of how various Calc formulas are formatted in @TeX{}:
  12118. @example
  12119. @group
  12120. sin(a^2 / b_i)
  12121. \sin\left( {a^2 \over b_i} \right)
  12122. @end group
  12123. @end example
  12124. @tex
  12125. $$ \sin\left( a^2 \over b_i \right) $$
  12126. @end tex
  12127. @sp 1
  12128. @example
  12129. @group
  12130. [(3, 4), 3:4, 3 +/- 4, [3 .. inf)]
  12131. [3 + 4i, @{3 \over 4@}, 3 \pm 4, [3 \ldots \infty)]
  12132. @end group
  12133. @end example
  12134. @tex
  12135. $$ [3 + 4i, {3 \over 4}, 3 \pm 4, [ 3 \ldots \infty)] $$
  12136. @end tex
  12137. @sp 1
  12138. @example
  12139. @group
  12140. [abs(a), abs(a / b), floor(a), ceil(a / b)]
  12141. [|a|, \left| a \over b \right|,
  12142. \lfloor a \rfloor, \left\lceil a \over b \right\rceil]
  12143. @end group
  12144. @end example
  12145. @tex
  12146. $$ [|a|, \left| a \over b \right|,
  12147. \lfloor a \rfloor, \left\lceil a \over b \right\rceil] $$
  12148. @end tex
  12149. @sp 1
  12150. @example
  12151. @group
  12152. [sin(a), sin(2 a), sin(2 + a), sin(a / b)]
  12153. [\sin@{a@}, \sin@{2 a@}, \sin(2 + a),
  12154. \sin\left( @{a \over b@} \right)]
  12155. @end group
  12156. @end example
  12157. @tex
  12158. $$ [\sin{a}, \sin{2 a}, \sin(2 + a), \sin\left( {a \over b} \right)] $$
  12159. @end tex
  12160. @sp 2
  12161. First with plain @kbd{d T}, then with @kbd{C-u d T}, then finally with
  12162. @kbd{C-u - d T} (using the example definition
  12163. @samp{\def\foo#1@{\tilde F(#1)@}}:
  12164. @example
  12165. @group
  12166. [f(a), foo(bar), sin(pi)]
  12167. [f(a), foo(bar), \sin{\pi}]
  12168. [f(a), \hbox@{foo@}(\hbox@{bar@}), \sin@{\pi@}]
  12169. [f(a), \foo@{\hbox@{bar@}@}, \sin@{\pi@}]
  12170. @end group
  12171. @end example
  12172. @tex
  12173. $$ [f(a), foo(bar), \sin{\pi}] $$
  12174. $$ [f(a), \hbox{foo}(\hbox{bar}), \sin{\pi}] $$
  12175. $$ [f(a), \tilde F(\hbox{bar}), \sin{\pi}] $$
  12176. @end tex
  12177. @sp 2
  12178. First with @samp{\def\evalto@{@}}, then with @samp{\def\evalto#1\to@{@}}:
  12179. @example
  12180. @group
  12181. 2 + 3 => 5
  12182. \evalto 2 + 3 \to 5
  12183. @end group
  12184. @end example
  12185. @tex
  12186. $$ 2 + 3 \to 5 $$
  12187. $$ 5 $$
  12188. @end tex
  12189. @sp 2
  12190. First with standard @code{\to}, then with @samp{\let\to\Rightarrow}:
  12191. @example
  12192. @group
  12193. [2 + 3 => 5, a / 2 => (b + c) / 2]
  12194. [@{2 + 3 \to 5@}, @{@{a \over 2@} \to @{b + c \over 2@}@}]
  12195. @end group
  12196. @end example
  12197. @tex
  12198. $$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$
  12199. {\let\to\Rightarrow
  12200. $$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$}
  12201. @end tex
  12202. @sp 2
  12203. Matrices normally, then changing @code{\matrix} to @code{\pmatrix}:
  12204. @example
  12205. @group
  12206. [ [ a / b, 0 ], [ 0, 2^(x + 1) ] ]
  12207. \matrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
  12208. \pmatrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
  12209. @end group
  12210. @end example
  12211. @tex
  12212. $$ \matrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
  12213. $$ \pmatrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
  12214. @end tex
  12215. @sp 2
  12216. @end iftex
  12217. @node Eqn Language Mode, Yacas Language Mode, TeX and LaTeX Language Modes, Language Modes
  12218. @subsection Eqn Language Mode
  12219. @noindent
  12220. @kindex d E
  12221. @pindex calc-eqn-language
  12222. @dfn{Eqn} is another popular formatter for math formulas. It is
  12223. designed for use with the TROFF text formatter, and comes standard
  12224. with many versions of Unix. The @kbd{d E} (@code{calc-eqn-language})
  12225. command selects @dfn{eqn} notation.
  12226. The @dfn{eqn} language's main idiosyncrasy is that whitespace plays
  12227. a significant part in the parsing of the language. For example,
  12228. @samp{sqrt x+1 + y} treats @samp{x+1} as the argument of the
  12229. @code{sqrt} operator. @dfn{Eqn} also understands more conventional
  12230. grouping using curly braces: @samp{sqrt@{x+1@} + y}. Braces are
  12231. required only when the argument contains spaces.
  12232. In Calc's @dfn{eqn} mode, however, curly braces are required to
  12233. delimit arguments of operators like @code{sqrt}. The first of the
  12234. above examples would treat only the @samp{x} as the argument of
  12235. @code{sqrt}, and in fact @samp{sin x+1} would be interpreted as
  12236. @samp{sin * x + 1}, because @code{sin} is not a special operator
  12237. in the @dfn{eqn} language. If you always surround the argument
  12238. with curly braces, Calc will never misunderstand.
  12239. Calc also understands parentheses as grouping characters. Another
  12240. peculiarity of @dfn{eqn}'s syntax makes it advisable to separate
  12241. words with spaces from any surrounding characters that aren't curly
  12242. braces, so Calc writes @samp{sin ( x + y )} in @dfn{eqn} mode.
  12243. (The spaces around @code{sin} are important to make @dfn{eqn}
  12244. recognize that @code{sin} should be typeset in a roman font, and
  12245. the spaces around @code{x} and @code{y} are a good idea just in
  12246. case the @dfn{eqn} document has defined special meanings for these
  12247. names, too.)
  12248. Powers and subscripts are written with the @code{sub} and @code{sup}
  12249. operators, respectively. Note that the caret symbol @samp{^} is
  12250. treated the same as a space in @dfn{eqn} mode, as is the @samp{~}
  12251. symbol (these are used to introduce spaces of various widths into
  12252. the typeset output of @dfn{eqn}).
  12253. As in @LaTeX{} mode, Calc's formatter omits parentheses around the
  12254. arguments of functions like @code{ln} and @code{sin} if they are
  12255. ``simple-looking''; in this case Calc surrounds the argument with
  12256. braces, separated by a @samp{~} from the function name: @samp{sin~@{x@}}.
  12257. Font change codes (like @samp{roman @var{x}}) and positioning codes
  12258. (like @samp{~} and @samp{down @var{n} @var{x}}) are ignored by the
  12259. @dfn{eqn} reader. Also ignored are the words @code{left}, @code{right},
  12260. @code{mark}, and @code{lineup}. Quotation marks in @dfn{eqn} mode input
  12261. are treated the same as curly braces: @samp{sqrt "1+x"} is equivalent to
  12262. @samp{sqrt @{1+x@}}; this is only an approximation to the true meaning
  12263. of quotes in @dfn{eqn}, but it is good enough for most uses.
  12264. Accent codes (@samp{@var{x} dot}) are handled by treating them as
  12265. function calls (@samp{dot(@var{x})}) internally.
  12266. @xref{TeX and LaTeX Language Modes}, for a table of these accent
  12267. functions. The @code{prime} accent is treated specially if it occurs on
  12268. a variable or function name: @samp{f prime prime @w{( x prime )}} is
  12269. stored internally as @samp{f'@w{'}(x')}. For example, taking the
  12270. derivative of @samp{f(2 x)} with @kbd{a d x} will produce @samp{2 f'(2
  12271. x)}, which @dfn{eqn} mode will display as @samp{2 f prime ( 2 x )}.
  12272. Assignments are written with the @samp{<-} (left-arrow) symbol,
  12273. and @code{evalto} operators are written with @samp{->} or
  12274. @samp{evalto ... ->} (@pxref{TeX and LaTeX Language Modes}, for a discussion
  12275. of this). The regular Calc symbols @samp{:=} and @samp{=>} are also
  12276. recognized for these operators during reading.
  12277. Vectors in @dfn{eqn} mode use regular Calc square brackets, but
  12278. matrices are formatted as @samp{matrix @{ ccol @{ a above b @} ... @}}.
  12279. The words @code{lcol} and @code{rcol} are recognized as synonyms
  12280. for @code{ccol} during input, and are generated instead of @code{ccol}
  12281. if the matrix justification mode so specifies.
  12282. @node Yacas Language Mode, Maxima Language Mode, Eqn Language Mode, Language Modes
  12283. @subsection Yacas Language Mode
  12284. @noindent
  12285. @kindex d Y
  12286. @pindex calc-yacas-language
  12287. @cindex Yacas language
  12288. The @kbd{d Y} (@code{calc-yacas-language}) command selects the
  12289. conventions of Yacas, a free computer algebra system. While the
  12290. operators and functions in Yacas are similar to those of Calc, the names
  12291. of built-in functions in Yacas are capitalized. The Calc formula
  12292. @samp{sin(2 x)}, for example, is entered and displayed @samp{Sin(2 x)}
  12293. in Yacas mode, and `@samp{arcsin(x^2)} is @samp{ArcSin(x^2)} in Yacas
  12294. mode. Complex numbers are written are written @samp{3 + 4 I}.
  12295. The standard special constants are written @code{Pi}, @code{E},
  12296. @code{I}, @code{GoldenRatio} and @code{Gamma}. @code{Infinity}
  12297. represents both @code{inf} and @code{uinf}, and @code{Undefined}
  12298. represents @code{nan}.
  12299. Certain operators on functions, such as @code{D} for differentiation
  12300. and @code{Integrate} for integration, take a prefix form in Yacas. For
  12301. example, the derivative of @w{@samp{e^x sin(x)}} can be computed with
  12302. @w{@samp{D(x) Exp(x)*Sin(x)}}.
  12303. Other notable differences between Yacas and standard Calc expressions
  12304. are that vectors and matrices use curly braces in Yacas, and subscripts
  12305. use square brackets. If, for example, @samp{A} represents the list
  12306. @samp{@{a,2,c,4@}}, then @samp{A[3]} would equal @samp{c}.
  12307. @node Maxima Language Mode, Giac Language Mode, Yacas Language Mode, Language Modes
  12308. @subsection Maxima Language Mode
  12309. @noindent
  12310. @kindex d X
  12311. @pindex calc-maxima-language
  12312. @cindex Maxima language
  12313. The @kbd{d X} (@code{calc-maxima-language}) command selects the
  12314. conventions of Maxima, another free computer algebra system. The
  12315. function names in Maxima are similar, but not always identical, to Calc.
  12316. For example, instead of @samp{arcsin(x)}, Maxima will use
  12317. @samp{asin(x)}. Complex numbers are written @samp{3 + 4 %i}. The
  12318. standard special constants are written @code{%pi}, @code{%e},
  12319. @code{%i}, @code{%phi} and @code{%gamma}. In Maxima, @code{inf} means
  12320. the same as in Calc, but @code{infinity} represents Calc's @code{uinf}.
  12321. Underscores as well as percent signs are allowed in function and
  12322. variable names in Maxima mode. The underscore again is equivalent to
  12323. the @samp{#} in Normal mode, and the percent sign is equivalent to
  12324. @samp{o'o}.
  12325. Maxima uses square brackets for lists and vectors, and matrices are
  12326. written as calls to the function @code{matrix}, given the row vectors of
  12327. the matrix as arguments. Square brackets are also used as subscripts.
  12328. @node Giac Language Mode, Mathematica Language Mode, Maxima Language Mode, Language Modes
  12329. @subsection Giac Language Mode
  12330. @noindent
  12331. @kindex d A
  12332. @pindex calc-giac-language
  12333. @cindex Giac language
  12334. The @kbd{d A} (@code{calc-giac-language}) command selects the
  12335. conventions of Giac, another free computer algebra system. The function
  12336. names in Giac are similar to Maxima. Complex numbers are written
  12337. @samp{3 + 4 i}. The standard special constants in Giac are the same as
  12338. in Calc, except that @code{infinity} represents both Calc's @code{inf}
  12339. and @code{uinf}.
  12340. Underscores are allowed in function and variable names in Giac mode.
  12341. Brackets are used for subscripts. In Giac, indexing of lists begins at
  12342. 0, instead of 1 as in Calc. So if @samp{A} represents the list
  12343. @samp{[a,2,c,4]}, then @samp{A[2]} would equal @samp{c}. In general,
  12344. @samp{A[n]} in Giac mode corresponds to @samp{A_(n+1)} in Normal mode.
  12345. The Giac interval notation @samp{2 .. 3} has no surrounding brackets;
  12346. Calc reads @samp{2 .. 3} as the closed interval @samp{[2 .. 3]} and
  12347. writes any kind of interval as @samp{2 .. 3}. This means you cannot see
  12348. the difference between an open and a closed interval while in Giac mode.
  12349. @node Mathematica Language Mode, Maple Language Mode, Giac Language Mode, Language Modes
  12350. @subsection Mathematica Language Mode
  12351. @noindent
  12352. @kindex d M
  12353. @pindex calc-mathematica-language
  12354. @cindex Mathematica language
  12355. The @kbd{d M} (@code{calc-mathematica-language}) command selects the
  12356. conventions of Mathematica. Notable differences in Mathematica mode
  12357. are that the names of built-in functions are capitalized, and function
  12358. calls use square brackets instead of parentheses. Thus the Calc
  12359. formula @samp{sin(2 x)} is entered and displayed @w{@samp{Sin[2 x]}} in
  12360. Mathematica mode.
  12361. Vectors and matrices use curly braces in Mathematica. Complex numbers
  12362. are written @samp{3 + 4 I}. The standard special constants in Calc are
  12363. written @code{Pi}, @code{E}, @code{I}, @code{GoldenRatio}, @code{EulerGamma},
  12364. @code{Infinity}, @code{ComplexInfinity}, and @code{Indeterminate} in
  12365. Mathematica mode.
  12366. Non-decimal numbers are written, e.g., @samp{16^^7fff}. Floating-point
  12367. numbers in scientific notation are written @samp{1.23*10.^3}.
  12368. Subscripts use double square brackets: @samp{a[[i]]}.
  12369. @node Maple Language Mode, Compositions, Mathematica Language Mode, Language Modes
  12370. @subsection Maple Language Mode
  12371. @noindent
  12372. @kindex d W
  12373. @pindex calc-maple-language
  12374. @cindex Maple language
  12375. The @kbd{d W} (@code{calc-maple-language}) command selects the
  12376. conventions of Maple.
  12377. Maple's language is much like C@. Underscores are allowed in symbol
  12378. names; square brackets are used for subscripts; explicit @samp{*}s for
  12379. multiplications are required. Use either @samp{^} or @samp{**} to
  12380. denote powers.
  12381. Maple uses square brackets for lists and curly braces for sets. Calc
  12382. interprets both notations as vectors, and displays vectors with square
  12383. brackets. This means Maple sets will be converted to lists when they
  12384. pass through Calc. As a special case, matrices are written as calls
  12385. to the function @code{matrix}, given a list of lists as the argument,
  12386. and can be read in this form or with all-capitals @code{MATRIX}.
  12387. The Maple interval notation @samp{2 .. 3} is like Giac's interval
  12388. notation, and is handled the same by Calc.
  12389. Maple writes complex numbers as @samp{3 + 4*I}. Its special constants
  12390. are @code{Pi}, @code{E}, @code{I}, and @code{infinity} (all three of
  12391. @code{inf}, @code{uinf}, and @code{nan} display as @code{infinity}).
  12392. Floating-point numbers are written @samp{1.23*10.^3}.
  12393. Among things not currently handled by Calc's Maple mode are the
  12394. various quote symbols, procedures and functional operators, and
  12395. inert (@samp{&}) operators.
  12396. @node Compositions, Syntax Tables, Maple Language Mode, Language Modes
  12397. @subsection Compositions
  12398. @noindent
  12399. @cindex Compositions
  12400. There are several @dfn{composition functions} which allow you to get
  12401. displays in a variety of formats similar to those in Big language
  12402. mode. Most of these functions do not evaluate to anything; they are
  12403. placeholders which are left in symbolic form by Calc's evaluator but
  12404. are recognized by Calc's display formatting routines.
  12405. Two of these, @code{string} and @code{bstring}, are described elsewhere.
  12406. @xref{Strings}. For example, @samp{string("ABC")} is displayed as
  12407. @samp{ABC}. When viewed on the stack it will be indistinguishable from
  12408. the variable @code{ABC}, but internally it will be stored as
  12409. @samp{string([65, 66, 67])} and can still be manipulated this way; for
  12410. example, the selection and vector commands @kbd{j 1 v v j u} would
  12411. select the vector portion of this object and reverse the elements, then
  12412. deselect to reveal a string whose characters had been reversed.
  12413. The composition functions do the same thing in all language modes
  12414. (although their components will of course be formatted in the current
  12415. language mode). The one exception is Unformatted mode (@kbd{d U}),
  12416. which does not give the composition functions any special treatment.
  12417. The functions are discussed here because of their relationship to
  12418. the language modes.
  12419. @menu
  12420. * Composition Basics::
  12421. * Horizontal Compositions::
  12422. * Vertical Compositions::
  12423. * Other Compositions::
  12424. * Information about Compositions::
  12425. * User-Defined Compositions::
  12426. @end menu
  12427. @node Composition Basics, Horizontal Compositions, Compositions, Compositions
  12428. @subsubsection Composition Basics
  12429. @noindent
  12430. Compositions are generally formed by stacking formulas together
  12431. horizontally or vertically in various ways. Those formulas are
  12432. themselves compositions. @TeX{} users will find this analogous
  12433. to @TeX{}'s ``boxes.'' Each multi-line composition has a
  12434. @dfn{baseline}; horizontal compositions use the baselines to
  12435. decide how formulas should be positioned relative to one another.
  12436. For example, in the Big mode formula
  12437. @example
  12438. @group
  12439. 2
  12440. a + b
  12441. 17 + ------
  12442. c
  12443. @end group
  12444. @end example
  12445. @noindent
  12446. the second term of the sum is four lines tall and has line three as
  12447. its baseline. Thus when the term is combined with 17, line three
  12448. is placed on the same level as the baseline of 17.
  12449. @tex
  12450. \bigskip
  12451. @end tex
  12452. Another important composition concept is @dfn{precedence}. This is
  12453. an integer that represents the binding strength of various operators.
  12454. For example, @samp{*} has higher precedence (195) than @samp{+} (180),
  12455. which means that @samp{(a * b) + c} will be formatted without the
  12456. parentheses, but @samp{a * (b + c)} will keep the parentheses.
  12457. The operator table used by normal and Big language modes has the
  12458. following precedences:
  12459. @example
  12460. _ 1200 @r{(subscripts)}
  12461. % 1100 @r{(as in n}%@r{)}
  12462. ! 1000 @r{(as in }!@r{n)}
  12463. mod 400
  12464. +/- 300
  12465. !! 210 @r{(as in n}!!@r{)}
  12466. ! 210 @r{(as in n}!@r{)}
  12467. ^ 200
  12468. - 197 @r{(as in }-@r{n)}
  12469. * 195 @r{(or implicit multiplication)}
  12470. / % \ 190
  12471. + - 180 @r{(as in a}+@r{b)}
  12472. | 170
  12473. < = 160 @r{(and other relations)}
  12474. && 110
  12475. || 100
  12476. ? : 90
  12477. !!! 85
  12478. &&& 80
  12479. ||| 75
  12480. := 50
  12481. :: 45
  12482. => 40
  12483. @end example
  12484. The general rule is that if an operator with precedence @expr{n}
  12485. occurs as an argument to an operator with precedence @expr{m}, then
  12486. the argument is enclosed in parentheses if @expr{n < m}. Top-level
  12487. expressions and expressions which are function arguments, vector
  12488. components, etc., are formatted with precedence zero (so that they
  12489. normally never get additional parentheses).
  12490. For binary left-associative operators like @samp{+}, the righthand
  12491. argument is actually formatted with one-higher precedence than shown
  12492. in the table. This makes sure @samp{(a + b) + c} omits the parentheses,
  12493. but the unnatural form @samp{a + (b + c)} keeps its parentheses.
  12494. Right-associative operators like @samp{^} format the lefthand argument
  12495. with one-higher precedence.
  12496. @ignore
  12497. @starindex
  12498. @end ignore
  12499. @tindex cprec
  12500. The @code{cprec} function formats an expression with an arbitrary
  12501. precedence. For example, @samp{cprec(abc, 185)} will combine into
  12502. sums and products as follows: @samp{7 + abc}, @samp{7 (abc)} (because
  12503. this @code{cprec} form has higher precedence than addition, but lower
  12504. precedence than multiplication).
  12505. @tex
  12506. \bigskip
  12507. @end tex
  12508. A final composition issue is @dfn{line breaking}. Calc uses two
  12509. different strategies for ``flat'' and ``non-flat'' compositions.
  12510. A non-flat composition is anything that appears on multiple lines
  12511. (not counting line breaking). Examples would be matrices and Big
  12512. mode powers and quotients. Non-flat compositions are displayed
  12513. exactly as specified. If they come out wider than the current
  12514. window, you must use horizontal scrolling (@kbd{<} and @kbd{>}) to
  12515. view them.
  12516. Flat compositions, on the other hand, will be broken across several
  12517. lines if they are too wide to fit the window. Certain points in a
  12518. composition are noted internally as @dfn{break points}. Calc's
  12519. general strategy is to fill each line as much as possible, then to
  12520. move down to the next line starting at the first break point that
  12521. didn't fit. However, the line breaker understands the hierarchical
  12522. structure of formulas. It will not break an ``inner'' formula if
  12523. it can use an earlier break point from an ``outer'' formula instead.
  12524. For example, a vector of sums might be formatted as:
  12525. @example
  12526. @group
  12527. [ a + b + c, d + e + f,
  12528. g + h + i, j + k + l, m ]
  12529. @end group
  12530. @end example
  12531. @noindent
  12532. If the @samp{m} can fit, then so, it seems, could the @samp{g}.
  12533. But Calc prefers to break at the comma since the comma is part
  12534. of a ``more outer'' formula. Calc would break at a plus sign
  12535. only if it had to, say, if the very first sum in the vector had
  12536. itself been too large to fit.
  12537. Of the composition functions described below, only @code{choriz}
  12538. generates break points. The @code{bstring} function (@pxref{Strings})
  12539. also generates breakable items: A break point is added after every
  12540. space (or group of spaces) except for spaces at the very beginning or
  12541. end of the string.
  12542. Composition functions themselves count as levels in the formula
  12543. hierarchy, so a @code{choriz} that is a component of a larger
  12544. @code{choriz} will be less likely to be broken. As a special case,
  12545. if a @code{bstring} occurs as a component of a @code{choriz} or
  12546. @code{choriz}-like object (such as a vector or a list of arguments
  12547. in a function call), then the break points in that @code{bstring}
  12548. will be on the same level as the break points of the surrounding
  12549. object.
  12550. @node Horizontal Compositions, Vertical Compositions, Composition Basics, Compositions
  12551. @subsubsection Horizontal Compositions
  12552. @noindent
  12553. @ignore
  12554. @starindex
  12555. @end ignore
  12556. @tindex choriz
  12557. The @code{choriz} function takes a vector of objects and composes
  12558. them horizontally. For example, @samp{choriz([17, a b/c, d])} formats
  12559. as @w{@samp{17a b / cd}} in Normal language mode, or as
  12560. @example
  12561. @group
  12562. a b
  12563. 17---d
  12564. c
  12565. @end group
  12566. @end example
  12567. @noindent
  12568. in Big language mode. This is actually one case of the general
  12569. function @samp{choriz(@var{vec}, @var{sep}, @var{prec})}, where
  12570. either or both of @var{sep} and @var{prec} may be omitted.
  12571. @var{Prec} gives the @dfn{precedence} to use when formatting
  12572. each of the components of @var{vec}. The default precedence is
  12573. the precedence from the surrounding environment.
  12574. @var{Sep} is a string (i.e., a vector of character codes as might
  12575. be entered with @code{" "} notation) which should separate components
  12576. of the composition. Also, if @var{sep} is given, the line breaker
  12577. will allow lines to be broken after each occurrence of @var{sep}.
  12578. If @var{sep} is omitted, the composition will not be breakable
  12579. (unless any of its component compositions are breakable).
  12580. For example, @samp{2 choriz([a, b c, d = e], " + ", 180)} is
  12581. formatted as @samp{2 a + b c + (d = e)}. To get the @code{choriz}
  12582. to have precedence 180 ``outwards'' as well as ``inwards,''
  12583. enclose it in a @code{cprec} form: @samp{2 cprec(choriz(...), 180)}
  12584. formats as @samp{2 (a + b c + (d = e))}.
  12585. The baseline of a horizontal composition is the same as the
  12586. baselines of the component compositions, which are all aligned.
  12587. @node Vertical Compositions, Other Compositions, Horizontal Compositions, Compositions
  12588. @subsubsection Vertical Compositions
  12589. @noindent
  12590. @ignore
  12591. @starindex
  12592. @end ignore
  12593. @tindex cvert
  12594. The @code{cvert} function makes a vertical composition. Each
  12595. component of the vector is centered in a column. The baseline of
  12596. the result is by default the top line of the resulting composition.
  12597. For example, @samp{f(cvert([a, bb, ccc]), cvert([a^2 + 1, b^2]))}
  12598. formats in Big mode as
  12599. @example
  12600. @group
  12601. f( a , 2 )
  12602. bb a + 1
  12603. ccc 2
  12604. b
  12605. @end group
  12606. @end example
  12607. @ignore
  12608. @starindex
  12609. @end ignore
  12610. @tindex cbase
  12611. There are several special composition functions that work only as
  12612. components of a vertical composition. The @code{cbase} function
  12613. controls the baseline of the vertical composition; the baseline
  12614. will be the same as the baseline of whatever component is enclosed
  12615. in @code{cbase}. Thus @samp{f(cvert([a, cbase(bb), ccc]),
  12616. cvert([a^2 + 1, cbase(b^2)]))} displays as
  12617. @example
  12618. @group
  12619. 2
  12620. a + 1
  12621. a 2
  12622. f(bb , b )
  12623. ccc
  12624. @end group
  12625. @end example
  12626. @ignore
  12627. @starindex
  12628. @end ignore
  12629. @tindex ctbase
  12630. @ignore
  12631. @starindex
  12632. @end ignore
  12633. @tindex cbbase
  12634. There are also @code{ctbase} and @code{cbbase} functions which
  12635. make the baseline of the vertical composition equal to the top
  12636. or bottom line (rather than the baseline) of that component.
  12637. Thus @samp{cvert([cbase(a / b)]) + cvert([ctbase(a / b)]) +
  12638. cvert([cbbase(a / b)])} gives
  12639. @example
  12640. @group
  12641. a
  12642. a -
  12643. - + a + b
  12644. b -
  12645. b
  12646. @end group
  12647. @end example
  12648. There should be only one @code{cbase}, @code{ctbase}, or @code{cbbase}
  12649. function in a given vertical composition. These functions can also
  12650. be written with no arguments: @samp{ctbase()} is a zero-height object
  12651. which means the baseline is the top line of the following item, and
  12652. @samp{cbbase()} means the baseline is the bottom line of the preceding
  12653. item.
  12654. @ignore
  12655. @starindex
  12656. @end ignore
  12657. @tindex crule
  12658. The @code{crule} function builds a ``rule,'' or horizontal line,
  12659. across a vertical composition. By itself @samp{crule()} uses @samp{-}
  12660. characters to build the rule. You can specify any other character,
  12661. e.g., @samp{crule("=")}. The argument must be a character code or
  12662. vector of exactly one character code. It is repeated to match the
  12663. width of the widest item in the stack. For example, a quotient
  12664. with a thick line is @samp{cvert([a + 1, cbase(crule("=")), b^2])}:
  12665. @example
  12666. @group
  12667. a + 1
  12668. =====
  12669. 2
  12670. b
  12671. @end group
  12672. @end example
  12673. @ignore
  12674. @starindex
  12675. @end ignore
  12676. @tindex clvert
  12677. @ignore
  12678. @starindex
  12679. @end ignore
  12680. @tindex crvert
  12681. Finally, the functions @code{clvert} and @code{crvert} act exactly
  12682. like @code{cvert} except that the items are left- or right-justified
  12683. in the stack. Thus @samp{clvert([a, bb, ccc]) + crvert([a, bb, ccc])}
  12684. gives:
  12685. @example
  12686. @group
  12687. a + a
  12688. bb bb
  12689. ccc ccc
  12690. @end group
  12691. @end example
  12692. Like @code{choriz}, the vertical compositions accept a second argument
  12693. which gives the precedence to use when formatting the components.
  12694. Vertical compositions do not support separator strings.
  12695. @node Other Compositions, Information about Compositions, Vertical Compositions, Compositions
  12696. @subsubsection Other Compositions
  12697. @noindent
  12698. @ignore
  12699. @starindex
  12700. @end ignore
  12701. @tindex csup
  12702. The @code{csup} function builds a superscripted expression. For
  12703. example, @samp{csup(a, b)} looks the same as @samp{a^b} does in Big
  12704. language mode. This is essentially a horizontal composition of
  12705. @samp{a} and @samp{b}, where @samp{b} is shifted up so that its
  12706. bottom line is one above the baseline.
  12707. @ignore
  12708. @starindex
  12709. @end ignore
  12710. @tindex csub
  12711. Likewise, the @code{csub} function builds a subscripted expression.
  12712. This shifts @samp{b} down so that its top line is one below the
  12713. bottom line of @samp{a} (note that this is not quite analogous to
  12714. @code{csup}). Other arrangements can be obtained by using
  12715. @code{choriz} and @code{cvert} directly.
  12716. @ignore
  12717. @starindex
  12718. @end ignore
  12719. @tindex cflat
  12720. The @code{cflat} function formats its argument in ``flat'' mode,
  12721. as obtained by @samp{d O}, if the current language mode is normal
  12722. or Big. It has no effect in other language modes. For example,
  12723. @samp{a^(b/c)} is formatted by Big mode like @samp{csup(a, cflat(b/c))}
  12724. to improve its readability.
  12725. @ignore
  12726. @starindex
  12727. @end ignore
  12728. @tindex cspace
  12729. The @code{cspace} function creates horizontal space. For example,
  12730. @samp{cspace(4)} is effectively the same as @samp{string(" ")}.
  12731. A second string (i.e., vector of characters) argument is repeated
  12732. instead of the space character. For example, @samp{cspace(4, "ab")}
  12733. looks like @samp{abababab}. If the second argument is not a string,
  12734. it is formatted in the normal way and then several copies of that
  12735. are composed together: @samp{cspace(4, a^2)} yields
  12736. @example
  12737. @group
  12738. 2 2 2 2
  12739. a a a a
  12740. @end group
  12741. @end example
  12742. @noindent
  12743. If the number argument is zero, this is a zero-width object.
  12744. @ignore
  12745. @starindex
  12746. @end ignore
  12747. @tindex cvspace
  12748. The @code{cvspace} function creates vertical space, or a vertical
  12749. stack of copies of a certain string or formatted object. The
  12750. baseline is the center line of the resulting stack. A numerical
  12751. argument of zero will produce an object which contributes zero
  12752. height if used in a vertical composition.
  12753. @ignore
  12754. @starindex
  12755. @end ignore
  12756. @tindex ctspace
  12757. @ignore
  12758. @starindex
  12759. @end ignore
  12760. @tindex cbspace
  12761. There are also @code{ctspace} and @code{cbspace} functions which
  12762. create vertical space with the baseline the same as the baseline
  12763. of the top or bottom copy, respectively, of the second argument.
  12764. Thus @samp{cvspace(2, a/b) + ctspace(2, a/b) + cbspace(2, a/b)}
  12765. displays as:
  12766. @example
  12767. @group
  12768. a
  12769. -
  12770. a b
  12771. - a a
  12772. b + - + -
  12773. a b b
  12774. - a
  12775. b -
  12776. b
  12777. @end group
  12778. @end example
  12779. @node Information about Compositions, User-Defined Compositions, Other Compositions, Compositions
  12780. @subsubsection Information about Compositions
  12781. @noindent
  12782. The functions in this section are actual functions; they compose their
  12783. arguments according to the current language and other display modes,
  12784. then return a certain measurement of the composition as an integer.
  12785. @ignore
  12786. @starindex
  12787. @end ignore
  12788. @tindex cwidth
  12789. The @code{cwidth} function measures the width, in characters, of a
  12790. composition. For example, @samp{cwidth(a + b)} is 5, and
  12791. @samp{cwidth(a / b)} is 5 in Normal mode, 1 in Big mode, and 11 in
  12792. @TeX{} mode (for @samp{@{a \over b@}}). The argument may involve
  12793. the composition functions described in this section.
  12794. @ignore
  12795. @starindex
  12796. @end ignore
  12797. @tindex cheight
  12798. The @code{cheight} function measures the height of a composition.
  12799. This is the total number of lines in the argument's printed form.
  12800. @ignore
  12801. @starindex
  12802. @end ignore
  12803. @tindex cascent
  12804. @ignore
  12805. @starindex
  12806. @end ignore
  12807. @tindex cdescent
  12808. The functions @code{cascent} and @code{cdescent} measure the amount
  12809. of the height that is above (and including) the baseline, or below
  12810. the baseline, respectively. Thus @samp{cascent(@var{x}) + cdescent(@var{x})}
  12811. always equals @samp{cheight(@var{x})}. For a one-line formula like
  12812. @samp{a + b}, @code{cascent} returns 1 and @code{cdescent} returns 0.
  12813. For @samp{a / b} in Big mode, @code{cascent} returns 2 and @code{cdescent}
  12814. returns 1. The only formula for which @code{cascent} will return zero
  12815. is @samp{cvspace(0)} or equivalents.
  12816. @node User-Defined Compositions, , Information about Compositions, Compositions
  12817. @subsubsection User-Defined Compositions
  12818. @noindent
  12819. @kindex Z C
  12820. @pindex calc-user-define-composition
  12821. The @kbd{Z C} (@code{calc-user-define-composition}) command lets you
  12822. define the display format for any algebraic function. You provide a
  12823. formula containing a certain number of argument variables on the stack.
  12824. Any time Calc formats a call to the specified function in the current
  12825. language mode and with that number of arguments, Calc effectively
  12826. replaces the function call with that formula with the arguments
  12827. replaced.
  12828. Calc builds the default argument list by sorting all the variable names
  12829. that appear in the formula into alphabetical order. You can edit this
  12830. argument list before pressing @key{RET} if you wish. Any variables in
  12831. the formula that do not appear in the argument list will be displayed
  12832. literally; any arguments that do not appear in the formula will not
  12833. affect the display at all.
  12834. You can define formats for built-in functions, for functions you have
  12835. defined with @kbd{Z F} (@pxref{Algebraic Definitions}), or for functions
  12836. which have no definitions but are being used as purely syntactic objects.
  12837. You can define different formats for each language mode, and for each
  12838. number of arguments, using a succession of @kbd{Z C} commands. When
  12839. Calc formats a function call, it first searches for a format defined
  12840. for the current language mode (and number of arguments); if there is
  12841. none, it uses the format defined for the Normal language mode. If
  12842. neither format exists, Calc uses its built-in standard format for that
  12843. function (usually just @samp{@var{func}(@var{args})}).
  12844. If you execute @kbd{Z C} with the number 0 on the stack instead of a
  12845. formula, any defined formats for the function in the current language
  12846. mode will be removed. The function will revert to its standard format.
  12847. For example, the default format for the binomial coefficient function
  12848. @samp{choose(n, m)} in the Big language mode is
  12849. @example
  12850. @group
  12851. n
  12852. ( )
  12853. m
  12854. @end group
  12855. @end example
  12856. @noindent
  12857. You might prefer the notation,
  12858. @example
  12859. @group
  12860. C
  12861. n m
  12862. @end group
  12863. @end example
  12864. @noindent
  12865. To define this notation, first make sure you are in Big mode,
  12866. then put the formula
  12867. @smallexample
  12868. choriz([cvert([cvspace(1), n]), C, cvert([cvspace(1), m])])
  12869. @end smallexample
  12870. @noindent
  12871. on the stack and type @kbd{Z C}. Answer the first prompt with
  12872. @code{choose}. The second prompt will be the default argument list
  12873. of @samp{(C m n)}. Edit this list to be @samp{(n m)} and press
  12874. @key{RET}. Now, try it out: For example, turn simplification
  12875. off with @kbd{m O} and enter @samp{choose(a,b) + choose(7,3)}
  12876. as an algebraic entry.
  12877. @example
  12878. @group
  12879. C + C
  12880. a b 7 3
  12881. @end group
  12882. @end example
  12883. As another example, let's define the usual notation for Stirling
  12884. numbers of the first kind, @samp{stir1(n, m)}. This is just like
  12885. the regular format for binomial coefficients but with square brackets
  12886. instead of parentheses.
  12887. @smallexample
  12888. choriz([string("["), cvert([n, cbase(cvspace(1)), m]), string("]")])
  12889. @end smallexample
  12890. Now type @kbd{Z C stir1 @key{RET}}, edit the argument list to
  12891. @samp{(n m)}, and type @key{RET}.
  12892. The formula provided to @kbd{Z C} usually will involve composition
  12893. functions, but it doesn't have to. Putting the formula @samp{a + b + c}
  12894. onto the stack and typing @kbd{Z C foo @key{RET} @key{RET}} would define
  12895. the function @samp{foo(x,y,z)} to display like @samp{x + y + z}.
  12896. This ``sum'' will act exactly like a real sum for all formatting
  12897. purposes (it will be parenthesized the same, and so on). However
  12898. it will be computationally unrelated to a sum. For example, the
  12899. formula @samp{2 * foo(1, 2, 3)} will display as @samp{2 (1 + 2 + 3)}.
  12900. Operator precedences have caused the ``sum'' to be written in
  12901. parentheses, but the arguments have not actually been summed.
  12902. (Generally a display format like this would be undesirable, since
  12903. it can easily be confused with a real sum.)
  12904. The special function @code{eval} can be used inside a @kbd{Z C}
  12905. composition formula to cause all or part of the formula to be
  12906. evaluated at display time. For example, if the formula is
  12907. @samp{a + eval(b + c)}, then @samp{foo(1, 2, 3)} will be displayed
  12908. as @samp{1 + 5}. Evaluation will use the default simplifications,
  12909. regardless of the current simplification mode. There are also
  12910. @code{evalsimp} and @code{evalextsimp} which simplify as if by
  12911. @kbd{a s} and @kbd{a e} (respectively). Note that these ``functions''
  12912. operate only in the context of composition formulas (and also in
  12913. rewrite rules, where they serve a similar purpose; @pxref{Rewrite
  12914. Rules}). On the stack, a call to @code{eval} will be left in
  12915. symbolic form.
  12916. It is not a good idea to use @code{eval} except as a last resort.
  12917. It can cause the display of formulas to be extremely slow. For
  12918. example, while @samp{eval(a + b)} might seem quite fast and simple,
  12919. there are several situations where it could be slow. For example,
  12920. @samp{a} and/or @samp{b} could be polar complex numbers, in which
  12921. case doing the sum requires trigonometry. Or, @samp{a} could be
  12922. the factorial @samp{fact(100)} which is unevaluated because you
  12923. have typed @kbd{m O}; @code{eval} will evaluate it anyway to
  12924. produce a large, unwieldy integer.
  12925. You can save your display formats permanently using the @kbd{Z P}
  12926. command (@pxref{Creating User Keys}).
  12927. @node Syntax Tables, , Compositions, Language Modes
  12928. @subsection Syntax Tables
  12929. @noindent
  12930. @cindex Syntax tables
  12931. @cindex Parsing formulas, customized
  12932. Syntax tables do for input what compositions do for output: They
  12933. allow you to teach custom notations to Calc's formula parser.
  12934. Calc keeps a separate syntax table for each language mode.
  12935. (Note that the Calc ``syntax tables'' discussed here are completely
  12936. unrelated to the syntax tables described in the Emacs manual.)
  12937. @kindex Z S
  12938. @pindex calc-edit-user-syntax
  12939. The @kbd{Z S} (@code{calc-edit-user-syntax}) command edits the
  12940. syntax table for the current language mode. If you want your
  12941. syntax to work in any language, define it in the Normal language
  12942. mode. Type @kbd{C-c C-c} to finish editing the syntax table, or
  12943. @kbd{C-x k} to cancel the edit. The @kbd{m m} command saves all
  12944. the syntax tables along with the other mode settings;
  12945. @pxref{General Mode Commands}.
  12946. @menu
  12947. * Syntax Table Basics::
  12948. * Precedence in Syntax Tables::
  12949. * Advanced Syntax Patterns::
  12950. * Conditional Syntax Rules::
  12951. @end menu
  12952. @node Syntax Table Basics, Precedence in Syntax Tables, Syntax Tables, Syntax Tables
  12953. @subsubsection Syntax Table Basics
  12954. @noindent
  12955. @dfn{Parsing} is the process of converting a raw string of characters,
  12956. such as you would type in during algebraic entry, into a Calc formula.
  12957. Calc's parser works in two stages. First, the input is broken down
  12958. into @dfn{tokens}, such as words, numbers, and punctuation symbols
  12959. like @samp{+}, @samp{:=}, and @samp{+/-}. Space between tokens is
  12960. ignored (except when it serves to separate adjacent words). Next,
  12961. the parser matches this string of tokens against various built-in
  12962. syntactic patterns, such as ``an expression followed by @samp{+}
  12963. followed by another expression'' or ``a name followed by @samp{(},
  12964. zero or more expressions separated by commas, and @samp{)}.''
  12965. A @dfn{syntax table} is a list of user-defined @dfn{syntax rules},
  12966. which allow you to specify new patterns to define your own
  12967. favorite input notations. Calc's parser always checks the syntax
  12968. table for the current language mode, then the table for the Normal
  12969. language mode, before it uses its built-in rules to parse an
  12970. algebraic formula you have entered. Each syntax rule should go on
  12971. its own line; it consists of a @dfn{pattern}, a @samp{:=} symbol,
  12972. and a Calc formula with an optional @dfn{condition}. (Syntax rules
  12973. resemble algebraic rewrite rules, but the notation for patterns is
  12974. completely different.)
  12975. A syntax pattern is a list of tokens, separated by spaces.
  12976. Except for a few special symbols, tokens in syntax patterns are
  12977. matched literally, from left to right. For example, the rule,
  12978. @example
  12979. foo ( ) := 2+3
  12980. @end example
  12981. @noindent
  12982. would cause Calc to parse the formula @samp{4+foo()*5} as if it
  12983. were @samp{4+(2+3)*5}. Notice that the parentheses were written
  12984. as two separate tokens in the rule. As a result, the rule works
  12985. for both @samp{foo()} and @w{@samp{foo ( )}}. If we had written
  12986. the rule as @samp{foo () := 2+3}, then Calc would treat @samp{()}
  12987. as a single, indivisible token, so that @w{@samp{foo( )}} would
  12988. not be recognized by the rule. (It would be parsed as a regular
  12989. zero-argument function call instead.) In fact, this rule would
  12990. also make trouble for the rest of Calc's parser: An unrelated
  12991. formula like @samp{bar()} would now be tokenized into @samp{bar ()}
  12992. instead of @samp{bar ( )}, so that the standard parser for function
  12993. calls would no longer recognize it!
  12994. While it is possible to make a token with a mixture of letters
  12995. and punctuation symbols, this is not recommended. It is better to
  12996. break it into several tokens, as we did with @samp{foo()} above.
  12997. The symbol @samp{#} in a syntax pattern matches any Calc expression.
  12998. On the righthand side, the things that matched the @samp{#}s can
  12999. be referred to as @samp{#1}, @samp{#2}, and so on (where @samp{#1}
  13000. matches the leftmost @samp{#} in the pattern). For example, these
  13001. rules match a user-defined function, prefix operator, infix operator,
  13002. and postfix operator, respectively:
  13003. @example
  13004. foo ( # ) := myfunc(#1)
  13005. foo # := myprefix(#1)
  13006. # foo # := myinfix(#1,#2)
  13007. # foo := mypostfix(#1)
  13008. @end example
  13009. Thus @samp{foo(3)} will parse as @samp{myfunc(3)}, and @samp{2+3 foo}
  13010. will parse as @samp{mypostfix(2+3)}.
  13011. It is important to write the first two rules in the order shown,
  13012. because Calc tries rules in order from first to last. If the
  13013. pattern @samp{foo #} came first, it would match anything that could
  13014. match the @samp{foo ( # )} rule, since an expression in parentheses
  13015. is itself a valid expression. Thus the @w{@samp{foo ( # )}} rule would
  13016. never get to match anything. Likewise, the last two rules must be
  13017. written in the order shown or else @samp{3 foo 4} will be parsed as
  13018. @samp{mypostfix(3) * 4}. (Of course, the best way to avoid these
  13019. ambiguities is not to use the same symbol in more than one way at
  13020. the same time! In case you're not convinced, try the following
  13021. exercise: How will the above rules parse the input @samp{foo(3,4)},
  13022. if at all? Work it out for yourself, then try it in Calc and see.)
  13023. Calc is quite flexible about what sorts of patterns are allowed.
  13024. The only rule is that every pattern must begin with a literal
  13025. token (like @samp{foo} in the first two patterns above), or with
  13026. a @samp{#} followed by a literal token (as in the last two
  13027. patterns). After that, any mixture is allowed, although putting
  13028. two @samp{#}s in a row will not be very useful since two
  13029. expressions with nothing between them will be parsed as one
  13030. expression that uses implicit multiplication.
  13031. As a more practical example, Maple uses the notation
  13032. @samp{sum(a(i), i=1..10)} for sums, which Calc's Maple mode doesn't
  13033. recognize at present. To handle this syntax, we simply add the
  13034. rule,
  13035. @example
  13036. sum ( # , # = # .. # ) := sum(#1,#2,#3,#4)
  13037. @end example
  13038. @noindent
  13039. to the Maple mode syntax table. As another example, C mode can't
  13040. read assignment operators like @samp{++} and @samp{*=}. We can
  13041. define these operators quite easily:
  13042. @example
  13043. # *= # := muleq(#1,#2)
  13044. # ++ := postinc(#1)
  13045. ++ # := preinc(#1)
  13046. @end example
  13047. @noindent
  13048. To complete the job, we would use corresponding composition functions
  13049. and @kbd{Z C} to cause these functions to display in their respective
  13050. Maple and C notations. (Note that the C example ignores issues of
  13051. operator precedence, which are discussed in the next section.)
  13052. You can enclose any token in quotes to prevent its usual
  13053. interpretation in syntax patterns:
  13054. @example
  13055. # ":=" # := becomes(#1,#2)
  13056. @end example
  13057. Quotes also allow you to include spaces in a token, although once
  13058. again it is generally better to use two tokens than one token with
  13059. an embedded space. To include an actual quotation mark in a quoted
  13060. token, precede it with a backslash. (This also works to include
  13061. backslashes in tokens.)
  13062. @example
  13063. # "bad token" # "/\"\\" # := silly(#1,#2,#3)
  13064. @end example
  13065. @noindent
  13066. This will parse @samp{3 bad token 4 /"\ 5} to @samp{silly(3,4,5)}.
  13067. The token @kbd{#} has a predefined meaning in Calc's formula parser;
  13068. it is not valid to use @samp{"#"} in a syntax rule. However, longer
  13069. tokens that include the @samp{#} character are allowed. Also, while
  13070. @samp{"$"} and @samp{"\""} are allowed as tokens, their presence in
  13071. the syntax table will prevent those characters from working in their
  13072. usual ways (referring to stack entries and quoting strings,
  13073. respectively).
  13074. Finally, the notation @samp{%%} anywhere in a syntax table causes
  13075. the rest of the line to be ignored as a comment.
  13076. @node Precedence in Syntax Tables, Advanced Syntax Patterns, Syntax Table Basics, Syntax Tables
  13077. @subsubsection Precedence
  13078. @noindent
  13079. Different operators are generally assigned different @dfn{precedences}.
  13080. By default, an operator defined by a rule like
  13081. @example
  13082. # foo # := foo(#1,#2)
  13083. @end example
  13084. @noindent
  13085. will have an extremely low precedence, so that @samp{2*3+4 foo 5 == 6}
  13086. will be parsed as @samp{(2*3+4) foo (5 == 6)}. To change the
  13087. precedence of an operator, use the notation @samp{#/@var{p}} in
  13088. place of @samp{#}, where @var{p} is an integer precedence level.
  13089. For example, 185 lies between the precedences for @samp{+} and
  13090. @samp{*}, so if we change this rule to
  13091. @example
  13092. #/185 foo #/186 := foo(#1,#2)
  13093. @end example
  13094. @noindent
  13095. then @samp{2+3 foo 4*5} will be parsed as @samp{2+(3 foo (4*5))}.
  13096. Also, because we've given the righthand expression slightly higher
  13097. precedence, our new operator will be left-associative:
  13098. @samp{1 foo 2 foo 3} will be parsed as @samp{(1 foo 2) foo 3}.
  13099. By raising the precedence of the lefthand expression instead, we
  13100. can create a right-associative operator.
  13101. @xref{Composition Basics}, for a table of precedences of the
  13102. standard Calc operators. For the precedences of operators in other
  13103. language modes, look in the Calc source file @file{calc-lang.el}.
  13104. @node Advanced Syntax Patterns, Conditional Syntax Rules, Precedence in Syntax Tables, Syntax Tables
  13105. @subsubsection Advanced Syntax Patterns
  13106. @noindent
  13107. To match a function with a variable number of arguments, you could
  13108. write
  13109. @example
  13110. foo ( # ) := myfunc(#1)
  13111. foo ( # , # ) := myfunc(#1,#2)
  13112. foo ( # , # , # ) := myfunc(#1,#2,#3)
  13113. @end example
  13114. @noindent
  13115. but this isn't very elegant. To match variable numbers of items,
  13116. Calc uses some notations inspired regular expressions and the
  13117. ``extended BNF'' style used by some language designers.
  13118. @example
  13119. foo ( @{ # @}*, ) := apply(myfunc,#1)
  13120. @end example
  13121. The token @samp{@{} introduces a repeated or optional portion.
  13122. One of the three tokens @samp{@}*}, @samp{@}+}, or @samp{@}?}
  13123. ends the portion. These will match zero or more, one or more,
  13124. or zero or one copies of the enclosed pattern, respectively.
  13125. In addition, @samp{@}*} and @samp{@}+} can be followed by a
  13126. separator token (with no space in between, as shown above).
  13127. Thus @samp{@{ # @}*,} matches nothing, or one expression, or
  13128. several expressions separated by commas.
  13129. A complete @samp{@{ ... @}} item matches as a vector of the
  13130. items that matched inside it. For example, the above rule will
  13131. match @samp{foo(1,2,3)} to get @samp{apply(myfunc,[1,2,3])}.
  13132. The Calc @code{apply} function takes a function name and a vector
  13133. of arguments and builds a call to the function with those
  13134. arguments, so the net result is the formula @samp{myfunc(1,2,3)}.
  13135. If the body of a @samp{@{ ... @}} contains several @samp{#}s
  13136. (or nested @samp{@{ ... @}} constructs), then the items will be
  13137. strung together into the resulting vector. If the body
  13138. does not contain anything but literal tokens, the result will
  13139. always be an empty vector.
  13140. @example
  13141. foo ( @{ # , # @}+, ) := bar(#1)
  13142. foo ( @{ @{ # @}*, @}*; ) := matrix(#1)
  13143. @end example
  13144. @noindent
  13145. will parse @samp{foo(1, 2, 3, 4)} as @samp{bar([1, 2, 3, 4])}, and
  13146. @samp{foo(1, 2; 3, 4)} as @samp{matrix([[1, 2], [3, 4]])}. Also, after
  13147. some thought it's easy to see how this pair of rules will parse
  13148. @samp{foo(1, 2, 3)} as @samp{matrix([[1, 2, 3]])}, since the first
  13149. rule will only match an even number of arguments. The rule
  13150. @example
  13151. foo ( # @{ , # , # @}? ) := bar(#1,#2)
  13152. @end example
  13153. @noindent
  13154. will parse @samp{foo(2,3,4)} as @samp{bar(2,[3,4])}, and
  13155. @samp{foo(2)} as @samp{bar(2,[])}.
  13156. The notation @samp{@{ ... @}?.} (note the trailing period) works
  13157. just the same as regular @samp{@{ ... @}?}, except that it does not
  13158. count as an argument; the following two rules are equivalent:
  13159. @example
  13160. foo ( # , @{ also @}? # ) := bar(#1,#3)
  13161. foo ( # , @{ also @}?. # ) := bar(#1,#2)
  13162. @end example
  13163. @noindent
  13164. Note that in the first case the optional text counts as @samp{#2},
  13165. which will always be an empty vector, but in the second case no
  13166. empty vector is produced.
  13167. Another variant is @samp{@{ ... @}?$}, which means the body is
  13168. optional only at the end of the input formula. All built-in syntax
  13169. rules in Calc use this for closing delimiters, so that during
  13170. algebraic entry you can type @kbd{[sqrt(2), sqrt(3 @key{RET}}, omitting
  13171. the closing parenthesis and bracket. Calc does this automatically
  13172. for trailing @samp{)}, @samp{]}, and @samp{>} tokens in syntax
  13173. rules, but you can use @samp{@{ ... @}?$} explicitly to get
  13174. this effect with any token (such as @samp{"@}"} or @samp{end}).
  13175. Like @samp{@{ ... @}?.}, this notation does not count as an
  13176. argument. Conversely, you can use quotes, as in @samp{")"}, to
  13177. prevent a closing-delimiter token from being automatically treated
  13178. as optional.
  13179. Calc's parser does not have full backtracking, which means some
  13180. patterns will not work as you might expect:
  13181. @example
  13182. foo ( @{ # , @}? # , # ) := bar(#1,#2,#3)
  13183. @end example
  13184. @noindent
  13185. Here we are trying to make the first argument optional, so that
  13186. @samp{foo(2,3)} parses as @samp{bar([],2,3)}. Unfortunately, Calc
  13187. first tries to match @samp{2,} against the optional part of the
  13188. pattern, finds a match, and so goes ahead to match the rest of the
  13189. pattern. Later on it will fail to match the second comma, but it
  13190. doesn't know how to go back and try the other alternative at that
  13191. point. One way to get around this would be to use two rules:
  13192. @example
  13193. foo ( # , # , # ) := bar([#1],#2,#3)
  13194. foo ( # , # ) := bar([],#1,#2)
  13195. @end example
  13196. More precisely, when Calc wants to match an optional or repeated
  13197. part of a pattern, it scans forward attempting to match that part.
  13198. If it reaches the end of the optional part without failing, it
  13199. ``finalizes'' its choice and proceeds. If it fails, though, it
  13200. backs up and tries the other alternative. Thus Calc has ``partial''
  13201. backtracking. A fully backtracking parser would go on to make sure
  13202. the rest of the pattern matched before finalizing the choice.
  13203. @node Conditional Syntax Rules, , Advanced Syntax Patterns, Syntax Tables
  13204. @subsubsection Conditional Syntax Rules
  13205. @noindent
  13206. It is possible to attach a @dfn{condition} to a syntax rule. For
  13207. example, the rules
  13208. @example
  13209. foo ( # ) := ifoo(#1) :: integer(#1)
  13210. foo ( # ) := gfoo(#1)
  13211. @end example
  13212. @noindent
  13213. will parse @samp{foo(3)} as @samp{ifoo(3)}, but will parse
  13214. @samp{foo(3.5)} and @samp{foo(x)} as calls to @code{gfoo}. Any
  13215. number of conditions may be attached; all must be true for the
  13216. rule to succeed. A condition is ``true'' if it evaluates to a
  13217. nonzero number. @xref{Logical Operations}, for a list of Calc
  13218. functions like @code{integer} that perform logical tests.
  13219. The exact sequence of events is as follows: When Calc tries a
  13220. rule, it first matches the pattern as usual. It then substitutes
  13221. @samp{#1}, @samp{#2}, etc., in the conditions, if any. Next, the
  13222. conditions are simplified and evaluated in order from left to right,
  13223. using the algebraic simplifications (@pxref{Simplifying Formulas}).
  13224. Each result is true if it is a nonzero number, or an expression
  13225. that can be proven to be nonzero (@pxref{Declarations}). If the
  13226. results of all conditions are true, the expression (such as
  13227. @samp{ifoo(#1)}) has its @samp{#}s substituted, and that is the
  13228. result of the parse. If the result of any condition is false, Calc
  13229. goes on to try the next rule in the syntax table.
  13230. Syntax rules also support @code{let} conditions, which operate in
  13231. exactly the same way as they do in algebraic rewrite rules.
  13232. @xref{Other Features of Rewrite Rules}, for details. A @code{let}
  13233. condition is always true, but as a side effect it defines a
  13234. variable which can be used in later conditions, and also in the
  13235. expression after the @samp{:=} sign:
  13236. @example
  13237. foo ( # ) := hifoo(x) :: let(x := #1 + 0.5) :: dnumint(x)
  13238. @end example
  13239. @noindent
  13240. The @code{dnumint} function tests if a value is numerically an
  13241. integer, i.e., either a true integer or an integer-valued float.
  13242. This rule will parse @code{foo} with a half-integer argument,
  13243. like @samp{foo(3.5)}, to a call like @samp{hifoo(4.)}.
  13244. The lefthand side of a syntax rule @code{let} must be a simple
  13245. variable, not the arbitrary pattern that is allowed in rewrite
  13246. rules.
  13247. The @code{matches} function is also treated specially in syntax
  13248. rule conditions (again, in the same way as in rewrite rules).
  13249. @xref{Matching Commands}. If the matching pattern contains
  13250. meta-variables, then those meta-variables may be used in later
  13251. conditions and in the result expression. The arguments to
  13252. @code{matches} are not evaluated in this situation.
  13253. @example
  13254. sum ( # , # ) := sum(#1,a,b,c) :: matches(#2, a=[b..c])
  13255. @end example
  13256. @noindent
  13257. This is another way to implement the Maple mode @code{sum} notation.
  13258. In this approach, we allow @samp{#2} to equal the whole expression
  13259. @samp{i=1..10}. Then, we use @code{matches} to break it apart into
  13260. its components. If the expression turns out not to match the pattern,
  13261. the syntax rule will fail. Note that @kbd{Z S} always uses Calc's
  13262. Normal language mode for editing expressions in syntax rules, so we
  13263. must use regular Calc notation for the interval @samp{[b..c]} that
  13264. will correspond to the Maple mode interval @samp{1..10}.
  13265. @node Modes Variable, Calc Mode Line, Language Modes, Mode Settings
  13266. @section The @code{Modes} Variable
  13267. @noindent
  13268. @kindex m g
  13269. @pindex calc-get-modes
  13270. The @kbd{m g} (@code{calc-get-modes}) command pushes onto the stack
  13271. a vector of numbers that describes the various mode settings that
  13272. are in effect. With a numeric prefix argument, it pushes only the
  13273. @var{n}th mode, i.e., the @var{n}th element of this vector. Keyboard
  13274. macros can use the @kbd{m g} command to modify their behavior based
  13275. on the current mode settings.
  13276. @cindex @code{Modes} variable
  13277. @vindex Modes
  13278. The modes vector is also available in the special variable
  13279. @code{Modes}. In other words, @kbd{m g} is like @kbd{s r Modes @key{RET}}.
  13280. It will not work to store into this variable; in fact, if you do,
  13281. @code{Modes} will cease to track the current modes. (The @kbd{m g}
  13282. command will continue to work, however.)
  13283. In general, each number in this vector is suitable as a numeric
  13284. prefix argument to the associated mode-setting command. (Recall
  13285. that the @kbd{~} key takes a number from the stack and gives it as
  13286. a numeric prefix to the next command.)
  13287. The elements of the modes vector are as follows:
  13288. @enumerate
  13289. @item
  13290. Current precision. Default is 12; associated command is @kbd{p}.
  13291. @item
  13292. Binary word size. Default is 32; associated command is @kbd{b w}.
  13293. @item
  13294. Stack size (not counting the value about to be pushed by @kbd{m g}).
  13295. This is zero if @kbd{m g} is executed with an empty stack.
  13296. @item
  13297. Number radix. Default is 10; command is @kbd{d r}.
  13298. @item
  13299. Floating-point format. This is the number of digits, plus the
  13300. constant 0 for normal notation, 10000 for scientific notation,
  13301. 20000 for engineering notation, or 30000 for fixed-point notation.
  13302. These codes are acceptable as prefix arguments to the @kbd{d n}
  13303. command, but note that this may lose information: For example,
  13304. @kbd{d s} and @kbd{C-u 12 d s} have similar (but not quite
  13305. identical) effects if the current precision is 12, but they both
  13306. produce a code of 10012, which will be treated by @kbd{d n} as
  13307. @kbd{C-u 12 d s}. If the precision then changes, the float format
  13308. will still be frozen at 12 significant figures.
  13309. @item
  13310. Angular mode. Default is 1 (degrees). Other values are 2 (radians)
  13311. and 3 (HMS). The @kbd{m d} command accepts these prefixes.
  13312. @item
  13313. Symbolic mode. Value is 0 or 1; default is 0. Command is @kbd{m s}.
  13314. @item
  13315. Fraction mode. Value is 0 or 1; default is 0. Command is @kbd{m f}.
  13316. @item
  13317. Polar mode. Value is 0 (rectangular) or 1 (polar); default is 0.
  13318. Command is @kbd{m p}.
  13319. @item
  13320. Matrix/Scalar mode. Default value is @mathit{-1}. Value is 0 for Scalar
  13321. mode, @mathit{-2} for Matrix mode, @mathit{-3} for square Matrix mode,
  13322. or @var{N} for
  13323. @texline @math{N\times N}
  13324. @infoline @var{N}x@var{N}
  13325. Matrix mode. Command is @kbd{m v}.
  13326. @item
  13327. Simplification mode. Default is 1. Value is @mathit{-1} for off (@kbd{m O}),
  13328. 0 for @kbd{m N}, 2 for @kbd{m B}, 3 for @kbd{m A}, 4 for @kbd{m E},
  13329. or 5 for @w{@kbd{m U}}. The @kbd{m D} command accepts these prefixes.
  13330. @item
  13331. Infinite mode. Default is @mathit{-1} (off). Value is 1 if the mode is on,
  13332. or 0 if the mode is on with positive zeros. Command is @kbd{m i}.
  13333. @end enumerate
  13334. For example, the sequence @kbd{M-1 m g @key{RET} 2 + ~ p} increases the
  13335. precision by two, leaving a copy of the old precision on the stack.
  13336. Later, @kbd{~ p} will restore the original precision using that
  13337. stack value. (This sequence might be especially useful inside a
  13338. keyboard macro.)
  13339. As another example, @kbd{M-3 m g 1 - ~ @key{DEL}} deletes all but the
  13340. oldest (bottommost) stack entry.
  13341. Yet another example: The HP-48 ``round'' command rounds a number
  13342. to the current displayed precision. You could roughly emulate this
  13343. in Calc with the sequence @kbd{M-5 m g 10000 % ~ c c}. (This
  13344. would not work for fixed-point mode, but it wouldn't be hard to
  13345. do a full emulation with the help of the @kbd{Z [} and @kbd{Z ]}
  13346. programming commands. @xref{Conditionals in Macros}.)
  13347. @node Calc Mode Line, , Modes Variable, Mode Settings
  13348. @section The Calc Mode Line
  13349. @noindent
  13350. @cindex Mode line indicators
  13351. This section is a summary of all symbols that can appear on the
  13352. Calc mode line, the highlighted bar that appears under the Calc
  13353. stack window (or under an editing window in Embedded mode).
  13354. The basic mode line format is:
  13355. @example
  13356. --%*-Calc: 12 Deg @var{other modes} (Calculator)
  13357. @end example
  13358. The @samp{%*} indicates that the buffer is ``read-only''; it shows that
  13359. regular Emacs commands are not allowed to edit the stack buffer
  13360. as if it were text.
  13361. The word @samp{Calc:} changes to @samp{CalcEmbed:} if Embedded mode
  13362. is enabled. The words after this describe the various Calc modes
  13363. that are in effect.
  13364. The first mode is always the current precision, an integer.
  13365. The second mode is always the angular mode, either @code{Deg},
  13366. @code{Rad}, or @code{Hms}.
  13367. Here is a complete list of the remaining symbols that can appear
  13368. on the mode line:
  13369. @table @code
  13370. @item Alg
  13371. Algebraic mode (@kbd{m a}; @pxref{Algebraic Entry}).
  13372. @item Alg[(
  13373. Incomplete algebraic mode (@kbd{C-u m a}).
  13374. @item Alg*
  13375. Total algebraic mode (@kbd{m t}).
  13376. @item Symb
  13377. Symbolic mode (@kbd{m s}; @pxref{Symbolic Mode}).
  13378. @item Matrix
  13379. Matrix mode (@kbd{m v}; @pxref{Matrix Mode}).
  13380. @item Matrix@var{n}
  13381. Dimensioned Matrix mode (@kbd{C-u @var{n} m v}; @pxref{Matrix Mode}).
  13382. @item SqMatrix
  13383. Square Matrix mode (@kbd{C-u m v}; @pxref{Matrix Mode}).
  13384. @item Scalar
  13385. Scalar mode (@kbd{m v}; @pxref{Matrix Mode}).
  13386. @item Polar
  13387. Polar complex mode (@kbd{m p}; @pxref{Polar Mode}).
  13388. @item Frac
  13389. Fraction mode (@kbd{m f}; @pxref{Fraction Mode}).
  13390. @item Inf
  13391. Infinite mode (@kbd{m i}; @pxref{Infinite Mode}).
  13392. @item +Inf
  13393. Positive Infinite mode (@kbd{C-u 0 m i}).
  13394. @item NoSimp
  13395. Default simplifications off (@kbd{m O}; @pxref{Simplification Modes}).
  13396. @item NumSimp
  13397. Default simplifications for numeric arguments only (@kbd{m N}).
  13398. @item BinSimp@var{w}
  13399. Binary-integer simplification mode; word size @var{w} (@kbd{m B}, @kbd{b w}).
  13400. @item BasicSimp
  13401. Basic simplification mode (@kbd{m I}).
  13402. @item ExtSimp
  13403. Extended algebraic simplification mode (@kbd{m E}).
  13404. @item UnitSimp
  13405. Units simplification mode (@kbd{m U}).
  13406. @item Bin
  13407. Current radix is 2 (@kbd{d 2}; @pxref{Radix Modes}).
  13408. @item Oct
  13409. Current radix is 8 (@kbd{d 8}).
  13410. @item Hex
  13411. Current radix is 16 (@kbd{d 6}).
  13412. @item Radix@var{n}
  13413. Current radix is @var{n} (@kbd{d r}).
  13414. @item Zero
  13415. Leading zeros (@kbd{d z}; @pxref{Radix Modes}).
  13416. @item Big
  13417. Big language mode (@kbd{d B}; @pxref{Normal Language Modes}).
  13418. @item Flat
  13419. One-line normal language mode (@kbd{d O}).
  13420. @item Unform
  13421. Unformatted language mode (@kbd{d U}).
  13422. @item C
  13423. C language mode (@kbd{d C}; @pxref{C FORTRAN Pascal}).
  13424. @item Pascal
  13425. Pascal language mode (@kbd{d P}).
  13426. @item Fortran
  13427. FORTRAN language mode (@kbd{d F}).
  13428. @item TeX
  13429. @TeX{} language mode (@kbd{d T}; @pxref{TeX and LaTeX Language Modes}).
  13430. @item LaTeX
  13431. @LaTeX{} language mode (@kbd{d L}; @pxref{TeX and LaTeX Language Modes}).
  13432. @item Eqn
  13433. @dfn{Eqn} language mode (@kbd{d E}; @pxref{Eqn Language Mode}).
  13434. @item Math
  13435. Mathematica language mode (@kbd{d M}; @pxref{Mathematica Language Mode}).
  13436. @item Maple
  13437. Maple language mode (@kbd{d W}; @pxref{Maple Language Mode}).
  13438. @item Norm@var{n}
  13439. Normal float mode with @var{n} digits (@kbd{d n}; @pxref{Float Formats}).
  13440. @item Fix@var{n}
  13441. Fixed point mode with @var{n} digits after the point (@kbd{d f}).
  13442. @item Sci
  13443. Scientific notation mode (@kbd{d s}).
  13444. @item Sci@var{n}
  13445. Scientific notation with @var{n} digits (@kbd{d s}).
  13446. @item Eng
  13447. Engineering notation mode (@kbd{d e}).
  13448. @item Eng@var{n}
  13449. Engineering notation with @var{n} digits (@kbd{d e}).
  13450. @item Left@var{n}
  13451. Left-justified display indented by @var{n} (@kbd{d <}; @pxref{Justification}).
  13452. @item Right
  13453. Right-justified display (@kbd{d >}).
  13454. @item Right@var{n}
  13455. Right-justified display with width @var{n} (@kbd{d >}).
  13456. @item Center
  13457. Centered display (@kbd{d =}).
  13458. @item Center@var{n}
  13459. Centered display with center column @var{n} (@kbd{d =}).
  13460. @item Wid@var{n}
  13461. Line breaking with width @var{n} (@kbd{d b}; @pxref{Normal Language Modes}).
  13462. @item Wide
  13463. No line breaking (@kbd{d b}).
  13464. @item Break
  13465. Selections show deep structure (@kbd{j b}; @pxref{Making Selections}).
  13466. @item Save
  13467. Record modes in @file{~/.emacs.d/calc.el} (@kbd{m R}; @pxref{General Mode Commands}).
  13468. @item Local
  13469. Record modes in Embedded buffer (@kbd{m R}).
  13470. @item LocEdit
  13471. Record modes as editing-only in Embedded buffer (@kbd{m R}).
  13472. @item LocPerm
  13473. Record modes as permanent-only in Embedded buffer (@kbd{m R}).
  13474. @item Global
  13475. Record modes as global in Embedded buffer (@kbd{m R}).
  13476. @item Manual
  13477. Automatic recomputation turned off (@kbd{m C}; @pxref{Automatic
  13478. Recomputation}).
  13479. @item Graph
  13480. GNUPLOT process is alive in background (@pxref{Graphics}).
  13481. @item Sel
  13482. Top-of-stack has a selection (Embedded only; @pxref{Making Selections}).
  13483. @item Dirty
  13484. The stack display may not be up-to-date (@pxref{Display Modes}).
  13485. @item Inv
  13486. ``Inverse'' prefix was pressed (@kbd{I}; @pxref{Inverse and Hyperbolic}).
  13487. @item Hyp
  13488. ``Hyperbolic'' prefix was pressed (@kbd{H}).
  13489. @item Keep
  13490. ``Keep-arguments'' prefix was pressed (@kbd{K}).
  13491. @item Narrow
  13492. Stack is truncated (@kbd{d t}; @pxref{Truncating the Stack}).
  13493. @end table
  13494. In addition, the symbols @code{Active} and @code{~Active} can appear
  13495. as minor modes on an Embedded buffer's mode line. @xref{Embedded Mode}.
  13496. @node Arithmetic, Scientific Functions, Mode Settings, Top
  13497. @chapter Arithmetic Functions
  13498. @noindent
  13499. This chapter describes the Calc commands for doing simple calculations
  13500. on numbers, such as addition, absolute value, and square roots. These
  13501. commands work by removing the top one or two values from the stack,
  13502. performing the desired operation, and pushing the result back onto the
  13503. stack. If the operation cannot be performed, the result pushed is a
  13504. formula instead of a number, such as @samp{2/0} (because division by zero
  13505. is invalid) or @samp{sqrt(x)} (because the argument @samp{x} is a formula).
  13506. Most of the commands described here can be invoked by a single keystroke.
  13507. Some of the more obscure ones are two-letter sequences beginning with
  13508. the @kbd{f} (``functions'') prefix key.
  13509. @xref{Prefix Arguments}, for a discussion of the effect of numeric
  13510. prefix arguments on commands in this chapter which do not otherwise
  13511. interpret a prefix argument.
  13512. @menu
  13513. * Basic Arithmetic::
  13514. * Integer Truncation::
  13515. * Complex Number Functions::
  13516. * Conversions::
  13517. * Date Arithmetic::
  13518. * Financial Functions::
  13519. * Binary Functions::
  13520. @end menu
  13521. @node Basic Arithmetic, Integer Truncation, Arithmetic, Arithmetic
  13522. @section Basic Arithmetic
  13523. @noindent
  13524. @kindex +
  13525. @pindex calc-plus
  13526. @ignore
  13527. @mindex @null
  13528. @end ignore
  13529. @tindex +
  13530. The @kbd{+} (@code{calc-plus}) command adds two numbers. The numbers may
  13531. be any of the standard Calc data types. The resulting sum is pushed back
  13532. onto the stack.
  13533. If both arguments of @kbd{+} are vectors or matrices (of matching dimensions),
  13534. the result is a vector or matrix sum. If one argument is a vector and the
  13535. other a scalar (i.e., a non-vector), the scalar is added to each of the
  13536. elements of the vector to form a new vector. If the scalar is not a
  13537. number, the operation is left in symbolic form: Suppose you added @samp{x}
  13538. to the vector @samp{[1,2]}. You may want the result @samp{[1+x,2+x]}, or
  13539. you may plan to substitute a 2-vector for @samp{x} in the future. Since
  13540. the Calculator can't tell which interpretation you want, it makes the
  13541. safest assumption. @xref{Reducing and Mapping}, for a way to add @samp{x}
  13542. to every element of a vector.
  13543. If either argument of @kbd{+} is a complex number, the result will in general
  13544. be complex. If one argument is in rectangular form and the other polar,
  13545. the current Polar mode determines the form of the result. If Symbolic
  13546. mode is enabled, the sum may be left as a formula if the necessary
  13547. conversions for polar addition are non-trivial.
  13548. If both arguments of @kbd{+} are HMS forms, the forms are added according to
  13549. the usual conventions of hours-minutes-seconds notation. If one argument
  13550. is an HMS form and the other is a number, that number is converted from
  13551. degrees or radians (depending on the current Angular mode) to HMS format
  13552. and then the two HMS forms are added.
  13553. If one argument of @kbd{+} is a date form, the other can be either a
  13554. real number, which advances the date by a certain number of days, or
  13555. an HMS form, which advances the date by a certain amount of time.
  13556. Subtracting two date forms yields the number of days between them.
  13557. Adding two date forms is meaningless, but Calc interprets it as the
  13558. subtraction of one date form and the negative of the other. (The
  13559. negative of a date form can be understood by remembering that dates
  13560. are stored as the number of days before or after Jan 1, 1 AD.)
  13561. If both arguments of @kbd{+} are error forms, the result is an error form
  13562. with an appropriately computed standard deviation. If one argument is an
  13563. error form and the other is a number, the number is taken to have zero error.
  13564. Error forms may have symbolic formulas as their mean and/or error parts;
  13565. adding these will produce a symbolic error form result. However, adding an
  13566. error form to a plain symbolic formula (as in @samp{(a +/- b) + c}) will not
  13567. work, for the same reasons just mentioned for vectors. Instead you must
  13568. write @samp{(a +/- b) + (c +/- 0)}.
  13569. If both arguments of @kbd{+} are modulo forms with equal values of @expr{M},
  13570. or if one argument is a modulo form and the other a plain number, the
  13571. result is a modulo form which represents the sum, modulo @expr{M}, of
  13572. the two values.
  13573. If both arguments of @kbd{+} are intervals, the result is an interval
  13574. which describes all possible sums of the possible input values. If
  13575. one argument is a plain number, it is treated as the interval
  13576. @w{@samp{[x ..@: x]}}.
  13577. If one argument of @kbd{+} is an infinity and the other is not, the
  13578. result is that same infinity. If both arguments are infinite and in
  13579. the same direction, the result is the same infinity, but if they are
  13580. infinite in different directions the result is @code{nan}.
  13581. @kindex -
  13582. @pindex calc-minus
  13583. @ignore
  13584. @mindex @null
  13585. @end ignore
  13586. @tindex -
  13587. The @kbd{-} (@code{calc-minus}) command subtracts two values. The top
  13588. number on the stack is subtracted from the one behind it, so that the
  13589. computation @kbd{5 @key{RET} 2 -} produces 3, not @mathit{-3}. All options
  13590. available for @kbd{+} are available for @kbd{-} as well.
  13591. @kindex *
  13592. @pindex calc-times
  13593. @ignore
  13594. @mindex @null
  13595. @end ignore
  13596. @tindex *
  13597. The @kbd{*} (@code{calc-times}) command multiplies two numbers. If one
  13598. argument is a vector and the other a scalar, the scalar is multiplied by
  13599. the elements of the vector to produce a new vector. If both arguments
  13600. are vectors, the interpretation depends on the dimensions of the
  13601. vectors: If both arguments are matrices, a matrix multiplication is
  13602. done. If one argument is a matrix and the other a plain vector, the
  13603. vector is interpreted as a row vector or column vector, whichever is
  13604. dimensionally correct. If both arguments are plain vectors, the result
  13605. is a single scalar number which is the dot product of the two vectors.
  13606. If one argument of @kbd{*} is an HMS form and the other a number, the
  13607. HMS form is multiplied by that amount. It is an error to multiply two
  13608. HMS forms together, or to attempt any multiplication involving date
  13609. forms. Error forms, modulo forms, and intervals can be multiplied;
  13610. see the comments for addition of those forms. When two error forms
  13611. or intervals are multiplied they are considered to be statistically
  13612. independent; thus, @samp{[-2 ..@: 3] * [-2 ..@: 3]} is @samp{[-6 ..@: 9]},
  13613. whereas @w{@samp{[-2 ..@: 3] ^ 2}} is @samp{[0 ..@: 9]}.
  13614. @kindex /
  13615. @pindex calc-divide
  13616. @ignore
  13617. @mindex @null
  13618. @end ignore
  13619. @tindex /
  13620. The @kbd{/} (@code{calc-divide}) command divides two numbers.
  13621. When combining multiplication and division in an algebraic formula, it
  13622. is good style to use parentheses to distinguish between possible
  13623. interpretations; the expression @samp{a/b*c} should be written
  13624. @samp{(a/b)*c} or @samp{a/(b*c)}, as appropriate. Without the
  13625. parentheses, Calc will interpret @samp{a/b*c} as @samp{a/(b*c)}, since
  13626. in algebraic entry Calc gives division a lower precedence than
  13627. multiplication. (This is not standard across all computer languages, and
  13628. Calc may change the precedence depending on the language mode being used.
  13629. @xref{Language Modes}.) This default ordering can be changed by setting
  13630. the customizable variable @code{calc-multiplication-has-precedence} to
  13631. @code{nil} (@pxref{Customizing Calc}); this will give multiplication and
  13632. division equal precedences. Note that Calc's default choice of
  13633. precedence allows @samp{a b / c d} to be used as a shortcut for
  13634. @smallexample
  13635. @group
  13636. a b
  13637. ---.
  13638. c d
  13639. @end group
  13640. @end smallexample
  13641. When dividing a scalar @expr{B} by a square matrix @expr{A}, the
  13642. computation performed is @expr{B} times the inverse of @expr{A}. This
  13643. also occurs if @expr{B} is itself a vector or matrix, in which case the
  13644. effect is to solve the set of linear equations represented by @expr{B}.
  13645. If @expr{B} is a matrix with the same number of rows as @expr{A}, or a
  13646. plain vector (which is interpreted here as a column vector), then the
  13647. equation @expr{A X = B} is solved for the vector or matrix @expr{X}.
  13648. Otherwise, if @expr{B} is a non-square matrix with the same number of
  13649. @emph{columns} as @expr{A}, the equation @expr{X A = B} is solved. If
  13650. you wish a vector @expr{B} to be interpreted as a row vector to be
  13651. solved as @expr{X A = B}, make it into a one-row matrix with @kbd{C-u 1
  13652. v p} first. To force a left-handed solution with a square matrix
  13653. @expr{B}, transpose @expr{A} and @expr{B} before dividing, then
  13654. transpose the result.
  13655. HMS forms can be divided by real numbers or by other HMS forms. Error
  13656. forms can be divided in any combination of ways. Modulo forms where both
  13657. values and the modulo are integers can be divided to get an integer modulo
  13658. form result. Intervals can be divided; dividing by an interval that
  13659. encompasses zero or has zero as a limit will result in an infinite
  13660. interval.
  13661. @kindex ^
  13662. @pindex calc-power
  13663. @ignore
  13664. @mindex @null
  13665. @end ignore
  13666. @tindex ^
  13667. The @kbd{^} (@code{calc-power}) command raises a number to a power. If
  13668. the power is an integer, an exact result is computed using repeated
  13669. multiplications. For non-integer powers, Calc uses Newton's method or
  13670. logarithms and exponentials. Square matrices can be raised to integer
  13671. powers. If either argument is an error (or interval or modulo) form,
  13672. the result is also an error (or interval or modulo) form.
  13673. @kindex I ^
  13674. @tindex nroot
  13675. If you press the @kbd{I} (inverse) key first, the @kbd{I ^} command
  13676. computes an Nth root: @kbd{125 @key{RET} 3 I ^} computes the number 5.
  13677. (This is entirely equivalent to @kbd{125 @key{RET} 1:3 ^}.)
  13678. @kindex \
  13679. @pindex calc-idiv
  13680. @tindex idiv
  13681. @ignore
  13682. @mindex @null
  13683. @end ignore
  13684. @tindex \
  13685. The @kbd{\} (@code{calc-idiv}) command divides two numbers on the stack
  13686. to produce an integer result. It is equivalent to dividing with
  13687. @key{/}, then rounding down with @kbd{F} (@code{calc-floor}), only a bit
  13688. more convenient and efficient. Also, since it is an all-integer
  13689. operation when the arguments are integers, it avoids problems that
  13690. @kbd{/ F} would have with floating-point roundoff.
  13691. @kindex %
  13692. @pindex calc-mod
  13693. @ignore
  13694. @mindex @null
  13695. @end ignore
  13696. @tindex %
  13697. The @kbd{%} (@code{calc-mod}) command performs a ``modulo'' (or ``remainder'')
  13698. operation. Mathematically, @samp{a%b = a - (a\b)*b}, and is defined
  13699. for all real numbers @expr{a} and @expr{b} (except @expr{b=0}). For
  13700. positive @expr{b}, the result will always be between 0 (inclusive) and
  13701. @expr{b} (exclusive). Modulo does not work for HMS forms and error forms.
  13702. If @expr{a} is a modulo form, its modulo is changed to @expr{b}, which
  13703. must be positive real number.
  13704. @kindex :
  13705. @pindex calc-fdiv
  13706. @tindex fdiv
  13707. The @kbd{:} (@code{calc-fdiv}) [@code{fdiv}] command
  13708. divides the two integers on the top of the stack to produce a fractional
  13709. result. This is a convenient shorthand for enabling Fraction mode (with
  13710. @kbd{m f}) temporarily and using @samp{/}. Note that during numeric entry
  13711. the @kbd{:} key is interpreted as a fraction separator, so to divide 8 by 6
  13712. you would have to type @kbd{8 @key{RET} 6 @key{RET} :}. (Of course, in
  13713. this case, it would be much easier simply to enter the fraction directly
  13714. as @kbd{8:6 @key{RET}}!)
  13715. @kindex n
  13716. @pindex calc-change-sign
  13717. The @kbd{n} (@code{calc-change-sign}) command negates the number on the top
  13718. of the stack. It works on numbers, vectors and matrices, HMS forms, date
  13719. forms, error forms, intervals, and modulo forms.
  13720. @kindex A
  13721. @pindex calc-abs
  13722. @tindex abs
  13723. The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the absolute
  13724. value of a number. The result of @code{abs} is always a nonnegative
  13725. real number: With a complex argument, it computes the complex magnitude.
  13726. With a vector or matrix argument, it computes the Frobenius norm, i.e.,
  13727. the square root of the sum of the squares of the absolute values of the
  13728. elements. The absolute value of an error form is defined by replacing
  13729. the mean part with its absolute value and leaving the error part the same.
  13730. The absolute value of a modulo form is undefined. The absolute value of
  13731. an interval is defined in the obvious way.
  13732. @kindex f A
  13733. @pindex calc-abssqr
  13734. @tindex abssqr
  13735. The @kbd{f A} (@code{calc-abssqr}) [@code{abssqr}] command computes the
  13736. absolute value squared of a number, vector or matrix, or error form.
  13737. @kindex f s
  13738. @pindex calc-sign
  13739. @tindex sign
  13740. The @kbd{f s} (@code{calc-sign}) [@code{sign}] command returns 1 if its
  13741. argument is positive, @mathit{-1} if its argument is negative, or 0 if its
  13742. argument is zero. In algebraic form, you can also write @samp{sign(a,x)}
  13743. which evaluates to @samp{x * sign(a)}, i.e., either @samp{x}, @samp{-x}, or
  13744. zero depending on the sign of @samp{a}.
  13745. @kindex &
  13746. @pindex calc-inv
  13747. @tindex inv
  13748. @cindex Reciprocal
  13749. The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
  13750. reciprocal of a number, i.e., @expr{1 / x}. Operating on a square
  13751. matrix, it computes the inverse of that matrix.
  13752. @kindex Q
  13753. @pindex calc-sqrt
  13754. @tindex sqrt
  13755. The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] command computes the square
  13756. root of a number. For a negative real argument, the result will be a
  13757. complex number whose form is determined by the current Polar mode.
  13758. @kindex f h
  13759. @pindex calc-hypot
  13760. @tindex hypot
  13761. The @kbd{f h} (@code{calc-hypot}) [@code{hypot}] command computes the square
  13762. root of the sum of the squares of two numbers. That is, @samp{hypot(a,b)}
  13763. is the length of the hypotenuse of a right triangle with sides @expr{a}
  13764. and @expr{b}. If the arguments are complex numbers, their squared
  13765. magnitudes are used.
  13766. @kindex f Q
  13767. @pindex calc-isqrt
  13768. @tindex isqrt
  13769. The @kbd{f Q} (@code{calc-isqrt}) [@code{isqrt}] command computes the
  13770. integer square root of an integer. This is the true square root of the
  13771. number, rounded down to an integer. For example, @samp{isqrt(10)}
  13772. produces 3. Note that, like @kbd{\} [@code{idiv}], this uses exact
  13773. integer arithmetic throughout to avoid roundoff problems. If the input
  13774. is a floating-point number or other non-integer value, this is exactly
  13775. the same as @samp{floor(sqrt(x))}.
  13776. @kindex f n
  13777. @kindex f x
  13778. @pindex calc-min
  13779. @tindex min
  13780. @pindex calc-max
  13781. @tindex max
  13782. The @kbd{f n} (@code{calc-min}) [@code{min}] and @kbd{f x} (@code{calc-max})
  13783. [@code{max}] commands take the minimum or maximum of two real numbers,
  13784. respectively. These commands also work on HMS forms, date forms,
  13785. intervals, and infinities. (In algebraic expressions, these functions
  13786. take any number of arguments and return the maximum or minimum among
  13787. all the arguments.)
  13788. @kindex f M
  13789. @kindex f X
  13790. @pindex calc-mant-part
  13791. @tindex mant
  13792. @pindex calc-xpon-part
  13793. @tindex xpon
  13794. The @kbd{f M} (@code{calc-mant-part}) [@code{mant}] function extracts
  13795. the ``mantissa'' part @expr{m} of its floating-point argument; @kbd{f X}
  13796. (@code{calc-xpon-part}) [@code{xpon}] extracts the ``exponent'' part
  13797. @expr{e}. The original number is equal to
  13798. @texline @math{m \times 10^e},
  13799. @infoline @expr{m * 10^e},
  13800. where @expr{m} is in the interval @samp{[1.0 ..@: 10.0)} except that
  13801. @expr{m=e=0} if the original number is zero. For integers
  13802. and fractions, @code{mant} returns the number unchanged and @code{xpon}
  13803. returns zero. The @kbd{v u} (@code{calc-unpack}) command can also be
  13804. used to ``unpack'' a floating-point number; this produces an integer
  13805. mantissa and exponent, with the constraint that the mantissa is not
  13806. a multiple of ten (again except for the @expr{m=e=0} case).
  13807. @kindex f S
  13808. @pindex calc-scale-float
  13809. @tindex scf
  13810. The @kbd{f S} (@code{calc-scale-float}) [@code{scf}] function scales a number
  13811. by a given power of ten. Thus, @samp{scf(mant(x), xpon(x)) = x} for any
  13812. real @samp{x}. The second argument must be an integer, but the first
  13813. may actually be any numeric value. For example, @samp{scf(5,-2) = 0.05}
  13814. or @samp{1:20} depending on the current Fraction mode.
  13815. @kindex f [
  13816. @kindex f ]
  13817. @pindex calc-decrement
  13818. @pindex calc-increment
  13819. @tindex decr
  13820. @tindex incr
  13821. The @kbd{f [} (@code{calc-decrement}) [@code{decr}] and @kbd{f ]}
  13822. (@code{calc-increment}) [@code{incr}] functions decrease or increase
  13823. a number by one unit. For integers, the effect is obvious. For
  13824. floating-point numbers, the change is by one unit in the last place.
  13825. For example, incrementing @samp{12.3456} when the current precision
  13826. is 6 digits yields @samp{12.3457}. If the current precision had been
  13827. 8 digits, the result would have been @samp{12.345601}. Incrementing
  13828. @samp{0.0} produces
  13829. @texline @math{10^{-p}},
  13830. @infoline @expr{10^-p},
  13831. where @expr{p} is the current
  13832. precision. These operations are defined only on integers and floats.
  13833. With numeric prefix arguments, they change the number by @expr{n} units.
  13834. Note that incrementing followed by decrementing, or vice-versa, will
  13835. almost but not quite always cancel out. Suppose the precision is
  13836. 6 digits and the number @samp{9.99999} is on the stack. Incrementing
  13837. will produce @samp{10.0000}; decrementing will produce @samp{9.9999}.
  13838. One digit has been dropped. This is an unavoidable consequence of the
  13839. way floating-point numbers work.
  13840. Incrementing a date/time form adjusts it by a certain number of seconds.
  13841. Incrementing a pure date form adjusts it by a certain number of days.
  13842. @node Integer Truncation, Complex Number Functions, Basic Arithmetic, Arithmetic
  13843. @section Integer Truncation
  13844. @noindent
  13845. There are four commands for truncating a real number to an integer,
  13846. differing mainly in their treatment of negative numbers. All of these
  13847. commands have the property that if the argument is an integer, the result
  13848. is the same integer. An integer-valued floating-point argument is converted
  13849. to integer form.
  13850. If you press @kbd{H} (@code{calc-hyperbolic}) first, the result will be
  13851. expressed as an integer-valued floating-point number.
  13852. @cindex Integer part of a number
  13853. @kindex F
  13854. @pindex calc-floor
  13855. @tindex floor
  13856. @tindex ffloor
  13857. @ignore
  13858. @mindex @null
  13859. @end ignore
  13860. @kindex H F
  13861. The @kbd{F} (@code{calc-floor}) [@code{floor} or @code{ffloor}] command
  13862. truncates a real number to the next lower integer, i.e., toward minus
  13863. infinity. Thus @kbd{3.6 F} produces 3, but @kbd{_3.6 F} produces
  13864. @mathit{-4}.
  13865. @kindex I F
  13866. @pindex calc-ceiling
  13867. @tindex ceil
  13868. @tindex fceil
  13869. @ignore
  13870. @mindex @null
  13871. @end ignore
  13872. @kindex H I F
  13873. The @kbd{I F} (@code{calc-ceiling}) [@code{ceil} or @code{fceil}]
  13874. command truncates toward positive infinity. Thus @kbd{3.6 I F} produces
  13875. 4, and @kbd{_3.6 I F} produces @mathit{-3}.
  13876. @kindex R
  13877. @pindex calc-round
  13878. @tindex round
  13879. @tindex fround
  13880. @ignore
  13881. @mindex @null
  13882. @end ignore
  13883. @kindex H R
  13884. The @kbd{R} (@code{calc-round}) [@code{round} or @code{fround}] command
  13885. rounds to the nearest integer. When the fractional part is .5 exactly,
  13886. this command rounds away from zero. (All other rounding in the
  13887. Calculator uses this convention as well.) Thus @kbd{3.5 R} produces 4
  13888. but @kbd{3.4 R} produces 3; @kbd{_3.5 R} produces @mathit{-4}.
  13889. @kindex I R
  13890. @pindex calc-trunc
  13891. @tindex trunc
  13892. @tindex ftrunc
  13893. @ignore
  13894. @mindex @null
  13895. @end ignore
  13896. @kindex H I R
  13897. The @kbd{I R} (@code{calc-trunc}) [@code{trunc} or @code{ftrunc}]
  13898. command truncates toward zero. In other words, it ``chops off''
  13899. everything after the decimal point. Thus @kbd{3.6 I R} produces 3 and
  13900. @kbd{_3.6 I R} produces @mathit{-3}.
  13901. These functions may not be applied meaningfully to error forms, but they
  13902. do work for intervals. As a convenience, applying @code{floor} to a
  13903. modulo form floors the value part of the form. Applied to a vector,
  13904. these functions operate on all elements of the vector one by one.
  13905. Applied to a date form, they operate on the internal numerical
  13906. representation of dates, converting a date/time form into a pure date.
  13907. @ignore
  13908. @starindex
  13909. @end ignore
  13910. @tindex rounde
  13911. @ignore
  13912. @starindex
  13913. @end ignore
  13914. @tindex roundu
  13915. @ignore
  13916. @starindex
  13917. @end ignore
  13918. @tindex frounde
  13919. @ignore
  13920. @starindex
  13921. @end ignore
  13922. @tindex froundu
  13923. There are two more rounding functions which can only be entered in
  13924. algebraic notation. The @code{roundu} function is like @code{round}
  13925. except that it rounds up, toward plus infinity, when the fractional
  13926. part is .5. This distinction matters only for negative arguments.
  13927. Also, @code{rounde} rounds to an even number in the case of a tie,
  13928. rounding up or down as necessary. For example, @samp{rounde(3.5)} and
  13929. @samp{rounde(4.5)} both return 4, but @samp{rounde(5.5)} returns 6.
  13930. The advantage of round-to-even is that the net error due to rounding
  13931. after a long calculation tends to cancel out to zero. An important
  13932. subtle point here is that the number being fed to @code{rounde} will
  13933. already have been rounded to the current precision before @code{rounde}
  13934. begins. For example, @samp{rounde(2.500001)} with a current precision
  13935. of 6 will incorrectly, or at least surprisingly, yield 2 because the
  13936. argument will first have been rounded down to @expr{2.5} (which
  13937. @code{rounde} sees as an exact tie between 2 and 3).
  13938. Each of these functions, when written in algebraic formulas, allows
  13939. a second argument which specifies the number of digits after the
  13940. decimal point to keep. For example, @samp{round(123.4567, 2)} will
  13941. produce the answer 123.46, and @samp{round(123.4567, -1)} will
  13942. produce 120 (i.e., the cutoff is one digit to the @emph{left} of
  13943. the decimal point). A second argument of zero is equivalent to
  13944. no second argument at all.
  13945. @cindex Fractional part of a number
  13946. To compute the fractional part of a number (i.e., the amount which, when
  13947. added to `@tfn{floor(}@var{n}@tfn{)}', will produce @var{n}) just take @var{n}
  13948. modulo 1 using the @code{%} command.
  13949. Note also the @kbd{\} (integer quotient), @kbd{f I} (integer logarithm),
  13950. and @kbd{f Q} (integer square root) commands, which are analogous to
  13951. @kbd{/}, @kbd{B}, and @kbd{Q}, respectively, except that they take integer
  13952. arguments and return the result rounded down to an integer.
  13953. @node Complex Number Functions, Conversions, Integer Truncation, Arithmetic
  13954. @section Complex Number Functions
  13955. @noindent
  13956. @kindex J
  13957. @pindex calc-conj
  13958. @tindex conj
  13959. The @kbd{J} (@code{calc-conj}) [@code{conj}] command computes the
  13960. complex conjugate of a number. For complex number @expr{a+bi}, the
  13961. complex conjugate is @expr{a-bi}. If the argument is a real number,
  13962. this command leaves it the same. If the argument is a vector or matrix,
  13963. this command replaces each element by its complex conjugate.
  13964. @kindex G
  13965. @pindex calc-argument
  13966. @tindex arg
  13967. The @kbd{G} (@code{calc-argument}) [@code{arg}] command computes the
  13968. ``argument'' or polar angle of a complex number. For a number in polar
  13969. notation, this is simply the second component of the pair
  13970. @texline `@tfn{(}@var{r}@tfn{;}@math{\theta}@tfn{)}'.
  13971. @infoline `@tfn{(}@var{r}@tfn{;}@var{theta}@tfn{)}'.
  13972. The result is expressed according to the current angular mode and will
  13973. be in the range @mathit{-180} degrees (exclusive) to @mathit{+180} degrees
  13974. (inclusive), or the equivalent range in radians.
  13975. @pindex calc-imaginary
  13976. The @code{calc-imaginary} command multiplies the number on the
  13977. top of the stack by the imaginary number @expr{i = (0,1)}. This
  13978. command is not normally bound to a key in Calc, but it is available
  13979. on the @key{IMAG} button in Keypad mode.
  13980. @kindex f r
  13981. @pindex calc-re
  13982. @tindex re
  13983. The @kbd{f r} (@code{calc-re}) [@code{re}] command replaces a complex number
  13984. by its real part. This command has no effect on real numbers. (As an
  13985. added convenience, @code{re} applied to a modulo form extracts
  13986. the value part.)
  13987. @kindex f i
  13988. @pindex calc-im
  13989. @tindex im
  13990. The @kbd{f i} (@code{calc-im}) [@code{im}] command replaces a complex number
  13991. by its imaginary part; real numbers are converted to zero. With a vector
  13992. or matrix argument, these functions operate element-wise.
  13993. @ignore
  13994. @mindex v p
  13995. @end ignore
  13996. @kindex v p (complex)
  13997. @kindex V p (complex)
  13998. @pindex calc-pack
  13999. The @kbd{v p} (@code{calc-pack}) command can pack the top two numbers on
  14000. the stack into a composite object such as a complex number. With
  14001. a prefix argument of @mathit{-1}, it produces a rectangular complex number;
  14002. with an argument of @mathit{-2}, it produces a polar complex number.
  14003. (Also, @pxref{Building Vectors}.)
  14004. @ignore
  14005. @mindex v u
  14006. @end ignore
  14007. @kindex v u (complex)
  14008. @kindex V u (complex)
  14009. @pindex calc-unpack
  14010. The @kbd{v u} (@code{calc-unpack}) command takes the complex number
  14011. (or other composite object) on the top of the stack and unpacks it
  14012. into its separate components.
  14013. @node Conversions, Date Arithmetic, Complex Number Functions, Arithmetic
  14014. @section Conversions
  14015. @noindent
  14016. The commands described in this section convert numbers from one form
  14017. to another; they are two-key sequences beginning with the letter @kbd{c}.
  14018. @kindex c f
  14019. @pindex calc-float
  14020. @tindex pfloat
  14021. The @kbd{c f} (@code{calc-float}) [@code{pfloat}] command converts the
  14022. number on the top of the stack to floating-point form. For example,
  14023. @expr{23} is converted to @expr{23.0}, @expr{3:2} is converted to
  14024. @expr{1.5}, and @expr{2.3} is left the same. If the value is a composite
  14025. object such as a complex number or vector, each of the components is
  14026. converted to floating-point. If the value is a formula, all numbers
  14027. in the formula are converted to floating-point. Note that depending
  14028. on the current floating-point precision, conversion to floating-point
  14029. format may lose information.
  14030. As a special exception, integers which appear as powers or subscripts
  14031. are not floated by @kbd{c f}. If you really want to float a power,
  14032. you can use a @kbd{j s} command to select the power followed by @kbd{c f}.
  14033. Because @kbd{c f} cannot examine the formula outside of the selection,
  14034. it does not notice that the thing being floated is a power.
  14035. @xref{Selecting Subformulas}.
  14036. The normal @kbd{c f} command is ``pervasive'' in the sense that it
  14037. applies to all numbers throughout the formula. The @code{pfloat}
  14038. algebraic function never stays around in a formula; @samp{pfloat(a + 1)}
  14039. changes to @samp{a + 1.0} as soon as it is evaluated.
  14040. @kindex H c f
  14041. @tindex float
  14042. With the Hyperbolic flag, @kbd{H c f} [@code{float}] operates
  14043. only on the number or vector of numbers at the top level of its
  14044. argument. Thus, @samp{float(1)} is 1.0, but @samp{float(a + 1)}
  14045. is left unevaluated because its argument is not a number.
  14046. You should use @kbd{H c f} if you wish to guarantee that the final
  14047. value, once all the variables have been assigned, is a float; you
  14048. would use @kbd{c f} if you wish to do the conversion on the numbers
  14049. that appear right now.
  14050. @kindex c F
  14051. @pindex calc-fraction
  14052. @tindex pfrac
  14053. The @kbd{c F} (@code{calc-fraction}) [@code{pfrac}] command converts a
  14054. floating-point number into a fractional approximation. By default, it
  14055. produces a fraction whose decimal representation is the same as the
  14056. input number, to within the current precision. You can also give a
  14057. numeric prefix argument to specify a tolerance, either directly, or,
  14058. if the prefix argument is zero, by using the number on top of the stack
  14059. as the tolerance. If the tolerance is a positive integer, the fraction
  14060. is correct to within that many significant figures. If the tolerance is
  14061. a non-positive integer, it specifies how many digits fewer than the current
  14062. precision to use. If the tolerance is a floating-point number, the
  14063. fraction is correct to within that absolute amount.
  14064. @kindex H c F
  14065. @tindex frac
  14066. The @code{pfrac} function is pervasive, like @code{pfloat}.
  14067. There is also a non-pervasive version, @kbd{H c F} [@code{frac}],
  14068. which is analogous to @kbd{H c f} discussed above.
  14069. @kindex c d
  14070. @pindex calc-to-degrees
  14071. @tindex deg
  14072. The @kbd{c d} (@code{calc-to-degrees}) [@code{deg}] command converts a
  14073. number into degrees form. The value on the top of the stack may be an
  14074. HMS form (interpreted as degrees-minutes-seconds), or a real number which
  14075. will be interpreted in radians regardless of the current angular mode.
  14076. @kindex c r
  14077. @pindex calc-to-radians
  14078. @tindex rad
  14079. The @kbd{c r} (@code{calc-to-radians}) [@code{rad}] command converts an
  14080. HMS form or angle in degrees into an angle in radians.
  14081. @kindex c h
  14082. @pindex calc-to-hms
  14083. @tindex hms
  14084. The @kbd{c h} (@code{calc-to-hms}) [@code{hms}] command converts a real
  14085. number, interpreted according to the current angular mode, to an HMS
  14086. form describing the same angle. In algebraic notation, the @code{hms}
  14087. function also accepts three arguments: @samp{hms(@var{h}, @var{m}, @var{s})}.
  14088. (The three-argument version is independent of the current angular mode.)
  14089. @pindex calc-from-hms
  14090. The @code{calc-from-hms} command converts the HMS form on the top of the
  14091. stack into a real number according to the current angular mode.
  14092. @kindex c p
  14093. @kindex I c p
  14094. @pindex calc-polar
  14095. @tindex polar
  14096. @tindex rect
  14097. The @kbd{c p} (@code{calc-polar}) command converts the complex number on
  14098. the top of the stack from polar to rectangular form, or from rectangular
  14099. to polar form, whichever is appropriate. Real numbers are left the same.
  14100. This command is equivalent to the @code{rect} or @code{polar}
  14101. functions in algebraic formulas, depending on the direction of
  14102. conversion. (It uses @code{polar}, except that if the argument is
  14103. already a polar complex number, it uses @code{rect} instead. The
  14104. @kbd{I c p} command always uses @code{rect}.)
  14105. @kindex c c
  14106. @pindex calc-clean
  14107. @tindex pclean
  14108. The @kbd{c c} (@code{calc-clean}) [@code{pclean}] command ``cleans'' the
  14109. number on the top of the stack. Floating point numbers are re-rounded
  14110. according to the current precision. Polar numbers whose angular
  14111. components have strayed from the @mathit{-180} to @mathit{+180} degree range
  14112. are normalized. (Note that results will be undesirable if the current
  14113. angular mode is different from the one under which the number was
  14114. produced!) Integers and fractions are generally unaffected by this
  14115. operation. Vectors and formulas are cleaned by cleaning each component
  14116. number (i.e., pervasively).
  14117. If the simplification mode is set below basic simplification, it is raised
  14118. for the purposes of this command. Thus, @kbd{c c} applies the basic
  14119. simplifications even if their automatic application is disabled.
  14120. @xref{Simplification Modes}.
  14121. @cindex Roundoff errors, correcting
  14122. A numeric prefix argument to @kbd{c c} sets the floating-point precision
  14123. to that value for the duration of the command. A positive prefix (of at
  14124. least 3) sets the precision to the specified value; a negative or zero
  14125. prefix decreases the precision by the specified amount.
  14126. @kindex c 0-9
  14127. @pindex calc-clean-num
  14128. The keystroke sequences @kbd{c 0} through @kbd{c 9} are equivalent
  14129. to @kbd{c c} with the corresponding negative prefix argument. If roundoff
  14130. errors have changed 2.0 into 1.999999, typing @kbd{c 1} to clip off one
  14131. decimal place often conveniently does the trick.
  14132. The @kbd{c c} command with a numeric prefix argument, and the @kbd{c 0}
  14133. through @kbd{c 9} commands, also ``clip'' very small floating-point
  14134. numbers to zero. If the exponent is less than or equal to the negative
  14135. of the specified precision, the number is changed to 0.0. For example,
  14136. if the current precision is 12, then @kbd{c 2} changes the vector
  14137. @samp{[1e-8, 1e-9, 1e-10, 1e-11]} to @samp{[1e-8, 1e-9, 0, 0]}.
  14138. Numbers this small generally arise from roundoff noise.
  14139. If the numbers you are using really are legitimately this small,
  14140. you should avoid using the @kbd{c 0} through @kbd{c 9} commands.
  14141. (The plain @kbd{c c} command rounds to the current precision but
  14142. does not clip small numbers.)
  14143. One more property of @kbd{c 0} through @kbd{c 9}, and of @kbd{c c} with
  14144. a prefix argument, is that integer-valued floats are converted to
  14145. plain integers, so that @kbd{c 1} on @samp{[1., 1.5, 2., 2.5, 3.]}
  14146. produces @samp{[1, 1.5, 2, 2.5, 3]}. This is not done for huge
  14147. numbers (@samp{1e100} is technically an integer-valued float, but
  14148. you wouldn't want it automatically converted to a 100-digit integer).
  14149. @kindex H c 0-9
  14150. @kindex H c c
  14151. @tindex clean
  14152. With the Hyperbolic flag, @kbd{H c c} and @kbd{H c 0} through @kbd{H c 9}
  14153. operate non-pervasively [@code{clean}].
  14154. @node Date Arithmetic, Financial Functions, Conversions, Arithmetic
  14155. @section Date Arithmetic
  14156. @noindent
  14157. @cindex Date arithmetic, additional functions
  14158. The commands described in this section perform various conversions
  14159. and calculations involving date forms (@pxref{Date Forms}). They
  14160. use the @kbd{t} (for time/date) prefix key followed by shifted
  14161. letters.
  14162. The simplest date arithmetic is done using the regular @kbd{+} and @kbd{-}
  14163. commands. In particular, adding a number to a date form advances the
  14164. date form by a certain number of days; adding an HMS form to a date
  14165. form advances the date by a certain amount of time; and subtracting two
  14166. date forms produces a difference measured in days. The commands
  14167. described here provide additional, more specialized operations on dates.
  14168. Many of these commands accept a numeric prefix argument; if you give
  14169. plain @kbd{C-u} as the prefix, these commands will instead take the
  14170. additional argument from the top of the stack.
  14171. @menu
  14172. * Date Conversions::
  14173. * Date Functions::
  14174. * Time Zones::
  14175. * Business Days::
  14176. @end menu
  14177. @node Date Conversions, Date Functions, Date Arithmetic, Date Arithmetic
  14178. @subsection Date Conversions
  14179. @noindent
  14180. @kindex t D
  14181. @pindex calc-date
  14182. @tindex date
  14183. The @kbd{t D} (@code{calc-date}) [@code{date}] command converts a
  14184. date form into a number, measured in days since Jan 1, 1 AD@. The
  14185. result will be an integer if @var{date} is a pure date form, or a
  14186. fraction or float if @var{date} is a date/time form. Or, if its
  14187. argument is a number, it converts this number into a date form.
  14188. With a numeric prefix argument, @kbd{t D} takes that many objects
  14189. (up to six) from the top of the stack and interprets them in one
  14190. of the following ways:
  14191. The @samp{date(@var{year}, @var{month}, @var{day})} function
  14192. builds a pure date form out of the specified year, month, and
  14193. day, which must all be integers. @var{Year} is a year number,
  14194. such as 1991 (@emph{not} the same as 91!). @var{Month} must be
  14195. an integer in the range 1 to 12; @var{day} must be in the range
  14196. 1 to 31. If the specified month has fewer than 31 days and
  14197. @var{day} is too large, the equivalent day in the following
  14198. month will be used.
  14199. The @samp{date(@var{month}, @var{day})} function builds a
  14200. pure date form using the current year, as determined by the
  14201. real-time clock.
  14202. The @samp{date(@var{year}, @var{month}, @var{day}, @var{hms})}
  14203. function builds a date/time form using an @var{hms} form.
  14204. The @samp{date(@var{year}, @var{month}, @var{day}, @var{hour},
  14205. @var{minute}, @var{second})} function builds a date/time form.
  14206. @var{hour} should be an integer in the range 0 to 23;
  14207. @var{minute} should be an integer in the range 0 to 59;
  14208. @var{second} should be any real number in the range @samp{[0 .. 60)}.
  14209. The last two arguments default to zero if omitted.
  14210. @kindex t J
  14211. @pindex calc-julian
  14212. @tindex julian
  14213. @cindex Julian day counts, conversions
  14214. The @kbd{t J} (@code{calc-julian}) [@code{julian}] command converts
  14215. a date form into a Julian day count, which is the number of days
  14216. since noon (GMT) on Jan 1, 4713 BC@. A pure date is converted to an
  14217. integer Julian count representing noon of that day. A date/time form
  14218. is converted to an exact floating-point Julian count, adjusted to
  14219. interpret the date form in the current time zone but the Julian
  14220. day count in Greenwich Mean Time. A numeric prefix argument allows
  14221. you to specify the time zone; @pxref{Time Zones}. Use a prefix of
  14222. zero to suppress the time zone adjustment. Note that pure date forms
  14223. are never time-zone adjusted.
  14224. This command can also do the opposite conversion, from a Julian day
  14225. count (either an integer day, or a floating-point day and time in
  14226. the GMT zone), into a pure date form or a date/time form in the
  14227. current or specified time zone.
  14228. @kindex t U
  14229. @pindex calc-unix-time
  14230. @tindex unixtime
  14231. @cindex Unix time format, conversions
  14232. The @kbd{t U} (@code{calc-unix-time}) [@code{unixtime}] command
  14233. converts a date form into a Unix time value, which is the number of
  14234. seconds since midnight on Jan 1, 1970, or vice-versa. The numeric result
  14235. will be an integer if the current precision is 12 or less; for higher
  14236. precision, the result may be a float with (@var{precision}@minus{}12)
  14237. digits after the decimal. Just as for @kbd{t J}, the numeric time
  14238. is interpreted in the GMT time zone and the date form is interpreted
  14239. in the current or specified zone. Some systems use Unix-like
  14240. numbering but with the local time zone; give a prefix of zero to
  14241. suppress the adjustment if so.
  14242. @kindex t C
  14243. @pindex calc-convert-time-zones
  14244. @tindex tzconv
  14245. @cindex Time Zones, converting between
  14246. The @kbd{t C} (@code{calc-convert-time-zones}) [@code{tzconv}]
  14247. command converts a date form from one time zone to another. You
  14248. are prompted for each time zone name in turn; you can answer with
  14249. any suitable Calc time zone expression (@pxref{Time Zones}).
  14250. If you answer either prompt with a blank line, the local time
  14251. zone is used for that prompt. You can also answer the first
  14252. prompt with @kbd{$} to take the two time zone names from the
  14253. stack (and the date to be converted from the third stack level).
  14254. @node Date Functions, Business Days, Date Conversions, Date Arithmetic
  14255. @subsection Date Functions
  14256. @noindent
  14257. @kindex t N
  14258. @pindex calc-now
  14259. @tindex now
  14260. The @kbd{t N} (@code{calc-now}) [@code{now}] command pushes the
  14261. current date and time on the stack as a date form. The time is
  14262. reported in terms of the specified time zone; with no numeric prefix
  14263. argument, @kbd{t N} reports for the current time zone.
  14264. @kindex t P
  14265. @pindex calc-date-part
  14266. The @kbd{t P} (@code{calc-date-part}) command extracts one part
  14267. of a date form. The prefix argument specifies the part; with no
  14268. argument, this command prompts for a part code from 1 to 9.
  14269. The various part codes are described in the following paragraphs.
  14270. @tindex year
  14271. The @kbd{M-1 t P} [@code{year}] function extracts the year number
  14272. from a date form as an integer, e.g., 1991. This and the
  14273. following functions will also accept a real number for an
  14274. argument, which is interpreted as a standard Calc day number.
  14275. Note that this function will never return zero, since the year
  14276. 1 BC immediately precedes the year 1 AD.
  14277. @tindex month
  14278. The @kbd{M-2 t P} [@code{month}] function extracts the month number
  14279. from a date form as an integer in the range 1 to 12.
  14280. @tindex day
  14281. The @kbd{M-3 t P} [@code{day}] function extracts the day number
  14282. from a date form as an integer in the range 1 to 31.
  14283. @tindex hour
  14284. The @kbd{M-4 t P} [@code{hour}] function extracts the hour from
  14285. a date form as an integer in the range 0 (midnight) to 23. Note
  14286. that 24-hour time is always used. This returns zero for a pure
  14287. date form. This function (and the following two) also accept
  14288. HMS forms as input.
  14289. @tindex minute
  14290. The @kbd{M-5 t P} [@code{minute}] function extracts the minute
  14291. from a date form as an integer in the range 0 to 59.
  14292. @tindex second
  14293. The @kbd{M-6 t P} [@code{second}] function extracts the second
  14294. from a date form. If the current precision is 12 or less,
  14295. the result is an integer in the range 0 to 59. For higher
  14296. precision, the result may instead be a floating-point number.
  14297. @tindex weekday
  14298. The @kbd{M-7 t P} [@code{weekday}] function extracts the weekday
  14299. number from a date form as an integer in the range 0 (Sunday)
  14300. to 6 (Saturday).
  14301. @tindex yearday
  14302. The @kbd{M-8 t P} [@code{yearday}] function extracts the day-of-year
  14303. number from a date form as an integer in the range 1 (January 1)
  14304. to 366 (December 31 of a leap year).
  14305. @tindex time
  14306. The @kbd{M-9 t P} [@code{time}] function extracts the time portion
  14307. of a date form as an HMS form. This returns @samp{0@@ 0' 0"}
  14308. for a pure date form.
  14309. @kindex t M
  14310. @pindex calc-new-month
  14311. @tindex newmonth
  14312. The @kbd{t M} (@code{calc-new-month}) [@code{newmonth}] command
  14313. computes a new date form that represents the first day of the month
  14314. specified by the input date. The result is always a pure date
  14315. form; only the year and month numbers of the input are retained.
  14316. With a numeric prefix argument @var{n} in the range from 1 to 31,
  14317. @kbd{t M} computes the @var{n}th day of the month. (If @var{n}
  14318. is greater than the actual number of days in the month, or if
  14319. @var{n} is zero, the last day of the month is used.)
  14320. @kindex t Y
  14321. @pindex calc-new-year
  14322. @tindex newyear
  14323. The @kbd{t Y} (@code{calc-new-year}) [@code{newyear}] command
  14324. computes a new pure date form that represents the first day of
  14325. the year specified by the input. The month, day, and time
  14326. of the input date form are lost. With a numeric prefix argument
  14327. @var{n} in the range from 1 to 366, @kbd{t Y} computes the
  14328. @var{n}th day of the year (366 is treated as 365 in non-leap
  14329. years). A prefix argument of 0 computes the last day of the
  14330. year (December 31). A negative prefix argument from @mathit{-1} to
  14331. @mathit{-12} computes the first day of the @var{n}th month of the year.
  14332. @kindex t W
  14333. @pindex calc-new-week
  14334. @tindex newweek
  14335. The @kbd{t W} (@code{calc-new-week}) [@code{newweek}] command
  14336. computes a new pure date form that represents the Sunday on or before
  14337. the input date. With a numeric prefix argument, it can be made to
  14338. use any day of the week as the starting day; the argument must be in
  14339. the range from 0 (Sunday) to 6 (Saturday). This function always
  14340. subtracts between 0 and 6 days from the input date.
  14341. Here's an example use of @code{newweek}: Find the date of the next
  14342. Wednesday after a given date. Using @kbd{M-3 t W} or @samp{newweek(d, 3)}
  14343. will give you the @emph{preceding} Wednesday, so @samp{newweek(d+7, 3)}
  14344. will give you the following Wednesday. A further look at the definition
  14345. of @code{newweek} shows that if the input date is itself a Wednesday,
  14346. this formula will return the Wednesday one week in the future. An
  14347. exercise for the reader is to modify this formula to yield the same day
  14348. if the input is already a Wednesday. Another interesting exercise is
  14349. to preserve the time-of-day portion of the input (@code{newweek} resets
  14350. the time to midnight; hint: how can @code{newweek} be defined in terms
  14351. of the @code{weekday} function?).
  14352. @ignore
  14353. @starindex
  14354. @end ignore
  14355. @tindex pwday
  14356. The @samp{pwday(@var{date})} function (not on any key) computes the
  14357. day-of-month number of the Sunday on or before @var{date}. With
  14358. two arguments, @samp{pwday(@var{date}, @var{day})} computes the day
  14359. number of the Sunday on or before day number @var{day} of the month
  14360. specified by @var{date}. The @var{day} must be in the range from
  14361. 7 to 31; if the day number is greater than the actual number of days
  14362. in the month, the true number of days is used instead. Thus
  14363. @samp{pwday(@var{date}, 7)} finds the first Sunday of the month, and
  14364. @samp{pwday(@var{date}, 31)} finds the last Sunday of the month.
  14365. With a third @var{weekday} argument, @code{pwday} can be made to look
  14366. for any day of the week instead of Sunday.
  14367. @kindex t I
  14368. @pindex calc-inc-month
  14369. @tindex incmonth
  14370. The @kbd{t I} (@code{calc-inc-month}) [@code{incmonth}] command
  14371. increases a date form by one month, or by an arbitrary number of
  14372. months specified by a numeric prefix argument. The time portion,
  14373. if any, of the date form stays the same. The day also stays the
  14374. same, except that if the new month has fewer days the day
  14375. number may be reduced to lie in the valid range. For example,
  14376. @samp{incmonth(<Jan 31, 1991>)} produces @samp{<Feb 28, 1991>}.
  14377. Because of this, @kbd{t I t I} and @kbd{M-2 t I} do not always give
  14378. the same results (@samp{<Mar 28, 1991>} versus @samp{<Mar 31, 1991>}
  14379. in this case).
  14380. @ignore
  14381. @starindex
  14382. @end ignore
  14383. @tindex incyear
  14384. The @samp{incyear(@var{date}, @var{step})} function increases
  14385. a date form by the specified number of years, which may be
  14386. any positive or negative integer. Note that @samp{incyear(d, n)}
  14387. is equivalent to @w{@samp{incmonth(d, 12*n)}}, but these do not have
  14388. simple equivalents in terms of day arithmetic because
  14389. months and years have varying lengths. If the @var{step}
  14390. argument is omitted, 1 year is assumed. There is no keyboard
  14391. command for this function; use @kbd{C-u 12 t I} instead.
  14392. There is no @code{newday} function at all because @kbd{F} [@code{floor}]
  14393. serves this purpose. Similarly, instead of @code{incday} and
  14394. @code{incweek} simply use @expr{d + n} or @expr{d + 7 n}.
  14395. @xref{Basic Arithmetic}, for the @kbd{f ]} [@code{incr}] command
  14396. which can adjust a date/time form by a certain number of seconds.
  14397. @node Business Days, Time Zones, Date Functions, Date Arithmetic
  14398. @subsection Business Days
  14399. @noindent
  14400. Often time is measured in ``business days'' or ``working days,''
  14401. where weekends and holidays are skipped. Calc's normal date
  14402. arithmetic functions use calendar days, so that subtracting two
  14403. consecutive Mondays will yield a difference of 7 days. By contrast,
  14404. subtracting two consecutive Mondays would yield 5 business days
  14405. (assuming two-day weekends and the absence of holidays).
  14406. @kindex t +
  14407. @kindex t -
  14408. @tindex badd
  14409. @tindex bsub
  14410. @pindex calc-business-days-plus
  14411. @pindex calc-business-days-minus
  14412. The @kbd{t +} (@code{calc-business-days-plus}) [@code{badd}]
  14413. and @kbd{t -} (@code{calc-business-days-minus}) [@code{bsub}]
  14414. commands perform arithmetic using business days. For @kbd{t +},
  14415. one argument must be a date form and the other must be a real
  14416. number (positive or negative). If the number is not an integer,
  14417. then a certain amount of time is added as well as a number of
  14418. days; for example, adding 0.5 business days to a time in Friday
  14419. evening will produce a time in Monday morning. It is also
  14420. possible to add an HMS form; adding @samp{12@@ 0' 0"} also adds
  14421. half a business day. For @kbd{t -}, the arguments are either a
  14422. date form and a number or HMS form, or two date forms, in which
  14423. case the result is the number of business days between the two
  14424. dates.
  14425. @cindex @code{Holidays} variable
  14426. @vindex Holidays
  14427. By default, Calc considers any day that is not a Saturday or
  14428. Sunday to be a business day. You can define any number of
  14429. additional holidays by editing the variable @code{Holidays}.
  14430. (There is an @w{@kbd{s H}} convenience command for editing this
  14431. variable.) Initially, @code{Holidays} contains the vector
  14432. @samp{[sat, sun]}. Entries in the @code{Holidays} vector may
  14433. be any of the following kinds of objects:
  14434. @itemize @bullet
  14435. @item
  14436. Date forms (pure dates, not date/time forms). These specify
  14437. particular days which are to be treated as holidays.
  14438. @item
  14439. Intervals of date forms. These specify a range of days, all of
  14440. which are holidays (e.g., Christmas week). @xref{Interval Forms}.
  14441. @item
  14442. Nested vectors of date forms. Each date form in the vector is
  14443. considered to be a holiday.
  14444. @item
  14445. Any Calc formula which evaluates to one of the above three things.
  14446. If the formula involves the variable @expr{y}, it stands for a
  14447. yearly repeating holiday; @expr{y} will take on various year
  14448. numbers like 1992. For example, @samp{date(y, 12, 25)} specifies
  14449. Christmas day, and @samp{newweek(date(y, 11, 7), 4) + 21} specifies
  14450. Thanksgiving (which is held on the fourth Thursday of November).
  14451. If the formula involves the variable @expr{m}, that variable
  14452. takes on month numbers from 1 to 12: @samp{date(y, m, 15)} is
  14453. a holiday that takes place on the 15th of every month.
  14454. @item
  14455. A weekday name, such as @code{sat} or @code{sun}. This is really
  14456. a variable whose name is a three-letter, lower-case day name.
  14457. @item
  14458. An interval of year numbers (integers). This specifies the span of
  14459. years over which this holiday list is to be considered valid. Any
  14460. business-day arithmetic that goes outside this range will result
  14461. in an error message. Use this if you are including an explicit
  14462. list of holidays, rather than a formula to generate them, and you
  14463. want to make sure you don't accidentally go beyond the last point
  14464. where the holidays you entered are complete. If there is no
  14465. limiting interval in the @code{Holidays} vector, the default
  14466. @samp{[1 .. 2737]} is used. (This is the absolute range of years
  14467. for which Calc's business-day algorithms will operate.)
  14468. @item
  14469. An interval of HMS forms. This specifies the span of hours that
  14470. are to be considered one business day. For example, if this
  14471. range is @samp{[9@@ 0' 0" .. 17@@ 0' 0"]} (i.e., 9am to 5pm), then
  14472. the business day is only eight hours long, so that @kbd{1.5 t +}
  14473. on @samp{<4:00pm Fri Dec 13, 1991>} will add one business day and
  14474. four business hours to produce @samp{<12:00pm Tue Dec 17, 1991>}.
  14475. Likewise, @kbd{t -} will now express differences in time as
  14476. fractions of an eight-hour day. Times before 9am will be treated
  14477. as 9am by business date arithmetic, and times at or after 5pm will
  14478. be treated as 4:59:59pm. If there is no HMS interval in @code{Holidays},
  14479. the full 24-hour day @samp{[0@ 0' 0" .. 24@ 0' 0"]} is assumed.
  14480. (Regardless of the type of bounds you specify, the interval is
  14481. treated as inclusive on the low end and exclusive on the high end,
  14482. so that the work day goes from 9am up to, but not including, 5pm.)
  14483. @end itemize
  14484. If the @code{Holidays} vector is empty, then @kbd{t +} and
  14485. @kbd{t -} will act just like @kbd{+} and @kbd{-} because there will
  14486. then be no difference between business days and calendar days.
  14487. Calc expands the intervals and formulas you give into a complete
  14488. list of holidays for internal use. This is done mainly to make
  14489. sure it can detect multiple holidays. (For example,
  14490. @samp{<Jan 1, 1989>} is both New Year's Day and a Sunday, but
  14491. Calc's algorithms take care to count it only once when figuring
  14492. the number of holidays between two dates.)
  14493. Since the complete list of holidays for all the years from 1 to
  14494. 2737 would be huge, Calc actually computes only the part of the
  14495. list between the smallest and largest years that have been involved
  14496. in business-day calculations so far. Normally, you won't have to
  14497. worry about this. Keep in mind, however, that if you do one
  14498. calculation for 1992, and another for 1792, even if both involve
  14499. only a small range of years, Calc will still work out all the
  14500. holidays that fall in that 200-year span.
  14501. If you add a (positive) number of days to a date form that falls on a
  14502. weekend or holiday, the date form is treated as if it were the most
  14503. recent business day. (Thus adding one business day to a Friday,
  14504. Saturday, or Sunday will all yield the following Monday.) If you
  14505. subtract a number of days from a weekend or holiday, the date is
  14506. effectively on the following business day. (So subtracting one business
  14507. day from Saturday, Sunday, or Monday yields the preceding Friday.) The
  14508. difference between two dates one or both of which fall on holidays
  14509. equals the number of actual business days between them. These
  14510. conventions are consistent in the sense that, if you add @var{n}
  14511. business days to any date, the difference between the result and the
  14512. original date will come out to @var{n} business days. (It can't be
  14513. completely consistent though; a subtraction followed by an addition
  14514. might come out a bit differently, since @kbd{t +} is incapable of
  14515. producing a date that falls on a weekend or holiday.)
  14516. @ignore
  14517. @starindex
  14518. @end ignore
  14519. @tindex holiday
  14520. There is a @code{holiday} function, not on any keys, that takes
  14521. any date form and returns 1 if that date falls on a weekend or
  14522. holiday, as defined in @code{Holidays}, or 0 if the date is a
  14523. business day.
  14524. @node Time Zones, , Business Days, Date Arithmetic
  14525. @subsection Time Zones
  14526. @noindent
  14527. @cindex Time zones
  14528. @cindex Daylight saving time
  14529. Time zones and daylight saving time are a complicated business.
  14530. The conversions to and from Julian and Unix-style dates automatically
  14531. compute the correct time zone and daylight saving adjustment to use,
  14532. provided they can figure out this information. This section describes
  14533. Calc's time zone adjustment algorithm in detail, in case you want to
  14534. do conversions in different time zones or in case Calc's algorithms
  14535. can't determine the right correction to use.
  14536. Adjustments for time zones and daylight saving time are done by
  14537. @kbd{t U}, @kbd{t J}, @kbd{t N}, and @kbd{t C}, but not by any other
  14538. commands. In particular, @samp{<may 1 1991> - <apr 1 1991>} evaluates
  14539. to exactly 30 days even though there is a daylight-saving
  14540. transition in between. This is also true for Julian pure dates:
  14541. @samp{julian(<may 1 1991>) - julian(<apr 1 1991>)}. But Julian
  14542. and Unix date/times will adjust for daylight saving time: using Calc's
  14543. default daylight saving time rule (see the explanation below),
  14544. @samp{julian(<12am may 1 1991>) - julian(<12am apr 1 1991>)}
  14545. evaluates to @samp{29.95833} (that's 29 days and 23 hours)
  14546. because one hour was lost when daylight saving commenced on
  14547. April 7, 1991.
  14548. In brief, the idiom @samp{julian(@var{date1}) - julian(@var{date2})}
  14549. computes the actual number of 24-hour periods between two dates, whereas
  14550. @samp{@var{date1} - @var{date2}} computes the number of calendar
  14551. days between two dates without taking daylight saving into account.
  14552. @pindex calc-time-zone
  14553. @ignore
  14554. @starindex
  14555. @end ignore
  14556. @tindex tzone
  14557. The @code{calc-time-zone} [@code{tzone}] command converts the time
  14558. zone specified by its numeric prefix argument into a number of
  14559. seconds difference from Greenwich mean time (GMT). If the argument
  14560. is a number, the result is simply that value multiplied by 3600.
  14561. Typical arguments for North America are 5 (Eastern) or 8 (Pacific). If
  14562. Daylight Saving time is in effect, one hour should be subtracted from
  14563. the normal difference.
  14564. If you give a prefix of plain @kbd{C-u}, @code{calc-time-zone} (like other
  14565. date arithmetic commands that include a time zone argument) takes the
  14566. zone argument from the top of the stack. (In the case of @kbd{t J}
  14567. and @kbd{t U}, the normal argument is then taken from the second-to-top
  14568. stack position.) This allows you to give a non-integer time zone
  14569. adjustment. The time-zone argument can also be an HMS form, or
  14570. it can be a variable which is a time zone name in upper- or lower-case.
  14571. For example @samp{tzone(PST) = tzone(8)} and @samp{tzone(pdt) = tzone(7)}
  14572. (for Pacific standard and daylight saving times, respectively).
  14573. North American and European time zone names are defined as follows;
  14574. note that for each time zone there is one name for standard time,
  14575. another for daylight saving time, and a third for ``generalized'' time
  14576. in which the daylight saving adjustment is computed from context.
  14577. @smallexample
  14578. @group
  14579. YST PST MST CST EST AST NST GMT WET MET MEZ
  14580. 9 8 7 6 5 4 3.5 0 -1 -2 -2
  14581. YDT PDT MDT CDT EDT ADT NDT BST WETDST METDST MESZ
  14582. 8 7 6 5 4 3 2.5 -1 -2 -3 -3
  14583. YGT PGT MGT CGT EGT AGT NGT BGT WEGT MEGT MEGZ
  14584. 9/8 8/7 7/6 6/5 5/4 4/3 3.5/2.5 0/-1 -1/-2 -2/-3 -2/-3
  14585. @end group
  14586. @end smallexample
  14587. @vindex math-tzone-names
  14588. To define time zone names that do not appear in the above table,
  14589. you must modify the Lisp variable @code{math-tzone-names}. This
  14590. is a list of lists describing the different time zone names; its
  14591. structure is best explained by an example. The three entries for
  14592. Pacific Time look like this:
  14593. @smallexample
  14594. @group
  14595. ( ( "PST" 8 0 ) ; Name as an upper-case string, then standard
  14596. ( "PDT" 8 -1 ) ; adjustment, then daylight saving adjustment.
  14597. ( "PGT" 8 "PST" "PDT" ) ) ; Generalized time zone.
  14598. @end group
  14599. @end smallexample
  14600. @cindex @code{TimeZone} variable
  14601. @vindex TimeZone
  14602. With no arguments, @code{calc-time-zone} or @samp{tzone()} will by
  14603. default get the time zone and daylight saving information from the
  14604. calendar (@pxref{Daylight Saving,Calendar/Diary,The Calendar and the Diary,
  14605. emacs,The GNU Emacs Manual}). To use a different time zone, or if the
  14606. calendar does not give the desired result, you can set the Calc variable
  14607. @code{TimeZone} (which is by default @code{nil}) to an appropriate
  14608. time zone name. (The easiest way to do this is to edit the
  14609. @code{TimeZone} variable using Calc's @kbd{s T} command, then use the
  14610. @kbd{s p} (@code{calc-permanent-variable}) command to save the value of
  14611. @code{TimeZone} permanently.)
  14612. If the time zone given by @code{TimeZone} is a generalized time zone,
  14613. e.g., @code{EGT}, Calc examines the date being converted to tell whether
  14614. to use standard or daylight saving time. But if the current time zone
  14615. is explicit, e.g., @code{EST} or @code{EDT}, then that adjustment is
  14616. used exactly and Calc's daylight saving algorithm is not consulted.
  14617. The special time zone name @code{local}
  14618. is equivalent to no argument; i.e., it uses the information obtained
  14619. from the calendar.
  14620. The @kbd{t J} and @code{t U} commands with no numeric prefix
  14621. arguments do the same thing as @samp{tzone()}; namely, use the
  14622. information from the calendar if @code{TimeZone} is @code{nil},
  14623. otherwise use the time zone given by @code{TimeZone}.
  14624. @vindex math-daylight-savings-hook
  14625. @findex math-std-daylight-savings
  14626. When Calc computes the daylight saving information itself (i.e., when
  14627. the @code{TimeZone} variable is set), it will by default consider
  14628. daylight saving time to begin at 2 a.m.@: on the second Sunday of March
  14629. (for years from 2007 on) or on the last Sunday in April (for years
  14630. before 2007), and to end at 2 a.m.@: on the first Sunday of
  14631. November. (for years from 2007 on) or the last Sunday in October (for
  14632. years before 2007). These are the rules that have been in effect in
  14633. much of North America since 1966 and take into account the rule change
  14634. that began in 2007. If you are in a country that uses different rules
  14635. for computing daylight saving time, you have two choices: Write your own
  14636. daylight saving hook, or control time zones explicitly by setting the
  14637. @code{TimeZone} variable and/or always giving a time-zone argument for
  14638. the conversion functions.
  14639. The Lisp variable @code{math-daylight-savings-hook} holds the
  14640. name of a function that is used to compute the daylight saving
  14641. adjustment for a given date. The default is
  14642. @code{math-std-daylight-savings}, which computes an adjustment
  14643. (either 0 or @mathit{-1}) using the North American rules given above.
  14644. The daylight saving hook function is called with four arguments:
  14645. The date, as a floating-point number in standard Calc format;
  14646. a six-element list of the date decomposed into year, month, day,
  14647. hour, minute, and second, respectively; a string which contains
  14648. the generalized time zone name in upper-case, e.g., @code{"WEGT"};
  14649. and a special adjustment to be applied to the hour value when
  14650. converting into a generalized time zone (see below).
  14651. @findex math-prev-weekday-in-month
  14652. The Lisp function @code{math-prev-weekday-in-month} is useful for
  14653. daylight saving computations. This is an internal version of
  14654. the user-level @code{pwday} function described in the previous
  14655. section. It takes four arguments: The floating-point date value,
  14656. the corresponding six-element date list, the day-of-month number,
  14657. and the weekday number (0--6).
  14658. The default daylight saving hook ignores the time zone name, but a
  14659. more sophisticated hook could use different algorithms for different
  14660. time zones. It would also be possible to use different algorithms
  14661. depending on the year number, but the default hook always uses the
  14662. algorithm for 1987 and later. Here is a listing of the default
  14663. daylight saving hook:
  14664. @smallexample
  14665. (defun math-std-daylight-savings (date dt zone bump)
  14666. (cond ((< (nth 1 dt) 4) 0)
  14667. ((= (nth 1 dt) 4)
  14668. (let ((sunday (math-prev-weekday-in-month date dt 7 0)))
  14669. (cond ((< (nth 2 dt) sunday) 0)
  14670. ((= (nth 2 dt) sunday)
  14671. (if (>= (nth 3 dt) (+ 3 bump)) -1 0))
  14672. (t -1))))
  14673. ((< (nth 1 dt) 10) -1)
  14674. ((= (nth 1 dt) 10)
  14675. (let ((sunday (math-prev-weekday-in-month date dt 31 0)))
  14676. (cond ((< (nth 2 dt) sunday) -1)
  14677. ((= (nth 2 dt) sunday)
  14678. (if (>= (nth 3 dt) (+ 2 bump)) 0 -1))
  14679. (t 0))))
  14680. (t 0))
  14681. )
  14682. @end smallexample
  14683. @noindent
  14684. The @code{bump} parameter is equal to zero when Calc is converting
  14685. from a date form in a generalized time zone into a GMT date value.
  14686. It is @mathit{-1} when Calc is converting in the other direction. The
  14687. adjustments shown above ensure that the conversion behaves correctly
  14688. and reasonably around the 2 a.m.@: transition in each direction.
  14689. There is a ``missing'' hour between 2 a.m.@: and 3 a.m.@: at the
  14690. beginning of daylight saving time; converting a date/time form that
  14691. falls in this hour results in a time value for the following hour,
  14692. from 3 a.m.@: to 4 a.m. At the end of daylight saving time, the
  14693. hour from 1 a.m.@: to 2 a.m.@: repeats itself; converting a date/time
  14694. form that falls in this hour results in a time value for the first
  14695. manifestation of that time (@emph{not} the one that occurs one hour
  14696. later).
  14697. If @code{math-daylight-savings-hook} is @code{nil}, then the
  14698. daylight saving adjustment is always taken to be zero.
  14699. In algebraic formulas, @samp{tzone(@var{zone}, @var{date})}
  14700. computes the time zone adjustment for a given zone name at a
  14701. given date. The @var{date} is ignored unless @var{zone} is a
  14702. generalized time zone. If @var{date} is a date form, the
  14703. daylight saving computation is applied to it as it appears.
  14704. If @var{date} is a numeric date value, it is adjusted for the
  14705. daylight-saving version of @var{zone} before being given to
  14706. the daylight saving hook. This odd-sounding rule ensures
  14707. that the daylight-saving computation is always done in
  14708. local time, not in the GMT time that a numeric @var{date}
  14709. is typically represented in.
  14710. @ignore
  14711. @starindex
  14712. @end ignore
  14713. @tindex dsadj
  14714. The @samp{dsadj(@var{date}, @var{zone})} function computes the
  14715. daylight saving adjustment that is appropriate for @var{date} in
  14716. time zone @var{zone}. If @var{zone} is explicitly in or not in
  14717. daylight saving time (e.g., @code{PDT} or @code{PST}) the
  14718. @var{date} is ignored. If @var{zone} is a generalized time zone,
  14719. the algorithms described above are used. If @var{zone} is omitted,
  14720. the computation is done for the current time zone.
  14721. @node Financial Functions, Binary Functions, Date Arithmetic, Arithmetic
  14722. @section Financial Functions
  14723. @noindent
  14724. Calc's financial or business functions use the @kbd{b} prefix
  14725. key followed by a shifted letter. (The @kbd{b} prefix followed by
  14726. a lower-case letter is used for operations on binary numbers.)
  14727. Note that the rate and the number of intervals given to these
  14728. functions must be on the same time scale, e.g., both months or
  14729. both years. Mixing an annual interest rate with a time expressed
  14730. in months will give you very wrong answers!
  14731. It is wise to compute these functions to a higher precision than
  14732. you really need, just to make sure your answer is correct to the
  14733. last penny; also, you may wish to check the definitions at the end
  14734. of this section to make sure the functions have the meaning you expect.
  14735. @menu
  14736. * Percentages::
  14737. * Future Value::
  14738. * Present Value::
  14739. * Related Financial Functions::
  14740. * Depreciation Functions::
  14741. * Definitions of Financial Functions::
  14742. @end menu
  14743. @node Percentages, Future Value, Financial Functions, Financial Functions
  14744. @subsection Percentages
  14745. @kindex M-%
  14746. @pindex calc-percent
  14747. @tindex %
  14748. @tindex percent
  14749. The @kbd{M-%} (@code{calc-percent}) command takes a percentage value,
  14750. say 5.4, and converts it to an equivalent actual number. For example,
  14751. @kbd{5.4 M-%} enters 0.054 on the stack. (That's the @key{META} or
  14752. @key{ESC} key combined with @kbd{%}.)
  14753. Actually, @kbd{M-%} creates a formula of the form @samp{5.4%}.
  14754. You can enter @samp{5.4%} yourself during algebraic entry. The
  14755. @samp{%} operator simply means, ``the preceding value divided by
  14756. 100.'' The @samp{%} operator has very high precedence, so that
  14757. @samp{1+8%} is interpreted as @samp{1+(8%)}, not as @samp{(1+8)%}.
  14758. (The @samp{%} operator is just a postfix notation for the
  14759. @code{percent} function, just like @samp{20!} is the notation for
  14760. @samp{fact(20)}, or twenty-factorial.)
  14761. The formula @samp{5.4%} would normally evaluate immediately to
  14762. 0.054, but the @kbd{M-%} command suppresses evaluation as it puts
  14763. the formula onto the stack. However, the next Calc command that
  14764. uses the formula @samp{5.4%} will evaluate it as its first step.
  14765. The net effect is that you get to look at @samp{5.4%} on the stack,
  14766. but Calc commands see it as @samp{0.054}, which is what they expect.
  14767. In particular, @samp{5.4%} and @samp{0.054} are suitable values
  14768. for the @var{rate} arguments of the various financial functions,
  14769. but the number @samp{5.4} is probably @emph{not} suitable---it
  14770. represents a rate of 540 percent!
  14771. The key sequence @kbd{M-% *} effectively means ``percent-of.''
  14772. For example, @kbd{68 @key{RET} 25 M-% *} computes 17, which is 25% of
  14773. 68 (and also 68% of 25, which comes out to the same thing).
  14774. @kindex c %
  14775. @pindex calc-convert-percent
  14776. The @kbd{c %} (@code{calc-convert-percent}) command converts the
  14777. value on the top of the stack from numeric to percentage form.
  14778. For example, if 0.08 is on the stack, @kbd{c %} converts it to
  14779. @samp{8%}. The quantity is the same, it's just represented
  14780. differently. (Contrast this with @kbd{M-%}, which would convert
  14781. this number to @samp{0.08%}.) The @kbd{=} key is a convenient way
  14782. to convert a formula like @samp{8%} back to numeric form, 0.08.
  14783. To compute what percentage one quantity is of another quantity,
  14784. use @kbd{/ c %}. For example, @w{@kbd{17 @key{RET} 68 / c %}} displays
  14785. @samp{25%}.
  14786. @kindex b %
  14787. @pindex calc-percent-change
  14788. @tindex relch
  14789. The @kbd{b %} (@code{calc-percent-change}) [@code{relch}] command
  14790. calculates the percentage change from one number to another.
  14791. For example, @kbd{40 @key{RET} 50 b %} produces the answer @samp{25%},
  14792. since 50 is 25% larger than 40. A negative result represents a
  14793. decrease: @kbd{50 @key{RET} 40 b %} produces @samp{-20%}, since 40 is
  14794. 20% smaller than 50. (The answers are different in magnitude
  14795. because, in the first case, we're increasing by 25% of 40, but
  14796. in the second case, we're decreasing by 20% of 50.) The effect
  14797. of @kbd{40 @key{RET} 50 b %} is to compute @expr{(50-40)/40}, converting
  14798. the answer to percentage form as if by @kbd{c %}.
  14799. @node Future Value, Present Value, Percentages, Financial Functions
  14800. @subsection Future Value
  14801. @noindent
  14802. @kindex b F
  14803. @pindex calc-fin-fv
  14804. @tindex fv
  14805. The @kbd{b F} (@code{calc-fin-fv}) [@code{fv}] command computes
  14806. the future value of an investment. It takes three arguments
  14807. from the stack: @samp{fv(@var{rate}, @var{n}, @var{payment})}.
  14808. If you give payments of @var{payment} every year for @var{n}
  14809. years, and the money you have paid earns interest at @var{rate} per
  14810. year, then this function tells you what your investment would be
  14811. worth at the end of the period. (The actual interval doesn't
  14812. have to be years, as long as @var{n} and @var{rate} are expressed
  14813. in terms of the same intervals.) This function assumes payments
  14814. occur at the @emph{end} of each interval.
  14815. @kindex I b F
  14816. @tindex fvb
  14817. The @kbd{I b F} [@code{fvb}] command does the same computation,
  14818. but assuming your payments are at the beginning of each interval.
  14819. Suppose you plan to deposit $1000 per year in a savings account
  14820. earning 5.4% interest, starting right now. How much will be
  14821. in the account after five years? @code{fvb(5.4%, 5, 1000) = 5870.73}.
  14822. Thus you will have earned $870 worth of interest over the years.
  14823. Using the stack, this calculation would have been
  14824. @kbd{5.4 M-% 5 @key{RET} 1000 I b F}. Note that the rate is expressed
  14825. as a number between 0 and 1, @emph{not} as a percentage.
  14826. @kindex H b F
  14827. @tindex fvl
  14828. The @kbd{H b F} [@code{fvl}] command computes the future value
  14829. of an initial lump sum investment. Suppose you could deposit
  14830. those five thousand dollars in the bank right now; how much would
  14831. they be worth in five years? @code{fvl(5.4%, 5, 5000) = 6503.89}.
  14832. The algebraic functions @code{fv} and @code{fvb} accept an optional
  14833. fourth argument, which is used as an initial lump sum in the sense
  14834. of @code{fvl}. In other words, @code{fv(@var{rate}, @var{n},
  14835. @var{payment}, @var{initial}) = fv(@var{rate}, @var{n}, @var{payment})
  14836. + fvl(@var{rate}, @var{n}, @var{initial})}.
  14837. To illustrate the relationships between these functions, we could
  14838. do the @code{fvb} calculation ``by hand'' using @code{fvl}. The
  14839. final balance will be the sum of the contributions of our five
  14840. deposits at various times. The first deposit earns interest for
  14841. five years: @code{fvl(5.4%, 5, 1000) = 1300.78}. The second
  14842. deposit only earns interest for four years: @code{fvl(5.4%, 4, 1000) =
  14843. 1234.13}. And so on down to the last deposit, which earns one
  14844. year's interest: @code{fvl(5.4%, 1, 1000) = 1054.00}. The sum of
  14845. these five values is, sure enough, $5870.73, just as was computed
  14846. by @code{fvb} directly.
  14847. What does @code{fv(5.4%, 5, 1000) = 5569.96} mean? The payments
  14848. are now at the ends of the periods. The end of one year is the same
  14849. as the beginning of the next, so what this really means is that we've
  14850. lost the payment at year zero (which contributed $1300.78), but we're
  14851. now counting the payment at year five (which, since it didn't have
  14852. a chance to earn interest, counts as $1000). Indeed, @expr{5569.96 =
  14853. 5870.73 - 1300.78 + 1000} (give or take a bit of roundoff error).
  14854. @node Present Value, Related Financial Functions, Future Value, Financial Functions
  14855. @subsection Present Value
  14856. @noindent
  14857. @kindex b P
  14858. @pindex calc-fin-pv
  14859. @tindex pv
  14860. The @kbd{b P} (@code{calc-fin-pv}) [@code{pv}] command computes
  14861. the present value of an investment. Like @code{fv}, it takes
  14862. three arguments: @code{pv(@var{rate}, @var{n}, @var{payment})}.
  14863. It computes the present value of a series of regular payments.
  14864. Suppose you have the chance to make an investment that will
  14865. pay $2000 per year over the next four years; as you receive
  14866. these payments you can put them in the bank at 9% interest.
  14867. You want to know whether it is better to make the investment, or
  14868. to keep the money in the bank where it earns 9% interest right
  14869. from the start. The calculation @code{pv(9%, 4, 2000)} gives the
  14870. result 6479.44. If your initial investment must be less than this,
  14871. say, $6000, then the investment is worthwhile. But if you had to
  14872. put up $7000, then it would be better just to leave it in the bank.
  14873. Here is the interpretation of the result of @code{pv}: You are
  14874. trying to compare the return from the investment you are
  14875. considering, which is @code{fv(9%, 4, 2000) = 9146.26}, with
  14876. the return from leaving the money in the bank, which is
  14877. @code{fvl(9%, 4, @var{x})} where @var{x} is the amount of money
  14878. you would have to put up in advance. The @code{pv} function
  14879. finds the break-even point, @expr{x = 6479.44}, at which
  14880. @code{fvl(9%, 4, 6479.44)} is also equal to 9146.26. This is
  14881. the largest amount you should be willing to invest.
  14882. @kindex I b P
  14883. @tindex pvb
  14884. The @kbd{I b P} [@code{pvb}] command solves the same problem,
  14885. but with payments occurring at the beginning of each interval.
  14886. It has the same relationship to @code{fvb} as @code{pv} has
  14887. to @code{fv}. For example @code{pvb(9%, 4, 2000) = 7062.59},
  14888. a larger number than @code{pv} produced because we get to start
  14889. earning interest on the return from our investment sooner.
  14890. @kindex H b P
  14891. @tindex pvl
  14892. The @kbd{H b P} [@code{pvl}] command computes the present value of
  14893. an investment that will pay off in one lump sum at the end of the
  14894. period. For example, if we get our $8000 all at the end of the
  14895. four years, @code{pvl(9%, 4, 8000) = 5667.40}. This is much
  14896. less than @code{pv} reported, because we don't earn any interest
  14897. on the return from this investment. Note that @code{pvl} and
  14898. @code{fvl} are simple inverses: @code{fvl(9%, 4, 5667.40) = 8000}.
  14899. You can give an optional fourth lump-sum argument to @code{pv}
  14900. and @code{pvb}; this is handled in exactly the same way as the
  14901. fourth argument for @code{fv} and @code{fvb}.
  14902. @kindex b N
  14903. @pindex calc-fin-npv
  14904. @tindex npv
  14905. The @kbd{b N} (@code{calc-fin-npv}) [@code{npv}] command computes
  14906. the net present value of a series of irregular investments.
  14907. The first argument is the interest rate. The second argument is
  14908. a vector which represents the expected return from the investment
  14909. at the end of each interval. For example, if the rate represents
  14910. a yearly interest rate, then the vector elements are the return
  14911. from the first year, second year, and so on.
  14912. Thus, @code{npv(9%, [2000,2000,2000,2000]) = pv(9%, 4, 2000) = 6479.44}.
  14913. Obviously this function is more interesting when the payments are
  14914. not all the same!
  14915. The @code{npv} function can actually have two or more arguments.
  14916. Multiple arguments are interpreted in the same way as for the
  14917. vector statistical functions like @code{vsum}.
  14918. @xref{Single-Variable Statistics}. Basically, if there are several
  14919. payment arguments, each either a vector or a plain number, all these
  14920. values are collected left-to-right into the complete list of payments.
  14921. A numeric prefix argument on the @kbd{b N} command says how many
  14922. payment values or vectors to take from the stack.
  14923. @kindex I b N
  14924. @tindex npvb
  14925. The @kbd{I b N} [@code{npvb}] command computes the net present
  14926. value where payments occur at the beginning of each interval
  14927. rather than at the end.
  14928. @node Related Financial Functions, Depreciation Functions, Present Value, Financial Functions
  14929. @subsection Related Financial Functions
  14930. @noindent
  14931. The functions in this section are basically inverses of the
  14932. present value functions with respect to the various arguments.
  14933. @kindex b M
  14934. @pindex calc-fin-pmt
  14935. @tindex pmt
  14936. The @kbd{b M} (@code{calc-fin-pmt}) [@code{pmt}] command computes
  14937. the amount of periodic payment necessary to amortize a loan.
  14938. Thus @code{pmt(@var{rate}, @var{n}, @var{amount})} equals the
  14939. value of @var{payment} such that @code{pv(@var{rate}, @var{n},
  14940. @var{payment}) = @var{amount}}.
  14941. @kindex I b M
  14942. @tindex pmtb
  14943. The @kbd{I b M} [@code{pmtb}] command does the same computation
  14944. but using @code{pvb} instead of @code{pv}. Like @code{pv} and
  14945. @code{pvb}, these functions can also take a fourth argument which
  14946. represents an initial lump-sum investment.
  14947. @kindex H b M
  14948. The @kbd{H b M} key just invokes the @code{fvl} function, which is
  14949. the inverse of @code{pvl}. There is no explicit @code{pmtl} function.
  14950. @kindex b #
  14951. @pindex calc-fin-nper
  14952. @tindex nper
  14953. The @kbd{b #} (@code{calc-fin-nper}) [@code{nper}] command computes
  14954. the number of regular payments necessary to amortize a loan.
  14955. Thus @code{nper(@var{rate}, @var{payment}, @var{amount})} equals
  14956. the value of @var{n} such that @code{pv(@var{rate}, @var{n},
  14957. @var{payment}) = @var{amount}}. If @var{payment} is too small
  14958. ever to amortize a loan for @var{amount} at interest rate @var{rate},
  14959. the @code{nper} function is left in symbolic form.
  14960. @kindex I b #
  14961. @tindex nperb
  14962. The @kbd{I b #} [@code{nperb}] command does the same computation
  14963. but using @code{pvb} instead of @code{pv}. You can give a fourth
  14964. lump-sum argument to these functions, but the computation will be
  14965. rather slow in the four-argument case.
  14966. @kindex H b #
  14967. @tindex nperl
  14968. The @kbd{H b #} [@code{nperl}] command does the same computation
  14969. using @code{pvl}. By exchanging @var{payment} and @var{amount} you
  14970. can also get the solution for @code{fvl}. For example,
  14971. @code{nperl(8%, 2000, 1000) = 9.006}, so if you place $1000 in a
  14972. bank account earning 8%, it will take nine years to grow to $2000.
  14973. @kindex b T
  14974. @pindex calc-fin-rate
  14975. @tindex rate
  14976. The @kbd{b T} (@code{calc-fin-rate}) [@code{rate}] command computes
  14977. the rate of return on an investment. This is also an inverse of @code{pv}:
  14978. @code{rate(@var{n}, @var{payment}, @var{amount})} computes the value of
  14979. @var{rate} such that @code{pv(@var{rate}, @var{n}, @var{payment}) =
  14980. @var{amount}}. The result is expressed as a formula like @samp{6.3%}.
  14981. @kindex I b T
  14982. @kindex H b T
  14983. @tindex rateb
  14984. @tindex ratel
  14985. The @kbd{I b T} [@code{rateb}] and @kbd{H b T} [@code{ratel}]
  14986. commands solve the analogous equations with @code{pvb} or @code{pvl}
  14987. in place of @code{pv}. Also, @code{rate} and @code{rateb} can
  14988. accept an optional fourth argument just like @code{pv} and @code{pvb}.
  14989. To redo the above example from a different perspective,
  14990. @code{ratel(9, 2000, 1000) = 8.00597%}, which says you will need an
  14991. interest rate of 8% in order to double your account in nine years.
  14992. @kindex b I
  14993. @pindex calc-fin-irr
  14994. @tindex irr
  14995. The @kbd{b I} (@code{calc-fin-irr}) [@code{irr}] command is the
  14996. analogous function to @code{rate} but for net present value.
  14997. Its argument is a vector of payments. Thus @code{irr(@var{payments})}
  14998. computes the @var{rate} such that @code{npv(@var{rate}, @var{payments}) = 0};
  14999. this rate is known as the @dfn{internal rate of return}.
  15000. @kindex I b I
  15001. @tindex irrb
  15002. The @kbd{I b I} [@code{irrb}] command computes the internal rate of
  15003. return assuming payments occur at the beginning of each period.
  15004. @node Depreciation Functions, Definitions of Financial Functions, Related Financial Functions, Financial Functions
  15005. @subsection Depreciation Functions
  15006. @noindent
  15007. The functions in this section calculate @dfn{depreciation}, which is
  15008. the amount of value that a possession loses over time. These functions
  15009. are characterized by three parameters: @var{cost}, the original cost
  15010. of the asset; @var{salvage}, the value the asset will have at the end
  15011. of its expected ``useful life''; and @var{life}, the number of years
  15012. (or other periods) of the expected useful life.
  15013. There are several methods for calculating depreciation that differ in
  15014. the way they spread the depreciation over the lifetime of the asset.
  15015. @kindex b S
  15016. @pindex calc-fin-sln
  15017. @tindex sln
  15018. The @kbd{b S} (@code{calc-fin-sln}) [@code{sln}] command computes the
  15019. ``straight-line'' depreciation. In this method, the asset depreciates
  15020. by the same amount every year (or period). For example,
  15021. @samp{sln(12000, 2000, 5)} returns 2000. The asset costs $12000
  15022. initially and will be worth $2000 after five years; it loses $2000
  15023. per year.
  15024. @kindex b Y
  15025. @pindex calc-fin-syd
  15026. @tindex syd
  15027. The @kbd{b Y} (@code{calc-fin-syd}) [@code{syd}] command computes the
  15028. accelerated ``sum-of-years'-digits'' depreciation. Here the depreciation
  15029. is higher during the early years of the asset's life. Since the
  15030. depreciation is different each year, @kbd{b Y} takes a fourth @var{period}
  15031. parameter which specifies which year is requested, from 1 to @var{life}.
  15032. If @var{period} is outside this range, the @code{syd} function will
  15033. return zero.
  15034. @kindex b D
  15035. @pindex calc-fin-ddb
  15036. @tindex ddb
  15037. The @kbd{b D} (@code{calc-fin-ddb}) [@code{ddb}] command computes an
  15038. accelerated depreciation using the double-declining balance method.
  15039. It also takes a fourth @var{period} parameter.
  15040. For symmetry, the @code{sln} function will accept a @var{period}
  15041. parameter as well, although it will ignore its value except that the
  15042. return value will as usual be zero if @var{period} is out of range.
  15043. For example, pushing the vector @expr{[1,2,3,4,5]} (perhaps with @kbd{v x 5})
  15044. and then mapping @kbd{V M ' [sln(12000,2000,5,$), syd(12000,2000,5,$),
  15045. ddb(12000,2000,5,$)] @key{RET}} produces a matrix that allows us to compare
  15046. the three depreciation methods:
  15047. @example
  15048. @group
  15049. [ [ 2000, 3333, 4800 ]
  15050. [ 2000, 2667, 2880 ]
  15051. [ 2000, 2000, 1728 ]
  15052. [ 2000, 1333, 592 ]
  15053. [ 2000, 667, 0 ] ]
  15054. @end group
  15055. @end example
  15056. @noindent
  15057. (Values have been rounded to nearest integers in this figure.)
  15058. We see that @code{sln} depreciates by the same amount each year,
  15059. @kbd{syd} depreciates more at the beginning and less at the end,
  15060. and @kbd{ddb} weights the depreciation even more toward the beginning.
  15061. Summing columns with @kbd{V R : +} yields @expr{[10000, 10000, 10000]};
  15062. the total depreciation in any method is (by definition) the
  15063. difference between the cost and the salvage value.
  15064. @node Definitions of Financial Functions, , Depreciation Functions, Financial Functions
  15065. @subsection Definitions
  15066. @noindent
  15067. For your reference, here are the actual formulas used to compute
  15068. Calc's financial functions.
  15069. Calc will not evaluate a financial function unless the @var{rate} or
  15070. @var{n} argument is known. However, @var{payment} or @var{amount} can
  15071. be a variable. Calc expands these functions according to the
  15072. formulas below for symbolic arguments only when you use the @kbd{a "}
  15073. (@code{calc-expand-formula}) command, or when taking derivatives or
  15074. integrals or solving equations involving the functions.
  15075. @ifnottex
  15076. These formulas are shown using the conventions of Big display
  15077. mode (@kbd{d B}); for example, the formula for @code{fv} written
  15078. linearly is @samp{pmt * ((1 + rate)^n) - 1) / rate}.
  15079. @example
  15080. n
  15081. (1 + rate) - 1
  15082. fv(rate, n, pmt) = pmt * ---------------
  15083. rate
  15084. n
  15085. ((1 + rate) - 1) (1 + rate)
  15086. fvb(rate, n, pmt) = pmt * ----------------------------
  15087. rate
  15088. n
  15089. fvl(rate, n, pmt) = pmt * (1 + rate)
  15090. -n
  15091. 1 - (1 + rate)
  15092. pv(rate, n, pmt) = pmt * ----------------
  15093. rate
  15094. -n
  15095. (1 - (1 + rate) ) (1 + rate)
  15096. pvb(rate, n, pmt) = pmt * -----------------------------
  15097. rate
  15098. -n
  15099. pvl(rate, n, pmt) = pmt * (1 + rate)
  15100. -1 -2 -3
  15101. npv(rate, [a, b, c]) = a*(1 + rate) + b*(1 + rate) + c*(1 + rate)
  15102. -1 -2
  15103. npvb(rate, [a, b, c]) = a + b*(1 + rate) + c*(1 + rate)
  15104. -n
  15105. (amt - x * (1 + rate) ) * rate
  15106. pmt(rate, n, amt, x) = -------------------------------
  15107. -n
  15108. 1 - (1 + rate)
  15109. -n
  15110. (amt - x * (1 + rate) ) * rate
  15111. pmtb(rate, n, amt, x) = -------------------------------
  15112. -n
  15113. (1 - (1 + rate) ) (1 + rate)
  15114. amt * rate
  15115. nper(rate, pmt, amt) = - log(1 - ------------, 1 + rate)
  15116. pmt
  15117. amt * rate
  15118. nperb(rate, pmt, amt) = - log(1 - ---------------, 1 + rate)
  15119. pmt * (1 + rate)
  15120. amt
  15121. nperl(rate, pmt, amt) = - log(---, 1 + rate)
  15122. pmt
  15123. 1/n
  15124. pmt
  15125. ratel(n, pmt, amt) = ------ - 1
  15126. 1/n
  15127. amt
  15128. cost - salv
  15129. sln(cost, salv, life) = -----------
  15130. life
  15131. (cost - salv) * (life - per + 1)
  15132. syd(cost, salv, life, per) = --------------------------------
  15133. life * (life + 1) / 2
  15134. book * 2
  15135. ddb(cost, salv, life, per) = --------, book = cost - depreciation so far
  15136. life
  15137. @end example
  15138. @end ifnottex
  15139. @tex
  15140. $$ \code{fv}(r, n, p) = p { (1 + r)^n - 1 \over r } $$
  15141. $$ \code{fvb}(r, n, p) = p { ((1 + r)^n - 1) (1 + r) \over r } $$
  15142. $$ \code{fvl}(r, n, p) = p (1 + r)^n $$
  15143. $$ \code{pv}(r, n, p) = p { 1 - (1 + r)^{-n} \over r } $$
  15144. $$ \code{pvb}(r, n, p) = p { (1 - (1 + r)^{-n}) (1 + r) \over r } $$
  15145. $$ \code{pvl}(r, n, p) = p (1 + r)^{-n} $$
  15146. $$ \code{npv}(r, [a,b,c]) = a (1 + r)^{-1} + b (1 + r)^{-2} + c (1 + r)^{-3} $$
  15147. $$ \code{npvb}(r, [a,b,c]) = a + b (1 + r)^{-1} + c (1 + r)^{-2} $$
  15148. $$ \code{pmt}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over 1 - (1 + r)^{-n} }$$
  15149. $$ \code{pmtb}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over
  15150. (1 - (1 + r)^{-n}) (1 + r) } $$
  15151. $$ \code{nper}(r, p, a) = -\code{log}(1 - { a r \over p }, 1 + r) $$
  15152. $$ \code{nperb}(r, p, a) = -\code{log}(1 - { a r \over p (1 + r) }, 1 + r) $$
  15153. $$ \code{nperl}(r, p, a) = -\code{log}({a \over p}, 1 + r) $$
  15154. $$ \code{ratel}(n, p, a) = { p^{1/n} \over a^{1/n} } - 1 $$
  15155. $$ \code{sln}(c, s, l) = { c - s \over l } $$
  15156. $$ \code{syd}(c, s, l, p) = { (c - s) (l - p + 1) \over l (l+1) / 2 } $$
  15157. $$ \code{ddb}(c, s, l, p) = { 2 (c - \hbox{depreciation so far}) \over l } $$
  15158. @end tex
  15159. @noindent
  15160. In @code{pmt} and @code{pmtb}, @expr{x=0} if omitted.
  15161. These functions accept any numeric objects, including error forms,
  15162. intervals, and even (though not very usefully) complex numbers. The
  15163. above formulas specify exactly the behavior of these functions with
  15164. all sorts of inputs.
  15165. Note that if the first argument to the @code{log} in @code{nper} is
  15166. negative, @code{nper} leaves itself in symbolic form rather than
  15167. returning a (financially meaningless) complex number.
  15168. @samp{rate(num, pmt, amt)} solves the equation
  15169. @samp{pv(rate, num, pmt) = amt} for @samp{rate} using @kbd{H a R}
  15170. (@code{calc-find-root}), with the interval @samp{[.01% .. 100%]}
  15171. for an initial guess. The @code{rateb} function is the same except
  15172. that it uses @code{pvb}. Note that @code{ratel} can be solved
  15173. directly; its formula is shown in the above list.
  15174. Similarly, @samp{irr(pmts)} solves the equation @samp{npv(rate, pmts) = 0}
  15175. for @samp{rate}.
  15176. If you give a fourth argument to @code{nper} or @code{nperb}, Calc
  15177. will also use @kbd{H a R} to solve the equation using an initial
  15178. guess interval of @samp{[0 .. 100]}.
  15179. A fourth argument to @code{fv} simply sums the two components
  15180. calculated from the above formulas for @code{fv} and @code{fvl}.
  15181. The same is true of @code{fvb}, @code{pv}, and @code{pvb}.
  15182. The @kbd{ddb} function is computed iteratively; the ``book'' value
  15183. starts out equal to @var{cost}, and decreases according to the above
  15184. formula for the specified number of periods. If the book value
  15185. would decrease below @var{salvage}, it only decreases to @var{salvage}
  15186. and the depreciation is zero for all subsequent periods. The @code{ddb}
  15187. function returns the amount the book value decreased in the specified
  15188. period.
  15189. @node Binary Functions, , Financial Functions, Arithmetic
  15190. @section Binary Number Functions
  15191. @noindent
  15192. The commands in this chapter all use two-letter sequences beginning with
  15193. the @kbd{b} prefix.
  15194. @cindex Binary numbers
  15195. The ``binary'' operations actually work regardless of the currently
  15196. displayed radix, although their results make the most sense in a radix
  15197. like 2, 8, or 16 (as obtained by the @kbd{d 2}, @kbd{d 8}, or @w{@kbd{d 6}}
  15198. commands, respectively). You may also wish to enable display of leading
  15199. zeros with @kbd{d z}. @xref{Radix Modes}.
  15200. @cindex Word size for binary operations
  15201. The Calculator maintains a current @dfn{word size} @expr{w}, an
  15202. arbitrary positive or negative integer. For a positive word size, all
  15203. of the binary operations described here operate modulo @expr{2^w}. In
  15204. particular, negative arguments are converted to positive integers modulo
  15205. @expr{2^w} by all binary functions.
  15206. If the word size is negative, binary operations produce twos-complement
  15207. integers from
  15208. @texline @math{-2^{-w-1}}
  15209. @infoline @expr{-(2^(-w-1))}
  15210. to
  15211. @texline @math{2^{-w-1}-1}
  15212. @infoline @expr{2^(-w-1)-1}
  15213. inclusive. Either mode accepts inputs in any range; the sign of
  15214. @expr{w} affects only the results produced.
  15215. @kindex b c
  15216. @pindex calc-clip
  15217. @tindex clip
  15218. The @kbd{b c} (@code{calc-clip})
  15219. [@code{clip}] command can be used to clip a number by reducing it modulo
  15220. @expr{2^w}. The commands described in this chapter automatically clip
  15221. their results to the current word size. Note that other operations like
  15222. addition do not use the current word size, since integer addition
  15223. generally is not ``binary.'' (However, @pxref{Simplification Modes},
  15224. @code{calc-bin-simplify-mode}.) For example, with a word size of 8
  15225. bits @kbd{b c} converts a number to the range 0 to 255; with a word
  15226. size of @mathit{-8} @kbd{b c} converts to the range @mathit{-128} to 127.
  15227. @kindex b w
  15228. @pindex calc-word-size
  15229. The default word size is 32 bits. All operations except the shifts and
  15230. rotates allow you to specify a different word size for that one
  15231. operation by giving a numeric prefix argument: @kbd{C-u 8 b c} clips the
  15232. top of stack to the range 0 to 255 regardless of the current word size.
  15233. To set the word size permanently, use @kbd{b w} (@code{calc-word-size}).
  15234. This command displays a prompt with the current word size; press @key{RET}
  15235. immediately to keep this word size, or type a new word size at the prompt.
  15236. When the binary operations are written in symbolic form, they take an
  15237. optional second (or third) word-size parameter. When a formula like
  15238. @samp{and(a,b)} is finally evaluated, the word size current at that time
  15239. will be used, but when @samp{and(a,b,-8)} is evaluated, a word size of
  15240. @mathit{-8} will always be used. A symbolic binary function will be left
  15241. in symbolic form unless the all of its argument(s) are integers or
  15242. integer-valued floats.
  15243. If either or both arguments are modulo forms for which @expr{M} is a
  15244. power of two, that power of two is taken as the word size unless a
  15245. numeric prefix argument overrides it. The current word size is never
  15246. consulted when modulo-power-of-two forms are involved.
  15247. @kindex b a
  15248. @pindex calc-and
  15249. @tindex and
  15250. The @kbd{b a} (@code{calc-and}) [@code{and}] command computes the bitwise
  15251. AND of the two numbers on the top of the stack. In other words, for each
  15252. of the @expr{w} binary digits of the two numbers (pairwise), the corresponding
  15253. bit of the result is 1 if and only if both input bits are 1:
  15254. @samp{and(2#1100, 2#1010) = 2#1000}.
  15255. @kindex b o
  15256. @pindex calc-or
  15257. @tindex or
  15258. The @kbd{b o} (@code{calc-or}) [@code{or}] command computes the bitwise
  15259. inclusive OR of two numbers. A bit is 1 if either of the input bits, or
  15260. both, are 1: @samp{or(2#1100, 2#1010) = 2#1110}.
  15261. @kindex b x
  15262. @pindex calc-xor
  15263. @tindex xor
  15264. The @kbd{b x} (@code{calc-xor}) [@code{xor}] command computes the bitwise
  15265. exclusive OR of two numbers. A bit is 1 if exactly one of the input bits
  15266. is 1: @samp{xor(2#1100, 2#1010) = 2#0110}.
  15267. @kindex b d
  15268. @pindex calc-diff
  15269. @tindex diff
  15270. The @kbd{b d} (@code{calc-diff}) [@code{diff}] command computes the bitwise
  15271. difference of two numbers; this is defined by @samp{diff(a,b) = and(a,not(b))},
  15272. so that @samp{diff(2#1100, 2#1010) = 2#0100}.
  15273. @kindex b n
  15274. @pindex calc-not
  15275. @tindex not
  15276. The @kbd{b n} (@code{calc-not}) [@code{not}] command computes the bitwise
  15277. NOT of a number. A bit is 1 if the input bit is 0 and vice-versa.
  15278. @kindex b l
  15279. @pindex calc-lshift-binary
  15280. @tindex lsh
  15281. The @kbd{b l} (@code{calc-lshift-binary}) [@code{lsh}] command shifts a
  15282. number left by one bit, or by the number of bits specified in the numeric
  15283. prefix argument. A negative prefix argument performs a logical right shift,
  15284. in which zeros are shifted in on the left. In symbolic form, @samp{lsh(a)}
  15285. is short for @samp{lsh(a,1)}, which in turn is short for @samp{lsh(a,n,w)}.
  15286. Bits shifted ``off the end,'' according to the current word size, are lost.
  15287. @kindex H b l
  15288. @kindex H b r
  15289. @ignore
  15290. @mindex @idots
  15291. @end ignore
  15292. @kindex H b L
  15293. @ignore
  15294. @mindex @null
  15295. @end ignore
  15296. @kindex H b R
  15297. @ignore
  15298. @mindex @null
  15299. @end ignore
  15300. @kindex H b t
  15301. The @kbd{H b l} command also does a left shift, but it takes two arguments
  15302. from the stack (the value to shift, and, at top-of-stack, the number of
  15303. bits to shift). This version interprets the prefix argument just like
  15304. the regular binary operations, i.e., as a word size. The Hyperbolic flag
  15305. has a similar effect on the rest of the binary shift and rotate commands.
  15306. @kindex b r
  15307. @pindex calc-rshift-binary
  15308. @tindex rsh
  15309. The @kbd{b r} (@code{calc-rshift-binary}) [@code{rsh}] command shifts a
  15310. number right by one bit, or by the number of bits specified in the numeric
  15311. prefix argument: @samp{rsh(a,n) = lsh(a,-n)}.
  15312. @kindex b L
  15313. @pindex calc-lshift-arith
  15314. @tindex ash
  15315. The @kbd{b L} (@code{calc-lshift-arith}) [@code{ash}] command shifts a
  15316. number left. It is analogous to @code{lsh}, except that if the shift
  15317. is rightward (the prefix argument is negative), an arithmetic shift
  15318. is performed as described below.
  15319. @kindex b R
  15320. @pindex calc-rshift-arith
  15321. @tindex rash
  15322. The @kbd{b R} (@code{calc-rshift-arith}) [@code{rash}] command performs
  15323. an ``arithmetic'' shift to the right, in which the leftmost bit (according
  15324. to the current word size) is duplicated rather than shifting in zeros.
  15325. This corresponds to dividing by a power of two where the input is interpreted
  15326. as a signed, twos-complement number. (The distinction between the @samp{rsh}
  15327. and @samp{rash} operations is totally independent from whether the word
  15328. size is positive or negative.) With a negative prefix argument, this
  15329. performs a standard left shift.
  15330. @kindex b t
  15331. @pindex calc-rotate-binary
  15332. @tindex rot
  15333. The @kbd{b t} (@code{calc-rotate-binary}) [@code{rot}] command rotates a
  15334. number one bit to the left. The leftmost bit (according to the current
  15335. word size) is dropped off the left and shifted in on the right. With a
  15336. numeric prefix argument, the number is rotated that many bits to the left
  15337. or right.
  15338. @xref{Set Operations}, for the @kbd{b p} and @kbd{b u} commands that
  15339. pack and unpack binary integers into sets. (For example, @kbd{b u}
  15340. unpacks the number @samp{2#11001} to the set of bit-numbers
  15341. @samp{[0, 3, 4]}.) Type @kbd{b u V #} to count the number of ``1''
  15342. bits in a binary integer.
  15343. Another interesting use of the set representation of binary integers
  15344. is to reverse the bits in, say, a 32-bit integer. Type @kbd{b u} to
  15345. unpack; type @kbd{31 @key{TAB} -} to replace each bit-number in the set
  15346. with 31 minus that bit-number; type @kbd{b p} to pack the set back
  15347. into a binary integer.
  15348. @node Scientific Functions, Matrix Functions, Arithmetic, Top
  15349. @chapter Scientific Functions
  15350. @noindent
  15351. The functions described here perform trigonometric and other transcendental
  15352. calculations. They generally produce floating-point answers correct to the
  15353. full current precision. The @kbd{H} (Hyperbolic) and @kbd{I} (Inverse)
  15354. flag keys must be used to get some of these functions from the keyboard.
  15355. @kindex P
  15356. @pindex calc-pi
  15357. @cindex @code{pi} variable
  15358. @vindex pi
  15359. @kindex H P
  15360. @cindex @code{e} variable
  15361. @vindex e
  15362. @kindex I P
  15363. @cindex @code{gamma} variable
  15364. @vindex gamma
  15365. @cindex Gamma constant, Euler's
  15366. @cindex Euler's gamma constant
  15367. @kindex H I P
  15368. @cindex @code{phi} variable
  15369. @cindex Phi, golden ratio
  15370. @cindex Golden ratio
  15371. One miscellaneous command is shift-@kbd{P} (@code{calc-pi}), which pushes
  15372. the value of @cpi{} (at the current precision) onto the stack. With the
  15373. Hyperbolic flag, it pushes the value @expr{e}, the base of natural logarithms.
  15374. With the Inverse flag, it pushes Euler's constant
  15375. @texline @math{\gamma}
  15376. @infoline @expr{gamma}
  15377. (about 0.5772). With both Inverse and Hyperbolic, it
  15378. pushes the ``golden ratio''
  15379. @texline @math{\phi}
  15380. @infoline @expr{phi}
  15381. (about 1.618). (At present, Euler's constant is not available
  15382. to unlimited precision; Calc knows only the first 100 digits.)
  15383. In Symbolic mode, these commands push the
  15384. actual variables @samp{pi}, @samp{e}, @samp{gamma}, and @samp{phi},
  15385. respectively, instead of their values; @pxref{Symbolic Mode}.
  15386. @ignore
  15387. @mindex Q
  15388. @end ignore
  15389. @ignore
  15390. @mindex I Q
  15391. @end ignore
  15392. @kindex I Q
  15393. @tindex sqr
  15394. The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] function is described elsewhere;
  15395. @pxref{Basic Arithmetic}. With the Inverse flag [@code{sqr}], this command
  15396. computes the square of the argument.
  15397. @xref{Prefix Arguments}, for a discussion of the effect of numeric
  15398. prefix arguments on commands in this chapter which do not otherwise
  15399. interpret a prefix argument.
  15400. @menu
  15401. * Logarithmic Functions::
  15402. * Trigonometric and Hyperbolic Functions::
  15403. * Advanced Math Functions::
  15404. * Branch Cuts::
  15405. * Random Numbers::
  15406. * Combinatorial Functions::
  15407. * Probability Distribution Functions::
  15408. @end menu
  15409. @node Logarithmic Functions, Trigonometric and Hyperbolic Functions, Scientific Functions, Scientific Functions
  15410. @section Logarithmic Functions
  15411. @noindent
  15412. @kindex L
  15413. @pindex calc-ln
  15414. @tindex ln
  15415. @ignore
  15416. @mindex @null
  15417. @end ignore
  15418. @kindex I E
  15419. The shift-@kbd{L} (@code{calc-ln}) [@code{ln}] command computes the natural
  15420. logarithm of the real or complex number on the top of the stack. With
  15421. the Inverse flag it computes the exponential function instead, although
  15422. this is redundant with the @kbd{E} command.
  15423. @kindex E
  15424. @pindex calc-exp
  15425. @tindex exp
  15426. @ignore
  15427. @mindex @null
  15428. @end ignore
  15429. @kindex I L
  15430. The shift-@kbd{E} (@code{calc-exp}) [@code{exp}] command computes the
  15431. exponential, i.e., @expr{e} raised to the power of the number on the stack.
  15432. The meanings of the Inverse and Hyperbolic flags follow from those for
  15433. the @code{calc-ln} command.
  15434. @kindex H L
  15435. @kindex H E
  15436. @pindex calc-log10
  15437. @tindex log10
  15438. @tindex exp10
  15439. @ignore
  15440. @mindex @null
  15441. @end ignore
  15442. @kindex H I L
  15443. @ignore
  15444. @mindex @null
  15445. @end ignore
  15446. @kindex H I E
  15447. The @kbd{H L} (@code{calc-log10}) [@code{log10}] command computes the common
  15448. (base-10) logarithm of a number. (With the Inverse flag [@code{exp10}],
  15449. it raises ten to a given power.) Note that the common logarithm of a
  15450. complex number is computed by taking the natural logarithm and dividing
  15451. by
  15452. @texline @math{\ln10}.
  15453. @infoline @expr{ln(10)}.
  15454. @kindex B
  15455. @kindex I B
  15456. @pindex calc-log
  15457. @tindex log
  15458. @tindex alog
  15459. The @kbd{B} (@code{calc-log}) [@code{log}] command computes a logarithm
  15460. to any base. For example, @kbd{1024 @key{RET} 2 B} produces 10, since
  15461. @texline @math{2^{10} = 1024}.
  15462. @infoline @expr{2^10 = 1024}.
  15463. In certain cases like @samp{log(3,9)}, the result
  15464. will be either @expr{1:2} or @expr{0.5} depending on the current Fraction
  15465. mode setting. With the Inverse flag [@code{alog}], this command is
  15466. similar to @kbd{^} except that the order of the arguments is reversed.
  15467. @kindex f I
  15468. @pindex calc-ilog
  15469. @tindex ilog
  15470. The @kbd{f I} (@code{calc-ilog}) [@code{ilog}] command computes the
  15471. integer logarithm of a number to any base. The number and the base must
  15472. themselves be positive integers. This is the true logarithm, rounded
  15473. down to an integer. Thus @kbd{ilog(x,10)} is 3 for all @expr{x} in the
  15474. range from 1000 to 9999. If both arguments are positive integers, exact
  15475. integer arithmetic is used; otherwise, this is equivalent to
  15476. @samp{floor(log(x,b))}.
  15477. @kindex f E
  15478. @pindex calc-expm1
  15479. @tindex expm1
  15480. The @kbd{f E} (@code{calc-expm1}) [@code{expm1}] command computes
  15481. @texline @math{e^x - 1},
  15482. @infoline @expr{exp(x)-1},
  15483. but using an algorithm that produces a more accurate
  15484. answer when the result is close to zero, i.e., when
  15485. @texline @math{e^x}
  15486. @infoline @expr{exp(x)}
  15487. is close to one.
  15488. @kindex f L
  15489. @pindex calc-lnp1
  15490. @tindex lnp1
  15491. The @kbd{f L} (@code{calc-lnp1}) [@code{lnp1}] command computes
  15492. @texline @math{\ln(x+1)},
  15493. @infoline @expr{ln(x+1)},
  15494. producing a more accurate answer when @expr{x} is close to zero.
  15495. @node Trigonometric and Hyperbolic Functions, Advanced Math Functions, Logarithmic Functions, Scientific Functions
  15496. @section Trigonometric/Hyperbolic Functions
  15497. @noindent
  15498. @kindex S
  15499. @pindex calc-sin
  15500. @tindex sin
  15501. The shift-@kbd{S} (@code{calc-sin}) [@code{sin}] command computes the sine
  15502. of an angle or complex number. If the input is an HMS form, it is interpreted
  15503. as degrees-minutes-seconds; otherwise, the input is interpreted according
  15504. to the current angular mode. It is best to use Radians mode when operating
  15505. on complex numbers.
  15506. Calc's ``units'' mechanism includes angular units like @code{deg},
  15507. @code{rad}, and @code{grad}. While @samp{sin(45 deg)} is not evaluated
  15508. all the time, the @kbd{u s} (@code{calc-simplify-units}) command will
  15509. simplify @samp{sin(45 deg)} by taking the sine of 45 degrees, regardless
  15510. of the current angular mode. @xref{Basic Operations on Units}.
  15511. Also, the symbolic variable @code{pi} is not ordinarily recognized in
  15512. arguments to trigonometric functions, as in @samp{sin(3 pi / 4)}, but
  15513. the default algebraic simplifications recognize many such
  15514. formulas when the current angular mode is Radians @emph{and} Symbolic
  15515. mode is enabled; this example would be replaced by @samp{sqrt(2) / 2}.
  15516. @xref{Symbolic Mode}. Beware, this simplification occurs even if you
  15517. have stored a different value in the variable @samp{pi}; this is one
  15518. reason why changing built-in variables is a bad idea. Arguments of
  15519. the form @expr{x} plus a multiple of @cpiover{2} are also simplified.
  15520. Calc includes similar formulas for @code{cos} and @code{tan}.
  15521. Calc's algebraic simplifications know all angles which are integer multiples of
  15522. @cpiover{12}, @cpiover{10}, or @cpiover{8} radians. In Degrees mode,
  15523. analogous simplifications occur for integer multiples of 15 or 18
  15524. degrees, and for arguments plus multiples of 90 degrees.
  15525. @kindex I S
  15526. @pindex calc-arcsin
  15527. @tindex arcsin
  15528. With the Inverse flag, @code{calc-sin} computes an arcsine. This is also
  15529. available as the @code{calc-arcsin} command or @code{arcsin} algebraic
  15530. function. The returned argument is converted to degrees, radians, or HMS
  15531. notation depending on the current angular mode.
  15532. @kindex H S
  15533. @pindex calc-sinh
  15534. @tindex sinh
  15535. @kindex H I S
  15536. @pindex calc-arcsinh
  15537. @tindex arcsinh
  15538. With the Hyperbolic flag, @code{calc-sin} computes the hyperbolic
  15539. sine, also available as @code{calc-sinh} [@code{sinh}]. With the
  15540. Hyperbolic and Inverse flags, it computes the hyperbolic arcsine
  15541. (@code{calc-arcsinh}) [@code{arcsinh}].
  15542. @kindex C
  15543. @pindex calc-cos
  15544. @tindex cos
  15545. @ignore
  15546. @mindex @idots
  15547. @end ignore
  15548. @kindex I C
  15549. @pindex calc-arccos
  15550. @ignore
  15551. @mindex @null
  15552. @end ignore
  15553. @tindex arccos
  15554. @ignore
  15555. @mindex @null
  15556. @end ignore
  15557. @kindex H C
  15558. @pindex calc-cosh
  15559. @ignore
  15560. @mindex @null
  15561. @end ignore
  15562. @tindex cosh
  15563. @ignore
  15564. @mindex @null
  15565. @end ignore
  15566. @kindex H I C
  15567. @pindex calc-arccosh
  15568. @ignore
  15569. @mindex @null
  15570. @end ignore
  15571. @tindex arccosh
  15572. @ignore
  15573. @mindex @null
  15574. @end ignore
  15575. @kindex T
  15576. @pindex calc-tan
  15577. @ignore
  15578. @mindex @null
  15579. @end ignore
  15580. @tindex tan
  15581. @ignore
  15582. @mindex @null
  15583. @end ignore
  15584. @kindex I T
  15585. @pindex calc-arctan
  15586. @ignore
  15587. @mindex @null
  15588. @end ignore
  15589. @tindex arctan
  15590. @ignore
  15591. @mindex @null
  15592. @end ignore
  15593. @kindex H T
  15594. @pindex calc-tanh
  15595. @ignore
  15596. @mindex @null
  15597. @end ignore
  15598. @tindex tanh
  15599. @ignore
  15600. @mindex @null
  15601. @end ignore
  15602. @kindex H I T
  15603. @pindex calc-arctanh
  15604. @ignore
  15605. @mindex @null
  15606. @end ignore
  15607. @tindex arctanh
  15608. The shift-@kbd{C} (@code{calc-cos}) [@code{cos}] command computes the cosine
  15609. of an angle or complex number, and shift-@kbd{T} (@code{calc-tan}) [@code{tan}]
  15610. computes the tangent, along with all the various inverse and hyperbolic
  15611. variants of these functions.
  15612. @kindex f T
  15613. @pindex calc-arctan2
  15614. @tindex arctan2
  15615. The @kbd{f T} (@code{calc-arctan2}) [@code{arctan2}] command takes two
  15616. numbers from the stack and computes the arc tangent of their ratio. The
  15617. result is in the full range from @mathit{-180} (exclusive) to @mathit{+180}
  15618. (inclusive) degrees, or the analogous range in radians. A similar
  15619. result would be obtained with @kbd{/} followed by @kbd{I T}, but the
  15620. value would only be in the range from @mathit{-90} to @mathit{+90} degrees
  15621. since the division loses information about the signs of the two
  15622. components, and an error might result from an explicit division by zero
  15623. which @code{arctan2} would avoid. By (arbitrary) definition,
  15624. @samp{arctan2(0,0)=0}.
  15625. @pindex calc-sincos
  15626. @ignore
  15627. @starindex
  15628. @end ignore
  15629. @tindex sincos
  15630. @ignore
  15631. @starindex
  15632. @end ignore
  15633. @ignore
  15634. @mindex arc@idots
  15635. @end ignore
  15636. @tindex arcsincos
  15637. The @code{calc-sincos} [@code{sincos}] command computes the sine and
  15638. cosine of a number, returning them as a vector of the form
  15639. @samp{[@var{cos}, @var{sin}]}.
  15640. With the Inverse flag [@code{arcsincos}], this command takes a two-element
  15641. vector as an argument and computes @code{arctan2} of the elements.
  15642. (This command does not accept the Hyperbolic flag.)
  15643. @pindex calc-sec
  15644. @tindex sec
  15645. @pindex calc-csc
  15646. @tindex csc
  15647. @pindex calc-cot
  15648. @tindex cot
  15649. @pindex calc-sech
  15650. @tindex sech
  15651. @pindex calc-csch
  15652. @tindex csch
  15653. @pindex calc-coth
  15654. @tindex coth
  15655. The remaining trigonometric functions, @code{calc-sec} [@code{sec}],
  15656. @code{calc-csc} [@code{csc}] and @code{calc-cot} [@code{cot}], are also
  15657. available. With the Hyperbolic flag, these compute their hyperbolic
  15658. counterparts, which are also available separately as @code{calc-sech}
  15659. [@code{sech}], @code{calc-csch} [@code{csch}] and @code{calc-coth}
  15660. [@code{coth}]. (These commands do not accept the Inverse flag.)
  15661. @node Advanced Math Functions, Branch Cuts, Trigonometric and Hyperbolic Functions, Scientific Functions
  15662. @section Advanced Mathematical Functions
  15663. @noindent
  15664. Calc can compute a variety of less common functions that arise in
  15665. various branches of mathematics. All of the functions described in
  15666. this section allow arbitrary complex arguments and, except as noted,
  15667. will work to arbitrarily large precision. They can not at present
  15668. handle error forms or intervals as arguments.
  15669. NOTE: These functions are still experimental. In particular, their
  15670. accuracy is not guaranteed in all domains. It is advisable to set the
  15671. current precision comfortably higher than you actually need when
  15672. using these functions. Also, these functions may be impractically
  15673. slow for some values of the arguments.
  15674. @kindex f g
  15675. @pindex calc-gamma
  15676. @tindex gamma
  15677. The @kbd{f g} (@code{calc-gamma}) [@code{gamma}] command computes the Euler
  15678. gamma function. For positive integer arguments, this is related to the
  15679. factorial function: @samp{gamma(n+1) = fact(n)}. For general complex
  15680. arguments the gamma function can be defined by the following definite
  15681. integral:
  15682. @texline @math{\Gamma(a) = \int_0^\infty t^{a-1} e^t dt}.
  15683. @infoline @expr{gamma(a) = integ(t^(a-1) exp(t), t, 0, inf)}.
  15684. (The actual implementation uses far more efficient computational methods.)
  15685. @kindex f G
  15686. @tindex gammaP
  15687. @ignore
  15688. @mindex @idots
  15689. @end ignore
  15690. @kindex I f G
  15691. @ignore
  15692. @mindex @null
  15693. @end ignore
  15694. @kindex H f G
  15695. @ignore
  15696. @mindex @null
  15697. @end ignore
  15698. @kindex H I f G
  15699. @pindex calc-inc-gamma
  15700. @ignore
  15701. @mindex @null
  15702. @end ignore
  15703. @tindex gammaQ
  15704. @ignore
  15705. @mindex @null
  15706. @end ignore
  15707. @tindex gammag
  15708. @ignore
  15709. @mindex @null
  15710. @end ignore
  15711. @tindex gammaG
  15712. The @kbd{f G} (@code{calc-inc-gamma}) [@code{gammaP}] command computes
  15713. the incomplete gamma function, denoted @samp{P(a,x)}. This is defined by
  15714. the integral,
  15715. @texline @math{P(a,x) = \left( \int_0^x t^{a-1} e^t dt \right) / \Gamma(a)}.
  15716. @infoline @expr{gammaP(a,x) = integ(t^(a-1) exp(t), t, 0, x) / gamma(a)}.
  15717. This implies that @samp{gammaP(a,inf) = 1} for any @expr{a} (see the
  15718. definition of the normal gamma function).
  15719. Several other varieties of incomplete gamma function are defined.
  15720. The complement of @expr{P(a,x)}, called @expr{Q(a,x) = 1-P(a,x)} by
  15721. some authors, is computed by the @kbd{I f G} [@code{gammaQ}] command.
  15722. You can think of this as taking the other half of the integral, from
  15723. @expr{x} to infinity.
  15724. @ifnottex
  15725. The functions corresponding to the integrals that define @expr{P(a,x)}
  15726. and @expr{Q(a,x)} but without the normalizing @expr{1/gamma(a)}
  15727. factor are called @expr{g(a,x)} and @expr{G(a,x)}, respectively
  15728. (where @expr{g} and @expr{G} represent the lower- and upper-case Greek
  15729. letter gamma). You can obtain these using the @kbd{H f G} [@code{gammag}]
  15730. and @kbd{H I f G} [@code{gammaG}] commands.
  15731. @end ifnottex
  15732. @tex
  15733. The functions corresponding to the integrals that define $P(a,x)$
  15734. and $Q(a,x)$ but without the normalizing $1/\Gamma(a)$
  15735. factor are called $\gamma(a,x)$ and $\Gamma(a,x)$, respectively.
  15736. You can obtain these using the \kbd{H f G} [\code{gammag}] and
  15737. \kbd{I H f G} [\code{gammaG}] commands.
  15738. @end tex
  15739. @kindex f b
  15740. @pindex calc-beta
  15741. @tindex beta
  15742. The @kbd{f b} (@code{calc-beta}) [@code{beta}] command computes the
  15743. Euler beta function, which is defined in terms of the gamma function as
  15744. @texline @math{B(a,b) = \Gamma(a) \Gamma(b) / \Gamma(a+b)},
  15745. @infoline @expr{beta(a,b) = gamma(a) gamma(b) / gamma(a+b)},
  15746. or by
  15747. @texline @math{B(a,b) = \int_0^1 t^{a-1} (1-t)^{b-1} dt}.
  15748. @infoline @expr{beta(a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, 1)}.
  15749. @kindex f B
  15750. @kindex H f B
  15751. @pindex calc-inc-beta
  15752. @tindex betaI
  15753. @tindex betaB
  15754. The @kbd{f B} (@code{calc-inc-beta}) [@code{betaI}] command computes
  15755. the incomplete beta function @expr{I(x,a,b)}. It is defined by
  15756. @texline @math{I(x,a,b) = \left( \int_0^x t^{a-1} (1-t)^{b-1} dt \right) / B(a,b)}.
  15757. @infoline @expr{betaI(x,a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, x) / beta(a,b)}.
  15758. Once again, the @kbd{H} (hyperbolic) prefix gives the corresponding
  15759. un-normalized version [@code{betaB}].
  15760. @kindex f e
  15761. @kindex I f e
  15762. @pindex calc-erf
  15763. @tindex erf
  15764. @tindex erfc
  15765. The @kbd{f e} (@code{calc-erf}) [@code{erf}] command computes the
  15766. error function
  15767. @texline @math{\hbox{erf}(x) = {2 \over \sqrt{\pi}} \int_0^x e^{-t^2} dt}.
  15768. @infoline @expr{erf(x) = 2 integ(exp(-(t^2)), t, 0, x) / sqrt(pi)}.
  15769. The complementary error function @kbd{I f e} (@code{calc-erfc}) [@code{erfc}]
  15770. is the corresponding integral from @samp{x} to infinity; the sum
  15771. @texline @math{\hbox{erf}(x) + \hbox{erfc}(x) = 1}.
  15772. @infoline @expr{erf(x) + erfc(x) = 1}.
  15773. @kindex f j
  15774. @kindex f y
  15775. @pindex calc-bessel-J
  15776. @pindex calc-bessel-Y
  15777. @tindex besJ
  15778. @tindex besY
  15779. The @kbd{f j} (@code{calc-bessel-J}) [@code{besJ}] and @kbd{f y}
  15780. (@code{calc-bessel-Y}) [@code{besY}] commands compute the Bessel
  15781. functions of the first and second kinds, respectively.
  15782. In @samp{besJ(n,x)} and @samp{besY(n,x)} the ``order'' parameter
  15783. @expr{n} is often an integer, but is not required to be one.
  15784. Calc's implementation of the Bessel functions currently limits the
  15785. precision to 8 digits, and may not be exact even to that precision.
  15786. Use with care!
  15787. @node Branch Cuts, Random Numbers, Advanced Math Functions, Scientific Functions
  15788. @section Branch Cuts and Principal Values
  15789. @noindent
  15790. @cindex Branch cuts
  15791. @cindex Principal values
  15792. All of the logarithmic, trigonometric, and other scientific functions are
  15793. defined for complex numbers as well as for reals.
  15794. This section describes the values
  15795. returned in cases where the general result is a family of possible values.
  15796. Calc follows section 12.5.3 of Steele's @dfn{Common Lisp, the Language},
  15797. second edition, in these matters. This section will describe each
  15798. function briefly; for a more detailed discussion (including some nifty
  15799. diagrams), consult Steele's book.
  15800. Note that the branch cuts for @code{arctan} and @code{arctanh} were
  15801. changed between the first and second editions of Steele. Recent
  15802. versions of Calc follow the second edition.
  15803. The new branch cuts exactly match those of the HP-28/48 calculators.
  15804. They also match those of Mathematica 1.2, except that Mathematica's
  15805. @code{arctan} cut is always in the right half of the complex plane,
  15806. and its @code{arctanh} cut is always in the top half of the plane.
  15807. Calc's cuts are continuous with quadrants I and III for @code{arctan},
  15808. or II and IV for @code{arctanh}.
  15809. Note: The current implementations of these functions with complex arguments
  15810. are designed with proper behavior around the branch cuts in mind, @emph{not}
  15811. efficiency or accuracy. You may need to increase the floating precision
  15812. and wait a while to get suitable answers from them.
  15813. For @samp{sqrt(a+bi)}: When @expr{a<0} and @expr{b} is small but positive
  15814. or zero, the result is close to the @expr{+i} axis. For @expr{b} small and
  15815. negative, the result is close to the @expr{-i} axis. The result always lies
  15816. in the right half of the complex plane.
  15817. For @samp{ln(a+bi)}: The real part is defined as @samp{ln(abs(a+bi))}.
  15818. The imaginary part is defined as @samp{arg(a+bi) = arctan2(b,a)}.
  15819. Thus the branch cuts for @code{sqrt} and @code{ln} both lie on the
  15820. negative real axis.
  15821. The following table describes these branch cuts in another way.
  15822. If the real and imaginary parts of @expr{z} are as shown, then
  15823. the real and imaginary parts of @expr{f(z)} will be as shown.
  15824. Here @code{eps} stands for a small positive value; each
  15825. occurrence of @code{eps} may stand for a different small value.
  15826. @smallexample
  15827. z sqrt(z) ln(z)
  15828. ----------------------------------------
  15829. +, 0 +, 0 any, 0
  15830. -, 0 0, + any, pi
  15831. -, +eps +eps, + +eps, +
  15832. -, -eps +eps, - +eps, -
  15833. @end smallexample
  15834. For @samp{z1^z2}: This is defined by @samp{exp(ln(z1)*z2)}.
  15835. One interesting consequence of this is that @samp{(-8)^1:3} does
  15836. not evaluate to @mathit{-2} as you might expect, but to the complex
  15837. number @expr{(1., 1.732)}. Both of these are valid cube roots
  15838. of @mathit{-8} (as is @expr{(1., -1.732)}); Calc chooses a perhaps
  15839. less-obvious root for the sake of mathematical consistency.
  15840. For @samp{arcsin(z)}: This is defined by @samp{-i*ln(i*z + sqrt(1-z^2))}.
  15841. The branch cuts are on the real axis, less than @mathit{-1} and greater than 1.
  15842. For @samp{arccos(z)}: This is defined by @samp{-i*ln(z + i*sqrt(1-z^2))},
  15843. or equivalently by @samp{pi/2 - arcsin(z)}. The branch cuts are on
  15844. the real axis, less than @mathit{-1} and greater than 1.
  15845. For @samp{arctan(z)}: This is defined by
  15846. @samp{(ln(1+i*z) - ln(1-i*z)) / (2*i)}. The branch cuts are on the
  15847. imaginary axis, below @expr{-i} and above @expr{i}.
  15848. For @samp{arcsinh(z)}: This is defined by @samp{ln(z + sqrt(1+z^2))}.
  15849. The branch cuts are on the imaginary axis, below @expr{-i} and
  15850. above @expr{i}.
  15851. For @samp{arccosh(z)}: This is defined by
  15852. @samp{ln(z + (z+1)*sqrt((z-1)/(z+1)))}. The branch cut is on the
  15853. real axis less than 1.
  15854. For @samp{arctanh(z)}: This is defined by @samp{(ln(1+z) - ln(1-z)) / 2}.
  15855. The branch cuts are on the real axis, less than @mathit{-1} and greater than 1.
  15856. The following tables for @code{arcsin}, @code{arccos}, and
  15857. @code{arctan} assume the current angular mode is Radians. The
  15858. hyperbolic functions operate independently of the angular mode.
  15859. @smallexample
  15860. z arcsin(z) arccos(z)
  15861. -------------------------------------------------------
  15862. (-1..1), 0 (-pi/2..pi/2), 0 (0..pi), 0
  15863. (-1..1), +eps (-pi/2..pi/2), +eps (0..pi), -eps
  15864. (-1..1), -eps (-pi/2..pi/2), -eps (0..pi), +eps
  15865. <-1, 0 -pi/2, + pi, -
  15866. <-1, +eps -pi/2 + eps, + pi - eps, -
  15867. <-1, -eps -pi/2 + eps, - pi - eps, +
  15868. >1, 0 pi/2, - 0, +
  15869. >1, +eps pi/2 - eps, + +eps, -
  15870. >1, -eps pi/2 - eps, - +eps, +
  15871. @end smallexample
  15872. @smallexample
  15873. z arccosh(z) arctanh(z)
  15874. -----------------------------------------------------
  15875. (-1..1), 0 0, (0..pi) any, 0
  15876. (-1..1), +eps +eps, (0..pi) any, +eps
  15877. (-1..1), -eps +eps, (-pi..0) any, -eps
  15878. <-1, 0 +, pi -, pi/2
  15879. <-1, +eps +, pi - eps -, pi/2 - eps
  15880. <-1, -eps +, -pi + eps -, -pi/2 + eps
  15881. >1, 0 +, 0 +, -pi/2
  15882. >1, +eps +, +eps +, pi/2 - eps
  15883. >1, -eps +, -eps +, -pi/2 + eps
  15884. @end smallexample
  15885. @smallexample
  15886. z arcsinh(z) arctan(z)
  15887. -----------------------------------------------------
  15888. 0, (-1..1) 0, (-pi/2..pi/2) 0, any
  15889. 0, <-1 -, -pi/2 -pi/2, -
  15890. +eps, <-1 +, -pi/2 + eps pi/2 - eps, -
  15891. -eps, <-1 -, -pi/2 + eps -pi/2 + eps, -
  15892. 0, >1 +, pi/2 pi/2, +
  15893. +eps, >1 +, pi/2 - eps pi/2 - eps, +
  15894. -eps, >1 -, pi/2 - eps -pi/2 + eps, +
  15895. @end smallexample
  15896. Finally, the following identities help to illustrate the relationship
  15897. between the complex trigonometric and hyperbolic functions. They
  15898. are valid everywhere, including on the branch cuts.
  15899. @smallexample
  15900. sin(i*z) = i*sinh(z) arcsin(i*z) = i*arcsinh(z)
  15901. cos(i*z) = cosh(z) arcsinh(i*z) = i*arcsin(z)
  15902. tan(i*z) = i*tanh(z) arctan(i*z) = i*arctanh(z)
  15903. sinh(i*z) = i*sin(z) cosh(i*z) = cos(z)
  15904. @end smallexample
  15905. The ``advanced math'' functions (gamma, Bessel, etc.@:) are also defined
  15906. for general complex arguments, but their branch cuts and principal values
  15907. are not rigorously specified at present.
  15908. @node Random Numbers, Combinatorial Functions, Branch Cuts, Scientific Functions
  15909. @section Random Numbers
  15910. @noindent
  15911. @kindex k r
  15912. @pindex calc-random
  15913. @tindex random
  15914. The @kbd{k r} (@code{calc-random}) [@code{random}] command produces
  15915. random numbers of various sorts.
  15916. Given a positive numeric prefix argument @expr{M}, it produces a random
  15917. integer @expr{N} in the range
  15918. @texline @math{0 \le N < M}.
  15919. @infoline @expr{0 <= N < M}.
  15920. Each possible value @expr{N} appears with equal probability.
  15921. With no numeric prefix argument, the @kbd{k r} command takes its argument
  15922. from the stack instead. Once again, if this is a positive integer @expr{M}
  15923. the result is a random integer less than @expr{M}. However, note that
  15924. while numeric prefix arguments are limited to six digits or so, an @expr{M}
  15925. taken from the stack can be arbitrarily large. If @expr{M} is negative,
  15926. the result is a random integer in the range
  15927. @texline @math{M < N \le 0}.
  15928. @infoline @expr{M < N <= 0}.
  15929. If the value on the stack is a floating-point number @expr{M}, the result
  15930. is a random floating-point number @expr{N} in the range
  15931. @texline @math{0 \le N < M}
  15932. @infoline @expr{0 <= N < M}
  15933. or
  15934. @texline @math{M < N \le 0},
  15935. @infoline @expr{M < N <= 0},
  15936. according to the sign of @expr{M}.
  15937. If @expr{M} is zero, the result is a Gaussian-distributed random real
  15938. number; the distribution has a mean of zero and a standard deviation
  15939. of one. The algorithm used generates random numbers in pairs; thus,
  15940. every other call to this function will be especially fast.
  15941. If @expr{M} is an error form
  15942. @texline @math{m} @code{+/-} @math{\sigma}
  15943. @infoline @samp{m +/- s}
  15944. where @var{m} and
  15945. @texline @math{\sigma}
  15946. @infoline @var{s}
  15947. are both real numbers, the result uses a Gaussian distribution with mean
  15948. @var{m} and standard deviation
  15949. @texline @math{\sigma}.
  15950. @infoline @var{s}.
  15951. If @expr{M} is an interval form, the lower and upper bounds specify the
  15952. acceptable limits of the random numbers. If both bounds are integers,
  15953. the result is a random integer in the specified range. If either bound
  15954. is floating-point, the result is a random real number in the specified
  15955. range. If the interval is open at either end, the result will be sure
  15956. not to equal that end value. (This makes a big difference for integer
  15957. intervals, but for floating-point intervals it's relatively minor:
  15958. with a precision of 6, @samp{random([1.0..2.0))} will return any of one
  15959. million numbers from 1.00000 to 1.99999; @samp{random([1.0..2.0])} may
  15960. additionally return 2.00000, but the probability of this happening is
  15961. extremely small.)
  15962. If @expr{M} is a vector, the result is one element taken at random from
  15963. the vector. All elements of the vector are given equal probabilities.
  15964. @vindex RandSeed
  15965. The sequence of numbers produced by @kbd{k r} is completely random by
  15966. default, i.e., the sequence is seeded each time you start Calc using
  15967. the current time and other information. You can get a reproducible
  15968. sequence by storing a particular ``seed value'' in the Calc variable
  15969. @code{RandSeed}. Any integer will do for a seed; integers of from 1
  15970. to 12 digits are good. If you later store a different integer into
  15971. @code{RandSeed}, Calc will switch to a different pseudo-random
  15972. sequence. If you ``unstore'' @code{RandSeed}, Calc will re-seed itself
  15973. from the current time. If you store the same integer that you used
  15974. before back into @code{RandSeed}, you will get the exact same sequence
  15975. of random numbers as before.
  15976. @pindex calc-rrandom
  15977. The @code{calc-rrandom} command (not on any key) produces a random real
  15978. number between zero and one. It is equivalent to @samp{random(1.0)}.
  15979. @kindex k a
  15980. @pindex calc-random-again
  15981. The @kbd{k a} (@code{calc-random-again}) command produces another random
  15982. number, re-using the most recent value of @expr{M}. With a numeric
  15983. prefix argument @var{n}, it produces @var{n} more random numbers using
  15984. that value of @expr{M}.
  15985. @kindex k h
  15986. @pindex calc-shuffle
  15987. @tindex shuffle
  15988. The @kbd{k h} (@code{calc-shuffle}) command produces a vector of several
  15989. random values with no duplicates. The value on the top of the stack
  15990. specifies the set from which the random values are drawn, and may be any
  15991. of the @expr{M} formats described above. The numeric prefix argument
  15992. gives the length of the desired list. (If you do not provide a numeric
  15993. prefix argument, the length of the list is taken from the top of the
  15994. stack, and @expr{M} from second-to-top.)
  15995. If @expr{M} is a floating-point number, zero, or an error form (so
  15996. that the random values are being drawn from the set of real numbers)
  15997. there is little practical difference between using @kbd{k h} and using
  15998. @kbd{k r} several times. But if the set of possible values consists
  15999. of just a few integers, or the elements of a vector, then there is
  16000. a very real chance that multiple @kbd{k r}'s will produce the same
  16001. number more than once. The @kbd{k h} command produces a vector whose
  16002. elements are always distinct. (Actually, there is a slight exception:
  16003. If @expr{M} is a vector, no given vector element will be drawn more
  16004. than once, but if several elements of @expr{M} are equal, they may
  16005. each make it into the result vector.)
  16006. One use of @kbd{k h} is to rearrange a list at random. This happens
  16007. if the prefix argument is equal to the number of values in the list:
  16008. @kbd{[1, 1.5, 2, 2.5, 3] 5 k h} might produce the permuted list
  16009. @samp{[2.5, 1, 1.5, 3, 2]}. As a convenient feature, if the argument
  16010. @var{n} is negative it is replaced by the size of the set represented
  16011. by @expr{M}. Naturally, this is allowed only when @expr{M} specifies
  16012. a small discrete set of possibilities.
  16013. To do the equivalent of @kbd{k h} but with duplications allowed,
  16014. given @expr{M} on the stack and with @var{n} just entered as a numeric
  16015. prefix, use @kbd{v b} to build a vector of copies of @expr{M}, then use
  16016. @kbd{V M k r} to ``map'' the normal @kbd{k r} function over the
  16017. elements of this vector. @xref{Matrix Functions}.
  16018. @menu
  16019. * Random Number Generator:: (Complete description of Calc's algorithm)
  16020. @end menu
  16021. @node Random Number Generator, , Random Numbers, Random Numbers
  16022. @subsection Random Number Generator
  16023. Calc's random number generator uses several methods to ensure that
  16024. the numbers it produces are highly random. Knuth's @emph{Art of
  16025. Computer Programming}, Volume II, contains a thorough description
  16026. of the theory of random number generators and their measurement and
  16027. characterization.
  16028. If @code{RandSeed} has no stored value, Calc calls Emacs's built-in
  16029. @code{random} function to get a stream of random numbers, which it
  16030. then treats in various ways to avoid problems inherent in the simple
  16031. random number generators that many systems use to implement @code{random}.
  16032. When Calc's random number generator is first invoked, it ``seeds''
  16033. the low-level random sequence using the time of day, so that the
  16034. random number sequence will be different every time you use Calc.
  16035. Since Emacs Lisp doesn't specify the range of values that will be
  16036. returned by its @code{random} function, Calc exercises the function
  16037. several times to estimate the range. When Calc subsequently uses
  16038. the @code{random} function, it takes only 10 bits of the result
  16039. near the most-significant end. (It avoids at least the bottom
  16040. four bits, preferably more, and also tries to avoid the top two
  16041. bits.) This strategy works well with the linear congruential
  16042. generators that are typically used to implement @code{random}.
  16043. If @code{RandSeed} contains an integer, Calc uses this integer to
  16044. seed an ``additive congruential'' method (Knuth's algorithm 3.2.2A,
  16045. computing
  16046. @texline @math{X_{n-55} - X_{n-24}}.
  16047. @infoline @expr{X_n-55 - X_n-24}).
  16048. This method expands the seed
  16049. value into a large table which is maintained internally; the variable
  16050. @code{RandSeed} is changed from, e.g., 42 to the vector @expr{[42]}
  16051. to indicate that the seed has been absorbed into this table. When
  16052. @code{RandSeed} contains a vector, @kbd{k r} and related commands
  16053. continue to use the same internal table as last time. There is no
  16054. way to extract the complete state of the random number generator
  16055. so that you can restart it from any point; you can only restart it
  16056. from the same initial seed value. A simple way to restart from the
  16057. same seed is to type @kbd{s r RandSeed} to get the seed vector,
  16058. @kbd{v u} to unpack it back into a number, then @kbd{s t RandSeed}
  16059. to reseed the generator with that number.
  16060. Calc uses a ``shuffling'' method as described in algorithm 3.2.2B
  16061. of Knuth. It fills a table with 13 random 10-bit numbers. Then,
  16062. to generate a new random number, it uses the previous number to
  16063. index into the table, picks the value it finds there as the new
  16064. random number, then replaces that table entry with a new value
  16065. obtained from a call to the base random number generator (either
  16066. the additive congruential generator or the @code{random} function
  16067. supplied by the system). If there are any flaws in the base
  16068. generator, shuffling will tend to even them out. But if the system
  16069. provides an excellent @code{random} function, shuffling will not
  16070. damage its randomness.
  16071. To create a random integer of a certain number of digits, Calc
  16072. builds the integer three decimal digits at a time. For each group
  16073. of three digits, Calc calls its 10-bit shuffling random number generator
  16074. (which returns a value from 0 to 1023); if the random value is 1000
  16075. or more, Calc throws it out and tries again until it gets a suitable
  16076. value.
  16077. To create a random floating-point number with precision @var{p}, Calc
  16078. simply creates a random @var{p}-digit integer and multiplies by
  16079. @texline @math{10^{-p}}.
  16080. @infoline @expr{10^-p}.
  16081. The resulting random numbers should be very clean, but note
  16082. that relatively small numbers will have few significant random digits.
  16083. In other words, with a precision of 12, you will occasionally get
  16084. numbers on the order of
  16085. @texline @math{10^{-9}}
  16086. @infoline @expr{10^-9}
  16087. or
  16088. @texline @math{10^{-10}},
  16089. @infoline @expr{10^-10},
  16090. but those numbers will only have two or three random digits since they
  16091. correspond to small integers times
  16092. @texline @math{10^{-12}}.
  16093. @infoline @expr{10^-12}.
  16094. To create a random integer in the interval @samp{[0 .. @var{m})}, Calc
  16095. counts the digits in @var{m}, creates a random integer with three
  16096. additional digits, then reduces modulo @var{m}. Unless @var{m} is a
  16097. power of ten the resulting values will be very slightly biased toward
  16098. the lower numbers, but this bias will be less than 0.1%. (For example,
  16099. if @var{m} is 42, Calc will reduce a random integer less than 100000
  16100. modulo 42 to get a result less than 42. It is easy to show that the
  16101. numbers 40 and 41 will be only 2380/2381 as likely to result from this
  16102. modulo operation as numbers 39 and below.) If @var{m} is a power of
  16103. ten, however, the numbers should be completely unbiased.
  16104. The Gaussian random numbers generated by @samp{random(0.0)} use the
  16105. ``polar'' method described in Knuth section 3.4.1C@. This method
  16106. generates a pair of Gaussian random numbers at a time, so only every
  16107. other call to @samp{random(0.0)} will require significant calculations.
  16108. @node Combinatorial Functions, Probability Distribution Functions, Random Numbers, Scientific Functions
  16109. @section Combinatorial Functions
  16110. @noindent
  16111. Commands relating to combinatorics and number theory begin with the
  16112. @kbd{k} key prefix.
  16113. @kindex k g
  16114. @pindex calc-gcd
  16115. @tindex gcd
  16116. The @kbd{k g} (@code{calc-gcd}) [@code{gcd}] command computes the
  16117. Greatest Common Divisor of two integers. It also accepts fractions;
  16118. the GCD of two fractions is defined by taking the GCD of the
  16119. numerators, and the LCM of the denominators. This definition is
  16120. consistent with the idea that @samp{a / gcd(a,x)} should yield an
  16121. integer for any @samp{a} and @samp{x}. For other types of arguments,
  16122. the operation is left in symbolic form.
  16123. @kindex k l
  16124. @pindex calc-lcm
  16125. @tindex lcm
  16126. The @kbd{k l} (@code{calc-lcm}) [@code{lcm}] command computes the
  16127. Least Common Multiple of two integers or fractions. The product of
  16128. the LCM and GCD of two numbers is equal to the product of the
  16129. numbers.
  16130. @kindex k E
  16131. @pindex calc-extended-gcd
  16132. @tindex egcd
  16133. The @kbd{k E} (@code{calc-extended-gcd}) [@code{egcd}] command computes
  16134. the GCD of two integers @expr{x} and @expr{y} and returns a vector
  16135. @expr{[g, a, b]} where
  16136. @texline @math{g = \gcd(x,y) = a x + b y}.
  16137. @infoline @expr{g = gcd(x,y) = a x + b y}.
  16138. @kindex !
  16139. @pindex calc-factorial
  16140. @tindex fact
  16141. @ignore
  16142. @mindex @null
  16143. @end ignore
  16144. @tindex !
  16145. The @kbd{!} (@code{calc-factorial}) [@code{fact}] command computes the
  16146. factorial of the number at the top of the stack. If the number is an
  16147. integer, the result is an exact integer. If the number is an
  16148. integer-valued float, the result is a floating-point approximation. If
  16149. the number is a non-integral real number, the generalized factorial is used,
  16150. as defined by the Euler Gamma function. Please note that computation of
  16151. large factorials can be slow; using floating-point format will help
  16152. since fewer digits must be maintained. The same is true of many of
  16153. the commands in this section.
  16154. @kindex k d
  16155. @pindex calc-double-factorial
  16156. @tindex dfact
  16157. @ignore
  16158. @mindex @null
  16159. @end ignore
  16160. @tindex !!
  16161. The @kbd{k d} (@code{calc-double-factorial}) [@code{dfact}] command
  16162. computes the ``double factorial'' of an integer. For an even integer,
  16163. this is the product of even integers from 2 to @expr{N}. For an odd
  16164. integer, this is the product of odd integers from 3 to @expr{N}. If
  16165. the argument is an integer-valued float, the result is a floating-point
  16166. approximation. This function is undefined for negative even integers.
  16167. The notation @expr{N!!} is also recognized for double factorials.
  16168. @kindex k c
  16169. @pindex calc-choose
  16170. @tindex choose
  16171. The @kbd{k c} (@code{calc-choose}) [@code{choose}] command computes the
  16172. binomial coefficient @expr{N}-choose-@expr{M}, where @expr{M} is the number
  16173. on the top of the stack and @expr{N} is second-to-top. If both arguments
  16174. are integers, the result is an exact integer. Otherwise, the result is a
  16175. floating-point approximation. The binomial coefficient is defined for all
  16176. real numbers by
  16177. @texline @math{N! \over M! (N-M)!\,}.
  16178. @infoline @expr{N! / M! (N-M)!}.
  16179. @kindex H k c
  16180. @pindex calc-perm
  16181. @tindex perm
  16182. @ifnottex
  16183. The @kbd{H k c} (@code{calc-perm}) [@code{perm}] command computes the
  16184. number-of-permutations function @expr{N! / (N-M)!}.
  16185. @end ifnottex
  16186. @tex
  16187. The \kbd{H k c} (\code{calc-perm}) [\code{perm}] command computes the
  16188. number-of-perm\-utations function $N! \over (N-M)!\,$.
  16189. @end tex
  16190. @kindex k b
  16191. @kindex H k b
  16192. @pindex calc-bernoulli-number
  16193. @tindex bern
  16194. The @kbd{k b} (@code{calc-bernoulli-number}) [@code{bern}] command
  16195. computes a given Bernoulli number. The value at the top of the stack
  16196. is a nonnegative integer @expr{n} that specifies which Bernoulli number
  16197. is desired. The @kbd{H k b} command computes a Bernoulli polynomial,
  16198. taking @expr{n} from the second-to-top position and @expr{x} from the
  16199. top of the stack. If @expr{x} is a variable or formula the result is
  16200. a polynomial in @expr{x}; if @expr{x} is a number the result is a number.
  16201. @kindex k e
  16202. @kindex H k e
  16203. @pindex calc-euler-number
  16204. @tindex euler
  16205. The @kbd{k e} (@code{calc-euler-number}) [@code{euler}] command similarly
  16206. computes an Euler number, and @w{@kbd{H k e}} computes an Euler polynomial.
  16207. Bernoulli and Euler numbers occur in the Taylor expansions of several
  16208. functions.
  16209. @kindex k s
  16210. @kindex H k s
  16211. @pindex calc-stirling-number
  16212. @tindex stir1
  16213. @tindex stir2
  16214. The @kbd{k s} (@code{calc-stirling-number}) [@code{stir1}] command
  16215. computes a Stirling number of the first
  16216. @texline kind@tie{}@math{n \brack m},
  16217. @infoline kind,
  16218. given two integers @expr{n} and @expr{m} on the stack. The @kbd{H k s}
  16219. [@code{stir2}] command computes a Stirling number of the second
  16220. @texline kind@tie{}@math{n \brace m}.
  16221. @infoline kind.
  16222. These are the number of @expr{m}-cycle permutations of @expr{n} objects,
  16223. and the number of ways to partition @expr{n} objects into @expr{m}
  16224. non-empty sets, respectively.
  16225. @kindex k p
  16226. @pindex calc-prime-test
  16227. @cindex Primes
  16228. The @kbd{k p} (@code{calc-prime-test}) command checks if the integer on
  16229. the top of the stack is prime. For integers less than eight million, the
  16230. answer is always exact and reasonably fast. For larger integers, a
  16231. probabilistic method is used (see Knuth vol.@: II, section 4.5.4, algorithm P).
  16232. The number is first checked against small prime factors (up to 13). Then,
  16233. any number of iterations of the algorithm are performed. Each step either
  16234. discovers that the number is non-prime, or substantially increases the
  16235. certainty that the number is prime. After a few steps, the chance that
  16236. a number was mistakenly described as prime will be less than one percent.
  16237. (Indeed, this is a worst-case estimate of the probability; in practice
  16238. even a single iteration is quite reliable.) After the @kbd{k p} command,
  16239. the number will be reported as definitely prime or non-prime if possible,
  16240. or otherwise ``probably'' prime with a certain probability of error.
  16241. @ignore
  16242. @starindex
  16243. @end ignore
  16244. @tindex prime
  16245. The normal @kbd{k p} command performs one iteration of the primality
  16246. test. Pressing @kbd{k p} repeatedly for the same integer will perform
  16247. additional iterations. Also, @kbd{k p} with a numeric prefix performs
  16248. the specified number of iterations. There is also an algebraic function
  16249. @samp{prime(n)} or @samp{prime(n,iters)} which returns 1 if @expr{n}
  16250. is (probably) prime and 0 if not.
  16251. @kindex k f
  16252. @pindex calc-prime-factors
  16253. @tindex prfac
  16254. The @kbd{k f} (@code{calc-prime-factors}) [@code{prfac}] command
  16255. attempts to decompose an integer into its prime factors. For numbers up
  16256. to 25 million, the answer is exact although it may take some time. The
  16257. result is a vector of the prime factors in increasing order. For larger
  16258. inputs, prime factors above 5000 may not be found, in which case the
  16259. last number in the vector will be an unfactored integer greater than 25
  16260. million (with a warning message). For negative integers, the first
  16261. element of the list will be @mathit{-1}. For inputs @mathit{-1}, @mathit{0}, and
  16262. @mathit{1}, the result is a list of the same number.
  16263. @kindex k n
  16264. @pindex calc-next-prime
  16265. @ignore
  16266. @mindex nextpr@idots
  16267. @end ignore
  16268. @tindex nextprime
  16269. The @kbd{k n} (@code{calc-next-prime}) [@code{nextprime}] command finds
  16270. the next prime above a given number. Essentially, it searches by calling
  16271. @code{calc-prime-test} on successive integers until it finds one that
  16272. passes the test. This is quite fast for integers less than eight million,
  16273. but once the probabilistic test comes into play the search may be rather
  16274. slow. Ordinarily this command stops for any prime that passes one iteration
  16275. of the primality test. With a numeric prefix argument, a number must pass
  16276. the specified number of iterations before the search stops. (This only
  16277. matters when searching above eight million.) You can always use additional
  16278. @kbd{k p} commands to increase your certainty that the number is indeed
  16279. prime.
  16280. @kindex I k n
  16281. @pindex calc-prev-prime
  16282. @ignore
  16283. @mindex prevpr@idots
  16284. @end ignore
  16285. @tindex prevprime
  16286. The @kbd{I k n} (@code{calc-prev-prime}) [@code{prevprime}] command
  16287. analogously finds the next prime less than a given number.
  16288. @kindex k t
  16289. @pindex calc-totient
  16290. @tindex totient
  16291. The @kbd{k t} (@code{calc-totient}) [@code{totient}] command computes the
  16292. Euler ``totient''
  16293. @texline function@tie{}@math{\phi(n)},
  16294. @infoline function,
  16295. the number of integers less than @expr{n} which
  16296. are relatively prime to @expr{n}.
  16297. @kindex k m
  16298. @pindex calc-moebius
  16299. @tindex moebius
  16300. The @kbd{k m} (@code{calc-moebius}) [@code{moebius}] command computes the
  16301. Möbius μ function. If the input number is a product of @expr{k}
  16302. distinct factors, this is @expr{(-1)^k}. If the input number has any
  16303. duplicate factors (i.e., can be divided by the same prime more than once),
  16304. the result is zero.
  16305. @node Probability Distribution Functions, , Combinatorial Functions, Scientific Functions
  16306. @section Probability Distribution Functions
  16307. @noindent
  16308. The functions in this section compute various probability distributions.
  16309. For continuous distributions, this is the integral of the probability
  16310. density function from @expr{x} to infinity. (These are the ``upper
  16311. tail'' distribution functions; there are also corresponding ``lower
  16312. tail'' functions which integrate from minus infinity to @expr{x}.)
  16313. For discrete distributions, the upper tail function gives the sum
  16314. from @expr{x} to infinity; the lower tail function gives the sum
  16315. from minus infinity up to, but not including,@w{ }@expr{x}.
  16316. To integrate from @expr{x} to @expr{y}, just use the distribution
  16317. function twice and subtract. For example, the probability that a
  16318. Gaussian random variable with mean 2 and standard deviation 1 will
  16319. lie in the range from 2.5 to 2.8 is @samp{utpn(2.5,2,1) - utpn(2.8,2,1)}
  16320. (``the probability that it is greater than 2.5, but not greater than 2.8''),
  16321. or equivalently @samp{ltpn(2.8,2,1) - ltpn(2.5,2,1)}.
  16322. @kindex k B
  16323. @kindex I k B
  16324. @pindex calc-utpb
  16325. @tindex utpb
  16326. @tindex ltpb
  16327. The @kbd{k B} (@code{calc-utpb}) [@code{utpb}] function uses the
  16328. binomial distribution. Push the parameters @var{n}, @var{p}, and
  16329. then @var{x} onto the stack; the result (@samp{utpb(x,n,p)}) is the
  16330. probability that an event will occur @var{x} or more times out
  16331. of @var{n} trials, if its probability of occurring in any given
  16332. trial is @var{p}. The @kbd{I k B} [@code{ltpb}] function is
  16333. the probability that the event will occur fewer than @var{x} times.
  16334. The other probability distribution functions similarly take the
  16335. form @kbd{k @var{X}} (@code{calc-utp@var{x}}) [@code{utp@var{x}}]
  16336. and @kbd{I k @var{X}} [@code{ltp@var{x}}], for various letters
  16337. @var{x}. The arguments to the algebraic functions are the value of
  16338. the random variable first, then whatever other parameters define the
  16339. distribution. Note these are among the few Calc functions where the
  16340. order of the arguments in algebraic form differs from the order of
  16341. arguments as found on the stack. (The random variable comes last on
  16342. the stack, so that you can type, e.g., @kbd{2 @key{RET} 1 @key{RET} 2.5
  16343. k N M-@key{RET} @key{DEL} 2.8 k N -}, using @kbd{M-@key{RET} @key{DEL}} to
  16344. recover the original arguments but substitute a new value for @expr{x}.)
  16345. @kindex k C
  16346. @pindex calc-utpc
  16347. @tindex utpc
  16348. @ignore
  16349. @mindex @idots
  16350. @end ignore
  16351. @kindex I k C
  16352. @ignore
  16353. @mindex @null
  16354. @end ignore
  16355. @tindex ltpc
  16356. The @samp{utpc(x,v)} function uses the chi-square distribution with
  16357. @texline @math{\nu}
  16358. @infoline @expr{v}
  16359. degrees of freedom. It is the probability that a model is
  16360. correct if its chi-square statistic is @expr{x}.
  16361. @kindex k F
  16362. @pindex calc-utpf
  16363. @tindex utpf
  16364. @ignore
  16365. @mindex @idots
  16366. @end ignore
  16367. @kindex I k F
  16368. @ignore
  16369. @mindex @null
  16370. @end ignore
  16371. @tindex ltpf
  16372. The @samp{utpf(F,v1,v2)} function uses the F distribution, used in
  16373. various statistical tests. The parameters
  16374. @texline @math{\nu_1}
  16375. @infoline @expr{v1}
  16376. and
  16377. @texline @math{\nu_2}
  16378. @infoline @expr{v2}
  16379. are the degrees of freedom in the numerator and denominator,
  16380. respectively, used in computing the statistic @expr{F}.
  16381. @kindex k N
  16382. @pindex calc-utpn
  16383. @tindex utpn
  16384. @ignore
  16385. @mindex @idots
  16386. @end ignore
  16387. @kindex I k N
  16388. @ignore
  16389. @mindex @null
  16390. @end ignore
  16391. @tindex ltpn
  16392. The @samp{utpn(x,m,s)} function uses a normal (Gaussian) distribution
  16393. with mean @expr{m} and standard deviation
  16394. @texline @math{\sigma}.
  16395. @infoline @expr{s}.
  16396. It is the probability that such a normal-distributed random variable
  16397. would exceed @expr{x}.
  16398. @kindex k P
  16399. @pindex calc-utpp
  16400. @tindex utpp
  16401. @ignore
  16402. @mindex @idots
  16403. @end ignore
  16404. @kindex I k P
  16405. @ignore
  16406. @mindex @null
  16407. @end ignore
  16408. @tindex ltpp
  16409. The @samp{utpp(n,x)} function uses a Poisson distribution with
  16410. mean @expr{x}. It is the probability that @expr{n} or more such
  16411. Poisson random events will occur.
  16412. @kindex k T
  16413. @pindex calc-ltpt
  16414. @tindex utpt
  16415. @ignore
  16416. @mindex @idots
  16417. @end ignore
  16418. @kindex I k T
  16419. @ignore
  16420. @mindex @null
  16421. @end ignore
  16422. @tindex ltpt
  16423. The @samp{utpt(t,v)} function uses the Student's ``t'' distribution
  16424. with
  16425. @texline @math{\nu}
  16426. @infoline @expr{v}
  16427. degrees of freedom. It is the probability that a
  16428. t-distributed random variable will be greater than @expr{t}.
  16429. (Note: This computes the distribution function
  16430. @texline @math{A(t|\nu)}
  16431. @infoline @expr{A(t|v)}
  16432. where
  16433. @texline @math{A(0|\nu) = 1}
  16434. @infoline @expr{A(0|v) = 1}
  16435. and
  16436. @texline @math{A(\infty|\nu) \to 0}.
  16437. @infoline @expr{A(inf|v) -> 0}.
  16438. The @code{UTPT} operation on the HP-48 uses a different definition which
  16439. returns half of Calc's value: @samp{UTPT(t,v) = .5*utpt(t,v)}.)
  16440. While Calc does not provide inverses of the probability distribution
  16441. functions, the @kbd{a R} command can be used to solve for the inverse.
  16442. Since the distribution functions are monotonic, @kbd{a R} is guaranteed
  16443. to be able to find a solution given any initial guess.
  16444. @xref{Numerical Solutions}.
  16445. @node Matrix Functions, Algebra, Scientific Functions, Top
  16446. @chapter Vector/Matrix Functions
  16447. @noindent
  16448. Many of the commands described here begin with the @kbd{v} prefix.
  16449. (For convenience, the shift-@kbd{V} prefix is equivalent to @kbd{v}.)
  16450. The commands usually apply to both plain vectors and matrices; some
  16451. apply only to matrices or only to square matrices. If the argument
  16452. has the wrong dimensions the operation is left in symbolic form.
  16453. Vectors are entered and displayed using @samp{[a,b,c]} notation.
  16454. Matrices are vectors of which all elements are vectors of equal length.
  16455. (Though none of the standard Calc commands use this concept, a
  16456. three-dimensional matrix or rank-3 tensor could be defined as a
  16457. vector of matrices, and so on.)
  16458. @menu
  16459. * Packing and Unpacking::
  16460. * Building Vectors::
  16461. * Extracting Elements::
  16462. * Manipulating Vectors::
  16463. * Vector and Matrix Arithmetic::
  16464. * Set Operations::
  16465. * Statistical Operations::
  16466. * Reducing and Mapping::
  16467. * Vector and Matrix Formats::
  16468. @end menu
  16469. @node Packing and Unpacking, Building Vectors, Matrix Functions, Matrix Functions
  16470. @section Packing and Unpacking
  16471. @noindent
  16472. Calc's ``pack'' and ``unpack'' commands collect stack entries to build
  16473. composite objects such as vectors and complex numbers. They are
  16474. described in this chapter because they are most often used to build
  16475. vectors.
  16476. @kindex v p
  16477. @kindex V p
  16478. @pindex calc-pack
  16479. The @kbd{v p} (@code{calc-pack}) [@code{pack}] command collects several
  16480. elements from the stack into a matrix, complex number, HMS form, error
  16481. form, etc. It uses a numeric prefix argument to specify the kind of
  16482. object to be built; this argument is referred to as the ``packing mode.''
  16483. If the packing mode is a nonnegative integer, a vector of that
  16484. length is created. For example, @kbd{C-u 5 v p} will pop the top
  16485. five stack elements and push back a single vector of those five
  16486. elements. (@kbd{C-u 0 v p} simply creates an empty vector.)
  16487. The same effect can be had by pressing @kbd{[} to push an incomplete
  16488. vector on the stack, using @key{TAB} (@code{calc-roll-down}) to sneak
  16489. the incomplete object up past a certain number of elements, and
  16490. then pressing @kbd{]} to complete the vector.
  16491. Negative packing modes create other kinds of composite objects:
  16492. @table @cite
  16493. @item -1
  16494. Two values are collected to build a complex number. For example,
  16495. @kbd{5 @key{RET} 7 C-u -1 v p} creates the complex number
  16496. @expr{(5, 7)}. The result is always a rectangular complex
  16497. number. The two input values must both be real numbers,
  16498. i.e., integers, fractions, or floats. If they are not, Calc
  16499. will instead build a formula like @samp{a + (0, 1) b}. (The
  16500. other packing modes also create a symbolic answer if the
  16501. components are not suitable.)
  16502. @item -2
  16503. Two values are collected to build a polar complex number.
  16504. The first is the magnitude; the second is the phase expressed
  16505. in either degrees or radians according to the current angular
  16506. mode.
  16507. @item -3
  16508. Three values are collected into an HMS form. The first
  16509. two values (hours and minutes) must be integers or
  16510. integer-valued floats. The third value may be any real
  16511. number.
  16512. @item -4
  16513. Two values are collected into an error form. The inputs
  16514. may be real numbers or formulas.
  16515. @item -5
  16516. Two values are collected into a modulo form. The inputs
  16517. must be real numbers.
  16518. @item -6
  16519. Two values are collected into the interval @samp{[a .. b]}.
  16520. The inputs may be real numbers, HMS or date forms, or formulas.
  16521. @item -7
  16522. Two values are collected into the interval @samp{[a .. b)}.
  16523. @item -8
  16524. Two values are collected into the interval @samp{(a .. b]}.
  16525. @item -9
  16526. Two values are collected into the interval @samp{(a .. b)}.
  16527. @item -10
  16528. Two integer values are collected into a fraction.
  16529. @item -11
  16530. Two values are collected into a floating-point number.
  16531. The first is the mantissa; the second, which must be an
  16532. integer, is the exponent. The result is the mantissa
  16533. times ten to the power of the exponent.
  16534. @item -12
  16535. This is treated the same as @mathit{-11} by the @kbd{v p} command.
  16536. When unpacking, @mathit{-12} specifies that a floating-point mantissa
  16537. is desired.
  16538. @item -13
  16539. A real number is converted into a date form.
  16540. @item -14
  16541. Three numbers (year, month, day) are packed into a pure date form.
  16542. @item -15
  16543. Six numbers are packed into a date/time form.
  16544. @end table
  16545. With any of the two-input negative packing modes, either or both
  16546. of the inputs may be vectors. If both are vectors of the same
  16547. length, the result is another vector made by packing corresponding
  16548. elements of the input vectors. If one input is a vector and the
  16549. other is a plain number, the number is packed along with each vector
  16550. element to produce a new vector. For example, @kbd{C-u -4 v p}
  16551. could be used to convert a vector of numbers and a vector of errors
  16552. into a single vector of error forms; @kbd{C-u -5 v p} could convert
  16553. a vector of numbers and a single number @var{M} into a vector of
  16554. numbers modulo @var{M}.
  16555. If you don't give a prefix argument to @kbd{v p}, it takes
  16556. the packing mode from the top of the stack. The elements to
  16557. be packed then begin at stack level 2. Thus
  16558. @kbd{1 @key{RET} 2 @key{RET} 4 n v p} is another way to
  16559. enter the error form @samp{1 +/- 2}.
  16560. If the packing mode taken from the stack is a vector, the result is a
  16561. matrix with the dimensions specified by the elements of the vector,
  16562. which must each be integers. For example, if the packing mode is
  16563. @samp{[2, 3]}, then six numbers will be taken from the stack and
  16564. returned in the form @samp{[@w{[a, b, c]}, [d, e, f]]}.
  16565. If any elements of the vector are negative, other kinds of
  16566. packing are done at that level as described above. For
  16567. example, @samp{[2, 3, -4]} takes 12 objects and creates a
  16568. @texline @math{2\times3}
  16569. @infoline 2x3
  16570. matrix of error forms: @samp{[[a +/- b, c +/- d ... ]]}.
  16571. Also, @samp{[-4, -10]} will convert four integers into an
  16572. error form consisting of two fractions: @samp{a:b +/- c:d}.
  16573. @ignore
  16574. @starindex
  16575. @end ignore
  16576. @tindex pack
  16577. There is an equivalent algebraic function,
  16578. @samp{pack(@var{mode}, @var{items})} where @var{mode} is a
  16579. packing mode (an integer or a vector of integers) and @var{items}
  16580. is a vector of objects to be packed (re-packed, really) according
  16581. to that mode. For example, @samp{pack([3, -4], [a,b,c,d,e,f])}
  16582. yields @samp{[a +/- b, @w{c +/- d}, e +/- f]}. The function is
  16583. left in symbolic form if the packing mode is invalid, or if the
  16584. number of data items does not match the number of items required
  16585. by the mode.
  16586. @kindex v u
  16587. @kindex V u
  16588. @pindex calc-unpack
  16589. The @kbd{v u} (@code{calc-unpack}) command takes the vector, complex
  16590. number, HMS form, or other composite object on the top of the stack and
  16591. ``unpacks'' it, pushing each of its elements onto the stack as separate
  16592. objects. Thus, it is the ``inverse'' of @kbd{v p}. If the value
  16593. at the top of the stack is a formula, @kbd{v u} unpacks it by pushing
  16594. each of the arguments of the top-level operator onto the stack.
  16595. You can optionally give a numeric prefix argument to @kbd{v u}
  16596. to specify an explicit (un)packing mode. If the packing mode is
  16597. negative and the input is actually a vector or matrix, the result
  16598. will be two or more similar vectors or matrices of the elements.
  16599. For example, given the vector @samp{[@w{a +/- b}, c^2, d +/- 7]},
  16600. the result of @kbd{C-u -4 v u} will be the two vectors
  16601. @samp{[a, c^2, d]} and @w{@samp{[b, 0, 7]}}.
  16602. Note that the prefix argument can have an effect even when the input is
  16603. not a vector. For example, if the input is the number @mathit{-5}, then
  16604. @kbd{c-u -1 v u} yields @mathit{-5} and 0 (the components of @mathit{-5}
  16605. when viewed as a rectangular complex number); @kbd{C-u -2 v u} yields 5
  16606. and 180 (assuming Degrees mode); and @kbd{C-u -10 v u} yields @mathit{-5}
  16607. and 1 (the numerator and denominator of @mathit{-5}, viewed as a rational
  16608. number). Plain @kbd{v u} with this input would complain that the input
  16609. is not a composite object.
  16610. Unpacking mode @mathit{-11} converts a float into an integer mantissa and
  16611. an integer exponent, where the mantissa is not divisible by 10
  16612. (except that 0.0 is represented by a mantissa and exponent of 0).
  16613. Unpacking mode @mathit{-12} converts a float into a floating-point mantissa
  16614. and integer exponent, where the mantissa (for non-zero numbers)
  16615. is guaranteed to lie in the range [1 .. 10). In both cases,
  16616. the mantissa is shifted left or right (and the exponent adjusted
  16617. to compensate) in order to satisfy these constraints.
  16618. Positive unpacking modes are treated differently than for @kbd{v p}.
  16619. A mode of 1 is much like plain @kbd{v u} with no prefix argument,
  16620. except that in addition to the components of the input object,
  16621. a suitable packing mode to re-pack the object is also pushed.
  16622. Thus, @kbd{C-u 1 v u} followed by @kbd{v p} will re-build the
  16623. original object.
  16624. A mode of 2 unpacks two levels of the object; the resulting
  16625. re-packing mode will be a vector of length 2. This might be used
  16626. to unpack a matrix, say, or a vector of error forms. Higher
  16627. unpacking modes unpack the input even more deeply.
  16628. @ignore
  16629. @starindex
  16630. @end ignore
  16631. @tindex unpack
  16632. There are two algebraic functions analogous to @kbd{v u}.
  16633. The @samp{unpack(@var{mode}, @var{item})} function unpacks the
  16634. @var{item} using the given @var{mode}, returning the result as
  16635. a vector of components. Here the @var{mode} must be an
  16636. integer, not a vector. For example, @samp{unpack(-4, a +/- b)}
  16637. returns @samp{[a, b]}, as does @samp{unpack(1, a +/- b)}.
  16638. @ignore
  16639. @starindex
  16640. @end ignore
  16641. @tindex unpackt
  16642. The @code{unpackt} function is like @code{unpack} but instead
  16643. of returning a simple vector of items, it returns a vector of
  16644. two things: The mode, and the vector of items. For example,
  16645. @samp{unpackt(1, 2:3 +/- 1:4)} returns @samp{[-4, [2:3, 1:4]]},
  16646. and @samp{unpackt(2, 2:3 +/- 1:4)} returns @samp{[[-4, -10], [2, 3, 1, 4]]}.
  16647. The identity for re-building the original object is
  16648. @samp{apply(pack, unpackt(@var{n}, @var{x})) = @var{x}}. (The
  16649. @code{apply} function builds a function call given the function
  16650. name and a vector of arguments.)
  16651. @cindex Numerator of a fraction, extracting
  16652. Subscript notation is a useful way to extract a particular part
  16653. of an object. For example, to get the numerator of a rational
  16654. number, you can use @samp{unpack(-10, @var{x})_1}.
  16655. @node Building Vectors, Extracting Elements, Packing and Unpacking, Matrix Functions
  16656. @section Building Vectors
  16657. @noindent
  16658. Vectors and matrices can be added,
  16659. subtracted, multiplied, and divided; @pxref{Basic Arithmetic}.
  16660. @kindex |
  16661. @pindex calc-concat
  16662. @ignore
  16663. @mindex @null
  16664. @end ignore
  16665. @tindex |
  16666. The @kbd{|} (@code{calc-concat}) [@code{vconcat}] command ``concatenates'' two vectors
  16667. into one. For example, after @kbd{@w{[ 1 , 2 ]} [ 3 , 4 ] |}, the stack
  16668. will contain the single vector @samp{[1, 2, 3, 4]}. If the arguments
  16669. are matrices, the rows of the first matrix are concatenated with the
  16670. rows of the second. (In other words, two matrices are just two vectors
  16671. of row-vectors as far as @kbd{|} is concerned.)
  16672. If either argument to @kbd{|} is a scalar (a non-vector), it is treated
  16673. like a one-element vector for purposes of concatenation: @kbd{1 [ 2 , 3 ] |}
  16674. produces the vector @samp{[1, 2, 3]}. Likewise, if one argument is a
  16675. matrix and the other is a plain vector, the vector is treated as a
  16676. one-row matrix.
  16677. @kindex H |
  16678. @tindex append
  16679. The @kbd{H |} (@code{calc-append}) [@code{append}] command concatenates
  16680. two vectors without any special cases. Both inputs must be vectors.
  16681. Whether or not they are matrices is not taken into account. If either
  16682. argument is a scalar, the @code{append} function is left in symbolic form.
  16683. See also @code{cons} and @code{rcons} below.
  16684. @kindex I |
  16685. @kindex H I |
  16686. The @kbd{I |} and @kbd{H I |} commands are similar, but they use their
  16687. two stack arguments in the opposite order. Thus @kbd{I |} is equivalent
  16688. to @kbd{@key{TAB} |}, but possibly more convenient and also a bit faster.
  16689. @kindex v d
  16690. @kindex V d
  16691. @pindex calc-diag
  16692. @tindex diag
  16693. The @kbd{v d} (@code{calc-diag}) [@code{diag}] function builds a diagonal
  16694. square matrix. The optional numeric prefix gives the number of rows
  16695. and columns in the matrix. If the value at the top of the stack is a
  16696. vector, the elements of the vector are used as the diagonal elements; the
  16697. prefix, if specified, must match the size of the vector. If the value on
  16698. the stack is a scalar, it is used for each element on the diagonal, and
  16699. the prefix argument is required.
  16700. To build a constant square matrix, e.g., a
  16701. @texline @math{3\times3}
  16702. @infoline 3x3
  16703. matrix filled with ones, use @kbd{0 M-3 v d 1 +}, i.e., build a zero
  16704. matrix first and then add a constant value to that matrix. (Another
  16705. alternative would be to use @kbd{v b} and @kbd{v a}; see below.)
  16706. @kindex v i
  16707. @kindex V i
  16708. @pindex calc-ident
  16709. @tindex idn
  16710. The @kbd{v i} (@code{calc-ident}) [@code{idn}] function builds an identity
  16711. matrix of the specified size. It is a convenient form of @kbd{v d}
  16712. where the diagonal element is always one. If no prefix argument is given,
  16713. this command prompts for one.
  16714. In algebraic notation, @samp{idn(a,n)} acts much like @samp{diag(a,n)},
  16715. except that @expr{a} is required to be a scalar (non-vector) quantity.
  16716. If @expr{n} is omitted, @samp{idn(a)} represents @expr{a} times an
  16717. identity matrix of unknown size. Calc can operate algebraically on
  16718. such generic identity matrices, and if one is combined with a matrix
  16719. whose size is known, it is converted automatically to an identity
  16720. matrix of a suitable matching size. The @kbd{v i} command with an
  16721. argument of zero creates a generic identity matrix, @samp{idn(1)}.
  16722. Note that in dimensioned Matrix mode (@pxref{Matrix Mode}), generic
  16723. identity matrices are immediately expanded to the current default
  16724. dimensions.
  16725. @kindex v x
  16726. @kindex V x
  16727. @pindex calc-index
  16728. @tindex index
  16729. The @kbd{v x} (@code{calc-index}) [@code{index}] function builds a vector
  16730. of consecutive integers from 1 to @var{n}, where @var{n} is the numeric
  16731. prefix argument. If you do not provide a prefix argument, you will be
  16732. prompted to enter a suitable number. If @var{n} is negative, the result
  16733. is a vector of negative integers from @var{n} to @mathit{-1}.
  16734. With a prefix argument of just @kbd{C-u}, the @kbd{v x} command takes
  16735. three values from the stack: @var{n}, @var{start}, and @var{incr} (with
  16736. @var{incr} at top-of-stack). Counting starts at @var{start} and increases
  16737. by @var{incr} for successive vector elements. If @var{start} or @var{n}
  16738. is in floating-point format, the resulting vector elements will also be
  16739. floats. Note that @var{start} and @var{incr} may in fact be any kind
  16740. of numbers or formulas.
  16741. When @var{start} and @var{incr} are specified, a negative @var{n} has a
  16742. different interpretation: It causes a geometric instead of arithmetic
  16743. sequence to be generated. For example, @samp{index(-3, a, b)} produces
  16744. @samp{[a, a b, a b^2]}. If you omit @var{incr} in the algebraic form,
  16745. @samp{index(@var{n}, @var{start})}, the default value for @var{incr}
  16746. is one for positive @var{n} or two for negative @var{n}.
  16747. @kindex v b
  16748. @kindex V b
  16749. @pindex calc-build-vector
  16750. @tindex cvec
  16751. The @kbd{v b} (@code{calc-build-vector}) [@code{cvec}] function builds a
  16752. vector of @var{n} copies of the value on the top of the stack, where @var{n}
  16753. is the numeric prefix argument. In algebraic formulas, @samp{cvec(x,n,m)}
  16754. can also be used to build an @var{n}-by-@var{m} matrix of copies of @var{x}.
  16755. (Interactively, just use @kbd{v b} twice: once to build a row, then again
  16756. to build a matrix of copies of that row.)
  16757. @kindex v h
  16758. @kindex V h
  16759. @kindex I v h
  16760. @kindex I V h
  16761. @pindex calc-head
  16762. @pindex calc-tail
  16763. @tindex head
  16764. @tindex tail
  16765. The @kbd{v h} (@code{calc-head}) [@code{head}] function returns the first
  16766. element of a vector. The @kbd{I v h} (@code{calc-tail}) [@code{tail}]
  16767. function returns the vector with its first element removed. In both
  16768. cases, the argument must be a non-empty vector.
  16769. @kindex v k
  16770. @kindex V k
  16771. @pindex calc-cons
  16772. @tindex cons
  16773. The @kbd{v k} (@code{calc-cons}) [@code{cons}] function takes a value @var{h}
  16774. and a vector @var{t} from the stack, and produces the vector whose head is
  16775. @var{h} and whose tail is @var{t}. This is similar to @kbd{|}, except
  16776. if @var{h} is itself a vector, @kbd{|} will concatenate the two vectors
  16777. whereas @code{cons} will insert @var{h} at the front of the vector @var{t}.
  16778. @kindex H v h
  16779. @kindex H V h
  16780. @tindex rhead
  16781. @ignore
  16782. @mindex @idots
  16783. @end ignore
  16784. @kindex H I v h
  16785. @kindex H I V h
  16786. @ignore
  16787. @mindex @null
  16788. @end ignore
  16789. @kindex H v k
  16790. @kindex H V k
  16791. @ignore
  16792. @mindex @null
  16793. @end ignore
  16794. @tindex rtail
  16795. @ignore
  16796. @mindex @null
  16797. @end ignore
  16798. @tindex rcons
  16799. Each of these three functions also accepts the Hyperbolic flag [@code{rhead},
  16800. @code{rtail}, @code{rcons}] in which case @var{t} instead represents
  16801. the @emph{last} single element of the vector, with @var{h}
  16802. representing the remainder of the vector. Thus the vector
  16803. @samp{[a, b, c, d] = cons(a, [b, c, d]) = rcons([a, b, c], d)}.
  16804. Also, @samp{head([a, b, c, d]) = a}, @samp{tail([a, b, c, d]) = [b, c, d]},
  16805. @samp{rhead([a, b, c, d]) = [a, b, c]}, and @samp{rtail([a, b, c, d]) = d}.
  16806. @node Extracting Elements, Manipulating Vectors, Building Vectors, Matrix Functions
  16807. @section Extracting Vector Elements
  16808. @noindent
  16809. @kindex v r
  16810. @kindex V r
  16811. @pindex calc-mrow
  16812. @tindex mrow
  16813. The @kbd{v r} (@code{calc-mrow}) [@code{mrow}] command extracts one row of
  16814. the matrix on the top of the stack, or one element of the plain vector on
  16815. the top of the stack. The row or element is specified by the numeric
  16816. prefix argument; the default is to prompt for the row or element number.
  16817. The matrix or vector is replaced by the specified row or element in the
  16818. form of a vector or scalar, respectively.
  16819. @cindex Permutations, applying
  16820. With a prefix argument of @kbd{C-u} only, @kbd{v r} takes the index of
  16821. the element or row from the top of the stack, and the vector or matrix
  16822. from the second-to-top position. If the index is itself a vector of
  16823. integers, the result is a vector of the corresponding elements of the
  16824. input vector, or a matrix of the corresponding rows of the input matrix.
  16825. This command can be used to obtain any permutation of a vector.
  16826. With @kbd{C-u}, if the index is an interval form with integer components,
  16827. it is interpreted as a range of indices and the corresponding subvector or
  16828. submatrix is returned.
  16829. @cindex Subscript notation
  16830. @kindex a _
  16831. @pindex calc-subscript
  16832. @tindex subscr
  16833. @tindex _
  16834. Subscript notation in algebraic formulas (@samp{a_b}) stands for the
  16835. Calc function @code{subscr}, which is synonymous with @code{mrow}.
  16836. Thus, @samp{[x, y, z]_k} produces @expr{x}, @expr{y}, or @expr{z} if
  16837. @expr{k} is one, two, or three, respectively. A double subscript
  16838. (@samp{M_i_j}, equivalent to @samp{subscr(subscr(M, i), j)}) will
  16839. access the element at row @expr{i}, column @expr{j} of a matrix.
  16840. The @kbd{a _} (@code{calc-subscript}) command creates a subscript
  16841. formula @samp{a_b} out of two stack entries. (It is on the @kbd{a}
  16842. ``algebra'' prefix because subscripted variables are often used
  16843. purely as an algebraic notation.)
  16844. @tindex mrrow
  16845. Given a negative prefix argument, @kbd{v r} instead deletes one row or
  16846. element from the matrix or vector on the top of the stack. Thus
  16847. @kbd{C-u 2 v r} replaces a matrix with its second row, but @kbd{C-u -2 v r}
  16848. replaces the matrix with the same matrix with its second row removed.
  16849. In algebraic form this function is called @code{mrrow}.
  16850. @tindex getdiag
  16851. Given a prefix argument of zero, @kbd{v r} extracts the diagonal elements
  16852. of a square matrix in the form of a vector. In algebraic form this
  16853. function is called @code{getdiag}.
  16854. @kindex v c
  16855. @kindex V c
  16856. @pindex calc-mcol
  16857. @tindex mcol
  16858. @tindex mrcol
  16859. The @kbd{v c} (@code{calc-mcol}) [@code{mcol} or @code{mrcol}] command is
  16860. the analogous operation on columns of a matrix. Given a plain vector
  16861. it extracts (or removes) one element, just like @kbd{v r}. If the
  16862. index in @kbd{C-u v c} is an interval or vector and the argument is a
  16863. matrix, the result is a submatrix with only the specified columns
  16864. retained (and possibly permuted in the case of a vector index).
  16865. To extract a matrix element at a given row and column, use @kbd{v r} to
  16866. extract the row as a vector, then @kbd{v c} to extract the column element
  16867. from that vector. In algebraic formulas, it is often more convenient to
  16868. use subscript notation: @samp{m_i_j} gives row @expr{i}, column @expr{j}
  16869. of matrix @expr{m}.
  16870. @kindex v s
  16871. @kindex V s
  16872. @pindex calc-subvector
  16873. @tindex subvec
  16874. The @kbd{v s} (@code{calc-subvector}) [@code{subvec}] command extracts
  16875. a subvector of a vector. The arguments are the vector, the starting
  16876. index, and the ending index, with the ending index in the top-of-stack
  16877. position. The starting index indicates the first element of the vector
  16878. to take. The ending index indicates the first element @emph{past} the
  16879. range to be taken. Thus, @samp{subvec([a, b, c, d, e], 2, 4)} produces
  16880. the subvector @samp{[b, c]}. You could get the same result using
  16881. @samp{mrow([a, b, c, d, e], @w{[2 .. 4)})}.
  16882. If either the start or the end index is zero or negative, it is
  16883. interpreted as relative to the end of the vector. Thus
  16884. @samp{subvec([a, b, c, d, e], 2, -2)} also produces @samp{[b, c]}. In
  16885. the algebraic form, the end index can be omitted in which case it
  16886. is taken as zero, i.e., elements from the starting element to the
  16887. end of the vector are used. The infinity symbol, @code{inf}, also
  16888. has this effect when used as the ending index.
  16889. @kindex I v s
  16890. @kindex I V s
  16891. @tindex rsubvec
  16892. With the Inverse flag, @kbd{I v s} [@code{rsubvec}] removes a subvector
  16893. from a vector. The arguments are interpreted the same as for the
  16894. normal @kbd{v s} command. Thus, @samp{rsubvec([a, b, c, d, e], 2, 4)}
  16895. produces @samp{[a, d, e]}. It is always true that @code{subvec} and
  16896. @code{rsubvec} return complementary parts of the input vector.
  16897. @xref{Selecting Subformulas}, for an alternative way to operate on
  16898. vectors one element at a time.
  16899. @node Manipulating Vectors, Vector and Matrix Arithmetic, Extracting Elements, Matrix Functions
  16900. @section Manipulating Vectors
  16901. @noindent
  16902. @kindex v l
  16903. @kindex V l
  16904. @pindex calc-vlength
  16905. @tindex vlen
  16906. The @kbd{v l} (@code{calc-vlength}) [@code{vlen}] command computes the
  16907. length of a vector. The length of a non-vector is considered to be zero.
  16908. Note that matrices are just vectors of vectors for the purposes of this
  16909. command.
  16910. @kindex H v l
  16911. @kindex H V l
  16912. @tindex mdims
  16913. With the Hyperbolic flag, @kbd{H v l} [@code{mdims}] computes a vector
  16914. of the dimensions of a vector, matrix, or higher-order object. For
  16915. example, @samp{mdims([[a,b,c],[d,e,f]])} returns @samp{[2, 3]} since
  16916. its argument is a
  16917. @texline @math{2\times3}
  16918. @infoline 2x3
  16919. matrix.
  16920. @kindex v f
  16921. @kindex V f
  16922. @pindex calc-vector-find
  16923. @tindex find
  16924. The @kbd{v f} (@code{calc-vector-find}) [@code{find}] command searches
  16925. along a vector for the first element equal to a given target. The target
  16926. is on the top of the stack; the vector is in the second-to-top position.
  16927. If a match is found, the result is the index of the matching element.
  16928. Otherwise, the result is zero. The numeric prefix argument, if given,
  16929. allows you to select any starting index for the search.
  16930. @kindex v a
  16931. @kindex V a
  16932. @pindex calc-arrange-vector
  16933. @tindex arrange
  16934. @cindex Arranging a matrix
  16935. @cindex Reshaping a matrix
  16936. @cindex Flattening a matrix
  16937. The @kbd{v a} (@code{calc-arrange-vector}) [@code{arrange}] command
  16938. rearranges a vector to have a certain number of columns and rows. The
  16939. numeric prefix argument specifies the number of columns; if you do not
  16940. provide an argument, you will be prompted for the number of columns.
  16941. The vector or matrix on the top of the stack is @dfn{flattened} into a
  16942. plain vector. If the number of columns is nonzero, this vector is
  16943. then formed into a matrix by taking successive groups of @var{n} elements.
  16944. If the number of columns does not evenly divide the number of elements
  16945. in the vector, the last row will be short and the result will not be
  16946. suitable for use as a matrix. For example, with the matrix
  16947. @samp{[[1, 2], @w{[3, 4]}]} on the stack, @kbd{v a 4} produces
  16948. @samp{[[1, 2, 3, 4]]} (a
  16949. @texline @math{1\times4}
  16950. @infoline 1x4
  16951. matrix), @kbd{v a 1} produces @samp{[[1], [2], [3], [4]]} (a
  16952. @texline @math{4\times1}
  16953. @infoline 4x1
  16954. matrix), @kbd{v a 2} produces @samp{[[1, 2], [3, 4]]} (the original
  16955. @texline @math{2\times2}
  16956. @infoline 2x2
  16957. matrix), @w{@kbd{v a 3}} produces @samp{[[1, 2, 3], [4]]} (not a
  16958. matrix), and @kbd{v a 0} produces the flattened list
  16959. @samp{[1, 2, @w{3, 4}]}.
  16960. @cindex Sorting data
  16961. @kindex v S
  16962. @kindex V S
  16963. @kindex I v S
  16964. @kindex I V S
  16965. @pindex calc-sort
  16966. @tindex sort
  16967. @tindex rsort
  16968. The @kbd{V S} (@code{calc-sort}) [@code{sort}] command sorts the elements of
  16969. a vector into increasing order. Real numbers, real infinities, and
  16970. constant interval forms come first in this ordering; next come other
  16971. kinds of numbers, then variables (in alphabetical order), then finally
  16972. come formulas and other kinds of objects; these are sorted according
  16973. to a kind of lexicographic ordering with the useful property that
  16974. one vector is less or greater than another if the first corresponding
  16975. unequal elements are less or greater, respectively. Since quoted strings
  16976. are stored by Calc internally as vectors of ASCII character codes
  16977. (@pxref{Strings}), this means vectors of strings are also sorted into
  16978. alphabetical order by this command.
  16979. The @kbd{I V S} [@code{rsort}] command sorts a vector into decreasing order.
  16980. @cindex Permutation, inverse of
  16981. @cindex Inverse of permutation
  16982. @cindex Index tables
  16983. @cindex Rank tables
  16984. @kindex v G
  16985. @kindex V G
  16986. @kindex I v G
  16987. @kindex I V G
  16988. @pindex calc-grade
  16989. @tindex grade
  16990. @tindex rgrade
  16991. The @kbd{V G} (@code{calc-grade}) [@code{grade}, @code{rgrade}] command
  16992. produces an index table or permutation vector which, if applied to the
  16993. input vector (as the index of @kbd{C-u v r}, say), would sort the vector.
  16994. A permutation vector is just a vector of integers from 1 to @var{n}, where
  16995. each integer occurs exactly once. One application of this is to sort a
  16996. matrix of data rows using one column as the sort key; extract that column,
  16997. grade it with @kbd{V G}, then use the result to reorder the original matrix
  16998. with @kbd{C-u v r}. Another interesting property of the @code{V G} command
  16999. is that, if the input is itself a permutation vector, the result will
  17000. be the inverse of the permutation. The inverse of an index table is
  17001. a rank table, whose @var{k}th element says where the @var{k}th original
  17002. vector element will rest when the vector is sorted. To get a rank
  17003. table, just use @kbd{V G V G}.
  17004. With the Inverse flag, @kbd{I V G} produces an index table that would
  17005. sort the input into decreasing order. Note that @kbd{V S} and @kbd{V G}
  17006. use a ``stable'' sorting algorithm, i.e., any two elements which are equal
  17007. will not be moved out of their original order. Generally there is no way
  17008. to tell with @kbd{V S}, since two elements which are equal look the same,
  17009. but with @kbd{V G} this can be an important issue. In the matrix-of-rows
  17010. example, suppose you have names and telephone numbers as two columns and
  17011. you wish to sort by phone number primarily, and by name when the numbers
  17012. are equal. You can sort the data matrix by names first, and then again
  17013. by phone numbers. Because the sort is stable, any two rows with equal
  17014. phone numbers will remain sorted by name even after the second sort.
  17015. @cindex Histograms
  17016. @kindex v H
  17017. @kindex V H
  17018. @pindex calc-histogram
  17019. @ignore
  17020. @mindex histo@idots
  17021. @end ignore
  17022. @tindex histogram
  17023. The @kbd{V H} (@code{calc-histogram}) [@code{histogram}] command builds a
  17024. histogram of a vector of numbers. Vector elements are assumed to be
  17025. integers or real numbers in the range [0..@var{n}) for some ``number of
  17026. bins'' @var{n}, which is the numeric prefix argument given to the
  17027. command. The result is a vector of @var{n} counts of how many times
  17028. each value appeared in the original vector. Non-integers in the input
  17029. are rounded down to integers. Any vector elements outside the specified
  17030. range are ignored. (You can tell if elements have been ignored by noting
  17031. that the counts in the result vector don't add up to the length of the
  17032. input vector.)
  17033. If no prefix is given, then you will be prompted for a vector which
  17034. will be used to determine the bins. (If a positive integer is given at
  17035. this prompt, it will be still treated as if it were given as a
  17036. prefix.) Each bin will consist of the interval of numbers closest to
  17037. the corresponding number of this new vector; if the vector
  17038. @expr{[a, b, c, ...]} is entered at the prompt, the bins will be
  17039. @expr{(-inf, (a+b)/2]}, @expr{((a+b)/2, (b+c)/2]}, etc. The result of
  17040. this command will be a vector counting how many elements of the
  17041. original vector are in each bin.
  17042. The result will then be a vector with the same length as this new vector;
  17043. each element of the new vector will be replaced by the number of
  17044. elements of the original vector which are closest to it.
  17045. @kindex H v H
  17046. @kindex H V H
  17047. With the Hyperbolic flag, @kbd{H V H} pulls two vectors from the stack.
  17048. The second-to-top vector is the list of numbers as before. The top
  17049. vector is an equal-sized list of ``weights'' to attach to the elements
  17050. of the data vector. For example, if the first data element is 4.2 and
  17051. the first weight is 10, then 10 will be added to bin 4 of the result
  17052. vector. Without the hyperbolic flag, every element has a weight of one.
  17053. @kindex v t
  17054. @kindex V t
  17055. @pindex calc-transpose
  17056. @tindex trn
  17057. The @kbd{v t} (@code{calc-transpose}) [@code{trn}] command computes
  17058. the transpose of the matrix at the top of the stack. If the argument
  17059. is a plain vector, it is treated as a row vector and transposed into
  17060. a one-column matrix.
  17061. @kindex v v
  17062. @kindex V v
  17063. @pindex calc-reverse-vector
  17064. @tindex rev
  17065. The @kbd{v v} (@code{calc-reverse-vector}) [@code{rev}] command reverses
  17066. a vector end-for-end. Given a matrix, it reverses the order of the rows.
  17067. (To reverse the columns instead, just use @kbd{v t v v v t}. The same
  17068. principle can be used to apply other vector commands to the columns of
  17069. a matrix.)
  17070. @kindex v m
  17071. @kindex V m
  17072. @pindex calc-mask-vector
  17073. @tindex vmask
  17074. The @kbd{v m} (@code{calc-mask-vector}) [@code{vmask}] command uses
  17075. one vector as a mask to extract elements of another vector. The mask
  17076. is in the second-to-top position; the target vector is on the top of
  17077. the stack. These vectors must have the same length. The result is
  17078. the same as the target vector, but with all elements which correspond
  17079. to zeros in the mask vector deleted. Thus, for example,
  17080. @samp{vmask([1, 0, 1, 0, 1], [a, b, c, d, e])} produces @samp{[a, c, e]}.
  17081. @xref{Logical Operations}.
  17082. @kindex v e
  17083. @kindex V e
  17084. @pindex calc-expand-vector
  17085. @tindex vexp
  17086. The @kbd{v e} (@code{calc-expand-vector}) [@code{vexp}] command
  17087. expands a vector according to another mask vector. The result is a
  17088. vector the same length as the mask, but with nonzero elements replaced
  17089. by successive elements from the target vector. The length of the target
  17090. vector is normally the number of nonzero elements in the mask. If the
  17091. target vector is longer, its last few elements are lost. If the target
  17092. vector is shorter, the last few nonzero mask elements are left
  17093. unreplaced in the result. Thus @samp{vexp([2, 0, 3, 0, 7], [a, b])}
  17094. produces @samp{[a, 0, b, 0, 7]}.
  17095. @kindex H v e
  17096. @kindex H V e
  17097. With the Hyperbolic flag, @kbd{H v e} takes a filler value from the
  17098. top of the stack; the mask and target vectors come from the third and
  17099. second elements of the stack. This filler is used where the mask is
  17100. zero: @samp{vexp([2, 0, 3, 0, 7], [a, b], z)} produces
  17101. @samp{[a, z, c, z, 7]}. If the filler value is itself a vector,
  17102. then successive values are taken from it, so that the effect is to
  17103. interleave two vectors according to the mask:
  17104. @samp{vexp([2, 0, 3, 7, 0, 0], [a, b], [x, y])} produces
  17105. @samp{[a, x, b, 7, y, 0]}.
  17106. Another variation on the masking idea is to combine @samp{[a, b, c, d, e]}
  17107. with the mask @samp{[1, 0, 1, 0, 1]} to produce @samp{[a, 0, c, 0, e]}.
  17108. You can accomplish this with @kbd{V M a &}, mapping the logical ``and''
  17109. operation across the two vectors. @xref{Logical Operations}. Note that
  17110. the @code{? :} operation also discussed there allows other types of
  17111. masking using vectors.
  17112. @node Vector and Matrix Arithmetic, Set Operations, Manipulating Vectors, Matrix Functions
  17113. @section Vector and Matrix Arithmetic
  17114. @noindent
  17115. Basic arithmetic operations like addition and multiplication are defined
  17116. for vectors and matrices as well as for numbers. Division of matrices, in
  17117. the sense of multiplying by the inverse, is supported. (Division by a
  17118. matrix actually uses LU-decomposition for greater accuracy and speed.)
  17119. @xref{Basic Arithmetic}.
  17120. The following functions are applied element-wise if their arguments are
  17121. vectors or matrices: @code{change-sign}, @code{conj}, @code{arg},
  17122. @code{re}, @code{im}, @code{polar}, @code{rect}, @code{clean},
  17123. @code{float}, @code{frac}. @xref{Function Index}.
  17124. @kindex v J
  17125. @kindex V J
  17126. @pindex calc-conj-transpose
  17127. @tindex ctrn
  17128. The @kbd{V J} (@code{calc-conj-transpose}) [@code{ctrn}] command computes
  17129. the conjugate transpose of its argument, i.e., @samp{conj(trn(x))}.
  17130. @ignore
  17131. @mindex A
  17132. @end ignore
  17133. @kindex A (vectors)
  17134. @pindex calc-abs (vectors)
  17135. @ignore
  17136. @mindex abs
  17137. @end ignore
  17138. @tindex abs (vectors)
  17139. The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the
  17140. Frobenius norm of a vector or matrix argument. This is the square
  17141. root of the sum of the squares of the absolute values of the
  17142. elements of the vector or matrix. If the vector is interpreted as
  17143. a point in two- or three-dimensional space, this is the distance
  17144. from that point to the origin.
  17145. @kindex v n
  17146. @kindex V n
  17147. @pindex calc-rnorm
  17148. @tindex rnorm
  17149. The @kbd{v n} (@code{calc-rnorm}) [@code{rnorm}] command computes the
  17150. infinity-norm of a vector, or the row norm of a matrix. For a plain
  17151. vector, this is the maximum of the absolute values of the elements. For
  17152. a matrix, this is the maximum of the row-absolute-value-sums, i.e., of
  17153. the sums of the absolute values of the elements along the various rows.
  17154. @kindex v N
  17155. @kindex V N
  17156. @pindex calc-cnorm
  17157. @tindex cnorm
  17158. The @kbd{V N} (@code{calc-cnorm}) [@code{cnorm}] command computes
  17159. the one-norm of a vector, or column norm of a matrix. For a plain
  17160. vector, this is the sum of the absolute values of the elements.
  17161. For a matrix, this is the maximum of the column-absolute-value-sums.
  17162. General @expr{k}-norms for @expr{k} other than one or infinity are
  17163. not provided. However, the 2-norm (or Frobenius norm) is provided for
  17164. vectors by the @kbd{A} (@code{calc-abs}) command.
  17165. @kindex v C
  17166. @kindex V C
  17167. @pindex calc-cross
  17168. @tindex cross
  17169. The @kbd{V C} (@code{calc-cross}) [@code{cross}] command computes the
  17170. right-handed cross product of two vectors, each of which must have
  17171. exactly three elements.
  17172. @ignore
  17173. @mindex &
  17174. @end ignore
  17175. @kindex & (matrices)
  17176. @pindex calc-inv (matrices)
  17177. @ignore
  17178. @mindex inv
  17179. @end ignore
  17180. @tindex inv (matrices)
  17181. The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
  17182. inverse of a square matrix. If the matrix is singular, the inverse
  17183. operation is left in symbolic form. Matrix inverses are recorded so
  17184. that once an inverse (or determinant) of a particular matrix has been
  17185. computed, the inverse and determinant of the matrix can be recomputed
  17186. quickly in the future.
  17187. If the argument to @kbd{&} is a plain number @expr{x}, this
  17188. command simply computes @expr{1/x}. This is okay, because the
  17189. @samp{/} operator also does a matrix inversion when dividing one
  17190. by a matrix.
  17191. @kindex v D
  17192. @kindex V D
  17193. @pindex calc-mdet
  17194. @tindex det
  17195. The @kbd{V D} (@code{calc-mdet}) [@code{det}] command computes the
  17196. determinant of a square matrix.
  17197. @kindex v L
  17198. @kindex V L
  17199. @pindex calc-mlud
  17200. @tindex lud
  17201. The @kbd{V L} (@code{calc-mlud}) [@code{lud}] command computes the
  17202. LU decomposition of a matrix. The result is a list of three matrices
  17203. which, when multiplied together left-to-right, form the original matrix.
  17204. The first is a permutation matrix that arises from pivoting in the
  17205. algorithm, the second is lower-triangular with ones on the diagonal,
  17206. and the third is upper-triangular.
  17207. @kindex v T
  17208. @kindex V T
  17209. @pindex calc-mtrace
  17210. @tindex tr
  17211. The @kbd{V T} (@code{calc-mtrace}) [@code{tr}] command computes the
  17212. trace of a square matrix. This is defined as the sum of the diagonal
  17213. elements of the matrix.
  17214. @kindex v K
  17215. @kindex V K
  17216. @pindex calc-kron
  17217. @tindex kron
  17218. The @kbd{V K} (@code{calc-kron}) [@code{kron}] command computes
  17219. the Kronecker product of two matrices.
  17220. @node Set Operations, Statistical Operations, Vector and Matrix Arithmetic, Matrix Functions
  17221. @section Set Operations using Vectors
  17222. @noindent
  17223. @cindex Sets, as vectors
  17224. Calc includes several commands which interpret vectors as @dfn{sets} of
  17225. objects. A set is a collection of objects; any given object can appear
  17226. only once in the set. Calc stores sets as vectors of objects in
  17227. sorted order. Objects in a Calc set can be any of the usual things,
  17228. such as numbers, variables, or formulas. Two set elements are considered
  17229. equal if they are identical, except that numerically equal numbers like
  17230. the integer 4 and the float 4.0 are considered equal even though they
  17231. are not ``identical.'' Variables are treated like plain symbols without
  17232. attached values by the set operations; subtracting the set @samp{[b]}
  17233. from @samp{[a, b]} always yields the set @samp{[a]} even though if
  17234. the variables @samp{a} and @samp{b} both equaled 17, you might
  17235. expect the answer @samp{[]}.
  17236. If a set contains interval forms, then it is assumed to be a set of
  17237. real numbers. In this case, all set operations require the elements
  17238. of the set to be only things that are allowed in intervals: Real
  17239. numbers, plus and minus infinity, HMS forms, and date forms. If
  17240. there are variables or other non-real objects present in a real set,
  17241. all set operations on it will be left in unevaluated form.
  17242. If the input to a set operation is a plain number or interval form
  17243. @var{a}, it is treated like the one-element vector @samp{[@var{a}]}.
  17244. The result is always a vector, except that if the set consists of a
  17245. single interval, the interval itself is returned instead.
  17246. @xref{Logical Operations}, for the @code{in} function which tests if
  17247. a certain value is a member of a given set. To test if the set @expr{A}
  17248. is a subset of the set @expr{B}, use @samp{vdiff(A, B) = []}.
  17249. @kindex v +
  17250. @kindex V +
  17251. @pindex calc-remove-duplicates
  17252. @tindex rdup
  17253. The @kbd{V +} (@code{calc-remove-duplicates}) [@code{rdup}] command
  17254. converts an arbitrary vector into set notation. It works by sorting
  17255. the vector as if by @kbd{V S}, then removing duplicates. (For example,
  17256. @kbd{[a, 5, 4, a, 4.0]} is sorted to @samp{[4, 4.0, 5, a, a]} and then
  17257. reduced to @samp{[4, 5, a]}). Overlapping intervals are merged as
  17258. necessary. You rarely need to use @kbd{V +} explicitly, since all the
  17259. other set-based commands apply @kbd{V +} to their inputs before using
  17260. them.
  17261. @kindex v V
  17262. @kindex V V
  17263. @pindex calc-set-union
  17264. @tindex vunion
  17265. The @kbd{V V} (@code{calc-set-union}) [@code{vunion}] command computes
  17266. the union of two sets. An object is in the union of two sets if and
  17267. only if it is in either (or both) of the input sets. (You could
  17268. accomplish the same thing by concatenating the sets with @kbd{|},
  17269. then using @kbd{V +}.)
  17270. @kindex v ^
  17271. @kindex V ^
  17272. @pindex calc-set-intersect
  17273. @tindex vint
  17274. The @kbd{V ^} (@code{calc-set-intersect}) [@code{vint}] command computes
  17275. the intersection of two sets. An object is in the intersection if
  17276. and only if it is in both of the input sets. Thus if the input
  17277. sets are disjoint, i.e., if they share no common elements, the result
  17278. will be the empty vector @samp{[]}. Note that the characters @kbd{V}
  17279. and @kbd{^} were chosen to be close to the conventional mathematical
  17280. notation for set
  17281. @texline union@tie{}(@math{A \cup B})
  17282. @infoline union
  17283. and
  17284. @texline intersection@tie{}(@math{A \cap B}).
  17285. @infoline intersection.
  17286. @kindex v -
  17287. @kindex V -
  17288. @pindex calc-set-difference
  17289. @tindex vdiff
  17290. The @kbd{V -} (@code{calc-set-difference}) [@code{vdiff}] command computes
  17291. the difference between two sets. An object is in the difference
  17292. @expr{A - B} if and only if it is in @expr{A} but not in @expr{B}.
  17293. Thus subtracting @samp{[y,z]} from a set will remove the elements
  17294. @samp{y} and @samp{z} if they are present. You can also think of this
  17295. as a general @dfn{set complement} operator; if @expr{A} is the set of
  17296. all possible values, then @expr{A - B} is the ``complement'' of @expr{B}.
  17297. Obviously this is only practical if the set of all possible values in
  17298. your problem is small enough to list in a Calc vector (or simple
  17299. enough to express in a few intervals).
  17300. @kindex v X
  17301. @kindex V X
  17302. @pindex calc-set-xor
  17303. @tindex vxor
  17304. The @kbd{V X} (@code{calc-set-xor}) [@code{vxor}] command computes
  17305. the ``exclusive-or,'' or ``symmetric difference'' of two sets.
  17306. An object is in the symmetric difference of two sets if and only
  17307. if it is in one, but @emph{not} both, of the sets. Objects that
  17308. occur in both sets ``cancel out.''
  17309. @kindex v ~
  17310. @kindex V ~
  17311. @pindex calc-set-complement
  17312. @tindex vcompl
  17313. The @kbd{V ~} (@code{calc-set-complement}) [@code{vcompl}] command
  17314. computes the complement of a set with respect to the real numbers.
  17315. Thus @samp{vcompl(x)} is equivalent to @samp{vdiff([-inf .. inf], x)}.
  17316. For example, @samp{vcompl([2, (3 .. 4]])} evaluates to
  17317. @samp{[[-inf .. 2), (2 .. 3], (4 .. inf]]}.
  17318. @kindex v F
  17319. @kindex V F
  17320. @pindex calc-set-floor
  17321. @tindex vfloor
  17322. The @kbd{V F} (@code{calc-set-floor}) [@code{vfloor}] command
  17323. reinterprets a set as a set of integers. Any non-integer values,
  17324. and intervals that do not enclose any integers, are removed. Open
  17325. intervals are converted to equivalent closed intervals. Successive
  17326. integers are converted into intervals of integers. For example, the
  17327. complement of the set @samp{[2, 6, 7, 8]} is messy, but if you wanted
  17328. the complement with respect to the set of integers you could type
  17329. @kbd{V ~ V F} to get @samp{[[-inf .. 1], [3 .. 5], [9 .. inf]]}.
  17330. @kindex v E
  17331. @kindex V E
  17332. @pindex calc-set-enumerate
  17333. @tindex venum
  17334. The @kbd{V E} (@code{calc-set-enumerate}) [@code{venum}] command
  17335. converts a set of integers into an explicit vector. Intervals in
  17336. the set are expanded out to lists of all integers encompassed by
  17337. the intervals. This only works for finite sets (i.e., sets which
  17338. do not involve @samp{-inf} or @samp{inf}).
  17339. @kindex v :
  17340. @kindex V :
  17341. @pindex calc-set-span
  17342. @tindex vspan
  17343. The @kbd{V :} (@code{calc-set-span}) [@code{vspan}] command converts any
  17344. set of reals into an interval form that encompasses all its elements.
  17345. The lower limit will be the smallest element in the set; the upper
  17346. limit will be the largest element. For an empty set, @samp{vspan([])}
  17347. returns the empty interval @w{@samp{[0 .. 0)}}.
  17348. @kindex v #
  17349. @kindex V #
  17350. @pindex calc-set-cardinality
  17351. @tindex vcard
  17352. The @kbd{V #} (@code{calc-set-cardinality}) [@code{vcard}] command counts
  17353. the number of integers in a set. The result is the length of the vector
  17354. that would be produced by @kbd{V E}, although the computation is much
  17355. more efficient than actually producing that vector.
  17356. @cindex Sets, as binary numbers
  17357. Another representation for sets that may be more appropriate in some
  17358. cases is binary numbers. If you are dealing with sets of integers
  17359. in the range 0 to 49, you can use a 50-bit binary number where a
  17360. particular bit is 1 if the corresponding element is in the set.
  17361. @xref{Binary Functions}, for a list of commands that operate on
  17362. binary numbers. Note that many of the above set operations have
  17363. direct equivalents in binary arithmetic: @kbd{b o} (@code{calc-or}),
  17364. @kbd{b a} (@code{calc-and}), @kbd{b d} (@code{calc-diff}),
  17365. @kbd{b x} (@code{calc-xor}), and @kbd{b n} (@code{calc-not}),
  17366. respectively. You can use whatever representation for sets is most
  17367. convenient to you.
  17368. @kindex b p
  17369. @kindex b u
  17370. @pindex calc-pack-bits
  17371. @pindex calc-unpack-bits
  17372. @tindex vpack
  17373. @tindex vunpack
  17374. The @kbd{b u} (@code{calc-unpack-bits}) [@code{vunpack}] command
  17375. converts an integer that represents a set in binary into a set
  17376. in vector/interval notation. For example, @samp{vunpack(67)}
  17377. returns @samp{[[0 .. 1], 6]}. If the input is negative, the set
  17378. it represents is semi-infinite: @samp{vunpack(-4) = [2 .. inf)}.
  17379. Use @kbd{V E} afterwards to expand intervals to individual
  17380. values if you wish. Note that this command uses the @kbd{b}
  17381. (binary) prefix key.
  17382. The @kbd{b p} (@code{calc-pack-bits}) [@code{vpack}] command
  17383. converts the other way, from a vector or interval representing
  17384. a set of nonnegative integers into a binary integer describing
  17385. the same set. The set may include positive infinity, but must
  17386. not include any negative numbers. The input is interpreted as a
  17387. set of integers in the sense of @kbd{V F} (@code{vfloor}). Beware
  17388. that a simple input like @samp{[100]} can result in a huge integer
  17389. representation
  17390. @texline (@math{2^{100}}, a 31-digit integer, in this case).
  17391. @infoline (@expr{2^100}, a 31-digit integer, in this case).
  17392. @node Statistical Operations, Reducing and Mapping, Set Operations, Matrix Functions
  17393. @section Statistical Operations on Vectors
  17394. @noindent
  17395. @cindex Statistical functions
  17396. The commands in this section take vectors as arguments and compute
  17397. various statistical measures on the data stored in the vectors. The
  17398. references used in the definitions of these functions are Bevington's
  17399. @emph{Data Reduction and Error Analysis for the Physical Sciences},
  17400. and @emph{Numerical Recipes} by Press, Flannery, Teukolsky and
  17401. Vetterling.
  17402. The statistical commands use the @kbd{u} prefix key followed by
  17403. a shifted letter or other character.
  17404. @xref{Manipulating Vectors}, for a description of @kbd{V H}
  17405. (@code{calc-histogram}).
  17406. @xref{Curve Fitting}, for the @kbd{a F} command for doing
  17407. least-squares fits to statistical data.
  17408. @xref{Probability Distribution Functions}, for several common
  17409. probability distribution functions.
  17410. @menu
  17411. * Single-Variable Statistics::
  17412. * Paired-Sample Statistics::
  17413. @end menu
  17414. @node Single-Variable Statistics, Paired-Sample Statistics, Statistical Operations, Statistical Operations
  17415. @subsection Single-Variable Statistics
  17416. @noindent
  17417. These functions do various statistical computations on single
  17418. vectors. Given a numeric prefix argument, they actually pop
  17419. @var{n} objects from the stack and combine them into a data
  17420. vector. Each object may be either a number or a vector; if a
  17421. vector, any sub-vectors inside it are ``flattened'' as if by
  17422. @kbd{v a 0}; @pxref{Manipulating Vectors}. By default one object
  17423. is popped, which (in order to be useful) is usually a vector.
  17424. If an argument is a variable name, and the value stored in that
  17425. variable is a vector, then the stored vector is used. This method
  17426. has the advantage that if your data vector is large, you can avoid
  17427. the slow process of manipulating it directly on the stack.
  17428. These functions are left in symbolic form if any of their arguments
  17429. are not numbers or vectors, e.g., if an argument is a formula, or
  17430. a non-vector variable. However, formulas embedded within vector
  17431. arguments are accepted; the result is a symbolic representation
  17432. of the computation, based on the assumption that the formula does
  17433. not itself represent a vector. All varieties of numbers such as
  17434. error forms and interval forms are acceptable.
  17435. Some of the functions in this section also accept a single error form
  17436. or interval as an argument. They then describe a property of the
  17437. normal or uniform (respectively) statistical distribution described
  17438. by the argument. The arguments are interpreted in the same way as
  17439. the @var{M} argument of the random number function @kbd{k r}. In
  17440. particular, an interval with integer limits is considered an integer
  17441. distribution, so that @samp{[2 .. 6)} is the same as @samp{[2 .. 5]}.
  17442. An interval with at least one floating-point limit is a continuous
  17443. distribution: @samp{[2.0 .. 6.0)} is @emph{not} the same as
  17444. @samp{[2.0 .. 5.0]}!
  17445. @kindex u #
  17446. @pindex calc-vector-count
  17447. @tindex vcount
  17448. The @kbd{u #} (@code{calc-vector-count}) [@code{vcount}] command
  17449. computes the number of data values represented by the inputs.
  17450. For example, @samp{vcount(1, [2, 3], [[4, 5], [], x, y])} returns 7.
  17451. If the argument is a single vector with no sub-vectors, this
  17452. simply computes the length of the vector.
  17453. @kindex u +
  17454. @kindex u *
  17455. @pindex calc-vector-sum
  17456. @pindex calc-vector-prod
  17457. @tindex vsum
  17458. @tindex vprod
  17459. @cindex Summations (statistical)
  17460. The @kbd{u +} (@code{calc-vector-sum}) [@code{vsum}] command
  17461. computes the sum of the data values. The @kbd{u *}
  17462. (@code{calc-vector-prod}) [@code{vprod}] command computes the
  17463. product of the data values. If the input is a single flat vector,
  17464. these are the same as @kbd{V R +} and @kbd{V R *}
  17465. (@pxref{Reducing and Mapping}).
  17466. @kindex u X
  17467. @kindex u N
  17468. @pindex calc-vector-max
  17469. @pindex calc-vector-min
  17470. @tindex vmax
  17471. @tindex vmin
  17472. The @kbd{u X} (@code{calc-vector-max}) [@code{vmax}] command
  17473. computes the maximum of the data values, and the @kbd{u N}
  17474. (@code{calc-vector-min}) [@code{vmin}] command computes the minimum.
  17475. If the argument is an interval, this finds the minimum or maximum
  17476. value in the interval. (Note that @samp{vmax([2..6)) = 5} as
  17477. described above.) If the argument is an error form, this returns
  17478. plus or minus infinity.
  17479. @kindex u M
  17480. @pindex calc-vector-mean
  17481. @tindex vmean
  17482. @cindex Mean of data values
  17483. The @kbd{u M} (@code{calc-vector-mean}) [@code{vmean}] command
  17484. computes the average (arithmetic mean) of the data values.
  17485. If the inputs are error forms
  17486. @texline @math{x \pm \sigma},
  17487. @infoline @samp{x +/- s},
  17488. this is the weighted mean of the @expr{x} values with weights
  17489. @texline @math{1 /\sigma^2}.
  17490. @infoline @expr{1 / s^2}.
  17491. @tex
  17492. $$ \mu = { \displaystyle \sum { x_i \over \sigma_i^2 } \over
  17493. \displaystyle \sum { 1 \over \sigma_i^2 } } $$
  17494. @end tex
  17495. If the inputs are not error forms, this is simply the sum of the
  17496. values divided by the count of the values.
  17497. Note that a plain number can be considered an error form with
  17498. error
  17499. @texline @math{\sigma = 0}.
  17500. @infoline @expr{s = 0}.
  17501. If the input to @kbd{u M} is a mixture of
  17502. plain numbers and error forms, the result is the mean of the
  17503. plain numbers, ignoring all values with non-zero errors. (By the
  17504. above definitions it's clear that a plain number effectively
  17505. has an infinite weight, next to which an error form with a finite
  17506. weight is completely negligible.)
  17507. This function also works for distributions (error forms or
  17508. intervals). The mean of an error form `@var{a} @tfn{+/-} @var{b}' is simply
  17509. @expr{a}. The mean of an interval is the mean of the minimum
  17510. and maximum values of the interval.
  17511. @kindex I u M
  17512. @pindex calc-vector-mean-error
  17513. @tindex vmeane
  17514. The @kbd{I u M} (@code{calc-vector-mean-error}) [@code{vmeane}]
  17515. command computes the mean of the data points expressed as an
  17516. error form. This includes the estimated error associated with
  17517. the mean. If the inputs are error forms, the error is the square
  17518. root of the reciprocal of the sum of the reciprocals of the squares
  17519. of the input errors. (I.e., the variance is the reciprocal of the
  17520. sum of the reciprocals of the variances.)
  17521. @tex
  17522. $$ \sigma_\mu^2 = {1 \over \displaystyle \sum {1 \over \sigma_i^2}} $$
  17523. @end tex
  17524. If the inputs are plain
  17525. numbers, the error is equal to the standard deviation of the values
  17526. divided by the square root of the number of values. (This works
  17527. out to be equivalent to calculating the standard deviation and
  17528. then assuming each value's error is equal to this standard
  17529. deviation.)
  17530. @tex
  17531. $$ \sigma_\mu^2 = {\sigma^2 \over N} $$
  17532. @end tex
  17533. @kindex H u M
  17534. @pindex calc-vector-median
  17535. @tindex vmedian
  17536. @cindex Median of data values
  17537. The @kbd{H u M} (@code{calc-vector-median}) [@code{vmedian}]
  17538. command computes the median of the data values. The values are
  17539. first sorted into numerical order; the median is the middle
  17540. value after sorting. (If the number of data values is even,
  17541. the median is taken to be the average of the two middle values.)
  17542. The median function is different from the other functions in
  17543. this section in that the arguments must all be real numbers;
  17544. variables are not accepted even when nested inside vectors.
  17545. (Otherwise it is not possible to sort the data values.) If
  17546. any of the input values are error forms, their error parts are
  17547. ignored.
  17548. The median function also accepts distributions. For both normal
  17549. (error form) and uniform (interval) distributions, the median is
  17550. the same as the mean.
  17551. @kindex H I u M
  17552. @pindex calc-vector-harmonic-mean
  17553. @tindex vhmean
  17554. @cindex Harmonic mean
  17555. The @kbd{H I u M} (@code{calc-vector-harmonic-mean}) [@code{vhmean}]
  17556. command computes the harmonic mean of the data values. This is
  17557. defined as the reciprocal of the arithmetic mean of the reciprocals
  17558. of the values.
  17559. @tex
  17560. $$ { N \over \displaystyle \sum {1 \over x_i} } $$
  17561. @end tex
  17562. @kindex u G
  17563. @pindex calc-vector-geometric-mean
  17564. @tindex vgmean
  17565. @cindex Geometric mean
  17566. The @kbd{u G} (@code{calc-vector-geometric-mean}) [@code{vgmean}]
  17567. command computes the geometric mean of the data values. This
  17568. is the @var{n}th root of the product of the values. This is also
  17569. equal to the @code{exp} of the arithmetic mean of the logarithms
  17570. of the data values.
  17571. @tex
  17572. $$ \exp \left ( \sum { \ln x_i } \right ) =
  17573. \left ( \prod { x_i } \right)^{1 / N} $$
  17574. @end tex
  17575. @kindex H u G
  17576. @tindex agmean
  17577. The @kbd{H u G} [@code{agmean}] command computes the ``arithmetic-geometric
  17578. mean'' of two numbers taken from the stack. This is computed by
  17579. replacing the two numbers with their arithmetic mean and geometric
  17580. mean, then repeating until the two values converge.
  17581. @tex
  17582. $$ a_{i+1} = { a_i + b_i \over 2 } , \qquad b_{i+1} = \sqrt{a_i b_i} $$
  17583. @end tex
  17584. @kindex u R
  17585. @cindex Root-mean-square
  17586. @tindex rms
  17587. The @kbd{u R} (@code{calc-vector-rms}) [@code{rms}]
  17588. command computes the RMS (root-mean-square) of the data values.
  17589. As its name suggests, this is the square root of the mean of the
  17590. squares of the data values.
  17591. @kindex u S
  17592. @pindex calc-vector-sdev
  17593. @tindex vsdev
  17594. @cindex Standard deviation
  17595. @cindex Sample statistics
  17596. The @kbd{u S} (@code{calc-vector-sdev}) [@code{vsdev}] command
  17597. computes the standard
  17598. @texline deviation@tie{}@math{\sigma}
  17599. @infoline deviation
  17600. of the data values. If the values are error forms, the errors are used
  17601. as weights just as for @kbd{u M}. This is the @emph{sample} standard
  17602. deviation, whose value is the square root of the sum of the squares of
  17603. the differences between the values and the mean of the @expr{N} values,
  17604. divided by @expr{N-1}.
  17605. @tex
  17606. $$ \sigma^2 = {1 \over N - 1} \sum (x_i - \mu)^2 $$
  17607. @end tex
  17608. This function also applies to distributions. The standard deviation
  17609. of a single error form is simply the error part. The standard deviation
  17610. of a continuous interval happens to equal the difference between the
  17611. limits, divided by
  17612. @texline @math{\sqrt{12}}.
  17613. @infoline @expr{sqrt(12)}.
  17614. The standard deviation of an integer interval is the same as the
  17615. standard deviation of a vector of those integers.
  17616. @kindex I u S
  17617. @pindex calc-vector-pop-sdev
  17618. @tindex vpsdev
  17619. @cindex Population statistics
  17620. The @kbd{I u S} (@code{calc-vector-pop-sdev}) [@code{vpsdev}]
  17621. command computes the @emph{population} standard deviation.
  17622. It is defined by the same formula as above but dividing
  17623. by @expr{N} instead of by @expr{N-1}. The population standard
  17624. deviation is used when the input represents the entire set of
  17625. data values in the distribution; the sample standard deviation
  17626. is used when the input represents a sample of the set of all
  17627. data values, so that the mean computed from the input is itself
  17628. only an estimate of the true mean.
  17629. @tex
  17630. $$ \sigma^2 = {1 \over N} \sum (x_i - \mu)^2 $$
  17631. @end tex
  17632. For error forms and continuous intervals, @code{vpsdev} works
  17633. exactly like @code{vsdev}. For integer intervals, it computes the
  17634. population standard deviation of the equivalent vector of integers.
  17635. @kindex H u S
  17636. @kindex H I u S
  17637. @pindex calc-vector-variance
  17638. @pindex calc-vector-pop-variance
  17639. @tindex vvar
  17640. @tindex vpvar
  17641. @cindex Variance of data values
  17642. The @kbd{H u S} (@code{calc-vector-variance}) [@code{vvar}] and
  17643. @kbd{H I u S} (@code{calc-vector-pop-variance}) [@code{vpvar}]
  17644. commands compute the variance of the data values. The variance
  17645. is the
  17646. @texline square@tie{}@math{\sigma^2}
  17647. @infoline square
  17648. of the standard deviation, i.e., the sum of the
  17649. squares of the deviations of the data values from the mean.
  17650. (This definition also applies when the argument is a distribution.)
  17651. @ignore
  17652. @starindex
  17653. @end ignore
  17654. @tindex vflat
  17655. The @code{vflat} algebraic function returns a vector of its
  17656. arguments, interpreted in the same way as the other functions
  17657. in this section. For example, @samp{vflat(1, [2, [3, 4]], 5)}
  17658. returns @samp{[1, 2, 3, 4, 5]}.
  17659. @node Paired-Sample Statistics, , Single-Variable Statistics, Statistical Operations
  17660. @subsection Paired-Sample Statistics
  17661. @noindent
  17662. The functions in this section take two arguments, which must be
  17663. vectors of equal size. The vectors are each flattened in the same
  17664. way as by the single-variable statistical functions. Given a numeric
  17665. prefix argument of 1, these functions instead take one object from
  17666. the stack, which must be an
  17667. @texline @math{N\times2}
  17668. @infoline Nx2
  17669. matrix of data values. Once again, variable names can be used in place
  17670. of actual vectors and matrices.
  17671. @kindex u C
  17672. @pindex calc-vector-covariance
  17673. @tindex vcov
  17674. @cindex Covariance
  17675. The @kbd{u C} (@code{calc-vector-covariance}) [@code{vcov}] command
  17676. computes the sample covariance of two vectors. The covariance
  17677. of vectors @var{x} and @var{y} is the sum of the products of the
  17678. differences between the elements of @var{x} and the mean of @var{x}
  17679. times the differences between the corresponding elements of @var{y}
  17680. and the mean of @var{y}, all divided by @expr{N-1}. Note that
  17681. the variance of a vector is just the covariance of the vector
  17682. with itself. Once again, if the inputs are error forms the
  17683. errors are used as weight factors. If both @var{x} and @var{y}
  17684. are composed of error forms, the error for a given data point
  17685. is taken as the square root of the sum of the squares of the two
  17686. input errors.
  17687. @tex
  17688. $$ \sigma_{x\!y}^2 = {1 \over N-1} \sum (x_i - \mu_x) (y_i - \mu_y) $$
  17689. $$ \sigma_{x\!y}^2 =
  17690. {\displaystyle {1 \over N-1}
  17691. \sum {(x_i - \mu_x) (y_i - \mu_y) \over \sigma_i^2}
  17692. \over \displaystyle {1 \over N} \sum {1 \over \sigma_i^2}}
  17693. $$
  17694. @end tex
  17695. @kindex I u C
  17696. @pindex calc-vector-pop-covariance
  17697. @tindex vpcov
  17698. The @kbd{I u C} (@code{calc-vector-pop-covariance}) [@code{vpcov}]
  17699. command computes the population covariance, which is the same as the
  17700. sample covariance computed by @kbd{u C} except dividing by @expr{N}
  17701. instead of @expr{N-1}.
  17702. @kindex H u C
  17703. @pindex calc-vector-correlation
  17704. @tindex vcorr
  17705. @cindex Correlation coefficient
  17706. @cindex Linear correlation
  17707. The @kbd{H u C} (@code{calc-vector-correlation}) [@code{vcorr}]
  17708. command computes the linear correlation coefficient of two vectors.
  17709. This is defined by the covariance of the vectors divided by the
  17710. product of their standard deviations. (There is no difference
  17711. between sample or population statistics here.)
  17712. @tex
  17713. $$ r_{x\!y} = { \sigma_{x\!y}^2 \over \sigma_x^2 \sigma_y^2 } $$
  17714. @end tex
  17715. @node Reducing and Mapping, Vector and Matrix Formats, Statistical Operations, Matrix Functions
  17716. @section Reducing and Mapping Vectors
  17717. @noindent
  17718. The commands in this section allow for more general operations on the
  17719. elements of vectors.
  17720. @kindex v A
  17721. @kindex V A
  17722. @pindex calc-apply
  17723. @tindex apply
  17724. The simplest of these operations is @kbd{V A} (@code{calc-apply})
  17725. [@code{apply}], which applies a given operator to the elements of a vector.
  17726. For example, applying the hypothetical function @code{f} to the vector
  17727. @w{@samp{[1, 2, 3]}} would produce the function call @samp{f(1, 2, 3)}.
  17728. Applying the @code{+} function to the vector @samp{[a, b]} gives
  17729. @samp{a + b}. Applying @code{+} to the vector @samp{[a, b, c]} is an
  17730. error, since the @code{+} function expects exactly two arguments.
  17731. While @kbd{V A} is useful in some cases, you will usually find that either
  17732. @kbd{V R} or @kbd{V M}, described below, is closer to what you want.
  17733. @menu
  17734. * Specifying Operators::
  17735. * Mapping::
  17736. * Reducing::
  17737. * Nesting and Fixed Points::
  17738. * Generalized Products::
  17739. @end menu
  17740. @node Specifying Operators, Mapping, Reducing and Mapping, Reducing and Mapping
  17741. @subsection Specifying Operators
  17742. @noindent
  17743. Commands in this section (like @kbd{V A}) prompt you to press the key
  17744. corresponding to the desired operator. Press @kbd{?} for a partial
  17745. list of the available operators. Generally, an operator is any key or
  17746. sequence of keys that would normally take one or more arguments from
  17747. the stack and replace them with a result. For example, @kbd{V A H C}
  17748. uses the hyperbolic cosine operator, @code{cosh}. (Since @code{cosh}
  17749. expects one argument, @kbd{V A H C} requires a vector with a single
  17750. element as its argument.)
  17751. You can press @kbd{x} at the operator prompt to select any algebraic
  17752. function by name to use as the operator. This includes functions you
  17753. have defined yourself using the @kbd{Z F} command. (@xref{Algebraic
  17754. Definitions}.) If you give a name for which no function has been
  17755. defined, the result is left in symbolic form, as in @samp{f(1, 2, 3)}.
  17756. Calc will prompt for the number of arguments the function takes if it
  17757. can't figure it out on its own (say, because you named a function that
  17758. is currently undefined). It is also possible to type a digit key before
  17759. the function name to specify the number of arguments, e.g.,
  17760. @kbd{V M 3 x f @key{RET}} calls @code{f} with three arguments even if it
  17761. looks like it ought to have only two. This technique may be necessary
  17762. if the function allows a variable number of arguments. For example,
  17763. the @kbd{v e} [@code{vexp}] function accepts two or three arguments;
  17764. if you want to map with the three-argument version, you will have to
  17765. type @kbd{V M 3 v e}.
  17766. It is also possible to apply any formula to a vector by treating that
  17767. formula as a function. When prompted for the operator to use, press
  17768. @kbd{'} (the apostrophe) and type your formula as an algebraic entry.
  17769. You will then be prompted for the argument list, which defaults to a
  17770. list of all variables that appear in the formula, sorted into alphabetic
  17771. order. For example, suppose you enter the formula @w{@samp{x + 2y^x}}.
  17772. The default argument list would be @samp{(x y)}, which means that if
  17773. this function is applied to the arguments @samp{[3, 10]} the result will
  17774. be @samp{3 + 2*10^3}. (If you plan to use a certain formula in this
  17775. way often, you might consider defining it as a function with @kbd{Z F}.)
  17776. Another way to specify the arguments to the formula you enter is with
  17777. @kbd{$}, @kbd{$$}, and so on. For example, @kbd{V A ' $$ + 2$^$$}
  17778. has the same effect as the previous example. The argument list is
  17779. automatically taken to be @samp{($$ $)}. (The order of the arguments
  17780. may seem backwards, but it is analogous to the way normal algebraic
  17781. entry interacts with the stack.)
  17782. If you press @kbd{$} at the operator prompt, the effect is similar to
  17783. the apostrophe except that the relevant formula is taken from top-of-stack
  17784. instead. The actual vector arguments of the @kbd{V A $} or related command
  17785. then start at the second-to-top stack position. You will still be
  17786. prompted for an argument list.
  17787. @cindex Nameless functions
  17788. @cindex Generic functions
  17789. A function can be written without a name using the notation @samp{<#1 - #2>},
  17790. which means ``a function of two arguments that computes the first
  17791. argument minus the second argument.'' The symbols @samp{#1} and @samp{#2}
  17792. are placeholders for the arguments. You can use any names for these
  17793. placeholders if you wish, by including an argument list followed by a
  17794. colon: @samp{<x, y : x - y>}. When you type @kbd{V A ' $$ + 2$^$$ @key{RET}},
  17795. Calc builds the nameless function @samp{<#1 + 2 #2^#1>} as the function
  17796. to map across the vectors. When you type @kbd{V A ' x + 2y^x @key{RET} @key{RET}},
  17797. Calc builds the nameless function @w{@samp{<x, y : x + 2 y^x>}}. In both
  17798. cases, Calc also writes the nameless function to the Trail so that you
  17799. can get it back later if you wish.
  17800. If there is only one argument, you can write @samp{#} in place of @samp{#1}.
  17801. (Note that @samp{< >} notation is also used for date forms. Calc tells
  17802. that @samp{<@var{stuff}>} is a nameless function by the presence of
  17803. @samp{#} signs inside @var{stuff}, or by the fact that @var{stuff}
  17804. begins with a list of variables followed by a colon.)
  17805. You can type a nameless function directly to @kbd{V A '}, or put one on
  17806. the stack and use it with @w{@kbd{V A $}}. Calc will not prompt for an
  17807. argument list in this case, since the nameless function specifies the
  17808. argument list as well as the function itself. In @kbd{V A '}, you can
  17809. omit the @samp{< >} marks if you use @samp{#} notation for the arguments,
  17810. so that @kbd{V A ' #1+#2 @key{RET}} is the same as @kbd{V A ' <#1+#2> @key{RET}},
  17811. which in turn is the same as @kbd{V A ' $$+$ @key{RET}}.
  17812. @cindex Lambda expressions
  17813. @ignore
  17814. @starindex
  17815. @end ignore
  17816. @tindex lambda
  17817. The internal format for @samp{<x, y : x + y>} is @samp{lambda(x, y, x + y)}.
  17818. (The word @code{lambda} derives from Lisp notation and the theory of
  17819. functions.) The internal format for @samp{<#1 + #2>} is @samp{lambda(ArgA,
  17820. ArgB, ArgA + ArgB)}. Note that there is no actual Calc function called
  17821. @code{lambda}; the whole point is that the @code{lambda} expression is
  17822. used in its symbolic form, not evaluated for an answer until it is applied
  17823. to specific arguments by a command like @kbd{V A} or @kbd{V M}.
  17824. (Actually, @code{lambda} does have one special property: Its arguments
  17825. are never evaluated; for example, putting @samp{<(2/3) #>} on the stack
  17826. will not simplify the @samp{2/3} until the nameless function is actually
  17827. called.)
  17828. @tindex add
  17829. @tindex sub
  17830. @ignore
  17831. @mindex @idots
  17832. @end ignore
  17833. @tindex mul
  17834. @ignore
  17835. @mindex @null
  17836. @end ignore
  17837. @tindex div
  17838. @ignore
  17839. @mindex @null
  17840. @end ignore
  17841. @tindex pow
  17842. @ignore
  17843. @mindex @null
  17844. @end ignore
  17845. @tindex neg
  17846. @ignore
  17847. @mindex @null
  17848. @end ignore
  17849. @tindex mod
  17850. @ignore
  17851. @mindex @null
  17852. @end ignore
  17853. @tindex vconcat
  17854. As usual, commands like @kbd{V A} have algebraic function name equivalents.
  17855. For example, @kbd{V A k g} with an argument of @samp{v} is equivalent to
  17856. @samp{apply(gcd, v)}. The first argument specifies the operator name,
  17857. and is either a variable whose name is the same as the function name,
  17858. or a nameless function like @samp{<#^3+1>}. Operators that are normally
  17859. written as algebraic symbols have the names @code{add}, @code{sub},
  17860. @code{mul}, @code{div}, @code{pow}, @code{neg}, @code{mod}, and
  17861. @code{vconcat}.
  17862. @ignore
  17863. @starindex
  17864. @end ignore
  17865. @tindex call
  17866. The @code{call} function builds a function call out of several arguments:
  17867. @samp{call(gcd, x, y)} is the same as @samp{apply(gcd, [x, y])}, which
  17868. in turn is the same as @samp{gcd(x, y)}. The first argument of @code{call},
  17869. like the other functions described here, may be either a variable naming a
  17870. function, or a nameless function (@samp{call(<#1+2#2>, x, y)} is the same
  17871. as @samp{x + 2y}).
  17872. (Experts will notice that it's not quite proper to use a variable to name
  17873. a function, since the name @code{gcd} corresponds to the Lisp variable
  17874. @code{var-gcd} but to the Lisp function @code{calcFunc-gcd}. Calc
  17875. automatically makes this translation, so you don't have to worry
  17876. about it.)
  17877. @node Mapping, Reducing, Specifying Operators, Reducing and Mapping
  17878. @subsection Mapping
  17879. @noindent
  17880. @kindex v M
  17881. @kindex V M
  17882. @pindex calc-map
  17883. @tindex map
  17884. The @kbd{V M} (@code{calc-map}) [@code{map}] command applies a given
  17885. operator elementwise to one or more vectors. For example, mapping
  17886. @code{A} [@code{abs}] produces a vector of the absolute values of the
  17887. elements in the input vector. Mapping @code{+} pops two vectors from
  17888. the stack, which must be of equal length, and produces a vector of the
  17889. pairwise sums of the elements. If either argument is a non-vector, it
  17890. is duplicated for each element of the other vector. For example,
  17891. @kbd{[1,2,3] 2 V M ^} squares the elements of the specified vector.
  17892. With the 2 listed first, it would have computed a vector of powers of
  17893. two. Mapping a user-defined function pops as many arguments from the
  17894. stack as the function requires. If you give an undefined name, you will
  17895. be prompted for the number of arguments to use.
  17896. If any argument to @kbd{V M} is a matrix, the operator is normally mapped
  17897. across all elements of the matrix. For example, given the matrix
  17898. @expr{[[1, -2, 3], [-4, 5, -6]]}, @kbd{V M A} takes six absolute values to
  17899. produce another
  17900. @texline @math{3\times2}
  17901. @infoline 3x2
  17902. matrix, @expr{[[1, 2, 3], [4, 5, 6]]}.
  17903. @tindex mapr
  17904. The command @kbd{V M _} [@code{mapr}] (i.e., type an underscore at the
  17905. operator prompt) maps by rows instead. For example, @kbd{V M _ A} views
  17906. the above matrix as a vector of two 3-element row vectors. It produces
  17907. a new vector which contains the absolute values of those row vectors,
  17908. namely @expr{[3.74, 8.77]}. (Recall, the absolute value of a vector is
  17909. defined as the square root of the sum of the squares of the elements.)
  17910. Some operators accept vectors and return new vectors; for example,
  17911. @kbd{v v} reverses a vector, so @kbd{V M _ v v} would reverse each row
  17912. of the matrix to get a new matrix, @expr{[[3, -2, 1], [-6, 5, -4]]}.
  17913. Sometimes a vector of vectors (representing, say, strings, sets, or lists)
  17914. happens to look like a matrix. If so, remember to use @kbd{V M _} if you
  17915. want to map a function across the whole strings or sets rather than across
  17916. their individual elements.
  17917. @tindex mapc
  17918. The command @kbd{V M :} [@code{mapc}] maps by columns. Basically, it
  17919. transposes the input matrix, maps by rows, and then, if the result is a
  17920. matrix, transposes again. For example, @kbd{V M : A} takes the absolute
  17921. values of the three columns of the matrix, treating each as a 2-vector,
  17922. and @kbd{V M : v v} reverses the columns to get the matrix
  17923. @expr{[[-4, 5, -6], [1, -2, 3]]}.
  17924. (The symbols @kbd{_} and @kbd{:} were chosen because they had row-like
  17925. and column-like appearances, and were not already taken by useful
  17926. operators. Also, they appear shifted on most keyboards so they are easy
  17927. to type after @kbd{V M}.)
  17928. The @kbd{_} and @kbd{:} modifiers have no effect on arguments that are
  17929. not matrices (so if none of the arguments are matrices, they have no
  17930. effect at all). If some of the arguments are matrices and others are
  17931. plain numbers, the plain numbers are held constant for all rows of the
  17932. matrix (so that @kbd{2 V M _ ^} squares every row of a matrix; squaring
  17933. a vector takes a dot product of the vector with itself).
  17934. If some of the arguments are vectors with the same lengths as the
  17935. rows (for @kbd{V M _}) or columns (for @kbd{V M :}) of the matrix
  17936. arguments, those vectors are also held constant for every row or
  17937. column.
  17938. Sometimes it is useful to specify another mapping command as the operator
  17939. to use with @kbd{V M}. For example, @kbd{V M _ V A +} applies @kbd{V A +}
  17940. to each row of the input matrix, which in turn adds the two values on that
  17941. row. If you give another vector-operator command as the operator for
  17942. @kbd{V M}, it automatically uses map-by-rows mode if you don't specify
  17943. otherwise; thus @kbd{V M V A +} is equivalent to @kbd{V M _ V A +}. (If
  17944. you really want to map-by-elements another mapping command, you can use
  17945. a triple-nested mapping command: @kbd{V M V M V A +} means to map
  17946. @kbd{V M V A +} over the rows of the matrix; in turn, @kbd{V A +} is
  17947. mapped over the elements of each row.)
  17948. @tindex mapa
  17949. @tindex mapd
  17950. Previous versions of Calc had ``map across'' and ``map down'' modes
  17951. that are now considered obsolete; the old ``map across'' is now simply
  17952. @kbd{V M V A}, and ``map down'' is now @kbd{V M : V A}. The algebraic
  17953. functions @code{mapa} and @code{mapd} are still supported, though.
  17954. Note also that, while the old mapping modes were persistent (once you
  17955. set the mode, it would apply to later mapping commands until you reset
  17956. it), the new @kbd{:} and @kbd{_} modifiers apply only to the current
  17957. mapping command. The default @kbd{V M} always means map-by-elements.
  17958. @xref{Algebraic Manipulation}, for the @kbd{a M} command, which is like
  17959. @kbd{V M} but for equations and inequalities instead of vectors.
  17960. @xref{Storing Variables}, for the @kbd{s m} command which modifies a
  17961. variable's stored value using a @kbd{V M}-like operator.
  17962. @node Reducing, Nesting and Fixed Points, Mapping, Reducing and Mapping
  17963. @subsection Reducing
  17964. @noindent
  17965. @kindex v R
  17966. @kindex V R
  17967. @pindex calc-reduce
  17968. @tindex reduce
  17969. The @kbd{V R} (@code{calc-reduce}) [@code{reduce}] command applies a given
  17970. binary operator across all the elements of a vector. A binary operator is
  17971. a function such as @code{+} or @code{max} which takes two arguments. For
  17972. example, reducing @code{+} over a vector computes the sum of the elements
  17973. of the vector. Reducing @code{-} computes the first element minus each of
  17974. the remaining elements. Reducing @code{max} computes the maximum element
  17975. and so on. In general, reducing @code{f} over the vector @samp{[a, b, c, d]}
  17976. produces @samp{f(f(f(a, b), c), d)}.
  17977. @kindex I v R
  17978. @kindex I V R
  17979. @tindex rreduce
  17980. The @kbd{I V R} [@code{rreduce}] command is similar to @kbd{V R} except
  17981. that works from right to left through the vector. For example, plain
  17982. @kbd{V R -} on the vector @samp{[a, b, c, d]} produces @samp{a - b - c - d}
  17983. but @kbd{I V R -} on the same vector produces @samp{a - (b - (c - d))},
  17984. or @samp{a - b + c - d}. This ``alternating sum'' occurs frequently
  17985. in power series expansions.
  17986. @kindex v U
  17987. @kindex V U
  17988. @tindex accum
  17989. The @kbd{V U} (@code{calc-accumulate}) [@code{accum}] command does an
  17990. accumulation operation. Here Calc does the corresponding reduction
  17991. operation, but instead of producing only the final result, it produces
  17992. a vector of all the intermediate results. Accumulating @code{+} over
  17993. the vector @samp{[a, b, c, d]} produces the vector
  17994. @samp{[a, a + b, a + b + c, a + b + c + d]}.
  17995. @kindex I v U
  17996. @kindex I V U
  17997. @tindex raccum
  17998. The @kbd{I V U} [@code{raccum}] command does a right-to-left accumulation.
  17999. For example, @kbd{I V U -} on the vector @samp{[a, b, c, d]} produces the
  18000. vector @samp{[a - b + c - d, b - c + d, c - d, d]}.
  18001. @tindex reducea
  18002. @tindex rreducea
  18003. @tindex reduced
  18004. @tindex rreduced
  18005. As for @kbd{V M}, @kbd{V R} normally reduces a matrix elementwise. For
  18006. example, given the matrix @expr{[[a, b, c], [d, e, f]]}, @kbd{V R +} will
  18007. compute @expr{a + b + c + d + e + f}. You can type @kbd{V R _} or
  18008. @kbd{V R :} to modify this behavior. The @kbd{V R _} [@code{reducea}]
  18009. command reduces ``across'' the matrix; it reduces each row of the matrix
  18010. as a vector, then collects the results. Thus @kbd{V R _ +} of this
  18011. matrix would produce @expr{[a + b + c, d + e + f]}. Similarly, @kbd{V R :}
  18012. [@code{reduced}] reduces down; @kbd{V R : +} would produce @expr{[a + d,
  18013. b + e, c + f]}.
  18014. @tindex reducer
  18015. @tindex rreducer
  18016. There is a third ``by rows'' mode for reduction that is occasionally
  18017. useful; @kbd{V R =} [@code{reducer}] simply reduces the operator over
  18018. the rows of the matrix themselves. Thus @kbd{V R = +} on the above
  18019. matrix would get the same result as @kbd{V R : +}, since adding two
  18020. row vectors is equivalent to adding their elements. But @kbd{V R = *}
  18021. would multiply the two rows (to get a single number, their dot product),
  18022. while @kbd{V R : *} would produce a vector of the products of the columns.
  18023. These three matrix reduction modes work with @kbd{V R} and @kbd{I V R},
  18024. but they are not currently supported with @kbd{V U} or @kbd{I V U}.
  18025. @tindex reducec
  18026. @tindex rreducec
  18027. The obsolete reduce-by-columns function, @code{reducec}, is still
  18028. supported but there is no way to get it through the @kbd{V R} command.
  18029. The commands @kbd{C-x * :} and @kbd{C-x * _} are equivalent to typing
  18030. @kbd{C-x * r} to grab a rectangle of data into Calc, and then typing
  18031. @kbd{V R : +} or @kbd{V R _ +}, respectively, to sum the columns or
  18032. rows of the matrix. @xref{Grabbing From Buffers}.
  18033. @node Nesting and Fixed Points, Generalized Products, Reducing, Reducing and Mapping
  18034. @subsection Nesting and Fixed Points
  18035. @noindent
  18036. @kindex H v R
  18037. @kindex H V R
  18038. @tindex nest
  18039. The @kbd{H V R} [@code{nest}] command applies a function to a given
  18040. argument repeatedly. It takes two values, @samp{a} and @samp{n}, from
  18041. the stack, where @samp{n} must be an integer. It then applies the
  18042. function nested @samp{n} times; if the function is @samp{f} and @samp{n}
  18043. is 3, the result is @samp{f(f(f(a)))}. The number @samp{n} may be
  18044. negative if Calc knows an inverse for the function @samp{f}; for
  18045. example, @samp{nest(sin, a, -2)} returns @samp{arcsin(arcsin(a))}.
  18046. @kindex H v U
  18047. @kindex H V U
  18048. @tindex anest
  18049. The @kbd{H V U} [@code{anest}] command is an accumulating version of
  18050. @code{nest}: It returns a vector of @samp{n+1} values, e.g.,
  18051. @samp{[a, f(a), f(f(a)), f(f(f(a)))]}. If @samp{n} is negative and
  18052. @samp{F} is the inverse of @samp{f}, then the result is of the
  18053. form @samp{[a, F(a), F(F(a)), F(F(F(a)))]}.
  18054. @kindex H I v R
  18055. @kindex H I V R
  18056. @tindex fixp
  18057. @cindex Fixed points
  18058. The @kbd{H I V R} [@code{fixp}] command is like @kbd{H V R}, except
  18059. that it takes only an @samp{a} value from the stack; the function is
  18060. applied until it reaches a ``fixed point,'' i.e., until the result
  18061. no longer changes.
  18062. @kindex H I v U
  18063. @kindex H I V U
  18064. @tindex afixp
  18065. The @kbd{H I V U} [@code{afixp}] command is an accumulating @code{fixp}.
  18066. The first element of the return vector will be the initial value @samp{a};
  18067. the last element will be the final result that would have been returned
  18068. by @code{fixp}.
  18069. For example, 0.739085 is a fixed point of the cosine function (in radians):
  18070. @samp{cos(0.739085) = 0.739085}. You can find this value by putting, say,
  18071. 1.0 on the stack and typing @kbd{H I V U C}. (We use the accumulating
  18072. version so we can see the intermediate results: @samp{[1, 0.540302, 0.857553,
  18073. 0.65329, ...]}. With a precision of six, this command will take 36 steps
  18074. to converge to 0.739085.)
  18075. Newton's method for finding roots is a classic example of iteration
  18076. to a fixed point. To find the square root of five starting with an
  18077. initial guess, Newton's method would look for a fixed point of the
  18078. function @samp{(x + 5/x) / 2}. Putting a guess of 1 on the stack
  18079. and typing @kbd{H I V R ' ($ + 5/$)/2 @key{RET}} quickly yields the result
  18080. 2.23607. This is equivalent to using the @kbd{a R} (@code{calc-find-root})
  18081. command to find a root of the equation @samp{x^2 = 5}.
  18082. These examples used numbers for @samp{a} values. Calc keeps applying
  18083. the function until two successive results are equal to within the
  18084. current precision. For complex numbers, both the real parts and the
  18085. imaginary parts must be equal to within the current precision. If
  18086. @samp{a} is a formula (say, a variable name), then the function is
  18087. applied until two successive results are exactly the same formula.
  18088. It is up to you to ensure that the function will eventually converge;
  18089. if it doesn't, you may have to press @kbd{C-g} to stop the Calculator.
  18090. The algebraic @code{fixp} function takes two optional arguments, @samp{n}
  18091. and @samp{tol}. The first is the maximum number of steps to be allowed,
  18092. and must be either an integer or the symbol @samp{inf} (infinity, the
  18093. default). The second is a convergence tolerance. If a tolerance is
  18094. specified, all results during the calculation must be numbers, not
  18095. formulas, and the iteration stops when the magnitude of the difference
  18096. between two successive results is less than or equal to the tolerance.
  18097. (This implies that a tolerance of zero iterates until the results are
  18098. exactly equal.)
  18099. Putting it all together, @samp{fixp(<(# + A/#)/2>, B, 20, 1e-10)}
  18100. computes the square root of @samp{A} given the initial guess @samp{B},
  18101. stopping when the result is correct within the specified tolerance, or
  18102. when 20 steps have been taken, whichever is sooner.
  18103. @node Generalized Products, , Nesting and Fixed Points, Reducing and Mapping
  18104. @subsection Generalized Products
  18105. @kindex v O
  18106. @kindex V O
  18107. @pindex calc-outer-product
  18108. @tindex outer
  18109. The @kbd{V O} (@code{calc-outer-product}) [@code{outer}] command applies
  18110. a given binary operator to all possible pairs of elements from two
  18111. vectors, to produce a matrix. For example, @kbd{V O *} with @samp{[a, b]}
  18112. and @samp{[x, y, z]} on the stack produces a multiplication table:
  18113. @samp{[[a x, a y, a z], [b x, b y, b z]]}. Element @var{r},@var{c} of
  18114. the result matrix is obtained by applying the operator to element @var{r}
  18115. of the lefthand vector and element @var{c} of the righthand vector.
  18116. @kindex v I
  18117. @kindex V I
  18118. @pindex calc-inner-product
  18119. @tindex inner
  18120. The @kbd{V I} (@code{calc-inner-product}) [@code{inner}] command computes
  18121. the generalized inner product of two vectors or matrices, given a
  18122. ``multiplicative'' operator and an ``additive'' operator. These can each
  18123. actually be any binary operators; if they are @samp{*} and @samp{+},
  18124. respectively, the result is a standard matrix multiplication. Element
  18125. @var{r},@var{c} of the result matrix is obtained by mapping the
  18126. multiplicative operator across row @var{r} of the lefthand matrix and
  18127. column @var{c} of the righthand matrix, and then reducing with the additive
  18128. operator. Just as for the standard @kbd{*} command, this can also do a
  18129. vector-matrix or matrix-vector inner product, or a vector-vector
  18130. generalized dot product.
  18131. Since @kbd{V I} requires two operators, it prompts twice. In each case,
  18132. you can use any of the usual methods for entering the operator. If you
  18133. use @kbd{$} twice to take both operator formulas from the stack, the
  18134. first (multiplicative) operator is taken from the top of the stack
  18135. and the second (additive) operator is taken from second-to-top.
  18136. @node Vector and Matrix Formats, , Reducing and Mapping, Matrix Functions
  18137. @section Vector and Matrix Display Formats
  18138. @noindent
  18139. Commands for controlling vector and matrix display use the @kbd{v} prefix
  18140. instead of the usual @kbd{d} prefix. But they are display modes; in
  18141. particular, they are influenced by the @kbd{I} and @kbd{H} prefix keys
  18142. in the same way (@pxref{Display Modes}). Matrix display is also
  18143. influenced by the @kbd{d O} (@code{calc-flat-language}) mode;
  18144. @pxref{Normal Language Modes}.
  18145. @kindex v <
  18146. @kindex V <
  18147. @pindex calc-matrix-left-justify
  18148. @kindex v =
  18149. @kindex V =
  18150. @pindex calc-matrix-center-justify
  18151. @kindex v >
  18152. @kindex V >
  18153. @pindex calc-matrix-right-justify
  18154. The commands @kbd{v <} (@code{calc-matrix-left-justify}), @kbd{v >}
  18155. (@code{calc-matrix-right-justify}), and @w{@kbd{v =}}
  18156. (@code{calc-matrix-center-justify}) control whether matrix elements
  18157. are justified to the left, right, or center of their columns.
  18158. @kindex v [
  18159. @kindex V [
  18160. @pindex calc-vector-brackets
  18161. @kindex v @{
  18162. @kindex V @{
  18163. @pindex calc-vector-braces
  18164. @kindex v (
  18165. @kindex V (
  18166. @pindex calc-vector-parens
  18167. The @kbd{v [} (@code{calc-vector-brackets}) command turns the square
  18168. brackets that surround vectors and matrices displayed in the stack on
  18169. and off. The @kbd{v @{} (@code{calc-vector-braces}) and @kbd{v (}
  18170. (@code{calc-vector-parens}) commands use curly braces or parentheses,
  18171. respectively, instead of square brackets. For example, @kbd{v @{} might
  18172. be used in preparation for yanking a matrix into a buffer running
  18173. Mathematica. (In fact, the Mathematica language mode uses this mode;
  18174. @pxref{Mathematica Language Mode}.) Note that, regardless of the
  18175. display mode, either brackets or braces may be used to enter vectors,
  18176. and parentheses may never be used for this purpose.
  18177. @kindex V ]
  18178. @kindex v ]
  18179. @kindex V )
  18180. @kindex v )
  18181. @kindex V @}
  18182. @kindex v @}
  18183. @pindex calc-matrix-brackets
  18184. The @kbd{v ]} (@code{calc-matrix-brackets}) command controls the
  18185. ``big'' style display of matrices, for matrices which have more than
  18186. one row. It prompts for a string of code letters; currently
  18187. implemented letters are @code{R}, which enables brackets on each row
  18188. of the matrix; @code{O}, which enables outer brackets in opposite
  18189. corners of the matrix; and @code{C}, which enables commas or
  18190. semicolons at the ends of all rows but the last. The default format
  18191. is @samp{RO}. (Before Calc 2.00, the format was fixed at @samp{ROC}.)
  18192. Here are some example matrices:
  18193. @example
  18194. @group
  18195. [ [ 123, 0, 0 ] [ [ 123, 0, 0 ],
  18196. [ 0, 123, 0 ] [ 0, 123, 0 ],
  18197. [ 0, 0, 123 ] ] [ 0, 0, 123 ] ]
  18198. RO ROC
  18199. @end group
  18200. @end example
  18201. @noindent
  18202. @example
  18203. @group
  18204. [ 123, 0, 0 [ 123, 0, 0 ;
  18205. 0, 123, 0 0, 123, 0 ;
  18206. 0, 0, 123 ] 0, 0, 123 ]
  18207. O OC
  18208. @end group
  18209. @end example
  18210. @noindent
  18211. @example
  18212. @group
  18213. [ 123, 0, 0 ] 123, 0, 0
  18214. [ 0, 123, 0 ] 0, 123, 0
  18215. [ 0, 0, 123 ] 0, 0, 123
  18216. R @r{blank}
  18217. @end group
  18218. @end example
  18219. @noindent
  18220. Note that of the formats shown here, @samp{RO}, @samp{ROC}, and
  18221. @samp{OC} are all recognized as matrices during reading, while
  18222. the others are useful for display only.
  18223. @kindex v ,
  18224. @kindex V ,
  18225. @pindex calc-vector-commas
  18226. The @kbd{v ,} (@code{calc-vector-commas}) command turns commas on and
  18227. off in vector and matrix display.
  18228. In vectors of length one, and in all vectors when commas have been
  18229. turned off, Calc adds extra parentheses around formulas that might
  18230. otherwise be ambiguous. For example, @samp{[a b]} could be a vector
  18231. of the one formula @samp{a b}, or it could be a vector of two
  18232. variables with commas turned off. Calc will display the former
  18233. case as @samp{[(a b)]}. You can disable these extra parentheses
  18234. (to make the output less cluttered at the expense of allowing some
  18235. ambiguity) by adding the letter @code{P} to the control string you
  18236. give to @kbd{v ]} (as described above).
  18237. @kindex v .
  18238. @kindex V .
  18239. @pindex calc-full-vectors
  18240. The @kbd{v .} (@code{calc-full-vectors}) command turns abbreviated
  18241. display of long vectors on and off. In this mode, vectors of six
  18242. or more elements, or matrices of six or more rows or columns, will
  18243. be displayed in an abbreviated form that displays only the first
  18244. three elements and the last element: @samp{[a, b, c, ..., z]}.
  18245. When very large vectors are involved this will substantially
  18246. improve Calc's display speed.
  18247. @kindex t .
  18248. @pindex calc-full-trail-vectors
  18249. The @kbd{t .} (@code{calc-full-trail-vectors}) command controls a
  18250. similar mode for recording vectors in the Trail. If you turn on
  18251. this mode, vectors of six or more elements and matrices of six or
  18252. more rows or columns will be abbreviated when they are put in the
  18253. Trail. The @kbd{t y} (@code{calc-trail-yank}) command will be
  18254. unable to recover those vectors. If you are working with very
  18255. large vectors, this mode will improve the speed of all operations
  18256. that involve the trail.
  18257. @kindex v /
  18258. @kindex V /
  18259. @pindex calc-break-vectors
  18260. The @kbd{v /} (@code{calc-break-vectors}) command turns multi-line
  18261. vector display on and off. Normally, matrices are displayed with one
  18262. row per line but all other types of vectors are displayed in a single
  18263. line. This mode causes all vectors, whether matrices or not, to be
  18264. displayed with a single element per line. Sub-vectors within the
  18265. vectors will still use the normal linear form.
  18266. @node Algebra, Units, Matrix Functions, Top
  18267. @chapter Algebra
  18268. @noindent
  18269. This section covers the Calc features that help you work with
  18270. algebraic formulas. First, the general sub-formula selection
  18271. mechanism is described; this works in conjunction with any Calc
  18272. commands. Then, commands for specific algebraic operations are
  18273. described. Finally, the flexible @dfn{rewrite rule} mechanism
  18274. is discussed.
  18275. The algebraic commands use the @kbd{a} key prefix; selection
  18276. commands use the @kbd{j} (for ``just a letter that wasn't used
  18277. for anything else'') prefix.
  18278. @xref{Editing Stack Entries}, to see how to manipulate formulas
  18279. using regular Emacs editing commands.
  18280. When doing algebraic work, you may find several of the Calculator's
  18281. modes to be helpful, including Algebraic Simplification mode (@kbd{m A})
  18282. or No-Simplification mode (@kbd{m O}),
  18283. Algebraic entry mode (@kbd{m a}), Fraction mode (@kbd{m f}), and
  18284. Symbolic mode (@kbd{m s}). @xref{Mode Settings}, for discussions
  18285. of these modes. You may also wish to select Big display mode (@kbd{d B}).
  18286. @xref{Normal Language Modes}.
  18287. @menu
  18288. * Selecting Subformulas::
  18289. * Algebraic Manipulation::
  18290. * Simplifying Formulas::
  18291. * Polynomials::
  18292. * Calculus::
  18293. * Solving Equations::
  18294. * Numerical Solutions::
  18295. * Curve Fitting::
  18296. * Summations::
  18297. * Logical Operations::
  18298. * Rewrite Rules::
  18299. @end menu
  18300. @node Selecting Subformulas, Algebraic Manipulation, Algebra, Algebra
  18301. @section Selecting Sub-Formulas
  18302. @noindent
  18303. @cindex Selections
  18304. @cindex Sub-formulas
  18305. @cindex Parts of formulas
  18306. When working with an algebraic formula it is often necessary to
  18307. manipulate a portion of the formula rather than the formula as a
  18308. whole. Calc allows you to ``select'' a portion of any formula on
  18309. the stack. Commands which would normally operate on that stack
  18310. entry will now operate only on the sub-formula, leaving the
  18311. surrounding part of the stack entry alone.
  18312. One common non-algebraic use for selection involves vectors. To work
  18313. on one element of a vector in-place, simply select that element as a
  18314. ``sub-formula'' of the vector.
  18315. @menu
  18316. * Making Selections::
  18317. * Changing Selections::
  18318. * Displaying Selections::
  18319. * Operating on Selections::
  18320. * Rearranging with Selections::
  18321. @end menu
  18322. @node Making Selections, Changing Selections, Selecting Subformulas, Selecting Subformulas
  18323. @subsection Making Selections
  18324. @noindent
  18325. @kindex j s
  18326. @pindex calc-select-here
  18327. To select a sub-formula, move the Emacs cursor to any character in that
  18328. sub-formula, and press @w{@kbd{j s}} (@code{calc-select-here}). Calc will
  18329. highlight the smallest portion of the formula that contains that
  18330. character. By default the sub-formula is highlighted by blanking out
  18331. all of the rest of the formula with dots. Selection works in any
  18332. display mode but is perhaps easiest in Big mode (@kbd{d B}).
  18333. Suppose you enter the following formula:
  18334. @smallexample
  18335. @group
  18336. 3 ___
  18337. (a + b) + V c
  18338. 1: ---------------
  18339. 2 x + 1
  18340. @end group
  18341. @end smallexample
  18342. @noindent
  18343. (by typing @kbd{' ((a+b)^3 + sqrt(c)) / (2x+1)}). If you move the
  18344. cursor to the letter @samp{b} and press @w{@kbd{j s}}, the display changes
  18345. to
  18346. @smallexample
  18347. @group
  18348. . ...
  18349. .. . b. . . .
  18350. 1* ...............
  18351. . . . .
  18352. @end group
  18353. @end smallexample
  18354. @noindent
  18355. Every character not part of the sub-formula @samp{b} has been changed
  18356. to a dot. (If the customizable variable
  18357. @code{calc-highlight-selections-with-faces} is non-@code{nil}, then the characters
  18358. not part of the sub-formula are de-emphasized by using a less
  18359. noticeable face instead of using dots. @pxref{Displaying Selections}.)
  18360. The @samp{*} next to the line number is to remind you that
  18361. the formula has a portion of it selected. (In this case, it's very
  18362. obvious, but it might not always be. If Embedded mode is enabled,
  18363. the word @samp{Sel} also appears in the mode line because the stack
  18364. may not be visible. @pxref{Embedded Mode}.)
  18365. If you had instead placed the cursor on the parenthesis immediately to
  18366. the right of the @samp{b}, the selection would have been:
  18367. @smallexample
  18368. @group
  18369. . ...
  18370. (a + b) . . .
  18371. 1* ...............
  18372. . . . .
  18373. @end group
  18374. @end smallexample
  18375. @noindent
  18376. The portion selected is always large enough to be considered a complete
  18377. formula all by itself, so selecting the parenthesis selects the whole
  18378. formula that it encloses. Putting the cursor on the @samp{+} sign
  18379. would have had the same effect.
  18380. (Strictly speaking, the Emacs cursor is really the manifestation of
  18381. the Emacs ``point,'' which is a position @emph{between} two characters
  18382. in the buffer. So purists would say that Calc selects the smallest
  18383. sub-formula which contains the character to the right of ``point.'')
  18384. If you supply a numeric prefix argument @var{n}, the selection is
  18385. expanded to the @var{n}th enclosing sub-formula. Thus, positioning
  18386. the cursor on the @samp{b} and typing @kbd{C-u 1 j s} will select
  18387. @samp{a + b}; typing @kbd{C-u 2 j s} will select @samp{(a + b)^3},
  18388. and so on.
  18389. If the cursor is not on any part of the formula, or if you give a
  18390. numeric prefix that is too large, the entire formula is selected.
  18391. If the cursor is on the @samp{.} line that marks the top of the stack
  18392. (i.e., its normal ``rest position''), this command selects the entire
  18393. formula at stack level 1. Most selection commands similarly operate
  18394. on the formula at the top of the stack if you haven't positioned the
  18395. cursor on any stack entry.
  18396. @kindex j a
  18397. @pindex calc-select-additional
  18398. The @kbd{j a} (@code{calc-select-additional}) command enlarges the
  18399. current selection to encompass the cursor. To select the smallest
  18400. sub-formula defined by two different points, move to the first and
  18401. press @kbd{j s}, then move to the other and press @kbd{j a}. This
  18402. is roughly analogous to using @kbd{C-@@} (@code{set-mark-command}) to
  18403. select the two ends of a region of text during normal Emacs editing.
  18404. @kindex j o
  18405. @pindex calc-select-once
  18406. The @kbd{j o} (@code{calc-select-once}) command selects a formula in
  18407. exactly the same way as @kbd{j s}, except that the selection will
  18408. last only as long as the next command that uses it. For example,
  18409. @kbd{j o 1 +} is a handy way to add one to the sub-formula indicated
  18410. by the cursor.
  18411. (A somewhat more precise definition: The @kbd{j o} command sets a flag
  18412. such that the next command involving selected stack entries will clear
  18413. the selections on those stack entries afterwards. All other selection
  18414. commands except @kbd{j a} and @kbd{j O} clear this flag.)
  18415. @kindex j S
  18416. @kindex j O
  18417. @pindex calc-select-here-maybe
  18418. @pindex calc-select-once-maybe
  18419. The @kbd{j S} (@code{calc-select-here-maybe}) and @kbd{j O}
  18420. (@code{calc-select-once-maybe}) commands are equivalent to @kbd{j s}
  18421. and @kbd{j o}, respectively, except that if the formula already
  18422. has a selection they have no effect. This is analogous to the
  18423. behavior of some commands such as @kbd{j r} (@code{calc-rewrite-selection};
  18424. @pxref{Selections with Rewrite Rules}) and is mainly intended to be
  18425. used in keyboard macros that implement your own selection-oriented
  18426. commands.
  18427. Selection of sub-formulas normally treats associative terms like
  18428. @samp{a + b - c + d} and @samp{x * y * z} as single levels of the formula.
  18429. If you place the cursor anywhere inside @samp{a + b - c + d} except
  18430. on one of the variable names and use @kbd{j s}, you will select the
  18431. entire four-term sum.
  18432. @kindex j b
  18433. @pindex calc-break-selections
  18434. The @kbd{j b} (@code{calc-break-selections}) command controls a mode
  18435. in which the ``deep structure'' of these associative formulas shows
  18436. through. Calc actually stores the above formulas as
  18437. @samp{((a + b) - c) + d} and @samp{x * (y * z)}. (Note that for certain
  18438. obscure reasons, by default Calc treats multiplication as
  18439. right-associative.) Once you have enabled @kbd{j b} mode, selecting
  18440. with the cursor on the @samp{-} sign would only select the @samp{a + b -
  18441. c} portion, which makes sense when the deep structure of the sum is
  18442. considered. There is no way to select the @samp{b - c + d} portion;
  18443. although this might initially look like just as legitimate a sub-formula
  18444. as @samp{a + b - c}, the deep structure shows that it isn't. The @kbd{d
  18445. U} command can be used to view the deep structure of any formula
  18446. (@pxref{Normal Language Modes}).
  18447. When @kbd{j b} mode has not been enabled, the deep structure is
  18448. generally hidden by the selection commands---what you see is what
  18449. you get.
  18450. @kindex j u
  18451. @pindex calc-unselect
  18452. The @kbd{j u} (@code{calc-unselect}) command unselects the formula
  18453. that the cursor is on. If there was no selection in the formula,
  18454. this command has no effect. With a numeric prefix argument, it
  18455. unselects the @var{n}th stack element rather than using the cursor
  18456. position.
  18457. @kindex j c
  18458. @pindex calc-clear-selections
  18459. The @kbd{j c} (@code{calc-clear-selections}) command unselects all
  18460. stack elements.
  18461. @node Changing Selections, Displaying Selections, Making Selections, Selecting Subformulas
  18462. @subsection Changing Selections
  18463. @noindent
  18464. @kindex j m
  18465. @pindex calc-select-more
  18466. Once you have selected a sub-formula, you can expand it using the
  18467. @w{@kbd{j m}} (@code{calc-select-more}) command. If @samp{a + b} is
  18468. selected, pressing @w{@kbd{j m}} repeatedly works as follows:
  18469. @smallexample
  18470. @group
  18471. 3 ... 3 ___ 3 ___
  18472. (a + b) . . . (a + b) + V c (a + b) + V c
  18473. 1* ............... 1* ............... 1* ---------------
  18474. . . . . . . . . 2 x + 1
  18475. @end group
  18476. @end smallexample
  18477. @noindent
  18478. In the last example, the entire formula is selected. This is roughly
  18479. the same as having no selection at all, but because there are subtle
  18480. differences the @samp{*} character is still there on the line number.
  18481. With a numeric prefix argument @var{n}, @kbd{j m} expands @var{n}
  18482. times (or until the entire formula is selected). Note that @kbd{j s}
  18483. with argument @var{n} is equivalent to plain @kbd{j s} followed by
  18484. @kbd{j m} with argument @var{n}. If @w{@kbd{j m}} is used when there
  18485. is no current selection, it is equivalent to @w{@kbd{j s}}.
  18486. Even though @kbd{j m} does not explicitly use the location of the
  18487. cursor within the formula, it nevertheless uses the cursor to determine
  18488. which stack element to operate on. As usual, @kbd{j m} when the cursor
  18489. is not on any stack element operates on the top stack element.
  18490. @kindex j l
  18491. @pindex calc-select-less
  18492. The @kbd{j l} (@code{calc-select-less}) command reduces the current
  18493. selection around the cursor position. That is, it selects the
  18494. immediate sub-formula of the current selection which contains the
  18495. cursor, the opposite of @kbd{j m}. If the cursor is not inside the
  18496. current selection, the command de-selects the formula.
  18497. @kindex j 1-9
  18498. @pindex calc-select-part
  18499. The @kbd{j 1} through @kbd{j 9} (@code{calc-select-part}) commands
  18500. select the @var{n}th sub-formula of the current selection. They are
  18501. like @kbd{j l} (@code{calc-select-less}) except they use counting
  18502. rather than the cursor position to decide which sub-formula to select.
  18503. For example, if the current selection is @kbd{a + b + c} or
  18504. @kbd{f(a, b, c)} or @kbd{[a, b, c]}, then @kbd{j 1} selects @samp{a},
  18505. @kbd{j 2} selects @samp{b}, and @kbd{j 3} selects @samp{c}; in each of
  18506. these cases, @kbd{j 4} through @kbd{j 9} would be errors.
  18507. If there is no current selection, @kbd{j 1} through @kbd{j 9} select
  18508. the @var{n}th top-level sub-formula. (In other words, they act as if
  18509. the entire stack entry were selected first.) To select the @var{n}th
  18510. sub-formula where @var{n} is greater than nine, you must instead invoke
  18511. @w{@kbd{j 1}} with @var{n} as a numeric prefix argument.
  18512. @kindex j n
  18513. @kindex j p
  18514. @pindex calc-select-next
  18515. @pindex calc-select-previous
  18516. The @kbd{j n} (@code{calc-select-next}) and @kbd{j p}
  18517. (@code{calc-select-previous}) commands change the current selection
  18518. to the next or previous sub-formula at the same level. For example,
  18519. if @samp{b} is selected in @w{@samp{2 + a*b*c + x}}, then @kbd{j n}
  18520. selects @samp{c}. Further @kbd{j n} commands would be in error because,
  18521. even though there is something to the right of @samp{c} (namely, @samp{x}),
  18522. it is not at the same level; in this case, it is not a term of the
  18523. same product as @samp{b} and @samp{c}. However, @kbd{j m} (to select
  18524. the whole product @samp{a*b*c} as a term of the sum) followed by
  18525. @w{@kbd{j n}} would successfully select the @samp{x}.
  18526. Similarly, @kbd{j p} moves the selection from the @samp{b} in this
  18527. sample formula to the @samp{a}. Both commands accept numeric prefix
  18528. arguments to move several steps at a time.
  18529. It is interesting to compare Calc's selection commands with the
  18530. Emacs Info system's commands for navigating through hierarchically
  18531. organized documentation. Calc's @kbd{j n} command is completely
  18532. analogous to Info's @kbd{n} command. Likewise, @kbd{j p} maps to
  18533. @kbd{p}, @kbd{j 2} maps to @kbd{2}, and Info's @kbd{u} is like @kbd{j m}.
  18534. (Note that @kbd{j u} stands for @code{calc-unselect}, not ``up''.)
  18535. The Info @kbd{m} command is somewhat similar to Calc's @kbd{j s} and
  18536. @kbd{j l}; in each case, you can jump directly to a sub-component
  18537. of the hierarchy simply by pointing to it with the cursor.
  18538. @node Displaying Selections, Operating on Selections, Changing Selections, Selecting Subformulas
  18539. @subsection Displaying Selections
  18540. @noindent
  18541. @kindex j d
  18542. @pindex calc-show-selections
  18543. @vindex calc-highlight-selections-with-faces
  18544. @vindex calc-selected-face
  18545. @vindex calc-nonselected-face
  18546. The @kbd{j d} (@code{calc-show-selections}) command controls how
  18547. selected sub-formulas are displayed. One of the alternatives is
  18548. illustrated in the above examples; if we press @kbd{j d} we switch
  18549. to the other style in which the selected portion itself is obscured
  18550. by @samp{#} signs:
  18551. @smallexample
  18552. @group
  18553. 3 ... # ___
  18554. (a + b) . . . ## # ## + V c
  18555. 1* ............... 1* ---------------
  18556. . . . . 2 x + 1
  18557. @end group
  18558. @end smallexample
  18559. If the customizable variable
  18560. @code{calc-highlight-selections-with-faces} is non-@code{nil}, then the
  18561. non-selected portion of the formula will be de-emphasized by using a
  18562. less noticeable face (@code{calc-nonselected-face}) instead of dots
  18563. and the selected sub-formula will be highlighted by using a more
  18564. noticeable face (@code{calc-selected-face}) instead of @samp{#}
  18565. signs. (@pxref{Customizing Calc}.)
  18566. @node Operating on Selections, Rearranging with Selections, Displaying Selections, Selecting Subformulas
  18567. @subsection Operating on Selections
  18568. @noindent
  18569. Once a selection is made, all Calc commands that manipulate items
  18570. on the stack will operate on the selected portions of the items
  18571. instead. (Note that several stack elements may have selections
  18572. at once, though there can be only one selection at a time in any
  18573. given stack element.)
  18574. @kindex j e
  18575. @pindex calc-enable-selections
  18576. The @kbd{j e} (@code{calc-enable-selections}) command disables the
  18577. effect that selections have on Calc commands. The current selections
  18578. still exist, but Calc commands operate on whole stack elements anyway.
  18579. This mode can be identified by the fact that the @samp{*} markers on
  18580. the line numbers are gone, even though selections are visible. To
  18581. reactivate the selections, press @kbd{j e} again.
  18582. To extract a sub-formula as a new formula, simply select the
  18583. sub-formula and press @key{RET}. This normally duplicates the top
  18584. stack element; here it duplicates only the selected portion of that
  18585. element.
  18586. To replace a sub-formula with something different, you can enter the
  18587. new value onto the stack and press @key{TAB}. This normally exchanges
  18588. the top two stack elements; here it swaps the value you entered into
  18589. the selected portion of the formula, returning the old selected
  18590. portion to the top of the stack.
  18591. @smallexample
  18592. @group
  18593. 3 ... ... ___
  18594. (a + b) . . . 17 x y . . . 17 x y + V c
  18595. 2* ............... 2* ............. 2: -------------
  18596. . . . . . . . . 2 x + 1
  18597. 3 3
  18598. 1: 17 x y 1: (a + b) 1: (a + b)
  18599. @end group
  18600. @end smallexample
  18601. In this example we select a sub-formula of our original example,
  18602. enter a new formula, @key{TAB} it into place, then deselect to see
  18603. the complete, edited formula.
  18604. If you want to swap whole formulas around even though they contain
  18605. selections, just use @kbd{j e} before and after.
  18606. @kindex j '
  18607. @pindex calc-enter-selection
  18608. The @kbd{j '} (@code{calc-enter-selection}) command is another way
  18609. to replace a selected sub-formula. This command does an algebraic
  18610. entry just like the regular @kbd{'} key. When you press @key{RET},
  18611. the formula you type replaces the original selection. You can use
  18612. the @samp{$} symbol in the formula to refer to the original
  18613. selection. If there is no selection in the formula under the cursor,
  18614. the cursor is used to make a temporary selection for the purposes of
  18615. the command. Thus, to change a term of a formula, all you have to
  18616. do is move the Emacs cursor to that term and press @kbd{j '}.
  18617. @kindex j `
  18618. @pindex calc-edit-selection
  18619. The @kbd{j `} (@code{calc-edit-selection}) command is a similar
  18620. analogue of the @kbd{`} (@code{calc-edit}) command. It edits the
  18621. selected sub-formula in a separate buffer. If there is no
  18622. selection, it edits the sub-formula indicated by the cursor.
  18623. To delete a sub-formula, press @key{DEL}. This generally replaces
  18624. the sub-formula with the constant zero, but in a few suitable contexts
  18625. it uses the constant one instead. The @key{DEL} key automatically
  18626. deselects and re-simplifies the entire formula afterwards. Thus:
  18627. @smallexample
  18628. @group
  18629. ###
  18630. 17 x y + # # 17 x y 17 # y 17 y
  18631. 1* ------------- 1: ------- 1* ------- 1: -------
  18632. 2 x + 1 2 x + 1 2 x + 1 2 x + 1
  18633. @end group
  18634. @end smallexample
  18635. In this example, we first delete the @samp{sqrt(c)} term; Calc
  18636. accomplishes this by replacing @samp{sqrt(c)} with zero and
  18637. resimplifying. We then delete the @kbd{x} in the numerator;
  18638. since this is part of a product, Calc replaces it with @samp{1}
  18639. and resimplifies.
  18640. If you select an element of a vector and press @key{DEL}, that
  18641. element is deleted from the vector. If you delete one side of
  18642. an equation or inequality, only the opposite side remains.
  18643. @kindex j @key{DEL}
  18644. @pindex calc-del-selection
  18645. The @kbd{j @key{DEL}} (@code{calc-del-selection}) command is like
  18646. @key{DEL} but with the auto-selecting behavior of @kbd{j '} and
  18647. @kbd{j `}. It deletes the selected portion of the formula
  18648. indicated by the cursor, or, in the absence of a selection, it
  18649. deletes the sub-formula indicated by the cursor position.
  18650. @kindex j @key{RET}
  18651. @pindex calc-grab-selection
  18652. (There is also an auto-selecting @kbd{j @key{RET}} (@code{calc-copy-selection})
  18653. command.)
  18654. Normal arithmetic operations also apply to sub-formulas. Here we
  18655. select the denominator, press @kbd{5 -} to subtract five from the
  18656. denominator, press @kbd{n} to negate the denominator, then
  18657. press @kbd{Q} to take the square root.
  18658. @smallexample
  18659. @group
  18660. .. . .. . .. . .. .
  18661. 1* ....... 1* ....... 1* ....... 1* ..........
  18662. 2 x + 1 2 x - 4 4 - 2 x _________
  18663. V 4 - 2 x
  18664. @end group
  18665. @end smallexample
  18666. Certain types of operations on selections are not allowed. For
  18667. example, for an arithmetic function like @kbd{-} no more than one of
  18668. the arguments may be a selected sub-formula. (As the above example
  18669. shows, the result of the subtraction is spliced back into the argument
  18670. which had the selection; if there were more than one selection involved,
  18671. this would not be well-defined.) If you try to subtract two selections,
  18672. the command will abort with an error message.
  18673. Operations on sub-formulas sometimes leave the formula as a whole
  18674. in an ``un-natural'' state. Consider negating the @samp{2 x} term
  18675. of our sample formula by selecting it and pressing @kbd{n}
  18676. (@code{calc-change-sign}).
  18677. @smallexample
  18678. @group
  18679. .. . .. .
  18680. 1* .......... 1* ...........
  18681. ......... ..........
  18682. . . . 2 x . . . -2 x
  18683. @end group
  18684. @end smallexample
  18685. Unselecting the sub-formula reveals that the minus sign, which would
  18686. normally have canceled out with the subtraction automatically, has
  18687. not been able to do so because the subtraction was not part of the
  18688. selected portion. Pressing @kbd{=} (@code{calc-evaluate}) or doing
  18689. any other mathematical operation on the whole formula will cause it
  18690. to be simplified.
  18691. @smallexample
  18692. @group
  18693. 17 y 17 y
  18694. 1: ----------- 1: ----------
  18695. __________ _________
  18696. V 4 - -2 x V 4 + 2 x
  18697. @end group
  18698. @end smallexample
  18699. @node Rearranging with Selections, , Operating on Selections, Selecting Subformulas
  18700. @subsection Rearranging Formulas using Selections
  18701. @noindent
  18702. @kindex j R
  18703. @pindex calc-commute-right
  18704. The @kbd{j R} (@code{calc-commute-right}) command moves the selected
  18705. sub-formula to the right in its surrounding formula. Generally the
  18706. selection is one term of a sum or product; the sum or product is
  18707. rearranged according to the commutative laws of algebra.
  18708. As with @kbd{j '} and @kbd{j @key{DEL}}, the term under the cursor is used
  18709. if there is no selection in the current formula. All commands described
  18710. in this section share this property. In this example, we place the
  18711. cursor on the @samp{a} and type @kbd{j R}, then repeat.
  18712. @smallexample
  18713. 1: a + b - c 1: b + a - c 1: b - c + a
  18714. @end smallexample
  18715. @noindent
  18716. Note that in the final step above, the @samp{a} is switched with
  18717. the @samp{c} but the signs are adjusted accordingly. When moving
  18718. terms of sums and products, @kbd{j R} will never change the
  18719. mathematical meaning of the formula.
  18720. The selected term may also be an element of a vector or an argument
  18721. of a function. The term is exchanged with the one to its right.
  18722. In this case, the ``meaning'' of the vector or function may of
  18723. course be drastically changed.
  18724. @smallexample
  18725. 1: [a, b, c] 1: [b, a, c] 1: [b, c, a]
  18726. 1: f(a, b, c) 1: f(b, a, c) 1: f(b, c, a)
  18727. @end smallexample
  18728. @kindex j L
  18729. @pindex calc-commute-left
  18730. The @kbd{j L} (@code{calc-commute-left}) command is like @kbd{j R}
  18731. except that it swaps the selected term with the one to its left.
  18732. With numeric prefix arguments, these commands move the selected
  18733. term several steps at a time. It is an error to try to move a
  18734. term left or right past the end of its enclosing formula.
  18735. With numeric prefix arguments of zero, these commands move the
  18736. selected term as far as possible in the given direction.
  18737. @kindex j D
  18738. @pindex calc-sel-distribute
  18739. The @kbd{j D} (@code{calc-sel-distribute}) command mixes the selected
  18740. sum or product into the surrounding formula using the distributive
  18741. law. For example, in @samp{a * (b - c)} with the @samp{b - c}
  18742. selected, the result is @samp{a b - a c}. This also distributes
  18743. products or quotients into surrounding powers, and can also do
  18744. transformations like @samp{exp(a + b)} to @samp{exp(a) exp(b)},
  18745. where @samp{a + b} is the selected term, and @samp{ln(a ^ b)}
  18746. to @samp{ln(a) b}, where @samp{a ^ b} is the selected term.
  18747. For multiple-term sums or products, @kbd{j D} takes off one term
  18748. at a time: @samp{a * (b + c - d)} goes to @samp{a * (c - d) + a b}
  18749. with the @samp{c - d} selected so that you can type @kbd{j D}
  18750. repeatedly to expand completely. The @kbd{j D} command allows a
  18751. numeric prefix argument which specifies the maximum number of
  18752. times to expand at once; the default is one time only.
  18753. @vindex DistribRules
  18754. The @kbd{j D} command is implemented using rewrite rules.
  18755. @xref{Selections with Rewrite Rules}. The rules are stored in
  18756. the Calc variable @code{DistribRules}. A convenient way to view
  18757. these rules is to use @kbd{s e} (@code{calc-edit-variable}) which
  18758. displays and edits the stored value of a variable. Press @kbd{C-c C-c}
  18759. to return from editing mode; be careful not to make any actual changes
  18760. or else you will affect the behavior of future @kbd{j D} commands!
  18761. To extend @kbd{j D} to handle new cases, just edit @code{DistribRules}
  18762. as described above. You can then use the @kbd{s p} command to save
  18763. this variable's value permanently for future Calc sessions.
  18764. @xref{Operations on Variables}.
  18765. @kindex j M
  18766. @pindex calc-sel-merge
  18767. @vindex MergeRules
  18768. The @kbd{j M} (@code{calc-sel-merge}) command is the complement
  18769. of @kbd{j D}; given @samp{a b - a c} with either @samp{a b} or
  18770. @samp{a c} selected, the result is @samp{a * (b - c)}. Once
  18771. again, @kbd{j M} can also merge calls to functions like @code{exp}
  18772. and @code{ln}; examine the variable @code{MergeRules} to see all
  18773. the relevant rules.
  18774. @kindex j C
  18775. @pindex calc-sel-commute
  18776. @vindex CommuteRules
  18777. The @kbd{j C} (@code{calc-sel-commute}) command swaps the arguments
  18778. of the selected sum, product, or equation. It always behaves as
  18779. if @kbd{j b} mode were in effect, i.e., the sum @samp{a + b + c} is
  18780. treated as the nested sums @samp{(a + b) + c} by this command.
  18781. If you put the cursor on the first @samp{+}, the result is
  18782. @samp{(b + a) + c}; if you put the cursor on the second @samp{+}, the
  18783. result is @samp{c + (a + b)} (which the default simplifications
  18784. will rearrange to @samp{(c + a) + b}). The relevant rules are stored
  18785. in the variable @code{CommuteRules}.
  18786. You may need to turn default simplifications off (with the @kbd{m O}
  18787. command) in order to get the full benefit of @kbd{j C}. For example,
  18788. commuting @samp{a - b} produces @samp{-b + a}, but the default
  18789. simplifications will ``simplify'' this right back to @samp{a - b} if
  18790. you don't turn them off. The same is true of some of the other
  18791. manipulations described in this section.
  18792. @kindex j N
  18793. @pindex calc-sel-negate
  18794. @vindex NegateRules
  18795. The @kbd{j N} (@code{calc-sel-negate}) command replaces the selected
  18796. term with the negative of that term, then adjusts the surrounding
  18797. formula in order to preserve the meaning. For example, given
  18798. @samp{exp(a - b)} where @samp{a - b} is selected, the result is
  18799. @samp{1 / exp(b - a)}. By contrast, selecting a term and using the
  18800. regular @kbd{n} (@code{calc-change-sign}) command negates the
  18801. term without adjusting the surroundings, thus changing the meaning
  18802. of the formula as a whole. The rules variable is @code{NegateRules}.
  18803. @kindex j &
  18804. @pindex calc-sel-invert
  18805. @vindex InvertRules
  18806. The @kbd{j &} (@code{calc-sel-invert}) command is similar to @kbd{j N}
  18807. except it takes the reciprocal of the selected term. For example,
  18808. given @samp{a - ln(b)} with @samp{b} selected, the result is
  18809. @samp{a + ln(1/b)}. The rules variable is @code{InvertRules}.
  18810. @kindex j E
  18811. @pindex calc-sel-jump-equals
  18812. @vindex JumpRules
  18813. The @kbd{j E} (@code{calc-sel-jump-equals}) command moves the
  18814. selected term from one side of an equation to the other. Given
  18815. @samp{a + b = c + d} with @samp{c} selected, the result is
  18816. @samp{a + b - c = d}. This command also works if the selected
  18817. term is part of a @samp{*}, @samp{/}, or @samp{^} formula. The
  18818. relevant rules variable is @code{JumpRules}.
  18819. @kindex j I
  18820. @kindex H j I
  18821. @pindex calc-sel-isolate
  18822. The @kbd{j I} (@code{calc-sel-isolate}) command isolates the
  18823. selected term on its side of an equation. It uses the @kbd{a S}
  18824. (@code{calc-solve-for}) command to solve the equation, and the
  18825. Hyperbolic flag affects it in the same way. @xref{Solving Equations}.
  18826. When it applies, @kbd{j I} is often easier to use than @kbd{j E}.
  18827. It understands more rules of algebra, and works for inequalities
  18828. as well as equations.
  18829. @kindex j *
  18830. @kindex j /
  18831. @pindex calc-sel-mult-both-sides
  18832. @pindex calc-sel-div-both-sides
  18833. The @kbd{j *} (@code{calc-sel-mult-both-sides}) command prompts for a
  18834. formula using algebraic entry, then multiplies both sides of the
  18835. selected quotient or equation by that formula. It performs the
  18836. default algebraic simplifications before re-forming the
  18837. quotient or equation. You can suppress this simplification by
  18838. providing a prefix argument: @kbd{C-u j *}. There is also a @kbd{j /}
  18839. (@code{calc-sel-div-both-sides}) which is similar to @kbd{j *} but
  18840. dividing instead of multiplying by the factor you enter.
  18841. If the selection is a quotient with numerator 1, then Calc's default
  18842. simplifications would normally cancel the new factors. To prevent
  18843. this, when the @kbd{j *} command is used on a selection whose numerator is
  18844. 1 or -1, the denominator is expanded at the top level using the
  18845. distributive law (as if using the @kbd{C-u 1 a x} command). Suppose the
  18846. formula on the stack is @samp{1 / (a + 1)} and you wish to multiplying the
  18847. top and bottom by @samp{a - 1}. Calc's default simplifications would
  18848. normally change the result @samp{(a - 1) /(a + 1) (a - 1)} back
  18849. to the original form by cancellation; when @kbd{j *} is used, Calc
  18850. expands the denominator to @samp{a (a - 1) + a - 1} to prevent this.
  18851. If you wish the @kbd{j *} command to completely expand the denominator
  18852. of a quotient you can call it with a zero prefix: @kbd{C-u 0 j *}. For
  18853. example, if the formula on the stack is @samp{1 / (sqrt(a) + 1)}, you may
  18854. wish to eliminate the square root in the denominator by multiplying
  18855. the top and bottom by @samp{sqrt(a) - 1}. If you did this simply by using
  18856. a simple @kbd{j *} command, you would get
  18857. @samp{(sqrt(a)-1)/ (sqrt(a) (sqrt(a) - 1) + sqrt(a) - 1)}. Instead,
  18858. you would probably want to use @kbd{C-u 0 j *}, which would expand the
  18859. bottom and give you the desired result @samp{(sqrt(a)-1)/(a-1)}. More
  18860. generally, if @kbd{j *} is called with an argument of a positive
  18861. integer @var{n}, then the denominator of the expression will be
  18862. expanded @var{n} times (as if with the @kbd{C-u @var{n} a x} command).
  18863. If the selection is an inequality, @kbd{j *} and @kbd{j /} will
  18864. accept any factor, but will warn unless they can prove the factor
  18865. is either positive or negative. (In the latter case the direction
  18866. of the inequality will be switched appropriately.) @xref{Declarations},
  18867. for ways to inform Calc that a given variable is positive or
  18868. negative. If Calc can't tell for sure what the sign of the factor
  18869. will be, it will assume it is positive and display a warning
  18870. message.
  18871. For selections that are not quotients, equations, or inequalities,
  18872. these commands pull out a multiplicative factor: They divide (or
  18873. multiply) by the entered formula, simplify, then multiply (or divide)
  18874. back by the formula.
  18875. @kindex j +
  18876. @kindex j -
  18877. @pindex calc-sel-add-both-sides
  18878. @pindex calc-sel-sub-both-sides
  18879. The @kbd{j +} (@code{calc-sel-add-both-sides}) and @kbd{j -}
  18880. (@code{calc-sel-sub-both-sides}) commands analogously add to or
  18881. subtract from both sides of an equation or inequality. For other
  18882. types of selections, they extract an additive factor. A numeric
  18883. prefix argument suppresses simplification of the intermediate
  18884. results.
  18885. @kindex j U
  18886. @pindex calc-sel-unpack
  18887. The @kbd{j U} (@code{calc-sel-unpack}) command replaces the
  18888. selected function call with its argument. For example, given
  18889. @samp{a + sin(x^2)} with @samp{sin(x^2)} selected, the result
  18890. is @samp{a + x^2}. (The @samp{x^2} will remain selected; if you
  18891. wanted to change the @code{sin} to @code{cos}, just press @kbd{C}
  18892. now to take the cosine of the selected part.)
  18893. @kindex j v
  18894. @pindex calc-sel-evaluate
  18895. The @kbd{j v} (@code{calc-sel-evaluate}) command performs the
  18896. basic simplifications on the selected sub-formula.
  18897. These simplifications would normally be done automatically
  18898. on all results, but may have been partially inhibited by
  18899. previous selection-related operations, or turned off altogether
  18900. by the @kbd{m O} command. This command is just an auto-selecting
  18901. version of the @w{@kbd{a v}} command (@pxref{Algebraic Manipulation}).
  18902. With a numeric prefix argument of 2, @kbd{C-u 2 j v} applies
  18903. the default algebraic simplifications to the selected
  18904. sub-formula. With a prefix argument of 3 or more, e.g., @kbd{C-u j v}
  18905. applies the @kbd{a e} (@code{calc-simplify-extended}) command.
  18906. @xref{Simplifying Formulas}. With a negative prefix argument
  18907. it simplifies at the top level only, just as with @kbd{a v}.
  18908. Here the ``top'' level refers to the top level of the selected
  18909. sub-formula.
  18910. @kindex j "
  18911. @pindex calc-sel-expand-formula
  18912. The @kbd{j "} (@code{calc-sel-expand-formula}) command is to @kbd{a "}
  18913. (@pxref{Algebraic Manipulation}) what @kbd{j v} is to @kbd{a v}.
  18914. You can use the @kbd{j r} (@code{calc-rewrite-selection}) command
  18915. to define other algebraic operations on sub-formulas. @xref{Rewrite Rules}.
  18916. @node Algebraic Manipulation, Simplifying Formulas, Selecting Subformulas, Algebra
  18917. @section Algebraic Manipulation
  18918. @noindent
  18919. The commands in this section perform general-purpose algebraic
  18920. manipulations. They work on the whole formula at the top of the
  18921. stack (unless, of course, you have made a selection in that
  18922. formula).
  18923. Many algebra commands prompt for a variable name or formula. If you
  18924. answer the prompt with a blank line, the variable or formula is taken
  18925. from top-of-stack, and the normal argument for the command is taken
  18926. from the second-to-top stack level.
  18927. @kindex a v
  18928. @pindex calc-alg-evaluate
  18929. The @kbd{a v} (@code{calc-alg-evaluate}) command performs the normal
  18930. default simplifications on a formula; for example, @samp{a - -b} is
  18931. changed to @samp{a + b}. These simplifications are normally done
  18932. automatically on all Calc results, so this command is useful only if
  18933. you have turned default simplifications off with an @kbd{m O}
  18934. command. @xref{Simplification Modes}.
  18935. It is often more convenient to type @kbd{=}, which is like @kbd{a v}
  18936. but which also substitutes stored values for variables in the formula.
  18937. Use @kbd{a v} if you want the variables to ignore their stored values.
  18938. If you give a numeric prefix argument of 2 to @kbd{a v}, it simplifies
  18939. using Calc's algebraic simplifications; @pxref{Simplifying Formulas}.
  18940. If you give a numeric prefix of 3 or more, it uses Extended
  18941. Simplification mode (@kbd{a e}).
  18942. If you give a negative prefix argument @mathit{-1}, @mathit{-2}, or @mathit{-3},
  18943. it simplifies in the corresponding mode but only works on the top-level
  18944. function call of the formula. For example, @samp{(2 + 3) * (2 + 3)} will
  18945. simplify to @samp{(2 + 3)^2}, without simplifying the sub-formulas
  18946. @samp{2 + 3}. As another example, typing @kbd{V R +} to sum the vector
  18947. @samp{[1, 2, 3, 4]} produces the formula @samp{reduce(add, [1, 2, 3, 4])}
  18948. in No-Simplify mode. Using @kbd{a v} will evaluate this all the way to
  18949. 10; using @kbd{C-u - a v} will evaluate it only to @samp{1 + 2 + 3 + 4}.
  18950. (@xref{Reducing and Mapping}.)
  18951. @tindex evalv
  18952. @tindex evalvn
  18953. The @kbd{=} command corresponds to the @code{evalv} function, and
  18954. the related @kbd{N} command, which is like @kbd{=} but temporarily
  18955. disables Symbolic mode (@kbd{m s}) during the evaluation, corresponds
  18956. to the @code{evalvn} function. (These commands interpret their prefix
  18957. arguments differently than @kbd{a v}; @kbd{=} treats the prefix as
  18958. the number of stack elements to evaluate at once, and @kbd{N} treats
  18959. it as a temporary different working precision.)
  18960. The @code{evalvn} function can take an alternate working precision
  18961. as an optional second argument. This argument can be either an
  18962. integer, to set the precision absolutely, or a vector containing
  18963. a single integer, to adjust the precision relative to the current
  18964. precision. Note that @code{evalvn} with a larger than current
  18965. precision will do the calculation at this higher precision, but the
  18966. result will as usual be rounded back down to the current precision
  18967. afterward. For example, @samp{evalvn(pi - 3.1415)} at a precision
  18968. of 12 will return @samp{9.265359e-5}; @samp{evalvn(pi - 3.1415, 30)}
  18969. will return @samp{9.26535897932e-5} (computing a 25-digit result which
  18970. is then rounded down to 12); and @samp{evalvn(pi - 3.1415, [-2])}
  18971. will return @samp{9.2654e-5}.
  18972. @kindex a "
  18973. @pindex calc-expand-formula
  18974. The @kbd{a "} (@code{calc-expand-formula}) command expands functions
  18975. into their defining formulas wherever possible. For example,
  18976. @samp{deg(x^2)} is changed to @samp{180 x^2 / pi}. Most functions,
  18977. like @code{sin} and @code{gcd}, are not defined by simple formulas
  18978. and so are unaffected by this command. One important class of
  18979. functions which @emph{can} be expanded is the user-defined functions
  18980. created by the @kbd{Z F} command. @xref{Algebraic Definitions}.
  18981. Other functions which @kbd{a "} can expand include the probability
  18982. distribution functions, most of the financial functions, and the
  18983. hyperbolic and inverse hyperbolic functions. A numeric prefix argument
  18984. affects @kbd{a "} in the same way as it does @kbd{a v}: A positive
  18985. argument expands all functions in the formula and then simplifies in
  18986. various ways; a negative argument expands and simplifies only the
  18987. top-level function call.
  18988. @kindex a M
  18989. @pindex calc-map-equation
  18990. @tindex mapeq
  18991. The @kbd{a M} (@code{calc-map-equation}) [@code{mapeq}] command applies
  18992. a given function or operator to one or more equations. It is analogous
  18993. to @kbd{V M}, which operates on vectors instead of equations.
  18994. @pxref{Reducing and Mapping}. For example, @kbd{a M S} changes
  18995. @samp{x = y+1} to @samp{sin(x) = sin(y+1)}, and @kbd{a M +} with
  18996. @samp{x = y+1} and @expr{6} on the stack produces @samp{x+6 = y+7}.
  18997. With two equations on the stack, @kbd{a M +} would add the lefthand
  18998. sides together and the righthand sides together to get the two
  18999. respective sides of a new equation.
  19000. Mapping also works on inequalities. Mapping two similar inequalities
  19001. produces another inequality of the same type. Mapping an inequality
  19002. with an equation produces an inequality of the same type. Mapping a
  19003. @samp{<=} with a @samp{<} or @samp{!=} (not-equal) produces a @samp{<}.
  19004. If inequalities with opposite direction (e.g., @samp{<} and @samp{>})
  19005. are mapped, the direction of the second inequality is reversed to
  19006. match the first: Using @kbd{a M +} on @samp{a < b} and @samp{a > 2}
  19007. reverses the latter to get @samp{2 < a}, which then allows the
  19008. combination @samp{a + 2 < b + a}, which the algebraic simplifications
  19009. can reduce to @samp{2 < b}.
  19010. Using @kbd{a M *}, @kbd{a M /}, @kbd{a M n}, or @kbd{a M &} to negate
  19011. or invert an inequality will reverse the direction of the inequality.
  19012. Other adjustments to inequalities are @emph{not} done automatically;
  19013. @kbd{a M S} will change @w{@samp{x < y}} to @samp{sin(x) < sin(y)} even
  19014. though this is not true for all values of the variables.
  19015. @kindex H a M
  19016. @tindex mapeqp
  19017. With the Hyperbolic flag, @kbd{H a M} [@code{mapeqp}] does a plain
  19018. mapping operation without reversing the direction of any inequalities.
  19019. Thus, @kbd{H a M &} would change @kbd{x > 2} to @kbd{1/x > 0.5}.
  19020. (This change is mathematically incorrect, but perhaps you were
  19021. fixing an inequality which was already incorrect.)
  19022. @kindex I a M
  19023. @tindex mapeqr
  19024. With the Inverse flag, @kbd{I a M} [@code{mapeqr}] always reverses
  19025. the direction of the inequality. You might use @kbd{I a M C} to
  19026. change @samp{x < y} to @samp{cos(x) > cos(y)} if you know you are
  19027. working with small positive angles.
  19028. @kindex a b
  19029. @pindex calc-substitute
  19030. @tindex subst
  19031. The @kbd{a b} (@code{calc-substitute}) [@code{subst}] command substitutes
  19032. all occurrences
  19033. of some variable or sub-expression of an expression with a new
  19034. sub-expression. For example, substituting @samp{sin(x)} with @samp{cos(y)}
  19035. in @samp{2 sin(x)^2 + x sin(x) + sin(2 x)} produces
  19036. @samp{2 cos(y)^2 + x cos(y) + @w{sin(2 x)}}.
  19037. Note that this is a purely structural substitution; the lone @samp{x} and
  19038. the @samp{sin(2 x)} stayed the same because they did not look like
  19039. @samp{sin(x)}. @xref{Rewrite Rules}, for a more general method for
  19040. doing substitutions.
  19041. The @kbd{a b} command normally prompts for two formulas, the old
  19042. one and the new one. If you enter a blank line for the first
  19043. prompt, all three arguments are taken from the stack (new, then old,
  19044. then target expression). If you type an old formula but then enter a
  19045. blank line for the new one, the new formula is taken from top-of-stack
  19046. and the target from second-to-top. If you answer both prompts, the
  19047. target is taken from top-of-stack as usual.
  19048. Note that @kbd{a b} has no understanding of commutativity or
  19049. associativity. The pattern @samp{x+y} will not match the formula
  19050. @samp{y+x}. Also, @samp{y+z} will not match inside the formula @samp{x+y+z}
  19051. because the @samp{+} operator is left-associative, so the ``deep
  19052. structure'' of that formula is @samp{(x+y) + z}. Use @kbd{d U}
  19053. (@code{calc-unformatted-language}) mode to see the true structure of
  19054. a formula. The rewrite rule mechanism, discussed later, does not have
  19055. these limitations.
  19056. As an algebraic function, @code{subst} takes three arguments:
  19057. Target expression, old, new. Note that @code{subst} is always
  19058. evaluated immediately, even if its arguments are variables, so if
  19059. you wish to put a call to @code{subst} onto the stack you must
  19060. turn the default simplifications off first (with @kbd{m O}).
  19061. @node Simplifying Formulas, Polynomials, Algebraic Manipulation, Algebra
  19062. @section Simplifying Formulas
  19063. @noindent
  19064. @kindex a s
  19065. @kindex I a s
  19066. @kindex H a s
  19067. @pindex calc-simplify
  19068. @tindex simplify
  19069. The sections below describe all the various kinds of
  19070. simplifications Calc provides in full detail. None of Calc's
  19071. simplification commands are designed to pull rabbits out of hats;
  19072. they simply apply certain specific rules to put formulas into
  19073. less redundant or more pleasing forms. Serious algebra in Calc
  19074. must be done manually, usually with a combination of selections
  19075. and rewrite rules. @xref{Rearranging with Selections}.
  19076. @xref{Rewrite Rules}.
  19077. @xref{Simplification Modes}, for commands to control what level of
  19078. simplification occurs automatically. Normally the algebraic
  19079. simplifications described below occur. If you have turned on a
  19080. simplification mode which does not do these algebraic simplifications,
  19081. you can still apply them to a formula with the @kbd{a s}
  19082. (@code{calc-simplify}) [@code{simplify}] command.
  19083. There are some simplifications that, while sometimes useful, are never
  19084. done automatically. For example, the @kbd{I} prefix can be given to
  19085. @kbd{a s}; the @kbd{I a s} command will change any trigonometric
  19086. function to the appropriate combination of @samp{sin}s and @samp{cos}s
  19087. before simplifying. This can be useful in simplifying even mildly
  19088. complicated trigonometric expressions. For example, while the algebraic
  19089. simplifications can reduce @samp{sin(x) csc(x)} to @samp{1}, they will not
  19090. simplify @samp{sin(x)^2 csc(x)}. The command @kbd{I a s} can be used to
  19091. simplify this latter expression; it will transform @samp{sin(x)^2
  19092. csc(x)} into @samp{sin(x)}. However, @kbd{I a s} will also perform
  19093. some ``simplifications'' which may not be desired; for example, it
  19094. will transform @samp{tan(x)^2} into @samp{sin(x)^2 / cos(x)^2}. The
  19095. Hyperbolic prefix @kbd{H} can be used similarly; the @kbd{H a s} will
  19096. replace any hyperbolic functions in the formula with the appropriate
  19097. combinations of @samp{sinh}s and @samp{cosh}s before simplifying.
  19098. @menu
  19099. * Basic Simplifications::
  19100. * Algebraic Simplifications::
  19101. * Unsafe Simplifications::
  19102. * Simplification of Units::
  19103. @end menu
  19104. @node Basic Simplifications, Algebraic Simplifications, Simplifying Formulas, Simplifying Formulas
  19105. @subsection Basic Simplifications
  19106. @noindent
  19107. @cindex Basic simplifications
  19108. This section describes basic simplifications which Calc performs in many
  19109. situations. For example, both binary simplifications and algebraic
  19110. simplifications begin by performing these basic simplifications. You
  19111. can type @kbd{m I} to restrict the simplifications done on the stack to
  19112. these simplifications.
  19113. The most basic simplification is the evaluation of functions.
  19114. For example, @expr{2 + 3} is evaluated to @expr{5}, and @expr{@tfn{sqrt}(9)}
  19115. is evaluated to @expr{3}. Evaluation does not occur if the arguments
  19116. to a function are somehow of the wrong type @expr{@tfn{tan}([2,3,4])}),
  19117. range (@expr{@tfn{tan}(90)}), or number (@expr{@tfn{tan}(3,5)}),
  19118. or if the function name is not recognized (@expr{@tfn{f}(5)}), or if
  19119. Symbolic mode (@pxref{Symbolic Mode}) prevents evaluation
  19120. (@expr{@tfn{sqrt}(2)}).
  19121. Calc simplifies (evaluates) the arguments to a function before it
  19122. simplifies the function itself. Thus @expr{@tfn{sqrt}(5+4)} is
  19123. simplified to @expr{@tfn{sqrt}(9)} before the @code{sqrt} function
  19124. itself is applied. There are very few exceptions to this rule:
  19125. @code{quote}, @code{lambda}, and @code{condition} (the @code{::}
  19126. operator) do not evaluate their arguments, @code{if} (the @code{? :}
  19127. operator) does not evaluate all of its arguments, and @code{evalto}
  19128. does not evaluate its lefthand argument.
  19129. Most commands apply at least these basic simplifications to all
  19130. arguments they take from the stack, perform a particular operation,
  19131. then simplify the result before pushing it back on the stack. In the
  19132. common special case of regular arithmetic commands like @kbd{+} and
  19133. @kbd{Q} [@code{sqrt}], the arguments are simply popped from the stack
  19134. and collected into a suitable function call, which is then simplified
  19135. (the arguments being simplified first as part of the process, as
  19136. described above).
  19137. Even the basic set of simplifications are too numerous to describe
  19138. completely here, but this section will describe the ones that apply to the
  19139. major arithmetic operators. This list will be rather technical in
  19140. nature, and will probably be interesting to you only if you are
  19141. a serious user of Calc's algebra facilities.
  19142. @tex
  19143. \bigskip
  19144. @end tex
  19145. As well as the simplifications described here, if you have stored
  19146. any rewrite rules in the variable @code{EvalRules} then these rules
  19147. will also be applied before any of the basic simplifications.
  19148. @xref{Automatic Rewrites}, for details.
  19149. @tex
  19150. \bigskip
  19151. @end tex
  19152. And now, on with the basic simplifications:
  19153. Arithmetic operators like @kbd{+} and @kbd{*} always take two
  19154. arguments in Calc's internal form. Sums and products of three or
  19155. more terms are arranged by the associative law of algebra into
  19156. a left-associative form for sums, @expr{((a + b) + c) + d}, and
  19157. (by default) a right-associative form for products,
  19158. @expr{a * (b * (c * d))}. Formulas like @expr{(a + b) + (c + d)} are
  19159. rearranged to left-associative form, though this rarely matters since
  19160. Calc's algebra commands are designed to hide the inner structure of sums
  19161. and products as much as possible. Sums and products in their proper
  19162. associative form will be written without parentheses in the examples
  19163. below.
  19164. Sums and products are @emph{not} rearranged according to the
  19165. commutative law (@expr{a + b} to @expr{b + a}) except in a few
  19166. special cases described below. Some algebra programs always
  19167. rearrange terms into a canonical order, which enables them to
  19168. see that @expr{a b + b a} can be simplified to @expr{2 a b}.
  19169. If you are using Basic Simplification mode, Calc assumes you have put
  19170. the terms into the order you want and generally leaves that order alone,
  19171. with the consequence that formulas like the above will only be
  19172. simplified if you explicitly give the @kbd{a s} command.
  19173. @xref{Algebraic Simplifications}.
  19174. Differences @expr{a - b} are treated like sums @expr{a + (-b)}
  19175. for purposes of simplification; one of the default simplifications
  19176. is to rewrite @expr{a + (-b)} or @expr{(-b) + a}, where @expr{-b}
  19177. represents a ``negative-looking'' term, into @expr{a - b} form.
  19178. ``Negative-looking'' means negative numbers, negated formulas like
  19179. @expr{-x}, and products or quotients in which either term is
  19180. negative-looking.
  19181. Other simplifications involving negation are @expr{-(-x)} to @expr{x};
  19182. @expr{-(a b)} or @expr{-(a/b)} where either @expr{a} or @expr{b} is
  19183. negative-looking, simplified by negating that term, or else where
  19184. @expr{a} or @expr{b} is any number, by negating that number;
  19185. @expr{-(a + b)} to @expr{-a - b}, and @expr{-(b - a)} to @expr{a - b}.
  19186. (This, and rewriting @expr{(-b) + a} to @expr{a - b}, are the only
  19187. cases where the order of terms in a sum is changed by the default
  19188. simplifications.)
  19189. The distributive law is used to simplify sums in some cases:
  19190. @expr{a x + b x} to @expr{(a + b) x}, where @expr{a} represents
  19191. a number or an implicit 1 or @mathit{-1} (as in @expr{x} or @expr{-x})
  19192. and similarly for @expr{b}. Use the @kbd{a c}, @w{@kbd{a f}}, or
  19193. @kbd{j M} commands to merge sums with non-numeric coefficients
  19194. using the distributive law.
  19195. The distributive law is only used for sums of two terms, or
  19196. for adjacent terms in a larger sum. Thus @expr{a + b + b + c}
  19197. is simplified to @expr{a + 2 b + c}, but @expr{a + b + c + b}
  19198. is not simplified. The reason is that comparing all terms of a
  19199. sum with one another would require time proportional to the
  19200. square of the number of terms; Calc omits potentially slow
  19201. operations like this in basic simplification mode.
  19202. Finally, @expr{a + 0} and @expr{0 + a} are simplified to @expr{a}.
  19203. A consequence of the above rules is that @expr{0 - a} is simplified
  19204. to @expr{-a}.
  19205. @tex
  19206. \bigskip
  19207. @end tex
  19208. The products @expr{1 a} and @expr{a 1} are simplified to @expr{a};
  19209. @expr{(-1) a} and @expr{a (-1)} are simplified to @expr{-a};
  19210. @expr{0 a} and @expr{a 0} are simplified to @expr{0}, except that
  19211. in Matrix mode where @expr{a} is not provably scalar the result
  19212. is the generic zero matrix @samp{idn(0)}, and that if @expr{a} is
  19213. infinite the result is @samp{nan}.
  19214. Also, @expr{(-a) b} and @expr{a (-b)} are simplified to @expr{-(a b)},
  19215. where this occurs for negated formulas but not for regular negative
  19216. numbers.
  19217. Products are commuted only to move numbers to the front:
  19218. @expr{a b 2} is commuted to @expr{2 a b}.
  19219. The product @expr{a (b + c)} is distributed over the sum only if
  19220. @expr{a} and at least one of @expr{b} and @expr{c} are numbers:
  19221. @expr{2 (x + 3)} goes to @expr{2 x + 6}. The formula
  19222. @expr{(-a) (b - c)}, where @expr{-a} is a negative number, is
  19223. rewritten to @expr{a (c - b)}.
  19224. The distributive law of products and powers is used for adjacent
  19225. terms of the product: @expr{x^a x^b} goes to
  19226. @texline @math{x^{a+b}}
  19227. @infoline @expr{x^(a+b)}
  19228. where @expr{a} is a number, or an implicit 1 (as in @expr{x}),
  19229. or the implicit one-half of @expr{@tfn{sqrt}(x)}, and similarly for
  19230. @expr{b}. The result is written using @samp{sqrt} or @samp{1/sqrt}
  19231. if the sum of the powers is @expr{1/2} or @expr{-1/2}, respectively.
  19232. If the sum of the powers is zero, the product is simplified to
  19233. @expr{1} or to @samp{idn(1)} if Matrix mode is enabled.
  19234. The product of a negative power times anything but another negative
  19235. power is changed to use division:
  19236. @texline @math{x^{-2} y}
  19237. @infoline @expr{x^(-2) y}
  19238. goes to @expr{y / x^2} unless Matrix mode is
  19239. in effect and neither @expr{x} nor @expr{y} are scalar (in which
  19240. case it is considered unsafe to rearrange the order of the terms).
  19241. Finally, @expr{a (b/c)} is rewritten to @expr{(a b)/c}, and also
  19242. @expr{(a/b) c} is changed to @expr{(a c)/b} unless in Matrix mode.
  19243. @tex
  19244. \bigskip
  19245. @end tex
  19246. Simplifications for quotients are analogous to those for products.
  19247. The quotient @expr{0 / x} is simplified to @expr{0}, with the same
  19248. exceptions that were noted for @expr{0 x}. Likewise, @expr{x / 1}
  19249. and @expr{x / (-1)} are simplified to @expr{x} and @expr{-x},
  19250. respectively.
  19251. The quotient @expr{x / 0} is left unsimplified or changed to an
  19252. infinite quantity, as directed by the current infinite mode.
  19253. @xref{Infinite Mode}.
  19254. The expression
  19255. @texline @math{a / b^{-c}}
  19256. @infoline @expr{a / b^(-c)}
  19257. is changed to @expr{a b^c}, where @expr{-c} is any negative-looking
  19258. power. Also, @expr{1 / b^c} is changed to
  19259. @texline @math{b^{-c}}
  19260. @infoline @expr{b^(-c)}
  19261. for any power @expr{c}.
  19262. Also, @expr{(-a) / b} and @expr{a / (-b)} go to @expr{-(a/b)};
  19263. @expr{(a/b) / c} goes to @expr{a / (b c)}; and @expr{a / (b/c)}
  19264. goes to @expr{(a c) / b} unless Matrix mode prevents this
  19265. rearrangement. Similarly, @expr{a / (b:c)} is simplified to
  19266. @expr{(c:b) a} for any fraction @expr{b:c}.
  19267. The distributive law is applied to @expr{(a + b) / c} only if
  19268. @expr{c} and at least one of @expr{a} and @expr{b} are numbers.
  19269. Quotients of powers and square roots are distributed just as
  19270. described for multiplication.
  19271. Quotients of products cancel only in the leading terms of the
  19272. numerator and denominator. In other words, @expr{a x b / a y b}
  19273. is canceled to @expr{x b / y b} but not to @expr{x / y}. Once
  19274. again this is because full cancellation can be slow; use @kbd{a s}
  19275. to cancel all terms of the quotient.
  19276. Quotients of negative-looking values are simplified according
  19277. to @expr{(-a) / (-b)} to @expr{a / b}, @expr{(-a) / (b - c)}
  19278. to @expr{a / (c - b)}, and @expr{(a - b) / (-c)} to @expr{(b - a) / c}.
  19279. @tex
  19280. \bigskip
  19281. @end tex
  19282. The formula @expr{x^0} is simplified to @expr{1}, or to @samp{idn(1)}
  19283. in Matrix mode. The formula @expr{0^x} is simplified to @expr{0}
  19284. unless @expr{x} is a negative number, complex number or zero.
  19285. If @expr{x} is negative, complex or @expr{0.0}, @expr{0^x} is an
  19286. infinity or an unsimplified formula according to the current infinite
  19287. mode. The expression @expr{0^0} is simplified to @expr{1}.
  19288. Powers of products or quotients @expr{(a b)^c}, @expr{(a/b)^c}
  19289. are distributed to @expr{a^c b^c}, @expr{a^c / b^c} only if @expr{c}
  19290. is an integer, or if either @expr{a} or @expr{b} are nonnegative
  19291. real numbers. Powers of powers @expr{(a^b)^c} are simplified to
  19292. @texline @math{a^{b c}}
  19293. @infoline @expr{a^(b c)}
  19294. only when @expr{c} is an integer and @expr{b c} also
  19295. evaluates to an integer. Without these restrictions these simplifications
  19296. would not be safe because of problems with principal values.
  19297. (In other words,
  19298. @texline @math{((-3)^{1/2})^2}
  19299. @infoline @expr{((-3)^1:2)^2}
  19300. is safe to simplify, but
  19301. @texline @math{((-3)^2)^{1/2}}
  19302. @infoline @expr{((-3)^2)^1:2}
  19303. is not.) @xref{Declarations}, for ways to inform Calc that your
  19304. variables satisfy these requirements.
  19305. As a special case of this rule, @expr{@tfn{sqrt}(x)^n} is simplified to
  19306. @texline @math{x^{n/2}}
  19307. @infoline @expr{x^(n/2)}
  19308. only for even integers @expr{n}.
  19309. If @expr{a} is known to be real, @expr{b} is an even integer, and
  19310. @expr{c} is a half- or quarter-integer, then @expr{(a^b)^c} is
  19311. simplified to @expr{@tfn{abs}(a^(b c))}.
  19312. Also, @expr{(-a)^b} is simplified to @expr{a^b} if @expr{b} is an
  19313. even integer, or to @expr{-(a^b)} if @expr{b} is an odd integer,
  19314. for any negative-looking expression @expr{-a}.
  19315. Square roots @expr{@tfn{sqrt}(x)} generally act like one-half powers
  19316. @texline @math{x^{1:2}}
  19317. @infoline @expr{x^1:2}
  19318. for the purposes of the above-listed simplifications.
  19319. Also, note that
  19320. @texline @math{1 / x^{1:2}}
  19321. @infoline @expr{1 / x^1:2}
  19322. is changed to
  19323. @texline @math{x^{-1:2}},
  19324. @infoline @expr{x^(-1:2)},
  19325. but @expr{1 / @tfn{sqrt}(x)} is left alone.
  19326. @tex
  19327. \bigskip
  19328. @end tex
  19329. Generic identity matrices (@pxref{Matrix Mode}) are simplified by the
  19330. following rules: @expr{@tfn{idn}(a) + b} to @expr{a + b} if @expr{b}
  19331. is provably scalar, or expanded out if @expr{b} is a matrix;
  19332. @expr{@tfn{idn}(a) + @tfn{idn}(b)} to @expr{@tfn{idn}(a + b)};
  19333. @expr{-@tfn{idn}(a)} to @expr{@tfn{idn}(-a)}; @expr{a @tfn{idn}(b)} to
  19334. @expr{@tfn{idn}(a b)} if @expr{a} is provably scalar, or to @expr{a b}
  19335. if @expr{a} is provably non-scalar; @expr{@tfn{idn}(a) @tfn{idn}(b)} to
  19336. @expr{@tfn{idn}(a b)}; analogous simplifications for quotients involving
  19337. @code{idn}; and @expr{@tfn{idn}(a)^n} to @expr{@tfn{idn}(a^n)} where
  19338. @expr{n} is an integer.
  19339. @tex
  19340. \bigskip
  19341. @end tex
  19342. The @code{floor} function and other integer truncation functions
  19343. vanish if the argument is provably integer-valued, so that
  19344. @expr{@tfn{floor}(@tfn{round}(x))} simplifies to @expr{@tfn{round}(x)}.
  19345. Also, combinations of @code{float}, @code{floor} and its friends,
  19346. and @code{ffloor} and its friends, are simplified in appropriate
  19347. ways. @xref{Integer Truncation}.
  19348. The expression @expr{@tfn{abs}(-x)} changes to @expr{@tfn{abs}(x)}.
  19349. The expression @expr{@tfn{abs}(@tfn{abs}(x))} changes to
  19350. @expr{@tfn{abs}(x)}; in fact, @expr{@tfn{abs}(x)} changes to @expr{x} or
  19351. @expr{-x} if @expr{x} is provably nonnegative or nonpositive
  19352. (@pxref{Declarations}).
  19353. While most functions do not recognize the variable @code{i} as an
  19354. imaginary number, the @code{arg} function does handle the two cases
  19355. @expr{@tfn{arg}(@tfn{i})} and @expr{@tfn{arg}(-@tfn{i})} just for convenience.
  19356. The expression @expr{@tfn{conj}(@tfn{conj}(x))} simplifies to @expr{x}.
  19357. Various other expressions involving @code{conj}, @code{re}, and
  19358. @code{im} are simplified, especially if some of the arguments are
  19359. provably real or involve the constant @code{i}. For example,
  19360. @expr{@tfn{conj}(a + b i)} is changed to
  19361. @expr{@tfn{conj}(a) - @tfn{conj}(b) i}, or to @expr{a - b i} if @expr{a}
  19362. and @expr{b} are known to be real.
  19363. Functions like @code{sin} and @code{arctan} generally don't have
  19364. any default simplifications beyond simply evaluating the functions
  19365. for suitable numeric arguments and infinity. The algebraic
  19366. simplifications described in the next section do provide some
  19367. simplifications for these functions, though.
  19368. One important simplification that does occur is that
  19369. @expr{@tfn{ln}(@tfn{e})} is simplified to 1, and @expr{@tfn{ln}(@tfn{e}^x)} is
  19370. simplified to @expr{x} for any @expr{x}. This occurs even if you have
  19371. stored a different value in the Calc variable @samp{e}; but this would
  19372. be a bad idea in any case if you were also using natural logarithms!
  19373. Among the logical functions, @tfn{!(@var{a} <= @var{b})} changes to
  19374. @tfn{@var{a} > @var{b}} and so on. Equations and inequalities where both sides
  19375. are either negative-looking or zero are simplified by negating both sides
  19376. and reversing the inequality. While it might seem reasonable to simplify
  19377. @expr{!!x} to @expr{x}, this would not be valid in general because
  19378. @expr{!!2} is 1, not 2.
  19379. Most other Calc functions have few if any basic simplifications
  19380. defined, aside of course from evaluation when the arguments are
  19381. suitable numbers.
  19382. @node Algebraic Simplifications, Unsafe Simplifications, Basic Simplifications, Simplifying Formulas
  19383. @subsection Algebraic Simplifications
  19384. @noindent
  19385. @cindex Algebraic simplifications
  19386. @kindex a s
  19387. @kindex m A
  19388. This section describes all simplifications that are performed by
  19389. the algebraic simplification mode, which is the default simplification
  19390. mode. If you have switched to a different simplification mode, you can
  19391. switch back with the @kbd{m A} command. Even in other simplification
  19392. modes, the @kbd{a s} command will use these algebraic simplifications to
  19393. simplify the formula.
  19394. There is a variable, @code{AlgSimpRules}, in which you can put rewrites
  19395. to be applied. Its use is analogous to @code{EvalRules},
  19396. but without the special restrictions. Basically, the simplifier does
  19397. @samp{@w{a r} AlgSimpRules} with an infinite repeat count on the whole
  19398. expression being simplified, then it traverses the expression applying
  19399. the built-in rules described below. If the result is different from
  19400. the original expression, the process repeats with the basic
  19401. simplifications (including @code{EvalRules}), then @code{AlgSimpRules},
  19402. then the built-in simplifications, and so on.
  19403. @tex
  19404. \bigskip
  19405. @end tex
  19406. Sums are simplified in two ways. Constant terms are commuted to the
  19407. end of the sum, so that @expr{a + 2 + b} changes to @expr{a + b + 2}.
  19408. The only exception is that a constant will not be commuted away
  19409. from the first position of a difference, i.e., @expr{2 - x} is not
  19410. commuted to @expr{-x + 2}.
  19411. Also, terms of sums are combined by the distributive law, as in
  19412. @expr{x + y + 2 x} to @expr{y + 3 x}. This always occurs for
  19413. adjacent terms, but Calc's algebraic simplifications compare all pairs
  19414. of terms including non-adjacent ones.
  19415. @tex
  19416. \bigskip
  19417. @end tex
  19418. Products are sorted into a canonical order using the commutative
  19419. law. For example, @expr{b c a} is commuted to @expr{a b c}.
  19420. This allows easier comparison of products; for example, the basic
  19421. simplifications will not change @expr{x y + y x} to @expr{2 x y},
  19422. but the algebraic simplifications; it first rewrites the sum to
  19423. @expr{x y + x y} which can then be recognized as a sum of identical
  19424. terms.
  19425. The canonical ordering used to sort terms of products has the
  19426. property that real-valued numbers, interval forms and infinities
  19427. come first, and are sorted into increasing order. The @kbd{V S}
  19428. command uses the same ordering when sorting a vector.
  19429. Sorting of terms of products is inhibited when Matrix mode is
  19430. turned on; in this case, Calc will never exchange the order of
  19431. two terms unless it knows at least one of the terms is a scalar.
  19432. Products of powers are distributed by comparing all pairs of
  19433. terms, using the same method that the default simplifications
  19434. use for adjacent terms of products.
  19435. Even though sums are not sorted, the commutative law is still
  19436. taken into account when terms of a product are being compared.
  19437. Thus @expr{(x + y) (y + x)} will be simplified to @expr{(x + y)^2}.
  19438. A subtle point is that @expr{(x - y) (y - x)} will @emph{not}
  19439. be simplified to @expr{-(x - y)^2}; Calc does not notice that
  19440. one term can be written as a constant times the other, even if
  19441. that constant is @mathit{-1}.
  19442. A fraction times any expression, @expr{(a:b) x}, is changed to
  19443. a quotient involving integers: @expr{a x / b}. This is not
  19444. done for floating-point numbers like @expr{0.5}, however. This
  19445. is one reason why you may find it convenient to turn Fraction mode
  19446. on while doing algebra; @pxref{Fraction Mode}.
  19447. @tex
  19448. \bigskip
  19449. @end tex
  19450. Quotients are simplified by comparing all terms in the numerator
  19451. with all terms in the denominator for possible cancellation using
  19452. the distributive law. For example, @expr{a x^2 b / c x^3 d} will
  19453. cancel @expr{x^2} from the top and bottom to get @expr{a b / c x d}.
  19454. (The terms in the denominator will then be rearranged to @expr{c d x}
  19455. as described above.) If there is any common integer or fractional
  19456. factor in the numerator and denominator, it is canceled out;
  19457. for example, @expr{(4 x + 6) / 8 x} simplifies to @expr{(2 x + 3) / 4 x}.
  19458. Non-constant common factors are not found even by algebraic
  19459. simplifications. To cancel the factor @expr{a} in
  19460. @expr{(a x + a) / a^2} you could first use @kbd{j M} on the product
  19461. @expr{a x} to Merge the numerator to @expr{a (1+x)}, which can then be
  19462. simplified successfully.
  19463. @tex
  19464. \bigskip
  19465. @end tex
  19466. Integer powers of the variable @code{i} are simplified according
  19467. to the identity @expr{i^2 = -1}. If you store a new value other
  19468. than the complex number @expr{(0,1)} in @code{i}, this simplification
  19469. will no longer occur. This is not done by the basic
  19470. simplifications; in case someone (unwisely) wants to use the name
  19471. @code{i} for a variable unrelated to complex numbers, they can use
  19472. basic simplification mode.
  19473. Square roots of integer or rational arguments are simplified in
  19474. several ways. (Note that these will be left unevaluated only in
  19475. Symbolic mode.) First, square integer or rational factors are
  19476. pulled out so that @expr{@tfn{sqrt}(8)} is rewritten as
  19477. @texline @math{2\,@tfn{sqrt}(2)}.
  19478. @infoline @expr{2 sqrt(2)}.
  19479. Conceptually speaking this implies factoring the argument into primes
  19480. and moving pairs of primes out of the square root, but for reasons of
  19481. efficiency Calc only looks for primes up to 29.
  19482. Square roots in the denominator of a quotient are moved to the
  19483. numerator: @expr{1 / @tfn{sqrt}(3)} changes to @expr{@tfn{sqrt}(3) / 3}.
  19484. The same effect occurs for the square root of a fraction:
  19485. @expr{@tfn{sqrt}(2:3)} changes to @expr{@tfn{sqrt}(6) / 3}.
  19486. @tex
  19487. \bigskip
  19488. @end tex
  19489. The @code{%} (modulo) operator is simplified in several ways
  19490. when the modulus @expr{M} is a positive real number. First, if
  19491. the argument is of the form @expr{x + n} for some real number
  19492. @expr{n}, then @expr{n} is itself reduced modulo @expr{M}. For
  19493. example, @samp{(x - 23) % 10} is simplified to @samp{(x + 7) % 10}.
  19494. If the argument is multiplied by a constant, and this constant
  19495. has a common integer divisor with the modulus, then this factor is
  19496. canceled out. For example, @samp{12 x % 15} is changed to
  19497. @samp{3 (4 x % 5)} by factoring out 3. Also, @samp{(12 x + 1) % 15}
  19498. is changed to @samp{3 ((4 x + 1:3) % 5)}. While these forms may
  19499. not seem ``simpler,'' they allow Calc to discover useful information
  19500. about modulo forms in the presence of declarations.
  19501. If the modulus is 1, then Calc can use @code{int} declarations to
  19502. evaluate the expression. For example, the idiom @samp{x % 2} is
  19503. often used to check whether a number is odd or even. As described
  19504. above, @w{@samp{2 n % 2}} and @samp{(2 n + 1) % 2} are simplified to
  19505. @samp{2 (n % 1)} and @samp{2 ((n + 1:2) % 1)}, respectively; Calc
  19506. can simplify these to 0 and 1 (respectively) if @code{n} has been
  19507. declared to be an integer.
  19508. @tex
  19509. \bigskip
  19510. @end tex
  19511. Trigonometric functions are simplified in several ways. Whenever a
  19512. products of two trigonometric functions can be replaced by a single
  19513. function, the replacement is made; for example,
  19514. @expr{@tfn{tan}(x) @tfn{cos}(x)} is simplified to @expr{@tfn{sin}(x)}.
  19515. Reciprocals of trigonometric functions are replaced by their reciprocal
  19516. function; for example, @expr{1/@tfn{sec}(x)} is simplified to
  19517. @expr{@tfn{cos}(x)}. The corresponding simplifications for the
  19518. hyperbolic functions are also handled.
  19519. Trigonometric functions of their inverse functions are
  19520. simplified. The expression @expr{@tfn{sin}(@tfn{arcsin}(x))} is
  19521. simplified to @expr{x}, and similarly for @code{cos} and @code{tan}.
  19522. Trigonometric functions of inverses of different trigonometric
  19523. functions can also be simplified, as in @expr{@tfn{sin}(@tfn{arccos}(x))}
  19524. to @expr{@tfn{sqrt}(1 - x^2)}.
  19525. If the argument to @code{sin} is negative-looking, it is simplified to
  19526. @expr{-@tfn{sin}(x)}, and similarly for @code{cos} and @code{tan}.
  19527. Finally, certain special values of the argument are recognized;
  19528. @pxref{Trigonometric and Hyperbolic Functions}.
  19529. Hyperbolic functions of their inverses and of negative-looking
  19530. arguments are also handled, as are exponentials of inverse
  19531. hyperbolic functions.
  19532. No simplifications for inverse trigonometric and hyperbolic
  19533. functions are known, except for negative arguments of @code{arcsin},
  19534. @code{arctan}, @code{arcsinh}, and @code{arctanh}. Note that
  19535. @expr{@tfn{arcsin}(@tfn{sin}(x))} can @emph{not} safely change to
  19536. @expr{x}, since this only correct within an integer multiple of
  19537. @texline @math{2 \pi}
  19538. @infoline @expr{2 pi}
  19539. radians or 360 degrees. However, @expr{@tfn{arcsinh}(@tfn{sinh}(x))} is
  19540. simplified to @expr{x} if @expr{x} is known to be real.
  19541. Several simplifications that apply to logarithms and exponentials
  19542. are that @expr{@tfn{exp}(@tfn{ln}(x))},
  19543. @texline @tfn{e}@math{^{\ln(x)}},
  19544. @infoline @expr{e^@tfn{ln}(x)},
  19545. and
  19546. @texline @math{10^{{\rm log10}(x)}}
  19547. @infoline @expr{10^@tfn{log10}(x)}
  19548. all reduce to @expr{x}. Also, @expr{@tfn{ln}(@tfn{exp}(x))}, etc., can
  19549. reduce to @expr{x} if @expr{x} is provably real. The form
  19550. @expr{@tfn{exp}(x)^y} is simplified to @expr{@tfn{exp}(x y)}. If @expr{x}
  19551. is a suitable multiple of
  19552. @texline @math{\pi i}
  19553. @infoline @expr{pi i}
  19554. (as described above for the trigonometric functions), then
  19555. @expr{@tfn{exp}(x)} or @expr{e^x} will be expanded. Finally,
  19556. @expr{@tfn{ln}(x)} is simplified to a form involving @code{pi} and
  19557. @code{i} where @expr{x} is provably negative, positive imaginary, or
  19558. negative imaginary.
  19559. The error functions @code{erf} and @code{erfc} are simplified when
  19560. their arguments are negative-looking or are calls to the @code{conj}
  19561. function.
  19562. @tex
  19563. \bigskip
  19564. @end tex
  19565. Equations and inequalities are simplified by canceling factors
  19566. of products, quotients, or sums on both sides. Inequalities
  19567. change sign if a negative multiplicative factor is canceled.
  19568. Non-constant multiplicative factors as in @expr{a b = a c} are
  19569. canceled from equations only if they are provably nonzero (generally
  19570. because they were declared so; @pxref{Declarations}). Factors
  19571. are canceled from inequalities only if they are nonzero and their
  19572. sign is known.
  19573. Simplification also replaces an equation or inequality with
  19574. 1 or 0 (``true'' or ``false'') if it can through the use of
  19575. declarations. If @expr{x} is declared to be an integer greater
  19576. than 5, then @expr{x < 3}, @expr{x = 3}, and @expr{x = 7.5} are
  19577. all simplified to 0, but @expr{x > 3} is simplified to 1.
  19578. By a similar analysis, @expr{abs(x) >= 0} is simplified to 1,
  19579. as is @expr{x^2 >= 0} if @expr{x} is known to be real.
  19580. @node Unsafe Simplifications, Simplification of Units, Algebraic Simplifications, Simplifying Formulas
  19581. @subsection ``Unsafe'' Simplifications
  19582. @noindent
  19583. @cindex Unsafe simplifications
  19584. @cindex Extended simplification
  19585. @kindex a e
  19586. @kindex m E
  19587. @pindex calc-simplify-extended
  19588. @ignore
  19589. @mindex esimpl@idots
  19590. @end ignore
  19591. @tindex esimplify
  19592. Calc is capable of performing some simplifications which may sometimes
  19593. be desired but which are not ``safe'' in all cases. The @kbd{a e}
  19594. (@code{calc-simplify-extended}) [@code{esimplify}] command
  19595. applies the algebraic simplifications as well as these extended, or
  19596. ``unsafe'', simplifications. Use this only if you know the values in
  19597. your formula lie in the restricted ranges for which these
  19598. simplifications are valid. You can use Extended Simplification mode
  19599. (@kbd{m E}) to have these simplifications done automatically.
  19600. The symbolic integrator uses these extended simplifications; one effect
  19601. of this is that the integrator's results must be used with caution.
  19602. Where an integral table will often attach conditions like ``for positive
  19603. @expr{a} only,'' Calc (like most other symbolic integration programs)
  19604. will simply produce an unqualified result.
  19605. Because @kbd{a e}'s simplifications are unsafe, it is sometimes better
  19606. to type @kbd{C-u -3 a v}, which does extended simplification only
  19607. on the top level of the formula without affecting the sub-formulas.
  19608. In fact, @kbd{C-u -3 j v} allows you to target extended simplification
  19609. to any specific part of a formula.
  19610. The variable @code{ExtSimpRules} contains rewrites to be applied when
  19611. the extended simplifications are used. These are applied in addition to
  19612. @code{EvalRules} and @code{AlgSimpRules}. (The @kbd{a r AlgSimpRules}
  19613. step described above is simply followed by an @kbd{a r ExtSimpRules} step.)
  19614. Following is a complete list of the ``unsafe'' simplifications.
  19615. @tex
  19616. \bigskip
  19617. @end tex
  19618. Inverse trigonometric or hyperbolic functions, called with their
  19619. corresponding non-inverse functions as arguments, are simplified.
  19620. For example, @expr{@tfn{arcsin}(@tfn{sin}(x))} changes
  19621. to @expr{x}. Also, @expr{@tfn{arcsin}(@tfn{cos}(x))} and
  19622. @expr{@tfn{arccos}(@tfn{sin}(x))} both change to @expr{@tfn{pi}/2 - x}.
  19623. These simplifications are unsafe because they are valid only for
  19624. values of @expr{x} in a certain range; outside that range, values
  19625. are folded down to the 360-degree range that the inverse trigonometric
  19626. functions always produce.
  19627. Powers of powers @expr{(x^a)^b} are simplified to
  19628. @texline @math{x^{a b}}
  19629. @infoline @expr{x^(a b)}
  19630. for all @expr{a} and @expr{b}. These results will be valid only
  19631. in a restricted range of @expr{x}; for example, in
  19632. @texline @math{(x^2)^{1:2}}
  19633. @infoline @expr{(x^2)^1:2}
  19634. the powers cancel to get @expr{x}, which is valid for positive values
  19635. of @expr{x} but not for negative or complex values.
  19636. Similarly, @expr{@tfn{sqrt}(x^a)} and @expr{@tfn{sqrt}(x)^a} are both
  19637. simplified (possibly unsafely) to
  19638. @texline @math{x^{a/2}}.
  19639. @infoline @expr{x^(a/2)}.
  19640. Forms like @expr{@tfn{sqrt}(1 - sin(x)^2)} are simplified to, e.g.,
  19641. @expr{@tfn{cos}(x)}. Calc has identities of this sort for @code{sin},
  19642. @code{cos}, @code{tan}, @code{sinh}, and @code{cosh}.
  19643. Arguments of square roots are partially factored to look for
  19644. squared terms that can be extracted. For example,
  19645. @expr{@tfn{sqrt}(a^2 b^3 + a^3 b^2)} simplifies to
  19646. @expr{a b @tfn{sqrt}(a+b)}.
  19647. The simplifications of @expr{@tfn{ln}(@tfn{exp}(x))},
  19648. @expr{@tfn{ln}(@tfn{e}^x)}, and @expr{@tfn{log10}(10^x)} to @expr{x} are also
  19649. unsafe because of problems with principal values (although these
  19650. simplifications are safe if @expr{x} is known to be real).
  19651. Common factors are canceled from products on both sides of an
  19652. equation, even if those factors may be zero: @expr{a x / b x}
  19653. to @expr{a / b}. Such factors are never canceled from
  19654. inequalities: Even the extended simplifications are not bold enough to
  19655. reduce @expr{a x < b x} to @expr{a < b} (or @expr{a > b}, depending
  19656. on whether you believe @expr{x} is positive or negative).
  19657. The @kbd{a M /} command can be used to divide a factor out of
  19658. both sides of an inequality.
  19659. @node Simplification of Units, , Unsafe Simplifications, Simplifying Formulas
  19660. @subsection Simplification of Units
  19661. @noindent
  19662. The simplifications described in this section (as well as the algebraic
  19663. simplifications) are applied when units need to be simplified. They can
  19664. be applied using the @kbd{u s} (@code{calc-simplify-units}) command, or
  19665. will be done automatically in Units Simplification mode (@kbd{m U}).
  19666. @xref{Basic Operations on Units}.
  19667. The variable @code{UnitSimpRules} contains rewrites to be applied by
  19668. units simplifications. These are applied in addition to @code{EvalRules}
  19669. and @code{AlgSimpRules}.
  19670. Scalar mode is automatically put into effect when simplifying units.
  19671. @xref{Matrix Mode}.
  19672. Sums @expr{a + b} involving units are simplified by extracting the
  19673. units of @expr{a} as if by the @kbd{u x} command (call the result
  19674. @expr{u_a}), then simplifying the expression @expr{b / u_a}
  19675. using @kbd{u b} and @kbd{u s}. If the result has units then the sum
  19676. is inconsistent and is left alone. Otherwise, it is rewritten
  19677. in terms of the units @expr{u_a}.
  19678. If units auto-ranging mode is enabled, products or quotients in
  19679. which the first argument is a number which is out of range for the
  19680. leading unit are modified accordingly.
  19681. When canceling and combining units in products and quotients,
  19682. Calc accounts for unit names that differ only in the prefix letter.
  19683. For example, @samp{2 km m} is simplified to @samp{2000 m^2}.
  19684. However, compatible but different units like @code{ft} and @code{in}
  19685. are not combined in this way.
  19686. Quotients @expr{a / b} are simplified in three additional ways. First,
  19687. if @expr{b} is a number or a product beginning with a number, Calc
  19688. computes the reciprocal of this number and moves it to the numerator.
  19689. Second, for each pair of unit names from the numerator and denominator
  19690. of a quotient, if the units are compatible (e.g., they are both
  19691. units of area) then they are replaced by the ratio between those
  19692. units. For example, in @samp{3 s in N / kg cm} the units
  19693. @samp{in / cm} will be replaced by @expr{2.54}.
  19694. Third, if the units in the quotient exactly cancel out, so that
  19695. a @kbd{u b} command on the quotient would produce a dimensionless
  19696. number for an answer, then the quotient simplifies to that number.
  19697. For powers and square roots, the ``unsafe'' simplifications
  19698. @expr{(a b)^c} to @expr{a^c b^c}, @expr{(a/b)^c} to @expr{a^c / b^c},
  19699. and @expr{(a^b)^c} to
  19700. @texline @math{a^{b c}}
  19701. @infoline @expr{a^(b c)}
  19702. are done if the powers are real numbers. (These are safe in the context
  19703. of units because all numbers involved can reasonably be assumed to be
  19704. real.)
  19705. Also, if a unit name is raised to a fractional power, and the
  19706. base units in that unit name all occur to powers which are a
  19707. multiple of the denominator of the power, then the unit name
  19708. is expanded out into its base units, which can then be simplified
  19709. according to the previous paragraph. For example, @samp{acre^1.5}
  19710. is simplified by noting that @expr{1.5 = 3:2}, that @samp{acre}
  19711. is defined in terms of @samp{m^2}, and that the 2 in the power of
  19712. @code{m} is a multiple of 2 in @expr{3:2}. Thus, @code{acre^1.5} is
  19713. replaced by approximately
  19714. @texline @math{(4046 m^2)^{1.5}}
  19715. @infoline @expr{(4046 m^2)^1.5},
  19716. which is then changed to
  19717. @texline @math{4046^{1.5} \, (m^2)^{1.5}},
  19718. @infoline @expr{4046^1.5 (m^2)^1.5},
  19719. then to @expr{257440 m^3}.
  19720. The functions @code{float}, @code{frac}, @code{clean}, @code{abs},
  19721. as well as @code{floor} and the other integer truncation functions,
  19722. applied to unit names or products or quotients involving units, are
  19723. simplified. For example, @samp{round(1.6 in)} is changed to
  19724. @samp{round(1.6) round(in)}; the lefthand term evaluates to 2,
  19725. and the righthand term simplifies to @code{in}.
  19726. The functions @code{sin}, @code{cos}, and @code{tan} with arguments
  19727. that have angular units like @code{rad} or @code{arcmin} are
  19728. simplified by converting to base units (radians), then evaluating
  19729. with the angular mode temporarily set to radians.
  19730. @node Polynomials, Calculus, Simplifying Formulas, Algebra
  19731. @section Polynomials
  19732. A @dfn{polynomial} is a sum of terms which are coefficients times
  19733. various powers of a ``base'' variable. For example, @expr{2 x^2 + 3 x - 4}
  19734. is a polynomial in @expr{x}. Some formulas can be considered
  19735. polynomials in several different variables: @expr{1 + 2 x + 3 y + 4 x y^2}
  19736. is a polynomial in both @expr{x} and @expr{y}. Polynomial coefficients
  19737. are often numbers, but they may in general be any formulas not
  19738. involving the base variable.
  19739. @kindex a f
  19740. @pindex calc-factor
  19741. @tindex factor
  19742. The @kbd{a f} (@code{calc-factor}) [@code{factor}] command factors a
  19743. polynomial into a product of terms. For example, the polynomial
  19744. @expr{x^3 + 2 x^2 + x} is factored into @samp{x*(x+1)^2}. As another
  19745. example, @expr{a c + b d + b c + a d} is factored into the product
  19746. @expr{(a + b) (c + d)}.
  19747. Calc currently has three algorithms for factoring. Formulas which are
  19748. linear in several variables, such as the second example above, are
  19749. merged according to the distributive law. Formulas which are
  19750. polynomials in a single variable, with constant integer or fractional
  19751. coefficients, are factored into irreducible linear and/or quadratic
  19752. terms. The first example above factors into three linear terms
  19753. (@expr{x}, @expr{x+1}, and @expr{x+1} again). Finally, formulas
  19754. which do not fit the above criteria are handled by the algebraic
  19755. rewrite mechanism.
  19756. Calc's polynomial factorization algorithm works by using the general
  19757. root-finding command (@w{@kbd{a P}}) to solve for the roots of the
  19758. polynomial. It then looks for roots which are rational numbers
  19759. or complex-conjugate pairs, and converts these into linear and
  19760. quadratic terms, respectively. Because it uses floating-point
  19761. arithmetic, it may be unable to find terms that involve large
  19762. integers (whose number of digits approaches the current precision).
  19763. Also, irreducible factors of degree higher than quadratic are not
  19764. found, and polynomials in more than one variable are not treated.
  19765. (A more robust factorization algorithm may be included in a future
  19766. version of Calc.)
  19767. @vindex FactorRules
  19768. @ignore
  19769. @starindex
  19770. @end ignore
  19771. @tindex thecoefs
  19772. @ignore
  19773. @starindex
  19774. @end ignore
  19775. @ignore
  19776. @mindex @idots
  19777. @end ignore
  19778. @tindex thefactors
  19779. The rewrite-based factorization method uses rules stored in the variable
  19780. @code{FactorRules}. @xref{Rewrite Rules}, for a discussion of the
  19781. operation of rewrite rules. The default @code{FactorRules} are able
  19782. to factor quadratic forms symbolically into two linear terms,
  19783. @expr{(a x + b) (c x + d)}. You can edit these rules to include other
  19784. cases if you wish. To use the rules, Calc builds the formula
  19785. @samp{thecoefs(x, [a, b, c, ...])} where @code{x} is the polynomial
  19786. base variable and @code{a}, @code{b}, etc., are polynomial coefficients
  19787. (which may be numbers or formulas). The constant term is written first,
  19788. i.e., in the @code{a} position. When the rules complete, they should have
  19789. changed the formula into the form @samp{thefactors(x, [f1, f2, f3, ...])}
  19790. where each @code{fi} should be a factored term, e.g., @samp{x - ai}.
  19791. Calc then multiplies these terms together to get the complete
  19792. factored form of the polynomial. If the rules do not change the
  19793. @code{thecoefs} call to a @code{thefactors} call, @kbd{a f} leaves the
  19794. polynomial alone on the assumption that it is unfactorable. (Note that
  19795. the function names @code{thecoefs} and @code{thefactors} are used only
  19796. as placeholders; there are no actual Calc functions by those names.)
  19797. @kindex H a f
  19798. @tindex factors
  19799. The @kbd{H a f} [@code{factors}] command also factors a polynomial,
  19800. but it returns a list of factors instead of an expression which is the
  19801. product of the factors. Each factor is represented by a sub-vector
  19802. of the factor, and the power with which it appears. For example,
  19803. @expr{x^5 + x^4 - 33 x^3 + 63 x^2} factors to @expr{(x + 7) x^2 (x - 3)^2}
  19804. in @kbd{a f}, or to @expr{[ [x, 2], [x+7, 1], [x-3, 2] ]} in @kbd{H a f}.
  19805. If there is an overall numeric factor, it always comes first in the list.
  19806. The functions @code{factor} and @code{factors} allow a second argument
  19807. when written in algebraic form; @samp{factor(x,v)} factors @expr{x} with
  19808. respect to the specific variable @expr{v}. The default is to factor with
  19809. respect to all the variables that appear in @expr{x}.
  19810. @kindex a c
  19811. @pindex calc-collect
  19812. @tindex collect
  19813. The @kbd{a c} (@code{calc-collect}) [@code{collect}] command rearranges a
  19814. formula as a
  19815. polynomial in a given variable, ordered in decreasing powers of that
  19816. variable. For example, given @expr{1 + 2 x + 3 y + 4 x y^2} on
  19817. the stack, @kbd{a c x} would produce @expr{(2 + 4 y^2) x + (1 + 3 y)},
  19818. and @kbd{a c y} would produce @expr{(4 x) y^2 + 3 y + (1 + 2 x)}.
  19819. The polynomial will be expanded out using the distributive law as
  19820. necessary: Collecting @expr{x} in @expr{(x - 1)^3} produces
  19821. @expr{x^3 - 3 x^2 + 3 x - 1}. Terms not involving @expr{x} will
  19822. not be expanded.
  19823. The ``variable'' you specify at the prompt can actually be any
  19824. expression: @kbd{a c ln(x+1)} will collect together all terms multiplied
  19825. by @samp{ln(x+1)} or integer powers thereof. If @samp{x} also appears
  19826. in the formula in a context other than @samp{ln(x+1)}, @kbd{a c} will
  19827. treat those occurrences as unrelated to @samp{ln(x+1)}, i.e., as constants.
  19828. @kindex a x
  19829. @pindex calc-expand
  19830. @tindex expand
  19831. The @kbd{a x} (@code{calc-expand}) [@code{expand}] command expands an
  19832. expression by applying the distributive law everywhere. It applies to
  19833. products, quotients, and powers involving sums. By default, it fully
  19834. distributes all parts of the expression. With a numeric prefix argument,
  19835. the distributive law is applied only the specified number of times, then
  19836. the partially expanded expression is left on the stack.
  19837. The @kbd{a x} and @kbd{j D} commands are somewhat redundant. Use
  19838. @kbd{a x} if you want to expand all products of sums in your formula.
  19839. Use @kbd{j D} if you want to expand a particular specified term of
  19840. the formula. There is an exactly analogous correspondence between
  19841. @kbd{a f} and @kbd{j M}. (The @kbd{j D} and @kbd{j M} commands
  19842. also know many other kinds of expansions, such as
  19843. @samp{exp(a + b) = exp(a) exp(b)}, which @kbd{a x} and @kbd{a f}
  19844. do not do.)
  19845. Calc's automatic simplifications will sometimes reverse a partial
  19846. expansion. For example, the first step in expanding @expr{(x+1)^3} is
  19847. to write @expr{(x+1) (x+1)^2}. If @kbd{a x} stops there and tries
  19848. to put this formula onto the stack, though, Calc will automatically
  19849. simplify it back to @expr{(x+1)^3} form. The solution is to turn
  19850. simplification off first (@pxref{Simplification Modes}), or to run
  19851. @kbd{a x} without a numeric prefix argument so that it expands all
  19852. the way in one step.
  19853. @kindex a a
  19854. @pindex calc-apart
  19855. @tindex apart
  19856. The @kbd{a a} (@code{calc-apart}) [@code{apart}] command expands a
  19857. rational function by partial fractions. A rational function is the
  19858. quotient of two polynomials; @code{apart} pulls this apart into a
  19859. sum of rational functions with simple denominators. In algebraic
  19860. notation, the @code{apart} function allows a second argument that
  19861. specifies which variable to use as the ``base''; by default, Calc
  19862. chooses the base variable automatically.
  19863. @kindex a n
  19864. @pindex calc-normalize-rat
  19865. @tindex nrat
  19866. The @kbd{a n} (@code{calc-normalize-rat}) [@code{nrat}] command
  19867. attempts to arrange a formula into a quotient of two polynomials.
  19868. For example, given @expr{1 + (a + b/c) / d}, the result would be
  19869. @expr{(b + a c + c d) / c d}. The quotient is reduced, so that
  19870. @kbd{a n} will simplify @expr{(x^2 + 2x + 1) / (x^2 - 1)} by dividing
  19871. out the common factor @expr{x + 1}, yielding @expr{(x + 1) / (x - 1)}.
  19872. @kindex a \
  19873. @pindex calc-poly-div
  19874. @tindex pdiv
  19875. The @kbd{a \} (@code{calc-poly-div}) [@code{pdiv}] command divides
  19876. two polynomials @expr{u} and @expr{v}, yielding a new polynomial
  19877. @expr{q}. If several variables occur in the inputs, the inputs are
  19878. considered multivariate polynomials. (Calc divides by the variable
  19879. with the largest power in @expr{u} first, or, in the case of equal
  19880. powers, chooses the variables in alphabetical order.) For example,
  19881. dividing @expr{x^2 + 3 x + 2} by @expr{x + 2} yields @expr{x + 1}.
  19882. The remainder from the division, if any, is reported at the bottom
  19883. of the screen and is also placed in the Trail along with the quotient.
  19884. Using @code{pdiv} in algebraic notation, you can specify the particular
  19885. variable to be used as the base: @code{pdiv(@var{a},@var{b},@var{x})}.
  19886. If @code{pdiv} is given only two arguments (as is always the case with
  19887. the @kbd{a \} command), then it does a multivariate division as outlined
  19888. above.
  19889. @kindex a %
  19890. @pindex calc-poly-rem
  19891. @tindex prem
  19892. The @kbd{a %} (@code{calc-poly-rem}) [@code{prem}] command divides
  19893. two polynomials and keeps the remainder @expr{r}. The quotient
  19894. @expr{q} is discarded. For any formulas @expr{a} and @expr{b}, the
  19895. results of @kbd{a \} and @kbd{a %} satisfy @expr{a = q b + r}.
  19896. (This is analogous to plain @kbd{\} and @kbd{%}, which compute the
  19897. integer quotient and remainder from dividing two numbers.)
  19898. @kindex a /
  19899. @kindex H a /
  19900. @pindex calc-poly-div-rem
  19901. @tindex pdivrem
  19902. @tindex pdivide
  19903. The @kbd{a /} (@code{calc-poly-div-rem}) [@code{pdivrem}] command
  19904. divides two polynomials and reports both the quotient and the
  19905. remainder as a vector @expr{[q, r]}. The @kbd{H a /} [@code{pdivide}]
  19906. command divides two polynomials and constructs the formula
  19907. @expr{q + r/b} on the stack. (Naturally if the remainder is zero,
  19908. this will immediately simplify to @expr{q}.)
  19909. @kindex a g
  19910. @pindex calc-poly-gcd
  19911. @tindex pgcd
  19912. The @kbd{a g} (@code{calc-poly-gcd}) [@code{pgcd}] command computes
  19913. the greatest common divisor of two polynomials. (The GCD actually
  19914. is unique only to within a constant multiplier; Calc attempts to
  19915. choose a GCD which will be unsurprising.) For example, the @kbd{a n}
  19916. command uses @kbd{a g} to take the GCD of the numerator and denominator
  19917. of a quotient, then divides each by the result using @kbd{a \}. (The
  19918. definition of GCD ensures that this division can take place without
  19919. leaving a remainder.)
  19920. While the polynomials used in operations like @kbd{a /} and @kbd{a g}
  19921. often have integer coefficients, this is not required. Calc can also
  19922. deal with polynomials over the rationals or floating-point reals.
  19923. Polynomials with modulo-form coefficients are also useful in many
  19924. applications; if you enter @samp{(x^2 + 3 x - 1) mod 5}, Calc
  19925. automatically transforms this into a polynomial over the field of
  19926. integers mod 5: @samp{(1 mod 5) x^2 + (3 mod 5) x + (4 mod 5)}.
  19927. Congratulations and thanks go to Ove Ewerlid
  19928. (@code{ewerlid@@mizar.DoCS.UU.SE}), who contributed many of the
  19929. polynomial routines used in the above commands.
  19930. @xref{Decomposing Polynomials}, for several useful functions for
  19931. extracting the individual coefficients of a polynomial.
  19932. @node Calculus, Solving Equations, Polynomials, Algebra
  19933. @section Calculus
  19934. @noindent
  19935. The following calculus commands do not automatically simplify their
  19936. inputs or outputs using @code{calc-simplify}. You may find it helps
  19937. to do this by hand by typing @kbd{a s} or @kbd{a e}. It may also help
  19938. to use @kbd{a x} and/or @kbd{a c} to arrange a result in the most
  19939. readable way.
  19940. @menu
  19941. * Differentiation::
  19942. * Integration::
  19943. * Customizing the Integrator::
  19944. * Numerical Integration::
  19945. * Taylor Series::
  19946. @end menu
  19947. @node Differentiation, Integration, Calculus, Calculus
  19948. @subsection Differentiation
  19949. @noindent
  19950. @kindex a d
  19951. @kindex H a d
  19952. @pindex calc-derivative
  19953. @tindex deriv
  19954. @tindex tderiv
  19955. The @kbd{a d} (@code{calc-derivative}) [@code{deriv}] command computes
  19956. the derivative of the expression on the top of the stack with respect to
  19957. some variable, which it will prompt you to enter. Normally, variables
  19958. in the formula other than the specified differentiation variable are
  19959. considered constant, i.e., @samp{deriv(y,x)} is reduced to zero. With
  19960. the Hyperbolic flag, the @code{tderiv} (total derivative) operation is used
  19961. instead, in which derivatives of variables are not reduced to zero
  19962. unless those variables are known to be ``constant,'' i.e., independent
  19963. of any other variables. (The built-in special variables like @code{pi}
  19964. are considered constant, as are variables that have been declared
  19965. @code{const}; @pxref{Declarations}.)
  19966. With a numeric prefix argument @var{n}, this command computes the
  19967. @var{n}th derivative.
  19968. When working with trigonometric functions, it is best to switch to
  19969. Radians mode first (with @w{@kbd{m r}}). The derivative of @samp{sin(x)}
  19970. in degrees is @samp{(pi/180) cos(x)}, probably not the expected
  19971. answer!
  19972. If you use the @code{deriv} function directly in an algebraic formula,
  19973. you can write @samp{deriv(f,x,x0)} which represents the derivative
  19974. of @expr{f} with respect to @expr{x}, evaluated at the point
  19975. @texline @math{x=x_0}.
  19976. @infoline @expr{x=x0}.
  19977. If the formula being differentiated contains functions which Calc does
  19978. not know, the derivatives of those functions are produced by adding
  19979. primes (apostrophe characters). For example, @samp{deriv(f(2x), x)}
  19980. produces @samp{2 f'(2 x)}, where the function @code{f'} represents the
  19981. derivative of @code{f}.
  19982. For functions you have defined with the @kbd{Z F} command, Calc expands
  19983. the functions according to their defining formulas unless you have
  19984. also defined @code{f'} suitably. For example, suppose we define
  19985. @samp{sinc(x) = sin(x)/x} using @kbd{Z F}. If we then differentiate
  19986. the formula @samp{sinc(2 x)}, the formula will be expanded to
  19987. @samp{sin(2 x) / (2 x)} and differentiated. However, if we also
  19988. define @samp{sinc'(x) = dsinc(x)}, say, then Calc will write the
  19989. result as @samp{2 dsinc(2 x)}. @xref{Algebraic Definitions}.
  19990. For multi-argument functions @samp{f(x,y,z)}, the derivative with respect
  19991. to the first argument is written @samp{f'(x,y,z)}; derivatives with
  19992. respect to the other arguments are @samp{f'2(x,y,z)} and @samp{f'3(x,y,z)}.
  19993. Various higher-order derivatives can be formed in the obvious way, e.g.,
  19994. @samp{f'@var{}'(x)} (the second derivative of @code{f}) or
  19995. @samp{f'@var{}'2'3(x,y,z)} (@code{f} differentiated with respect to each
  19996. argument once).
  19997. @node Integration, Customizing the Integrator, Differentiation, Calculus
  19998. @subsection Integration
  19999. @noindent
  20000. @kindex a i
  20001. @pindex calc-integral
  20002. @tindex integ
  20003. The @kbd{a i} (@code{calc-integral}) [@code{integ}] command computes the
  20004. indefinite integral of the expression on the top of the stack with
  20005. respect to a prompted-for variable. The integrator is not guaranteed to
  20006. work for all integrable functions, but it is able to integrate several
  20007. large classes of formulas. In particular, any polynomial or rational
  20008. function (a polynomial divided by a polynomial) is acceptable.
  20009. (Rational functions don't have to be in explicit quotient form, however;
  20010. @texline @math{x/(1+x^{-2})}
  20011. @infoline @expr{x/(1+x^-2)}
  20012. is not strictly a quotient of polynomials, but it is equivalent to
  20013. @expr{x^3/(x^2+1)}, which is.) Also, square roots of terms involving
  20014. @expr{x} and @expr{x^2} may appear in rational functions being
  20015. integrated. Finally, rational functions involving trigonometric or
  20016. hyperbolic functions can be integrated.
  20017. With an argument (@kbd{C-u a i}), this command will compute the definite
  20018. integral of the expression on top of the stack. In this case, the
  20019. command will again prompt for an integration variable, then prompt for a
  20020. lower limit and an upper limit.
  20021. @ifnottex
  20022. If you use the @code{integ} function directly in an algebraic formula,
  20023. you can also write @samp{integ(f,x,v)} which expresses the resulting
  20024. indefinite integral in terms of variable @code{v} instead of @code{x}.
  20025. With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
  20026. integral from @code{a} to @code{b}.
  20027. @end ifnottex
  20028. @tex
  20029. If you use the @code{integ} function directly in an algebraic formula,
  20030. you can also write @samp{integ(f,x,v)} which expresses the resulting
  20031. indefinite integral in terms of variable @code{v} instead of @code{x}.
  20032. With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
  20033. integral $\int_a^b f(x) \, dx$.
  20034. @end tex
  20035. Please note that the current implementation of Calc's integrator sometimes
  20036. produces results that are significantly more complex than they need to
  20037. be. For example, the integral Calc finds for
  20038. @texline @math{1/(x+\sqrt{x^2+1})}
  20039. @infoline @expr{1/(x+sqrt(x^2+1))}
  20040. is several times more complicated than the answer Mathematica
  20041. returns for the same input, although the two forms are numerically
  20042. equivalent. Also, any indefinite integral should be considered to have
  20043. an arbitrary constant of integration added to it, although Calc does not
  20044. write an explicit constant of integration in its result. For example,
  20045. Calc's solution for
  20046. @texline @math{1/(1+\tan x)}
  20047. @infoline @expr{1/(1+tan(x))}
  20048. differs from the solution given in the @emph{CRC Math Tables} by a
  20049. constant factor of
  20050. @texline @math{\pi i / 2}
  20051. @infoline @expr{pi i / 2},
  20052. due to a different choice of constant of integration.
  20053. The Calculator remembers all the integrals it has done. If conditions
  20054. change in a way that would invalidate the old integrals, say, a switch
  20055. from Degrees to Radians mode, then they will be thrown out. If you
  20056. suspect this is not happening when it should, use the
  20057. @code{calc-flush-caches} command; @pxref{Caches}.
  20058. @vindex IntegLimit
  20059. Calc normally will pursue integration by substitution or integration by
  20060. parts up to 3 nested times before abandoning an approach as fruitless.
  20061. If the integrator is taking too long, you can lower this limit by storing
  20062. a number (like 2) in the variable @code{IntegLimit}. (The @kbd{s I}
  20063. command is a convenient way to edit @code{IntegLimit}.) If this variable
  20064. has no stored value or does not contain a nonnegative integer, a limit
  20065. of 3 is used. The lower this limit is, the greater the chance that Calc
  20066. will be unable to integrate a function it could otherwise handle. Raising
  20067. this limit allows the Calculator to solve more integrals, though the time
  20068. it takes may grow exponentially. You can monitor the integrator's actions
  20069. by creating an Emacs buffer called @file{*Trace*}. If such a buffer
  20070. exists, the @kbd{a i} command will write a log of its actions there.
  20071. If you want to manipulate integrals in a purely symbolic way, you can
  20072. set the integration nesting limit to 0 to prevent all but fast
  20073. table-lookup solutions of integrals. You might then wish to define
  20074. rewrite rules for integration by parts, various kinds of substitutions,
  20075. and so on. @xref{Rewrite Rules}.
  20076. @node Customizing the Integrator, Numerical Integration, Integration, Calculus
  20077. @subsection Customizing the Integrator
  20078. @noindent
  20079. @vindex IntegRules
  20080. Calc has two built-in rewrite rules called @code{IntegRules} and
  20081. @code{IntegAfterRules} which you can edit to define new integration
  20082. methods. @xref{Rewrite Rules}. At each step of the integration process,
  20083. Calc wraps the current integrand in a call to the fictitious function
  20084. @samp{integtry(@var{expr},@var{var})}, where @var{expr} is the
  20085. integrand and @var{var} is the integration variable. If your rules
  20086. rewrite this to be a plain formula (not a call to @code{integtry}), then
  20087. Calc will use this formula as the integral of @var{expr}. For example,
  20088. the rule @samp{integtry(mysin(x),x) := -mycos(x)} would define a rule to
  20089. integrate a function @code{mysin} that acts like the sine function.
  20090. Then, putting @samp{4 mysin(2y+1)} on the stack and typing @kbd{a i y}
  20091. will produce the integral @samp{-2 mycos(2y+1)}. Note that Calc has
  20092. automatically made various transformations on the integral to allow it
  20093. to use your rule; integral tables generally give rules for
  20094. @samp{mysin(a x + b)}, but you don't need to use this much generality
  20095. in your @code{IntegRules}.
  20096. @cindex Exponential integral Ei(x)
  20097. @ignore
  20098. @starindex
  20099. @end ignore
  20100. @tindex Ei
  20101. As a more serious example, the expression @samp{exp(x)/x} cannot be
  20102. integrated in terms of the standard functions, so the ``exponential
  20103. integral'' function
  20104. @texline @math{{\rm Ei}(x)}
  20105. @infoline @expr{Ei(x)}
  20106. was invented to describe it.
  20107. We can get Calc to do this integral in terms of a made-up @code{Ei}
  20108. function by adding the rule @samp{[integtry(exp(x)/x, x) := Ei(x)]}
  20109. to @code{IntegRules}. Now entering @samp{exp(2x)/x} on the stack
  20110. and typing @kbd{a i x} yields @samp{Ei(2 x)}. This new rule will
  20111. work with Calc's various built-in integration methods (such as
  20112. integration by substitution) to solve a variety of other problems
  20113. involving @code{Ei}: For example, now Calc will also be able to
  20114. integrate @samp{exp(exp(x))} and @samp{ln(ln(x))} (to get @samp{Ei(exp(x))}
  20115. and @samp{x ln(ln(x)) - Ei(ln(x))}, respectively).
  20116. Your rule may do further integration by calling @code{integ}. For
  20117. example, @samp{integtry(twice(u),x) := twice(integ(u))} allows Calc
  20118. to integrate @samp{twice(sin(x))} to get @samp{twice(-cos(x))}.
  20119. Note that @code{integ} was called with only one argument. This notation
  20120. is allowed only within @code{IntegRules}; it means ``integrate this
  20121. with respect to the same integration variable.'' If Calc is unable
  20122. to integrate @code{u}, the integration that invoked @code{IntegRules}
  20123. also fails. Thus integrating @samp{twice(f(x))} fails, returning the
  20124. unevaluated integral @samp{integ(twice(f(x)), x)}. It is still valid
  20125. to call @code{integ} with two or more arguments, however; in this case,
  20126. if @code{u} is not integrable, @code{twice} itself will still be
  20127. integrated: If the above rule is changed to @samp{... := twice(integ(u,x))},
  20128. then integrating @samp{twice(f(x))} will yield @samp{twice(integ(f(x),x))}.
  20129. If a rule instead produces the formula @samp{integsubst(@var{sexpr},
  20130. @var{svar})}, either replacing the top-level @code{integtry} call or
  20131. nested anywhere inside the expression, then Calc will apply the
  20132. substitution @samp{@var{u} = @var{sexpr}(@var{svar})} to try to
  20133. integrate the original @var{expr}. For example, the rule
  20134. @samp{sqrt(a) := integsubst(sqrt(x),x)} says that if Calc ever finds
  20135. a square root in the integrand, it should attempt the substitution
  20136. @samp{u = sqrt(x)}. (This particular rule is unnecessary because
  20137. Calc always tries ``obvious'' substitutions where @var{sexpr} actually
  20138. appears in the integrand.) The variable @var{svar} may be the same
  20139. as the @var{var} that appeared in the call to @code{integtry}, but
  20140. it need not be.
  20141. When integrating according to an @code{integsubst}, Calc uses the
  20142. equation solver to find the inverse of @var{sexpr} (if the integrand
  20143. refers to @var{var} anywhere except in subexpressions that exactly
  20144. match @var{sexpr}). It uses the differentiator to find the derivative
  20145. of @var{sexpr} and/or its inverse (it has two methods that use one
  20146. derivative or the other). You can also specify these items by adding
  20147. extra arguments to the @code{integsubst} your rules construct; the
  20148. general form is @samp{integsubst(@var{sexpr}, @var{svar}, @var{sinv},
  20149. @var{sprime})}, where @var{sinv} is the inverse of @var{sexpr} (still
  20150. written as a function of @var{svar}), and @var{sprime} is the
  20151. derivative of @var{sexpr} with respect to @var{svar}. If you don't
  20152. specify these things, and Calc is not able to work them out on its
  20153. own with the information it knows, then your substitution rule will
  20154. work only in very specific, simple cases.
  20155. Calc applies @code{IntegRules} as if by @kbd{C-u 1 a r IntegRules};
  20156. in other words, Calc stops rewriting as soon as any rule in your rule
  20157. set succeeds. (If it weren't for this, the @samp{integsubst(sqrt(x),x)}
  20158. example above would keep on adding layers of @code{integsubst} calls
  20159. forever!)
  20160. @vindex IntegSimpRules
  20161. Another set of rules, stored in @code{IntegSimpRules}, are applied
  20162. every time the integrator uses algebraic simplifications to simplify an
  20163. intermediate result. For example, putting the rule
  20164. @samp{twice(x) := 2 x} into @code{IntegSimpRules} would tell Calc to
  20165. convert the @code{twice} function into a form it knows whenever
  20166. integration is attempted.
  20167. One more way to influence the integrator is to define a function with
  20168. the @kbd{Z F} command (@pxref{Algebraic Definitions}). Calc's
  20169. integrator automatically expands such functions according to their
  20170. defining formulas, even if you originally asked for the function to
  20171. be left unevaluated for symbolic arguments. (Certain other Calc
  20172. systems, such as the differentiator and the equation solver, also
  20173. do this.)
  20174. @vindex IntegAfterRules
  20175. Sometimes Calc is able to find a solution to your integral, but it
  20176. expresses the result in a way that is unnecessarily complicated. If
  20177. this happens, you can either use @code{integsubst} as described
  20178. above to try to hint at a more direct path to the desired result, or
  20179. you can use @code{IntegAfterRules}. This is an extra rule set that
  20180. runs after the main integrator returns its result; basically, Calc does
  20181. an @kbd{a r IntegAfterRules} on the result before showing it to you.
  20182. (It also does algebraic simplifications, without @code{IntegSimpRules},
  20183. after that to further simplify the result.) For example, Calc's integrator
  20184. sometimes produces expressions of the form @samp{ln(1+x) - ln(1-x)};
  20185. the default @code{IntegAfterRules} rewrite this into the more readable
  20186. form @samp{2 arctanh(x)}. Note that, unlike @code{IntegRules},
  20187. @code{IntegSimpRules} and @code{IntegAfterRules} are applied any number
  20188. of times until no further changes are possible. Rewriting by
  20189. @code{IntegAfterRules} occurs only after the main integrator has
  20190. finished, not at every step as for @code{IntegRules} and
  20191. @code{IntegSimpRules}.
  20192. @node Numerical Integration, Taylor Series, Customizing the Integrator, Calculus
  20193. @subsection Numerical Integration
  20194. @noindent
  20195. @kindex a I
  20196. @pindex calc-num-integral
  20197. @tindex ninteg
  20198. If you want a purely numerical answer to an integration problem, you can
  20199. use the @kbd{a I} (@code{calc-num-integral}) [@code{ninteg}] command. This
  20200. command prompts for an integration variable, a lower limit, and an
  20201. upper limit. Except for the integration variable, all other variables
  20202. that appear in the integrand formula must have stored values. (A stored
  20203. value, if any, for the integration variable itself is ignored.)
  20204. Numerical integration works by evaluating your formula at many points in
  20205. the specified interval. Calc uses an ``open Romberg'' method; this means
  20206. that it does not evaluate the formula actually at the endpoints (so that
  20207. it is safe to integrate @samp{sin(x)/x} from zero, for example). Also,
  20208. the Romberg method works especially well when the function being
  20209. integrated is fairly smooth. If the function is not smooth, Calc will
  20210. have to evaluate it at quite a few points before it can accurately
  20211. determine the value of the integral.
  20212. Integration is much faster when the current precision is small. It is
  20213. best to set the precision to the smallest acceptable number of digits
  20214. before you use @kbd{a I}. If Calc appears to be taking too long, press
  20215. @kbd{C-g} to halt it and try a lower precision. If Calc still appears
  20216. to need hundreds of evaluations, check to make sure your function is
  20217. well-behaved in the specified interval.
  20218. It is possible for the lower integration limit to be @samp{-inf} (minus
  20219. infinity). Likewise, the upper limit may be plus infinity. Calc
  20220. internally transforms the integral into an equivalent one with finite
  20221. limits. However, integration to or across singularities is not supported:
  20222. The integral of @samp{1/sqrt(x)} from 0 to 1 exists (it can be found
  20223. by Calc's symbolic integrator, for example), but @kbd{a I} will fail
  20224. because the integrand goes to infinity at one of the endpoints.
  20225. @node Taylor Series, , Numerical Integration, Calculus
  20226. @subsection Taylor Series
  20227. @noindent
  20228. @kindex a t
  20229. @pindex calc-taylor
  20230. @tindex taylor
  20231. The @kbd{a t} (@code{calc-taylor}) [@code{taylor}] command computes a
  20232. power series expansion or Taylor series of a function. You specify the
  20233. variable and the desired number of terms. You may give an expression of
  20234. the form @samp{@var{var} = @var{a}} or @samp{@var{var} - @var{a}} instead
  20235. of just a variable to produce a Taylor expansion about the point @var{a}.
  20236. You may specify the number of terms with a numeric prefix argument;
  20237. otherwise the command will prompt you for the number of terms. Note that
  20238. many series expansions have coefficients of zero for some terms, so you
  20239. may appear to get fewer terms than you asked for.
  20240. If the @kbd{a i} command is unable to find a symbolic integral for a
  20241. function, you can get an approximation by integrating the function's
  20242. Taylor series.
  20243. @node Solving Equations, Numerical Solutions, Calculus, Algebra
  20244. @section Solving Equations
  20245. @noindent
  20246. @kindex a S
  20247. @pindex calc-solve-for
  20248. @tindex solve
  20249. @cindex Equations, solving
  20250. @cindex Solving equations
  20251. The @kbd{a S} (@code{calc-solve-for}) [@code{solve}] command rearranges
  20252. an equation to solve for a specific variable. An equation is an
  20253. expression of the form @expr{L = R}. For example, the command @kbd{a S x}
  20254. will rearrange @expr{y = 3x + 6} to the form, @expr{x = y/3 - 2}. If the
  20255. input is not an equation, it is treated like an equation of the
  20256. form @expr{X = 0}.
  20257. This command also works for inequalities, as in @expr{y < 3x + 6}.
  20258. Some inequalities cannot be solved where the analogous equation could
  20259. be; for example, solving
  20260. @texline @math{a < b \, c}
  20261. @infoline @expr{a < b c}
  20262. for @expr{b} is impossible
  20263. without knowing the sign of @expr{c}. In this case, @kbd{a S} will
  20264. produce the result
  20265. @texline @math{b \mathbin{\hbox{\code{!=}}} a/c}
  20266. @infoline @expr{b != a/c}
  20267. (using the not-equal-to operator) to signify that the direction of the
  20268. inequality is now unknown. The inequality
  20269. @texline @math{a \le b \, c}
  20270. @infoline @expr{a <= b c}
  20271. is not even partially solved. @xref{Declarations}, for a way to tell
  20272. Calc that the signs of the variables in a formula are in fact known.
  20273. Two useful commands for working with the result of @kbd{a S} are
  20274. @kbd{a .} (@pxref{Logical Operations}), which converts @expr{x = y/3 - 2}
  20275. to @expr{y/3 - 2}, and @kbd{s l} (@pxref{Let Command}) which evaluates
  20276. another formula with @expr{x} set equal to @expr{y/3 - 2}.
  20277. @menu
  20278. * Multiple Solutions::
  20279. * Solving Systems of Equations::
  20280. * Decomposing Polynomials::
  20281. @end menu
  20282. @node Multiple Solutions, Solving Systems of Equations, Solving Equations, Solving Equations
  20283. @subsection Multiple Solutions
  20284. @noindent
  20285. @kindex H a S
  20286. @tindex fsolve
  20287. Some equations have more than one solution. The Hyperbolic flag
  20288. (@code{H a S}) [@code{fsolve}] tells the solver to report the fully
  20289. general family of solutions. It will invent variables @code{n1},
  20290. @code{n2}, @dots{}, which represent independent arbitrary integers, and
  20291. @code{s1}, @code{s2}, @dots{}, which represent independent arbitrary
  20292. signs (either @mathit{+1} or @mathit{-1}). If you don't use the Hyperbolic
  20293. flag, Calc will use zero in place of all arbitrary integers, and plus
  20294. one in place of all arbitrary signs. Note that variables like @code{n1}
  20295. and @code{s1} are not given any special interpretation in Calc except by
  20296. the equation solver itself. As usual, you can use the @w{@kbd{s l}}
  20297. (@code{calc-let}) command to obtain solutions for various actual values
  20298. of these variables.
  20299. For example, @kbd{' x^2 = y @key{RET} H a S x @key{RET}} solves to
  20300. get @samp{x = s1 sqrt(y)}, indicating that the two solutions to the
  20301. equation are @samp{sqrt(y)} and @samp{-sqrt(y)}. Another way to
  20302. think about it is that the square-root operation is really a
  20303. two-valued function; since every Calc function must return a
  20304. single result, @code{sqrt} chooses to return the positive result.
  20305. Then @kbd{H a S} doctors this result using @code{s1} to indicate
  20306. the full set of possible values of the mathematical square-root.
  20307. There is a similar phenomenon going the other direction: Suppose
  20308. we solve @samp{sqrt(y) = x} for @code{y}. Calc squares both sides
  20309. to get @samp{y = x^2}. This is correct, except that it introduces
  20310. some dubious solutions. Consider solving @samp{sqrt(y) = -3}:
  20311. Calc will report @expr{y = 9} as a valid solution, which is true
  20312. in the mathematical sense of square-root, but false (there is no
  20313. solution) for the actual Calc positive-valued @code{sqrt}. This
  20314. happens for both @kbd{a S} and @kbd{H a S}.
  20315. @cindex @code{GenCount} variable
  20316. @vindex GenCount
  20317. @ignore
  20318. @starindex
  20319. @end ignore
  20320. @tindex an
  20321. @ignore
  20322. @starindex
  20323. @end ignore
  20324. @tindex as
  20325. If you store a positive integer in the Calc variable @code{GenCount},
  20326. then Calc will generate formulas of the form @samp{as(@var{n})} for
  20327. arbitrary signs, and @samp{an(@var{n})} for arbitrary integers,
  20328. where @var{n} represents successive values taken by incrementing
  20329. @code{GenCount} by one. While the normal arbitrary sign and
  20330. integer symbols start over at @code{s1} and @code{n1} with each
  20331. new Calc command, the @code{GenCount} approach will give each
  20332. arbitrary value a name that is unique throughout the entire Calc
  20333. session. Also, the arbitrary values are function calls instead
  20334. of variables, which is advantageous in some cases. For example,
  20335. you can make a rewrite rule that recognizes all arbitrary signs
  20336. using a pattern like @samp{as(n)}. The @kbd{s l} command only works
  20337. on variables, but you can use the @kbd{a b} (@code{calc-substitute})
  20338. command to substitute actual values for function calls like @samp{as(3)}.
  20339. The @kbd{s G} (@code{calc-edit-GenCount}) command is a convenient
  20340. way to create or edit this variable. Press @kbd{C-c C-c} to finish.
  20341. If you have not stored a value in @code{GenCount}, or if the value
  20342. in that variable is not a positive integer, the regular
  20343. @code{s1}/@code{n1} notation is used.
  20344. @kindex I a S
  20345. @kindex H I a S
  20346. @tindex finv
  20347. @tindex ffinv
  20348. With the Inverse flag, @kbd{I a S} [@code{finv}] treats the expression
  20349. on top of the stack as a function of the specified variable and solves
  20350. to find the inverse function, written in terms of the same variable.
  20351. For example, @kbd{I a S x} inverts @expr{2x + 6} to @expr{x/2 - 3}.
  20352. You can use both Inverse and Hyperbolic [@code{ffinv}] to obtain a
  20353. fully general inverse, as described above.
  20354. @kindex a P
  20355. @pindex calc-poly-roots
  20356. @tindex roots
  20357. Some equations, specifically polynomials, have a known, finite number
  20358. of solutions. The @kbd{a P} (@code{calc-poly-roots}) [@code{roots}]
  20359. command uses @kbd{H a S} to solve an equation in general form, then, for
  20360. all arbitrary-sign variables like @code{s1}, and all arbitrary-integer
  20361. variables like @code{n1} for which @code{n1} only usefully varies over
  20362. a finite range, it expands these variables out to all their possible
  20363. values. The results are collected into a vector, which is returned.
  20364. For example, @samp{roots(x^4 = 1, x)} returns the four solutions
  20365. @samp{[1, -1, (0, 1), (0, -1)]}. Generally an @var{n}th degree
  20366. polynomial will always have @var{n} roots on the complex plane.
  20367. (If you have given a @code{real} declaration for the solution
  20368. variable, then only the real-valued solutions, if any, will be
  20369. reported; @pxref{Declarations}.)
  20370. Note that because @kbd{a P} uses @kbd{H a S}, it is able to deliver
  20371. symbolic solutions if the polynomial has symbolic coefficients. Also
  20372. note that Calc's solver is not able to get exact symbolic solutions
  20373. to all polynomials. Polynomials containing powers up to @expr{x^4}
  20374. can always be solved exactly; polynomials of higher degree sometimes
  20375. can be: @expr{x^6 + x^3 + 1} is converted to @expr{(x^3)^2 + (x^3) + 1},
  20376. which can be solved for @expr{x^3} using the quadratic equation, and then
  20377. for @expr{x} by taking cube roots. But in many cases, like
  20378. @expr{x^6 + x + 1}, Calc does not know how to rewrite the polynomial
  20379. into a form it can solve. The @kbd{a P} command can still deliver a
  20380. list of numerical roots, however, provided that Symbolic mode (@kbd{m s})
  20381. is not turned on. (If you work with Symbolic mode on, recall that the
  20382. @kbd{N} (@code{calc-eval-num}) key is a handy way to reevaluate the
  20383. formula on the stack with Symbolic mode temporarily off.) Naturally,
  20384. @kbd{a P} can only provide numerical roots if the polynomial coefficients
  20385. are all numbers (real or complex).
  20386. @node Solving Systems of Equations, Decomposing Polynomials, Multiple Solutions, Solving Equations
  20387. @subsection Solving Systems of Equations
  20388. @noindent
  20389. @cindex Systems of equations, symbolic
  20390. You can also use the commands described above to solve systems of
  20391. simultaneous equations. Just create a vector of equations, then
  20392. specify a vector of variables for which to solve. (You can omit
  20393. the surrounding brackets when entering the vector of variables
  20394. at the prompt.)
  20395. For example, putting @samp{[x + y = a, x - y = b]} on the stack
  20396. and typing @kbd{a S x,y @key{RET}} produces the vector of solutions
  20397. @samp{[x = a - (a-b)/2, y = (a-b)/2]}. The result vector will
  20398. have the same length as the variables vector, and the variables
  20399. will be listed in the same order there. Note that the solutions
  20400. are not always simplified as far as possible; the solution for
  20401. @expr{x} here could be improved by an application of the @kbd{a n}
  20402. command.
  20403. Calc's algorithm works by trying to eliminate one variable at a
  20404. time by solving one of the equations for that variable and then
  20405. substituting into the other equations. Calc will try all the
  20406. possibilities, but you can speed things up by noting that Calc
  20407. first tries to eliminate the first variable with the first
  20408. equation, then the second variable with the second equation,
  20409. and so on. It also helps to put the simpler (e.g., more linear)
  20410. equations toward the front of the list. Calc's algorithm will
  20411. solve any system of linear equations, and also many kinds of
  20412. nonlinear systems.
  20413. @ignore
  20414. @starindex
  20415. @end ignore
  20416. @tindex elim
  20417. Normally there will be as many variables as equations. If you
  20418. give fewer variables than equations (an ``over-determined'' system
  20419. of equations), Calc will find a partial solution. For example,
  20420. typing @kbd{a S y @key{RET}} with the above system of equations
  20421. would produce @samp{[y = a - x]}. There are now several ways to
  20422. express this solution in terms of the original variables; Calc uses
  20423. the first one that it finds. You can control the choice by adding
  20424. variable specifiers of the form @samp{elim(@var{v})} to the
  20425. variables list. This says that @var{v} should be eliminated from
  20426. the equations; the variable will not appear at all in the solution.
  20427. For example, typing @kbd{a S y,elim(x)} would yield
  20428. @samp{[y = a - (b+a)/2]}.
  20429. If the variables list contains only @code{elim} specifiers,
  20430. Calc simply eliminates those variables from the equations
  20431. and then returns the resulting set of equations. For example,
  20432. @kbd{a S elim(x)} produces @samp{[a - 2 y = b]}. Every variable
  20433. eliminated will reduce the number of equations in the system
  20434. by one.
  20435. Again, @kbd{a S} gives you one solution to the system of
  20436. equations. If there are several solutions, you can use @kbd{H a S}
  20437. to get a general family of solutions, or, if there is a finite
  20438. number of solutions, you can use @kbd{a P} to get a list. (In
  20439. the latter case, the result will take the form of a matrix where
  20440. the rows are different solutions and the columns correspond to the
  20441. variables you requested.)
  20442. Another way to deal with certain kinds of overdetermined systems of
  20443. equations is the @kbd{a F} command, which does least-squares fitting
  20444. to satisfy the equations. @xref{Curve Fitting}.
  20445. @node Decomposing Polynomials, , Solving Systems of Equations, Solving Equations
  20446. @subsection Decomposing Polynomials
  20447. @noindent
  20448. @ignore
  20449. @starindex
  20450. @end ignore
  20451. @tindex poly
  20452. The @code{poly} function takes a polynomial and a variable as
  20453. arguments, and returns a vector of polynomial coefficients (constant
  20454. coefficient first). For example, @samp{poly(x^3 + 2 x, x)} returns
  20455. @expr{[0, 2, 0, 1]}. If the input is not a polynomial in @expr{x},
  20456. the call to @code{poly} is left in symbolic form. If the input does
  20457. not involve the variable @expr{x}, the input is returned in a list
  20458. of length one, representing a polynomial with only a constant
  20459. coefficient. The call @samp{poly(x, x)} returns the vector @expr{[0, 1]}.
  20460. The last element of the returned vector is guaranteed to be nonzero;
  20461. note that @samp{poly(0, x)} returns the empty vector @expr{[]}.
  20462. Note also that @expr{x} may actually be any formula; for example,
  20463. @samp{poly(sin(x)^2 - sin(x) + 3, sin(x))} returns @expr{[3, -1, 1]}.
  20464. @cindex Coefficients of polynomial
  20465. @cindex Degree of polynomial
  20466. To get the @expr{x^k} coefficient of polynomial @expr{p}, use
  20467. @samp{poly(p, x)_(k+1)}. To get the degree of polynomial @expr{p},
  20468. use @samp{vlen(poly(p, x)) - 1}. For example, @samp{poly((x+1)^4, x)}
  20469. returns @samp{[1, 4, 6, 4, 1]}, so @samp{poly((x+1)^4, x)_(2+1)}
  20470. gives the @expr{x^2} coefficient of this polynomial, 6.
  20471. @ignore
  20472. @starindex
  20473. @end ignore
  20474. @tindex gpoly
  20475. One important feature of the solver is its ability to recognize
  20476. formulas which are ``essentially'' polynomials. This ability is
  20477. made available to the user through the @code{gpoly} function, which
  20478. is used just like @code{poly}: @samp{gpoly(@var{expr}, @var{var})}.
  20479. If @var{expr} is a polynomial in some term which includes @var{var}, then
  20480. this function will return a vector @samp{[@var{x}, @var{c}, @var{a}]}
  20481. where @var{x} is the term that depends on @var{var}, @var{c} is a
  20482. vector of polynomial coefficients (like the one returned by @code{poly}),
  20483. and @var{a} is a multiplier which is usually 1. Basically,
  20484. @samp{@var{expr} = @var{a}*(@var{c}_1 + @var{c}_2 @var{x} +
  20485. @var{c}_3 @var{x}^2 + ...)}. The last element of @var{c} is
  20486. guaranteed to be non-zero, and @var{c} will not equal @samp{[1]}
  20487. (i.e., the trivial decomposition @var{expr} = @var{x} is not
  20488. considered a polynomial). One side effect is that @samp{gpoly(x, x)}
  20489. and @samp{gpoly(6, x)}, both of which might be expected to recognize
  20490. their arguments as polynomials, will not because the decomposition
  20491. is considered trivial.
  20492. For example, @samp{gpoly((x-2)^2, x)} returns @samp{[x, [4, -4, 1], 1]},
  20493. since the expanded form of this polynomial is @expr{4 - 4 x + x^2}.
  20494. The term @var{x} may itself be a polynomial in @var{var}. This is
  20495. done to reduce the size of the @var{c} vector. For example,
  20496. @samp{gpoly(x^4 + x^2 - 1, x)} returns @samp{[x^2, [-1, 1, 1], 1]},
  20497. since a quadratic polynomial in @expr{x^2} is easier to solve than
  20498. a quartic polynomial in @expr{x}.
  20499. A few more examples of the kinds of polynomials @code{gpoly} can
  20500. discover:
  20501. @smallexample
  20502. sin(x) - 1 [sin(x), [-1, 1], 1]
  20503. x + 1/x - 1 [x, [1, -1, 1], 1/x]
  20504. x + 1/x [x^2, [1, 1], 1/x]
  20505. x^3 + 2 x [x^2, [2, 1], x]
  20506. x + x^2:3 + sqrt(x) [x^1:6, [1, 1, 0, 1], x^1:2]
  20507. x^(2a) + 2 x^a + 5 [x^a, [5, 2, 1], 1]
  20508. (exp(-x) + exp(x)) / 2 [e^(2 x), [0.5, 0.5], e^-x]
  20509. @end smallexample
  20510. The @code{poly} and @code{gpoly} functions accept a third integer argument
  20511. which specifies the largest degree of polynomial that is acceptable.
  20512. If this is @expr{n}, then only @var{c} vectors of length @expr{n+1}
  20513. or less will be returned. Otherwise, the @code{poly} or @code{gpoly}
  20514. call will remain in symbolic form. For example, the equation solver
  20515. can handle quartics and smaller polynomials, so it calls
  20516. @samp{gpoly(@var{expr}, @var{var}, 4)} to discover whether @var{expr}
  20517. can be treated by its linear, quadratic, cubic, or quartic formulas.
  20518. @ignore
  20519. @starindex
  20520. @end ignore
  20521. @tindex pdeg
  20522. The @code{pdeg} function computes the degree of a polynomial;
  20523. @samp{pdeg(p,x)} is the highest power of @code{x} that appears in
  20524. @code{p}. This is the same as @samp{vlen(poly(p,x))-1}, but is
  20525. much more efficient. If @code{p} is constant with respect to @code{x},
  20526. then @samp{pdeg(p,x) = 0}. If @code{p} is not a polynomial in @code{x}
  20527. (e.g., @samp{pdeg(2 cos(x), x)}, the function remains unevaluated.
  20528. It is possible to omit the second argument @code{x}, in which case
  20529. @samp{pdeg(p)} returns the highest total degree of any term of the
  20530. polynomial, counting all variables that appear in @code{p}. Note
  20531. that @code{pdeg(c) = pdeg(c,x) = 0} for any nonzero constant @code{c};
  20532. the degree of the constant zero is considered to be @code{-inf}
  20533. (minus infinity).
  20534. @ignore
  20535. @starindex
  20536. @end ignore
  20537. @tindex plead
  20538. The @code{plead} function finds the leading term of a polynomial.
  20539. Thus @samp{plead(p,x)} is equivalent to @samp{poly(p,x)_vlen(poly(p,x))},
  20540. though again more efficient. In particular, @samp{plead((2x+1)^10, x)}
  20541. returns 1024 without expanding out the list of coefficients. The
  20542. value of @code{plead(p,x)} will be zero only if @expr{p = 0}.
  20543. @ignore
  20544. @starindex
  20545. @end ignore
  20546. @tindex pcont
  20547. The @code{pcont} function finds the @dfn{content} of a polynomial. This
  20548. is the greatest common divisor of all the coefficients of the polynomial.
  20549. With two arguments, @code{pcont(p,x)} effectively uses @samp{poly(p,x)}
  20550. to get a list of coefficients, then uses @code{pgcd} (the polynomial
  20551. GCD function) to combine these into an answer. For example,
  20552. @samp{pcont(4 x y^2 + 6 x^2 y, x)} is @samp{2 y}. The content is
  20553. basically the ``biggest'' polynomial that can be divided into @code{p}
  20554. exactly. The sign of the content is the same as the sign of the leading
  20555. coefficient.
  20556. With only one argument, @samp{pcont(p)} computes the numerical
  20557. content of the polynomial, i.e., the @code{gcd} of the numerical
  20558. coefficients of all the terms in the formula. Note that @code{gcd}
  20559. is defined on rational numbers as well as integers; it computes
  20560. the @code{gcd} of the numerators and the @code{lcm} of the
  20561. denominators. Thus @samp{pcont(4:3 x y^2 + 6 x^2 y)} returns 2:3.
  20562. Dividing the polynomial by this number will clear all the
  20563. denominators, as well as dividing by any common content in the
  20564. numerators. The numerical content of a polynomial is negative only
  20565. if all the coefficients in the polynomial are negative.
  20566. @ignore
  20567. @starindex
  20568. @end ignore
  20569. @tindex pprim
  20570. The @code{pprim} function finds the @dfn{primitive part} of a
  20571. polynomial, which is simply the polynomial divided (using @code{pdiv}
  20572. if necessary) by its content. If the input polynomial has rational
  20573. coefficients, the result will have integer coefficients in simplest
  20574. terms.
  20575. @node Numerical Solutions, Curve Fitting, Solving Equations, Algebra
  20576. @section Numerical Solutions
  20577. @noindent
  20578. Not all equations can be solved symbolically. The commands in this
  20579. section use numerical algorithms that can find a solution to a specific
  20580. instance of an equation to any desired accuracy. Note that the
  20581. numerical commands are slower than their algebraic cousins; it is a
  20582. good idea to try @kbd{a S} before resorting to these commands.
  20583. (@xref{Curve Fitting}, for some other, more specialized, operations
  20584. on numerical data.)
  20585. @menu
  20586. * Root Finding::
  20587. * Minimization::
  20588. * Numerical Systems of Equations::
  20589. @end menu
  20590. @node Root Finding, Minimization, Numerical Solutions, Numerical Solutions
  20591. @subsection Root Finding
  20592. @noindent
  20593. @kindex a R
  20594. @pindex calc-find-root
  20595. @tindex root
  20596. @cindex Newton's method
  20597. @cindex Roots of equations
  20598. @cindex Numerical root-finding
  20599. The @kbd{a R} (@code{calc-find-root}) [@code{root}] command finds a
  20600. numerical solution (or @dfn{root}) of an equation. (This command treats
  20601. inequalities the same as equations. If the input is any other kind
  20602. of formula, it is interpreted as an equation of the form @expr{X = 0}.)
  20603. The @kbd{a R} command requires an initial guess on the top of the
  20604. stack, and a formula in the second-to-top position. It prompts for a
  20605. solution variable, which must appear in the formula. All other variables
  20606. that appear in the formula must have assigned values, i.e., when
  20607. a value is assigned to the solution variable and the formula is
  20608. evaluated with @kbd{=}, it should evaluate to a number. Any assigned
  20609. value for the solution variable itself is ignored and unaffected by
  20610. this command.
  20611. When the command completes, the initial guess is replaced on the stack
  20612. by a vector of two numbers: The value of the solution variable that
  20613. solves the equation, and the difference between the lefthand and
  20614. righthand sides of the equation at that value. Ordinarily, the second
  20615. number will be zero or very nearly zero. (Note that Calc uses a
  20616. slightly higher precision while finding the root, and thus the second
  20617. number may be slightly different from the value you would compute from
  20618. the equation yourself.)
  20619. The @kbd{v h} (@code{calc-head}) command is a handy way to extract
  20620. the first element of the result vector, discarding the error term.
  20621. The initial guess can be a real number, in which case Calc searches
  20622. for a real solution near that number, or a complex number, in which
  20623. case Calc searches the whole complex plane near that number for a
  20624. solution, or it can be an interval form which restricts the search
  20625. to real numbers inside that interval.
  20626. Calc tries to use @kbd{a d} to take the derivative of the equation.
  20627. If this succeeds, it uses Newton's method. If the equation is not
  20628. differentiable Calc uses a bisection method. (If Newton's method
  20629. appears to be going astray, Calc switches over to bisection if it
  20630. can, or otherwise gives up. In this case it may help to try again
  20631. with a slightly different initial guess.) If the initial guess is a
  20632. complex number, the function must be differentiable.
  20633. If the formula (or the difference between the sides of an equation)
  20634. is negative at one end of the interval you specify and positive at
  20635. the other end, the root finder is guaranteed to find a root.
  20636. Otherwise, Calc subdivides the interval into small parts looking for
  20637. positive and negative values to bracket the root. When your guess is
  20638. an interval, Calc will not look outside that interval for a root.
  20639. @kindex H a R
  20640. @tindex wroot
  20641. The @kbd{H a R} [@code{wroot}] command is similar to @kbd{a R}, except
  20642. that if the initial guess is an interval for which the function has
  20643. the same sign at both ends, then rather than subdividing the interval
  20644. Calc attempts to widen it to enclose a root. Use this mode if
  20645. you are not sure if the function has a root in your interval.
  20646. If the function is not differentiable, and you give a simple number
  20647. instead of an interval as your initial guess, Calc uses this widening
  20648. process even if you did not type the Hyperbolic flag. (If the function
  20649. @emph{is} differentiable, Calc uses Newton's method which does not
  20650. require a bounding interval in order to work.)
  20651. If Calc leaves the @code{root} or @code{wroot} function in symbolic
  20652. form on the stack, it will normally display an explanation for why
  20653. no root was found. If you miss this explanation, press @kbd{w}
  20654. (@code{calc-why}) to get it back.
  20655. @node Minimization, Numerical Systems of Equations, Root Finding, Numerical Solutions
  20656. @subsection Minimization
  20657. @noindent
  20658. @kindex a N
  20659. @kindex H a N
  20660. @kindex a X
  20661. @kindex H a X
  20662. @pindex calc-find-minimum
  20663. @pindex calc-find-maximum
  20664. @tindex minimize
  20665. @tindex maximize
  20666. @cindex Minimization, numerical
  20667. The @kbd{a N} (@code{calc-find-minimum}) [@code{minimize}] command
  20668. finds a minimum value for a formula. It is very similar in operation
  20669. to @kbd{a R} (@code{calc-find-root}): You give the formula and an initial
  20670. guess on the stack, and are prompted for the name of a variable. The guess
  20671. may be either a number near the desired minimum, or an interval enclosing
  20672. the desired minimum. The function returns a vector containing the
  20673. value of the variable which minimizes the formula's value, along
  20674. with the minimum value itself.
  20675. Note that this command looks for a @emph{local} minimum. Many functions
  20676. have more than one minimum; some, like
  20677. @texline @math{x \sin x},
  20678. @infoline @expr{x sin(x)},
  20679. have infinitely many. In fact, there is no easy way to define the
  20680. ``global'' minimum of
  20681. @texline @math{x \sin x}
  20682. @infoline @expr{x sin(x)}
  20683. but Calc can still locate any particular local minimum
  20684. for you. Calc basically goes downhill from the initial guess until it
  20685. finds a point at which the function's value is greater both to the left
  20686. and to the right. Calc does not use derivatives when minimizing a function.
  20687. If your initial guess is an interval and it looks like the minimum
  20688. occurs at one or the other endpoint of the interval, Calc will return
  20689. that endpoint only if that endpoint is closed; thus, minimizing @expr{17 x}
  20690. over @expr{[2..3]} will return @expr{[2, 38]}, but minimizing over
  20691. @expr{(2..3]} would report no minimum found. In general, you should
  20692. use closed intervals to find literally the minimum value in that
  20693. range of @expr{x}, or open intervals to find the local minimum, if
  20694. any, that happens to lie in that range.
  20695. Most functions are smooth and flat near their minimum values. Because
  20696. of this flatness, if the current precision is, say, 12 digits, the
  20697. variable can only be determined meaningfully to about six digits. Thus
  20698. you should set the precision to twice as many digits as you need in your
  20699. answer.
  20700. @ignore
  20701. @mindex wmin@idots
  20702. @end ignore
  20703. @tindex wminimize
  20704. @ignore
  20705. @mindex wmax@idots
  20706. @end ignore
  20707. @tindex wmaximize
  20708. The @kbd{H a N} [@code{wminimize}] command, analogously to @kbd{H a R},
  20709. expands the guess interval to enclose a minimum rather than requiring
  20710. that the minimum lie inside the interval you supply.
  20711. The @kbd{a X} (@code{calc-find-maximum}) [@code{maximize}] and
  20712. @kbd{H a X} [@code{wmaximize}] commands effectively minimize the
  20713. negative of the formula you supply.
  20714. The formula must evaluate to a real number at all points inside the
  20715. interval (or near the initial guess if the guess is a number). If
  20716. the initial guess is a complex number the variable will be minimized
  20717. over the complex numbers; if it is real or an interval it will
  20718. be minimized over the reals.
  20719. @node Numerical Systems of Equations, , Minimization, Numerical Solutions
  20720. @subsection Systems of Equations
  20721. @noindent
  20722. @cindex Systems of equations, numerical
  20723. The @kbd{a R} command can also solve systems of equations. In this
  20724. case, the equation should instead be a vector of equations, the
  20725. guess should instead be a vector of numbers (intervals are not
  20726. supported), and the variable should be a vector of variables. You
  20727. can omit the brackets while entering the list of variables. Each
  20728. equation must be differentiable by each variable for this mode to
  20729. work. The result will be a vector of two vectors: The variable
  20730. values that solved the system of equations, and the differences
  20731. between the sides of the equations with those variable values.
  20732. There must be the same number of equations as variables. Since
  20733. only plain numbers are allowed as guesses, the Hyperbolic flag has
  20734. no effect when solving a system of equations.
  20735. It is also possible to minimize over many variables with @kbd{a N}
  20736. (or maximize with @kbd{a X}). Once again the variable name should
  20737. be replaced by a vector of variables, and the initial guess should
  20738. be an equal-sized vector of initial guesses. But, unlike the case of
  20739. multidimensional @kbd{a R}, the formula being minimized should
  20740. still be a single formula, @emph{not} a vector. Beware that
  20741. multidimensional minimization is currently @emph{very} slow.
  20742. @node Curve Fitting, Summations, Numerical Solutions, Algebra
  20743. @section Curve Fitting
  20744. @noindent
  20745. The @kbd{a F} command fits a set of data to a @dfn{model formula},
  20746. such as @expr{y = m x + b} where @expr{m} and @expr{b} are parameters
  20747. to be determined. For a typical set of measured data there will be
  20748. no single @expr{m} and @expr{b} that exactly fit the data; in this
  20749. case, Calc chooses values of the parameters that provide the closest
  20750. possible fit. The model formula can be entered in various ways after
  20751. the key sequence @kbd{a F} is pressed.
  20752. If the letter @kbd{P} is pressed after @kbd{a F} but before the model
  20753. description is entered, the data as well as the model formula will be
  20754. plotted after the formula is determined. This will be indicated by a
  20755. ``P'' in the minibuffer after the help message.
  20756. @menu
  20757. * Linear Fits::
  20758. * Polynomial and Multilinear Fits::
  20759. * Error Estimates for Fits::
  20760. * Standard Nonlinear Models::
  20761. * Curve Fitting Details::
  20762. * Interpolation::
  20763. @end menu
  20764. @node Linear Fits, Polynomial and Multilinear Fits, Curve Fitting, Curve Fitting
  20765. @subsection Linear Fits
  20766. @noindent
  20767. @kindex a F
  20768. @pindex calc-curve-fit
  20769. @tindex fit
  20770. @cindex Linear regression
  20771. @cindex Least-squares fits
  20772. The @kbd{a F} (@code{calc-curve-fit}) [@code{fit}] command attempts
  20773. to fit a set of data (@expr{x} and @expr{y} vectors of numbers) to a
  20774. straight line, polynomial, or other function of @expr{x}. For the
  20775. moment we will consider only the case of fitting to a line, and we
  20776. will ignore the issue of whether or not the model was in fact a good
  20777. fit for the data.
  20778. In a standard linear least-squares fit, we have a set of @expr{(x,y)}
  20779. data points that we wish to fit to the model @expr{y = m x + b}
  20780. by adjusting the parameters @expr{m} and @expr{b} to make the @expr{y}
  20781. values calculated from the formula be as close as possible to the actual
  20782. @expr{y} values in the data set. (In a polynomial fit, the model is
  20783. instead, say, @expr{y = a x^3 + b x^2 + c x + d}. In a multilinear fit,
  20784. we have data points of the form @expr{(x_1,x_2,x_3,y)} and our model is
  20785. @expr{y = a x_1 + b x_2 + c x_3 + d}. These will be discussed later.)
  20786. In the model formula, variables like @expr{x} and @expr{x_2} are called
  20787. the @dfn{independent variables}, and @expr{y} is the @dfn{dependent
  20788. variable}. Variables like @expr{m}, @expr{a}, and @expr{b} are called
  20789. the @dfn{parameters} of the model.
  20790. The @kbd{a F} command takes the data set to be fitted from the stack.
  20791. By default, it expects the data in the form of a matrix. For example,
  20792. for a linear or polynomial fit, this would be a
  20793. @texline @math{2\times N}
  20794. @infoline 2xN
  20795. matrix where the first row is a list of @expr{x} values and the second
  20796. row has the corresponding @expr{y} values. For the multilinear fit
  20797. shown above, the matrix would have four rows (@expr{x_1}, @expr{x_2},
  20798. @expr{x_3}, and @expr{y}, respectively).
  20799. If you happen to have an
  20800. @texline @math{N\times2}
  20801. @infoline Nx2
  20802. matrix instead of a
  20803. @texline @math{2\times N}
  20804. @infoline 2xN
  20805. matrix, just press @kbd{v t} first to transpose the matrix.
  20806. After you type @kbd{a F}, Calc prompts you to select a model. For a
  20807. linear fit, press the digit @kbd{1}.
  20808. Calc then prompts for you to name the variables. By default it chooses
  20809. high letters like @expr{x} and @expr{y} for independent variables and
  20810. low letters like @expr{a} and @expr{b} for parameters. (The dependent
  20811. variable doesn't need a name.) The two kinds of variables are separated
  20812. by a semicolon. Since you generally care more about the names of the
  20813. independent variables than of the parameters, Calc also allows you to
  20814. name only those and let the parameters use default names.
  20815. For example, suppose the data matrix
  20816. @ifnottex
  20817. @example
  20818. @group
  20819. [ [ 1, 2, 3, 4, 5 ]
  20820. [ 5, 7, 9, 11, 13 ] ]
  20821. @end group
  20822. @end example
  20823. @end ifnottex
  20824. @tex
  20825. \beforedisplay
  20826. $$ \pmatrix{ 1 & 2 & 3 & 4 & 5 \cr
  20827. 5 & 7 & 9 & 11 & 13 }
  20828. $$
  20829. \afterdisplay
  20830. @end tex
  20831. @noindent
  20832. is on the stack and we wish to do a simple linear fit. Type
  20833. @kbd{a F}, then @kbd{1} for the model, then @key{RET} to use
  20834. the default names. The result will be the formula @expr{3. + 2. x}
  20835. on the stack. Calc has created the model expression @kbd{a + b x},
  20836. then found the optimal values of @expr{a} and @expr{b} to fit the
  20837. data. (In this case, it was able to find an exact fit.) Calc then
  20838. substituted those values for @expr{a} and @expr{b} in the model
  20839. formula.
  20840. The @kbd{a F} command puts two entries in the trail. One is, as
  20841. always, a copy of the result that went to the stack; the other is
  20842. a vector of the actual parameter values, written as equations:
  20843. @expr{[a = 3, b = 2]}, in case you'd rather read them in a list
  20844. than pick them out of the formula. (You can type @kbd{t y}
  20845. to move this vector to the stack; see @ref{Trail Commands}.
  20846. Specifying a different independent variable name will affect the
  20847. resulting formula: @kbd{a F 1 k @key{RET}} produces @kbd{3 + 2 k}.
  20848. Changing the parameter names (say, @kbd{a F 1 k;b,m @key{RET}}) will affect
  20849. the equations that go into the trail.
  20850. @tex
  20851. \bigskip
  20852. @end tex
  20853. To see what happens when the fit is not exact, we could change
  20854. the number 13 in the data matrix to 14 and try the fit again.
  20855. The result is:
  20856. @example
  20857. 2.6 + 2.2 x
  20858. @end example
  20859. Evaluating this formula, say with @kbd{v x 5 @key{RET} @key{TAB} V M $ @key{RET}}, shows
  20860. a reasonably close match to the y-values in the data.
  20861. @example
  20862. [4.8, 7., 9.2, 11.4, 13.6]
  20863. @end example
  20864. Since there is no line which passes through all the @var{n} data points,
  20865. Calc has chosen a line that best approximates the data points using
  20866. the method of least squares. The idea is to define the @dfn{chi-square}
  20867. error measure
  20868. @ifnottex
  20869. @example
  20870. chi^2 = sum((y_i - (a + b x_i))^2, i, 1, N)
  20871. @end example
  20872. @end ifnottex
  20873. @tex
  20874. \beforedisplay
  20875. $$ \chi^2 = \sum_{i=1}^N (y_i - (a + b x_i))^2 $$
  20876. \afterdisplay
  20877. @end tex
  20878. @noindent
  20879. which is clearly zero if @expr{a + b x} exactly fits all data points,
  20880. and increases as various @expr{a + b x_i} values fail to match the
  20881. corresponding @expr{y_i} values. There are several reasons why the
  20882. summand is squared, one of them being to ensure that
  20883. @texline @math{\chi^2 \ge 0}.
  20884. @infoline @expr{chi^2 >= 0}.
  20885. Least-squares fitting simply chooses the values of @expr{a} and @expr{b}
  20886. for which the error
  20887. @texline @math{\chi^2}
  20888. @infoline @expr{chi^2}
  20889. is as small as possible.
  20890. Other kinds of models do the same thing but with a different model
  20891. formula in place of @expr{a + b x_i}.
  20892. @tex
  20893. \bigskip
  20894. @end tex
  20895. A numeric prefix argument causes the @kbd{a F} command to take the
  20896. data in some other form than one big matrix. A positive argument @var{n}
  20897. will take @var{N} items from the stack, corresponding to the @var{n} rows
  20898. of a data matrix. In the linear case, @var{n} must be 2 since there
  20899. is always one independent variable and one dependent variable.
  20900. A prefix of zero or plain @kbd{C-u} is a compromise; Calc takes two
  20901. items from the stack, an @var{n}-row matrix of @expr{x} values, and a
  20902. vector of @expr{y} values. If there is only one independent variable,
  20903. the @expr{x} values can be either a one-row matrix or a plain vector,
  20904. in which case the @kbd{C-u} prefix is the same as a @w{@kbd{C-u 2}} prefix.
  20905. @node Polynomial and Multilinear Fits, Error Estimates for Fits, Linear Fits, Curve Fitting
  20906. @subsection Polynomial and Multilinear Fits
  20907. @noindent
  20908. To fit the data to higher-order polynomials, just type one of the
  20909. digits @kbd{2} through @kbd{9} when prompted for a model. For example,
  20910. we could fit the original data matrix from the previous section
  20911. (with 13, not 14) to a parabola instead of a line by typing
  20912. @kbd{a F 2 @key{RET}}.
  20913. @example
  20914. 2.00000000001 x - 1.5e-12 x^2 + 2.99999999999
  20915. @end example
  20916. Note that since the constant and linear terms are enough to fit the
  20917. data exactly, it's no surprise that Calc chose a tiny contribution
  20918. for @expr{x^2}. (The fact that it's not exactly zero is due only
  20919. to roundoff error. Since our data are exact integers, we could get
  20920. an exact answer by typing @kbd{m f} first to get Fraction mode.
  20921. Then the @expr{x^2} term would vanish altogether. Usually, though,
  20922. the data being fitted will be approximate floats so Fraction mode
  20923. won't help.)
  20924. Doing the @kbd{a F 2} fit on the data set with 14 instead of 13
  20925. gives a much larger @expr{x^2} contribution, as Calc bends the
  20926. line slightly to improve the fit.
  20927. @example
  20928. 0.142857142855 x^2 + 1.34285714287 x + 3.59999999998
  20929. @end example
  20930. An important result from the theory of polynomial fitting is that it
  20931. is always possible to fit @var{n} data points exactly using a polynomial
  20932. of degree @mathit{@var{n}-1}, sometimes called an @dfn{interpolating polynomial}.
  20933. Using the modified (14) data matrix, a model number of 4 gives
  20934. a polynomial that exactly matches all five data points:
  20935. @example
  20936. 0.04167 x^4 - 0.4167 x^3 + 1.458 x^2 - 0.08333 x + 4.
  20937. @end example
  20938. The actual coefficients we get with a precision of 12, like
  20939. @expr{0.0416666663588}, clearly suffer from loss of precision.
  20940. It is a good idea to increase the working precision to several
  20941. digits beyond what you need when you do a fitting operation.
  20942. Or, if your data are exact, use Fraction mode to get exact
  20943. results.
  20944. You can type @kbd{i} instead of a digit at the model prompt to fit
  20945. the data exactly to a polynomial. This just counts the number of
  20946. columns of the data matrix to choose the degree of the polynomial
  20947. automatically.
  20948. Fitting data ``exactly'' to high-degree polynomials is not always
  20949. a good idea, though. High-degree polynomials have a tendency to
  20950. wiggle uncontrollably in between the fitting data points. Also,
  20951. if the exact-fit polynomial is going to be used to interpolate or
  20952. extrapolate the data, it is numerically better to use the @kbd{a p}
  20953. command described below. @xref{Interpolation}.
  20954. @tex
  20955. \bigskip
  20956. @end tex
  20957. Another generalization of the linear model is to assume the
  20958. @expr{y} values are a sum of linear contributions from several
  20959. @expr{x} values. This is a @dfn{multilinear} fit, and it is also
  20960. selected by the @kbd{1} digit key. (Calc decides whether the fit
  20961. is linear or multilinear by counting the rows in the data matrix.)
  20962. Given the data matrix,
  20963. @example
  20964. @group
  20965. [ [ 1, 2, 3, 4, 5 ]
  20966. [ 7, 2, 3, 5, 2 ]
  20967. [ 14.5, 15, 18.5, 22.5, 24 ] ]
  20968. @end group
  20969. @end example
  20970. @noindent
  20971. the command @kbd{a F 1 @key{RET}} will call the first row @expr{x} and the
  20972. second row @expr{y}, and will fit the values in the third row to the
  20973. model @expr{a + b x + c y}.
  20974. @example
  20975. 8. + 3. x + 0.5 y
  20976. @end example
  20977. Calc can do multilinear fits with any number of independent variables
  20978. (i.e., with any number of data rows).
  20979. @tex
  20980. \bigskip
  20981. @end tex
  20982. Yet another variation is @dfn{homogeneous} linear models, in which
  20983. the constant term is known to be zero. In the linear case, this
  20984. means the model formula is simply @expr{a x}; in the multilinear
  20985. case, the model might be @expr{a x + b y + c z}; and in the polynomial
  20986. case, the model could be @expr{a x + b x^2 + c x^3}. You can get
  20987. a homogeneous linear or multilinear model by pressing the letter
  20988. @kbd{h} followed by a regular model key, like @kbd{1} or @kbd{2}.
  20989. This will be indicated by an ``h'' in the minibuffer after the help
  20990. message.
  20991. It is certainly possible to have other constrained linear models,
  20992. like @expr{2.3 + a x} or @expr{a - 4 x}. While there is no single
  20993. key to select models like these, a later section shows how to enter
  20994. any desired model by hand. In the first case, for example, you
  20995. would enter @kbd{a F ' 2.3 + a x}.
  20996. Another class of models that will work but must be entered by hand
  20997. are multinomial fits, e.g., @expr{a + b x + c y + d x^2 + e y^2 + f x y}.
  20998. @node Error Estimates for Fits, Standard Nonlinear Models, Polynomial and Multilinear Fits, Curve Fitting
  20999. @subsection Error Estimates for Fits
  21000. @noindent
  21001. @kindex H a F
  21002. @tindex efit
  21003. With the Hyperbolic flag, @kbd{H a F} [@code{efit}] performs the same
  21004. fitting operation as @kbd{a F}, but reports the coefficients as error
  21005. forms instead of plain numbers. Fitting our two data matrices (first
  21006. with 13, then with 14) to a line with @kbd{H a F} gives the results,
  21007. @example
  21008. 3. + 2. x
  21009. 2.6 +/- 0.382970843103 + 2.2 +/- 0.115470053838 x
  21010. @end example
  21011. In the first case the estimated errors are zero because the linear
  21012. fit is perfect. In the second case, the errors are nonzero but
  21013. moderately small, because the data are still very close to linear.
  21014. It is also possible for the @emph{input} to a fitting operation to
  21015. contain error forms. The data values must either all include errors
  21016. or all be plain numbers. Error forms can go anywhere but generally
  21017. go on the numbers in the last row of the data matrix. If the last
  21018. row contains error forms
  21019. @texline `@var{y_i}@w{ @tfn{+/-} }@math{\sigma_i}',
  21020. @infoline `@var{y_i}@w{ @tfn{+/-} }@var{sigma_i}',
  21021. then the
  21022. @texline @math{\chi^2}
  21023. @infoline @expr{chi^2}
  21024. statistic is now,
  21025. @ifnottex
  21026. @example
  21027. chi^2 = sum(((y_i - (a + b x_i)) / sigma_i)^2, i, 1, N)
  21028. @end example
  21029. @end ifnottex
  21030. @tex
  21031. \beforedisplay
  21032. $$ \chi^2 = \sum_{i=1}^N \left(y_i - (a + b x_i) \over \sigma_i\right)^2 $$
  21033. \afterdisplay
  21034. @end tex
  21035. @noindent
  21036. so that data points with larger error estimates contribute less to
  21037. the fitting operation.
  21038. If there are error forms on other rows of the data matrix, all the
  21039. errors for a given data point are combined; the square root of the
  21040. sum of the squares of the errors forms the
  21041. @texline @math{\sigma_i}
  21042. @infoline @expr{sigma_i}
  21043. used for the data point.
  21044. Both @kbd{a F} and @kbd{H a F} can accept error forms in the input
  21045. matrix, although if you are concerned about error analysis you will
  21046. probably use @kbd{H a F} so that the output also contains error
  21047. estimates.
  21048. If the input contains error forms but all the
  21049. @texline @math{\sigma_i}
  21050. @infoline @expr{sigma_i}
  21051. values are the same, it is easy to see that the resulting fitted model
  21052. will be the same as if the input did not have error forms at all
  21053. @texline (@math{\chi^2}
  21054. @infoline (@expr{chi^2}
  21055. is simply scaled uniformly by
  21056. @texline @math{1 / \sigma^2},
  21057. @infoline @expr{1 / sigma^2},
  21058. which doesn't affect where it has a minimum). But there @emph{will} be
  21059. a difference in the estimated errors of the coefficients reported by
  21060. @kbd{H a F}.
  21061. Consult any text on statistical modeling of data for a discussion
  21062. of where these error estimates come from and how they should be
  21063. interpreted.
  21064. @tex
  21065. \bigskip
  21066. @end tex
  21067. @kindex I a F
  21068. @tindex xfit
  21069. With the Inverse flag, @kbd{I a F} [@code{xfit}] produces even more
  21070. information. The result is a vector of six items:
  21071. @enumerate
  21072. @item
  21073. The model formula with error forms for its coefficients or
  21074. parameters. This is the result that @kbd{H a F} would have
  21075. produced.
  21076. @item
  21077. A vector of ``raw'' parameter values for the model. These are the
  21078. polynomial coefficients or other parameters as plain numbers, in the
  21079. same order as the parameters appeared in the final prompt of the
  21080. @kbd{I a F} command. For polynomials of degree @expr{d}, this vector
  21081. will have length @expr{M = d+1} with the constant term first.
  21082. @item
  21083. The covariance matrix @expr{C} computed from the fit. This is
  21084. an @var{m}x@var{m} symmetric matrix; the diagonal elements
  21085. @texline @math{C_{jj}}
  21086. @infoline @expr{C_j_j}
  21087. are the variances
  21088. @texline @math{\sigma_j^2}
  21089. @infoline @expr{sigma_j^2}
  21090. of the parameters. The other elements are covariances
  21091. @texline @math{\sigma_{ij}^2}
  21092. @infoline @expr{sigma_i_j^2}
  21093. that describe the correlation between pairs of parameters. (A related
  21094. set of numbers, the @dfn{linear correlation coefficients}
  21095. @texline @math{r_{ij}},
  21096. @infoline @expr{r_i_j},
  21097. are defined as
  21098. @texline @math{\sigma_{ij}^2 / \sigma_i \, \sigma_j}.)
  21099. @infoline @expr{sigma_i_j^2 / sigma_i sigma_j}.)
  21100. @item
  21101. A vector of @expr{M} ``parameter filter'' functions whose
  21102. meanings are described below. If no filters are necessary this
  21103. will instead be an empty vector; this is always the case for the
  21104. polynomial and multilinear fits described so far.
  21105. @item
  21106. The value of
  21107. @texline @math{\chi^2}
  21108. @infoline @expr{chi^2}
  21109. for the fit, calculated by the formulas shown above. This gives a
  21110. measure of the quality of the fit; statisticians consider
  21111. @texline @math{\chi^2 \approx N - M}
  21112. @infoline @expr{chi^2 = N - M}
  21113. to indicate a moderately good fit (where again @expr{N} is the number of
  21114. data points and @expr{M} is the number of parameters).
  21115. @item
  21116. A measure of goodness of fit expressed as a probability @expr{Q}.
  21117. This is computed from the @code{utpc} probability distribution
  21118. function using
  21119. @texline @math{\chi^2}
  21120. @infoline @expr{chi^2}
  21121. with @expr{N - M} degrees of freedom. A
  21122. value of 0.5 implies a good fit; some texts recommend that often
  21123. @expr{Q = 0.1} or even 0.001 can signify an acceptable fit. In
  21124. particular,
  21125. @texline @math{\chi^2}
  21126. @infoline @expr{chi^2}
  21127. statistics assume the errors in your inputs
  21128. follow a normal (Gaussian) distribution; if they don't, you may
  21129. have to accept smaller values of @expr{Q}.
  21130. The @expr{Q} value is computed only if the input included error
  21131. estimates. Otherwise, Calc will report the symbol @code{nan}
  21132. for @expr{Q}. The reason is that in this case the
  21133. @texline @math{\chi^2}
  21134. @infoline @expr{chi^2}
  21135. value has effectively been used to estimate the original errors
  21136. in the input, and thus there is no redundant information left
  21137. over to use for a confidence test.
  21138. @end enumerate
  21139. @node Standard Nonlinear Models, Curve Fitting Details, Error Estimates for Fits, Curve Fitting
  21140. @subsection Standard Nonlinear Models
  21141. @noindent
  21142. The @kbd{a F} command also accepts other kinds of models besides
  21143. lines and polynomials. Some common models have quick single-key
  21144. abbreviations; others must be entered by hand as algebraic formulas.
  21145. Here is a complete list of the standard models recognized by @kbd{a F}:
  21146. @table @kbd
  21147. @item 1
  21148. Linear or multilinear. @mathit{a + b x + c y + d z}.
  21149. @item 2-9
  21150. Polynomials. @mathit{a + b x + c x^2 + d x^3}.
  21151. @item e
  21152. Exponential. @mathit{a} @tfn{exp}@mathit{(b x)} @tfn{exp}@mathit{(c y)}.
  21153. @item E
  21154. Base-10 exponential. @mathit{a} @tfn{10^}@mathit{(b x)} @tfn{10^}@mathit{(c y)}.
  21155. @item x
  21156. Exponential (alternate notation). @tfn{exp}@mathit{(a + b x + c y)}.
  21157. @item X
  21158. Base-10 exponential (alternate). @tfn{10^}@mathit{(a + b x + c y)}.
  21159. @item l
  21160. Logarithmic. @mathit{a + b} @tfn{ln}@mathit{(x) + c} @tfn{ln}@mathit{(y)}.
  21161. @item L
  21162. Base-10 logarithmic. @mathit{a + b} @tfn{log10}@mathit{(x) + c} @tfn{log10}@mathit{(y)}.
  21163. @item ^
  21164. General exponential. @mathit{a b^x c^y}.
  21165. @item p
  21166. Power law. @mathit{a x^b y^c}.
  21167. @item q
  21168. Quadratic. @mathit{a + b (x-c)^2 + d (x-e)^2}.
  21169. @item g
  21170. Gaussian.
  21171. @texline @math{{a \over b \sqrt{2 \pi}} \exp\left( -{1 \over 2} \left( x - c \over b \right)^2 \right)}.
  21172. @infoline @mathit{(a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2)}.
  21173. @item s
  21174. Logistic @emph{s} curve.
  21175. @texline @math{a/(1+e^{b(x-c)})}.
  21176. @infoline @mathit{a/(1 + exp(b (x - c)))}.
  21177. @item b
  21178. Logistic bell curve.
  21179. @texline @math{ae^{b(x-c)}/(1+e^{b(x-c)})^2}.
  21180. @infoline @mathit{a exp(b (x - c))/(1 + exp(b (x - c)))^2}.
  21181. @item o
  21182. Hubbert linearization.
  21183. @texline @math{{y \over x} = a(1-x/b)}.
  21184. @infoline @mathit{(y/x) = a (1 - x/b)}.
  21185. @end table
  21186. All of these models are used in the usual way; just press the appropriate
  21187. letter at the model prompt, and choose variable names if you wish. The
  21188. result will be a formula as shown in the above table, with the best-fit
  21189. values of the parameters substituted. (You may find it easier to read
  21190. the parameter values from the vector that is placed in the trail.)
  21191. All models except Gaussian, logistics, Hubbert and polynomials can
  21192. generalize as shown to any number of independent variables. Also, all
  21193. the built-in models except for the logistic and Hubbert curves have an
  21194. additive or multiplicative parameter shown as @expr{a} in the above table
  21195. which can be replaced by zero or one, as appropriate, by typing @kbd{h}
  21196. before the model key.
  21197. Note that many of these models are essentially equivalent, but express
  21198. the parameters slightly differently. For example, @expr{a b^x} and
  21199. the other two exponential models are all algebraic rearrangements of
  21200. each other. Also, the ``quadratic'' model is just a degree-2 polynomial
  21201. with the parameters expressed differently. Use whichever form best
  21202. matches the problem.
  21203. The HP-28/48 calculators support four different models for curve
  21204. fitting, called @code{LIN}, @code{LOG}, @code{EXP}, and @code{PWR}.
  21205. These correspond to Calc models @samp{a + b x}, @samp{a + b ln(x)},
  21206. @samp{a exp(b x)}, and @samp{a x^b}, respectively. In each case,
  21207. @expr{a} is what the HP-48 identifies as the ``intercept,'' and
  21208. @expr{b} is what it calls the ``slope.''
  21209. @tex
  21210. \bigskip
  21211. @end tex
  21212. If the model you want doesn't appear on this list, press @kbd{'}
  21213. (the apostrophe key) at the model prompt to enter any algebraic
  21214. formula, such as @kbd{m x - b}, as the model. (Not all models
  21215. will work, though---see the next section for details.)
  21216. The model can also be an equation like @expr{y = m x + b}.
  21217. In this case, Calc thinks of all the rows of the data matrix on
  21218. equal terms; this model effectively has two parameters
  21219. (@expr{m} and @expr{b}) and two independent variables (@expr{x}
  21220. and @expr{y}), with no ``dependent'' variables. Model equations
  21221. do not need to take this @expr{y =} form. For example, the
  21222. implicit line equation @expr{a x + b y = 1} works fine as a
  21223. model.
  21224. When you enter a model, Calc makes an alphabetical list of all
  21225. the variables that appear in the model. These are used for the
  21226. default parameters, independent variables, and dependent variable
  21227. (in that order). If you enter a plain formula (not an equation),
  21228. Calc assumes the dependent variable does not appear in the formula
  21229. and thus does not need a name.
  21230. For example, if the model formula has the variables @expr{a,mu,sigma,t,x},
  21231. and the data matrix has three rows (meaning two independent variables),
  21232. Calc will use @expr{a,mu,sigma} as the default parameters, and the
  21233. data rows will be named @expr{t} and @expr{x}, respectively. If you
  21234. enter an equation instead of a plain formula, Calc will use @expr{a,mu}
  21235. as the parameters, and @expr{sigma,t,x} as the three independent
  21236. variables.
  21237. You can, of course, override these choices by entering something
  21238. different at the prompt. If you leave some variables out of the list,
  21239. those variables must have stored values and those stored values will
  21240. be used as constants in the model. (Stored values for the parameters
  21241. and independent variables are ignored by the @kbd{a F} command.)
  21242. If you list only independent variables, all the remaining variables
  21243. in the model formula will become parameters.
  21244. If there are @kbd{$} signs in the model you type, they will stand
  21245. for parameters and all other variables (in alphabetical order)
  21246. will be independent. Use @kbd{$} for one parameter, @kbd{$$} for
  21247. another, and so on. Thus @kbd{$ x + $$} is another way to describe
  21248. a linear model.
  21249. If you type a @kbd{$} instead of @kbd{'} at the model prompt itself,
  21250. Calc will take the model formula from the stack. (The data must then
  21251. appear at the second stack level.) The same conventions are used to
  21252. choose which variables in the formula are independent by default and
  21253. which are parameters.
  21254. Models taken from the stack can also be expressed as vectors of
  21255. two or three elements, @expr{[@var{model}, @var{vars}]} or
  21256. @expr{[@var{model}, @var{vars}, @var{params}]}. Each of @var{vars}
  21257. and @var{params} may be either a variable or a vector of variables.
  21258. (If @var{params} is omitted, all variables in @var{model} except
  21259. those listed as @var{vars} are parameters.)
  21260. When you enter a model manually with @kbd{'}, Calc puts a 3-vector
  21261. describing the model in the trail so you can get it back if you wish.
  21262. @tex
  21263. \bigskip
  21264. @end tex
  21265. @vindex Model1
  21266. @vindex Model2
  21267. Finally, you can store a model in one of the Calc variables
  21268. @code{Model1} or @code{Model2}, then use this model by typing
  21269. @kbd{a F u} or @kbd{a F U} (respectively). The value stored in
  21270. the variable can be any of the formats that @kbd{a F $} would
  21271. accept for a model on the stack.
  21272. @tex
  21273. \bigskip
  21274. @end tex
  21275. Calc uses the principal values of inverse functions like @code{ln}
  21276. and @code{arcsin} when doing fits. For example, when you enter
  21277. the model @samp{y = sin(a t + b)} Calc actually uses the easier
  21278. form @samp{arcsin(y) = a t + b}. The @code{arcsin} function always
  21279. returns results in the range from @mathit{-90} to 90 degrees (or the
  21280. equivalent range in radians). Suppose you had data that you
  21281. believed to represent roughly three oscillations of a sine wave,
  21282. so that the argument of the sine might go from zero to
  21283. @texline @math{3\times360}
  21284. @infoline @mathit{3*360}
  21285. degrees.
  21286. The above model would appear to be a good way to determine the
  21287. true frequency and phase of the sine wave, but in practice it
  21288. would fail utterly. The righthand side of the actual model
  21289. @samp{arcsin(y) = a t + b} will grow smoothly with @expr{t}, but
  21290. the lefthand side will bounce back and forth between @mathit{-90} and 90.
  21291. No values of @expr{a} and @expr{b} can make the two sides match,
  21292. even approximately.
  21293. There is no good solution to this problem at present. You could
  21294. restrict your data to small enough ranges so that the above problem
  21295. doesn't occur (i.e., not straddling any peaks in the sine wave).
  21296. Or, in this case, you could use a totally different method such as
  21297. Fourier analysis, which is beyond the scope of the @kbd{a F} command.
  21298. (Unfortunately, Calc does not currently have any facilities for
  21299. taking Fourier and related transforms.)
  21300. @node Curve Fitting Details, Interpolation, Standard Nonlinear Models, Curve Fitting
  21301. @subsection Curve Fitting Details
  21302. @noindent
  21303. Calc's internal least-squares fitter can only handle multilinear
  21304. models. More precisely, it can handle any model of the form
  21305. @expr{a f(x,y,z) + b g(x,y,z) + c h(x,y,z)}, where @expr{a,b,c}
  21306. are the parameters and @expr{x,y,z} are the independent variables
  21307. (of course there can be any number of each, not just three).
  21308. In a simple multilinear or polynomial fit, it is easy to see how
  21309. to convert the model into this form. For example, if the model
  21310. is @expr{a + b x + c x^2}, then @expr{f(x) = 1}, @expr{g(x) = x},
  21311. and @expr{h(x) = x^2} are suitable functions.
  21312. For most other models, Calc uses a variety of algebraic manipulations
  21313. to try to put the problem into the form
  21314. @smallexample
  21315. Y(x,y,z) = A(a,b,c) F(x,y,z) + B(a,b,c) G(x,y,z) + C(a,b,c) H(x,y,z)
  21316. @end smallexample
  21317. @noindent
  21318. where @expr{Y,A,B,C,F,G,H} are arbitrary functions. It computes
  21319. @expr{Y}, @expr{F}, @expr{G}, and @expr{H} for all the data points,
  21320. does a standard linear fit to find the values of @expr{A}, @expr{B},
  21321. and @expr{C}, then uses the equation solver to solve for @expr{a,b,c}
  21322. in terms of @expr{A,B,C}.
  21323. A remarkable number of models can be cast into this general form.
  21324. We'll look at two examples here to see how it works. The power-law
  21325. model @expr{y = a x^b} with two independent variables and two parameters
  21326. can be rewritten as follows:
  21327. @example
  21328. y = a x^b
  21329. y = a exp(b ln(x))
  21330. y = exp(ln(a) + b ln(x))
  21331. ln(y) = ln(a) + b ln(x)
  21332. @end example
  21333. @noindent
  21334. which matches the desired form with
  21335. @texline @math{Y = \ln(y)},
  21336. @infoline @expr{Y = ln(y)},
  21337. @texline @math{A = \ln(a)},
  21338. @infoline @expr{A = ln(a)},
  21339. @expr{F = 1}, @expr{B = b}, and
  21340. @texline @math{G = \ln(x)}.
  21341. @infoline @expr{G = ln(x)}.
  21342. Calc thus computes the logarithms of your @expr{y} and @expr{x} values,
  21343. does a linear fit for @expr{A} and @expr{B}, then solves to get
  21344. @texline @math{a = \exp(A)}
  21345. @infoline @expr{a = exp(A)}
  21346. and @expr{b = B}.
  21347. Another interesting example is the ``quadratic'' model, which can
  21348. be handled by expanding according to the distributive law.
  21349. @example
  21350. y = a + b*(x - c)^2
  21351. y = a + b c^2 - 2 b c x + b x^2
  21352. @end example
  21353. @noindent
  21354. which matches with @expr{Y = y}, @expr{A = a + b c^2}, @expr{F = 1},
  21355. @expr{B = -2 b c}, @expr{G = x} (the @mathit{-2} factor could just as easily
  21356. have been put into @expr{G} instead of @expr{B}), @expr{C = b}, and
  21357. @expr{H = x^2}.
  21358. The Gaussian model looks quite complicated, but a closer examination
  21359. shows that it's actually similar to the quadratic model but with an
  21360. exponential that can be brought to the top and moved into @expr{Y}.
  21361. The logistic models cannot be put into general linear form. For these
  21362. models, and the Hubbert linearization, Calc computes a rough
  21363. approximation for the parameters, then uses the Levenberg-Marquardt
  21364. iterative method to refine the approximations.
  21365. Another model that cannot be put into general linear
  21366. form is a Gaussian with a constant background added on, i.e.,
  21367. @expr{d} + the regular Gaussian formula. If you have a model like
  21368. this, your best bet is to replace enough of your parameters with
  21369. constants to make the model linearizable, then adjust the constants
  21370. manually by doing a series of fits. You can compare the fits by
  21371. graphing them, by examining the goodness-of-fit measures returned by
  21372. @kbd{I a F}, or by some other method suitable to your application.
  21373. Note that some models can be linearized in several ways. The
  21374. Gaussian-plus-@var{d} model can be linearized by setting @expr{d}
  21375. (the background) to a constant, or by setting @expr{b} (the standard
  21376. deviation) and @expr{c} (the mean) to constants.
  21377. To fit a model with constants substituted for some parameters, just
  21378. store suitable values in those parameter variables, then omit them
  21379. from the list of parameters when you answer the variables prompt.
  21380. @tex
  21381. \bigskip
  21382. @end tex
  21383. A last desperate step would be to use the general-purpose
  21384. @code{minimize} function rather than @code{fit}. After all, both
  21385. functions solve the problem of minimizing an expression (the
  21386. @texline @math{\chi^2}
  21387. @infoline @expr{chi^2}
  21388. sum) by adjusting certain parameters in the expression. The @kbd{a F}
  21389. command is able to use a vastly more efficient algorithm due to its
  21390. special knowledge about linear chi-square sums, but the @kbd{a N}
  21391. command can do the same thing by brute force.
  21392. A compromise would be to pick out a few parameters without which the
  21393. fit is linearizable, and use @code{minimize} on a call to @code{fit}
  21394. which efficiently takes care of the rest of the parameters. The thing
  21395. to be minimized would be the value of
  21396. @texline @math{\chi^2}
  21397. @infoline @expr{chi^2}
  21398. returned as the fifth result of the @code{xfit} function:
  21399. @smallexample
  21400. minimize(xfit(gaus(a,b,c,d,x), x, [a,b,c], data)_5, d, guess)
  21401. @end smallexample
  21402. @noindent
  21403. where @code{gaus} represents the Gaussian model with background,
  21404. @code{data} represents the data matrix, and @code{guess} represents
  21405. the initial guess for @expr{d} that @code{minimize} requires.
  21406. This operation will only be, shall we say, extraordinarily slow
  21407. rather than astronomically slow (as would be the case if @code{minimize}
  21408. were used by itself to solve the problem).
  21409. @tex
  21410. \bigskip
  21411. @end tex
  21412. The @kbd{I a F} [@code{xfit}] command is somewhat trickier when
  21413. nonlinear models are used. The second item in the result is the
  21414. vector of ``raw'' parameters @expr{A}, @expr{B}, @expr{C}. The
  21415. covariance matrix is written in terms of those raw parameters.
  21416. The fifth item is a vector of @dfn{filter} expressions. This
  21417. is the empty vector @samp{[]} if the raw parameters were the same
  21418. as the requested parameters, i.e., if @expr{A = a}, @expr{B = b},
  21419. and so on (which is always true if the model is already linear
  21420. in the parameters as written, e.g., for polynomial fits). If the
  21421. parameters had to be rearranged, the fifth item is instead a vector
  21422. of one formula per parameter in the original model. The raw
  21423. parameters are expressed in these ``filter'' formulas as
  21424. @samp{fitdummy(1)} for @expr{A}, @samp{fitdummy(2)} for @expr{B},
  21425. and so on.
  21426. When Calc needs to modify the model to return the result, it replaces
  21427. @samp{fitdummy(1)} in all the filters with the first item in the raw
  21428. parameters list, and so on for the other raw parameters, then
  21429. evaluates the resulting filter formulas to get the actual parameter
  21430. values to be substituted into the original model. In the case of
  21431. @kbd{H a F} and @kbd{I a F} where the parameters must be error forms,
  21432. Calc uses the square roots of the diagonal entries of the covariance
  21433. matrix as error values for the raw parameters, then lets Calc's
  21434. standard error-form arithmetic take it from there.
  21435. If you use @kbd{I a F} with a nonlinear model, be sure to remember
  21436. that the covariance matrix is in terms of the raw parameters,
  21437. @emph{not} the actual requested parameters. It's up to you to
  21438. figure out how to interpret the covariances in the presence of
  21439. nontrivial filter functions.
  21440. Things are also complicated when the input contains error forms.
  21441. Suppose there are three independent and dependent variables, @expr{x},
  21442. @expr{y}, and @expr{z}, one or more of which are error forms in the
  21443. data. Calc combines all the error values by taking the square root
  21444. of the sum of the squares of the errors. It then changes @expr{x}
  21445. and @expr{y} to be plain numbers, and makes @expr{z} into an error
  21446. form with this combined error. The @expr{Y(x,y,z)} part of the
  21447. linearized model is evaluated, and the result should be an error
  21448. form. The error part of that result is used for
  21449. @texline @math{\sigma_i}
  21450. @infoline @expr{sigma_i}
  21451. for the data point. If for some reason @expr{Y(x,y,z)} does not return
  21452. an error form, the combined error from @expr{z} is used directly for
  21453. @texline @math{\sigma_i}.
  21454. @infoline @expr{sigma_i}.
  21455. Finally, @expr{z} is also stripped of its error
  21456. for use in computing @expr{F(x,y,z)}, @expr{G(x,y,z)} and so on;
  21457. the righthand side of the linearized model is computed in regular
  21458. arithmetic with no error forms.
  21459. (While these rules may seem complicated, they are designed to do
  21460. the most reasonable thing in the typical case that @expr{Y(x,y,z)}
  21461. depends only on the dependent variable @expr{z}, and in fact is
  21462. often simply equal to @expr{z}. For common cases like polynomials
  21463. and multilinear models, the combined error is simply used as the
  21464. @texline @math{\sigma}
  21465. @infoline @expr{sigma}
  21466. for the data point with no further ado.)
  21467. @tex
  21468. \bigskip
  21469. @end tex
  21470. @vindex FitRules
  21471. It may be the case that the model you wish to use is linearizable,
  21472. but Calc's built-in rules are unable to figure it out. Calc uses
  21473. its algebraic rewrite mechanism to linearize a model. The rewrite
  21474. rules are kept in the variable @code{FitRules}. You can edit this
  21475. variable using the @kbd{s e FitRules} command; in fact, there is
  21476. a special @kbd{s F} command just for editing @code{FitRules}.
  21477. @xref{Operations on Variables}.
  21478. @xref{Rewrite Rules}, for a discussion of rewrite rules.
  21479. @ignore
  21480. @starindex
  21481. @end ignore
  21482. @tindex fitvar
  21483. @ignore
  21484. @starindex
  21485. @end ignore
  21486. @ignore
  21487. @mindex @idots
  21488. @end ignore
  21489. @tindex fitparam
  21490. @ignore
  21491. @starindex
  21492. @end ignore
  21493. @ignore
  21494. @mindex @null
  21495. @end ignore
  21496. @tindex fitmodel
  21497. @ignore
  21498. @starindex
  21499. @end ignore
  21500. @ignore
  21501. @mindex @null
  21502. @end ignore
  21503. @tindex fitsystem
  21504. @ignore
  21505. @starindex
  21506. @end ignore
  21507. @ignore
  21508. @mindex @null
  21509. @end ignore
  21510. @tindex fitdummy
  21511. Calc uses @code{FitRules} as follows. First, it converts the model
  21512. to an equation if necessary and encloses the model equation in a
  21513. call to the function @code{fitmodel} (which is not actually a defined
  21514. function in Calc; it is only used as a placeholder by the rewrite rules).
  21515. Parameter variables are renamed to function calls @samp{fitparam(1)},
  21516. @samp{fitparam(2)}, and so on, and independent variables are renamed
  21517. to @samp{fitvar(1)}, @samp{fitvar(2)}, etc. The dependent variable
  21518. is the highest-numbered @code{fitvar}. For example, the power law
  21519. model @expr{a x^b} is converted to @expr{y = a x^b}, then to
  21520. @smallexample
  21521. @group
  21522. fitmodel(fitvar(2) = fitparam(1) fitvar(1)^fitparam(2))
  21523. @end group
  21524. @end smallexample
  21525. Calc then applies the rewrites as if by @samp{C-u 0 a r FitRules}.
  21526. (The zero prefix means that rewriting should continue until no further
  21527. changes are possible.)
  21528. When rewriting is complete, the @code{fitmodel} call should have
  21529. been replaced by a @code{fitsystem} call that looks like this:
  21530. @example
  21531. fitsystem(@var{Y}, @var{FGH}, @var{abc})
  21532. @end example
  21533. @noindent
  21534. where @var{Y} is a formula that describes the function @expr{Y(x,y,z)},
  21535. @var{FGH} is the vector of formulas @expr{[F(x,y,z), G(x,y,z), H(x,y,z)]},
  21536. and @var{abc} is the vector of parameter filters which refer to the
  21537. raw parameters as @samp{fitdummy(1)} for @expr{A}, @samp{fitdummy(2)}
  21538. for @expr{B}, etc. While the number of raw parameters (the length of
  21539. the @var{FGH} vector) is usually the same as the number of original
  21540. parameters (the length of the @var{abc} vector), this is not required.
  21541. The power law model eventually boils down to
  21542. @smallexample
  21543. @group
  21544. fitsystem(ln(fitvar(2)),
  21545. [1, ln(fitvar(1))],
  21546. [exp(fitdummy(1)), fitdummy(2)])
  21547. @end group
  21548. @end smallexample
  21549. The actual implementation of @code{FitRules} is complicated; it
  21550. proceeds in four phases. First, common rearrangements are done
  21551. to try to bring linear terms together and to isolate functions like
  21552. @code{exp} and @code{ln} either all the way ``out'' (so that they
  21553. can be put into @var{Y}) or all the way ``in'' (so that they can
  21554. be put into @var{abc} or @var{FGH}). In particular, all
  21555. non-constant powers are converted to logs-and-exponentials form,
  21556. and the distributive law is used to expand products of sums.
  21557. Quotients are rewritten to use the @samp{fitinv} function, where
  21558. @samp{fitinv(x)} represents @expr{1/x} while the @code{FitRules}
  21559. are operating. (The use of @code{fitinv} makes recognition of
  21560. linear-looking forms easier.) If you modify @code{FitRules}, you
  21561. will probably only need to modify the rules for this phase.
  21562. Phase two, whose rules can actually also apply during phases one
  21563. and three, first rewrites @code{fitmodel} to a two-argument
  21564. form @samp{fitmodel(@var{Y}, @var{model})}, where @var{Y} is
  21565. initially zero and @var{model} has been changed from @expr{a=b}
  21566. to @expr{a-b} form. It then tries to peel off invertible functions
  21567. from the outside of @var{model} and put them into @var{Y} instead,
  21568. calling the equation solver to invert the functions. Finally, when
  21569. this is no longer possible, the @code{fitmodel} is changed to a
  21570. four-argument @code{fitsystem}, where the fourth argument is
  21571. @var{model} and the @var{FGH} and @var{abc} vectors are initially
  21572. empty. (The last vector is really @var{ABC}, corresponding to
  21573. raw parameters, for now.)
  21574. Phase three converts a sum of items in the @var{model} to a sum
  21575. of @samp{fitpart(@var{a}, @var{b}, @var{c})} terms which represent
  21576. terms @samp{@var{a}*@var{b}*@var{c}} of the sum, where @var{a}
  21577. is all factors that do not involve any variables, @var{b} is all
  21578. factors that involve only parameters, and @var{c} is the factors
  21579. that involve only independent variables. (If this decomposition
  21580. is not possible, the rule set will not complete and Calc will
  21581. complain that the model is too complex.) Then @code{fitpart}s
  21582. with equal @var{b} or @var{c} components are merged back together
  21583. using the distributive law in order to minimize the number of
  21584. raw parameters needed.
  21585. Phase four moves the @code{fitpart} terms into the @var{FGH} and
  21586. @var{ABC} vectors. Also, some of the algebraic expansions that
  21587. were done in phase 1 are undone now to make the formulas more
  21588. computationally efficient. Finally, it calls the solver one more
  21589. time to convert the @var{ABC} vector to an @var{abc} vector, and
  21590. removes the fourth @var{model} argument (which by now will be zero)
  21591. to obtain the three-argument @code{fitsystem} that the linear
  21592. least-squares solver wants to see.
  21593. @ignore
  21594. @starindex
  21595. @end ignore
  21596. @ignore
  21597. @mindex hasfit@idots
  21598. @end ignore
  21599. @tindex hasfitparams
  21600. @ignore
  21601. @starindex
  21602. @end ignore
  21603. @ignore
  21604. @mindex @null
  21605. @end ignore
  21606. @tindex hasfitvars
  21607. Two functions which are useful in connection with @code{FitRules}
  21608. are @samp{hasfitparams(x)} and @samp{hasfitvars(x)}, which check
  21609. whether @expr{x} refers to any parameters or independent variables,
  21610. respectively. Specifically, these functions return ``true'' if the
  21611. argument contains any @code{fitparam} (or @code{fitvar}) function
  21612. calls, and ``false'' otherwise. (Recall that ``true'' means a
  21613. nonzero number, and ``false'' means zero. The actual nonzero number
  21614. returned is the largest @var{n} from all the @samp{fitparam(@var{n})}s
  21615. or @samp{fitvar(@var{n})}s, respectively, that appear in the formula.)
  21616. @tex
  21617. \bigskip
  21618. @end tex
  21619. The @code{fit} function in algebraic notation normally takes four
  21620. arguments, @samp{fit(@var{model}, @var{vars}, @var{params}, @var{data})},
  21621. where @var{model} is the model formula as it would be typed after
  21622. @kbd{a F '}, @var{vars} is the independent variable or a vector of
  21623. independent variables, @var{params} likewise gives the parameter(s),
  21624. and @var{data} is the data matrix. Note that the length of @var{vars}
  21625. must be equal to the number of rows in @var{data} if @var{model} is
  21626. an equation, or one less than the number of rows if @var{model} is
  21627. a plain formula. (Actually, a name for the dependent variable is
  21628. allowed but will be ignored in the plain-formula case.)
  21629. If @var{params} is omitted, the parameters are all variables in
  21630. @var{model} except those that appear in @var{vars}. If @var{vars}
  21631. is also omitted, Calc sorts all the variables that appear in
  21632. @var{model} alphabetically and uses the higher ones for @var{vars}
  21633. and the lower ones for @var{params}.
  21634. Alternatively, @samp{fit(@var{modelvec}, @var{data})} is allowed
  21635. where @var{modelvec} is a 2- or 3-vector describing the model
  21636. and variables, as discussed previously.
  21637. If Calc is unable to do the fit, the @code{fit} function is left
  21638. in symbolic form, ordinarily with an explanatory message. The
  21639. message will be ``Model expression is too complex'' if the
  21640. linearizer was unable to put the model into the required form.
  21641. The @code{efit} (corresponding to @kbd{H a F}) and @code{xfit}
  21642. (for @kbd{I a F}) functions are completely analogous.
  21643. @node Interpolation, , Curve Fitting Details, Curve Fitting
  21644. @subsection Polynomial Interpolation
  21645. @kindex a p
  21646. @pindex calc-poly-interp
  21647. @tindex polint
  21648. The @kbd{a p} (@code{calc-poly-interp}) [@code{polint}] command does
  21649. a polynomial interpolation at a particular @expr{x} value. It takes
  21650. two arguments from the stack: A data matrix of the sort used by
  21651. @kbd{a F}, and a single number which represents the desired @expr{x}
  21652. value. Calc effectively does an exact polynomial fit as if by @kbd{a F i},
  21653. then substitutes the @expr{x} value into the result in order to get an
  21654. approximate @expr{y} value based on the fit. (Calc does not actually
  21655. use @kbd{a F i}, however; it uses a direct method which is both more
  21656. efficient and more numerically stable.)
  21657. The result of @kbd{a p} is actually a vector of two values: The @expr{y}
  21658. value approximation, and an error measure @expr{dy} that reflects Calc's
  21659. estimation of the probable error of the approximation at that value of
  21660. @expr{x}. If the input @expr{x} is equal to any of the @expr{x} values
  21661. in the data matrix, the output @expr{y} will be the corresponding @expr{y}
  21662. value from the matrix, and the output @expr{dy} will be exactly zero.
  21663. A prefix argument of 2 causes @kbd{a p} to take separate x- and
  21664. y-vectors from the stack instead of one data matrix.
  21665. If @expr{x} is a vector of numbers, @kbd{a p} will return a matrix of
  21666. interpolated results for each of those @expr{x} values. (The matrix will
  21667. have two columns, the @expr{y} values and the @expr{dy} values.)
  21668. If @expr{x} is a formula instead of a number, the @code{polint} function
  21669. remains in symbolic form; use the @kbd{a "} command to expand it out to
  21670. a formula that describes the fit in symbolic terms.
  21671. In all cases, the @kbd{a p} command leaves the data vectors or matrix
  21672. on the stack. Only the @expr{x} value is replaced by the result.
  21673. @kindex H a p
  21674. @tindex ratint
  21675. The @kbd{H a p} [@code{ratint}] command does a rational function
  21676. interpolation. It is used exactly like @kbd{a p}, except that it
  21677. uses as its model the quotient of two polynomials. If there are
  21678. @expr{N} data points, the numerator and denominator polynomials will
  21679. each have degree @expr{N/2} (if @expr{N} is odd, the denominator will
  21680. have degree one higher than the numerator).
  21681. Rational approximations have the advantage that they can accurately
  21682. describe functions that have poles (points at which the function's value
  21683. goes to infinity, so that the denominator polynomial of the approximation
  21684. goes to zero). If @expr{x} corresponds to a pole of the fitted rational
  21685. function, then the result will be a division by zero. If Infinite mode
  21686. is enabled, the result will be @samp{[uinf, uinf]}.
  21687. There is no way to get the actual coefficients of the rational function
  21688. used by @kbd{H a p}. (The algorithm never generates these coefficients
  21689. explicitly, and quotients of polynomials are beyond @w{@kbd{a F}}'s
  21690. capabilities to fit.)
  21691. @node Summations, Logical Operations, Curve Fitting, Algebra
  21692. @section Summations
  21693. @noindent
  21694. @cindex Summation of a series
  21695. @kindex a +
  21696. @pindex calc-summation
  21697. @tindex sum
  21698. The @kbd{a +} (@code{calc-summation}) [@code{sum}] command computes
  21699. the sum of a formula over a certain range of index values. The formula
  21700. is taken from the top of the stack; the command prompts for the
  21701. name of the summation index variable, the lower limit of the
  21702. sum (any formula), and the upper limit of the sum. If you
  21703. enter a blank line at any of these prompts, that prompt and
  21704. any later ones are answered by reading additional elements from
  21705. the stack. Thus, @kbd{' k^2 @key{RET} ' k @key{RET} 1 @key{RET} 5 @key{RET} a + @key{RET}}
  21706. produces the result 55.
  21707. @tex
  21708. $$ \sum_{k=1}^5 k^2 = 55 $$
  21709. @end tex
  21710. The choice of index variable is arbitrary, but it's best not to
  21711. use a variable with a stored value. In particular, while
  21712. @code{i} is often a favorite index variable, it should be avoided
  21713. in Calc because @code{i} has the imaginary constant @expr{(0, 1)}
  21714. as a value. If you pressed @kbd{=} on a sum over @code{i}, it would
  21715. be changed to a nonsensical sum over the ``variable'' @expr{(0, 1)}!
  21716. If you really want to use @code{i} as an index variable, use
  21717. @w{@kbd{s u i @key{RET}}} first to ``unstore'' this variable.
  21718. (@xref{Storing Variables}.)
  21719. A numeric prefix argument steps the index by that amount rather
  21720. than by one. Thus @kbd{' a_k @key{RET} C-u -2 a + k @key{RET} 10 @key{RET} 0 @key{RET}}
  21721. yields @samp{a_10 + a_8 + a_6 + a_4 + a_2 + a_0}. A prefix
  21722. argument of plain @kbd{C-u} causes @kbd{a +} to prompt for the
  21723. step value, in which case you can enter any formula or enter
  21724. a blank line to take the step value from the stack. With the
  21725. @kbd{C-u} prefix, @kbd{a +} can take up to five arguments from
  21726. the stack: The formula, the variable, the lower limit, the
  21727. upper limit, and (at the top of the stack), the step value.
  21728. Calc knows how to do certain sums in closed form. For example,
  21729. @samp{sum(6 k^2, k, 1, n) = @w{2 n^3} + 3 n^2 + n}. In particular,
  21730. this is possible if the formula being summed is polynomial or
  21731. exponential in the index variable. Sums of logarithms are
  21732. transformed into logarithms of products. Sums of trigonometric
  21733. and hyperbolic functions are transformed to sums of exponentials
  21734. and then done in closed form. Also, of course, sums in which the
  21735. lower and upper limits are both numbers can always be evaluated
  21736. just by grinding them out, although Calc will use closed forms
  21737. whenever it can for the sake of efficiency.
  21738. The notation for sums in algebraic formulas is
  21739. @samp{sum(@var{expr}, @var{var}, @var{low}, @var{high}, @var{step})}.
  21740. If @var{step} is omitted, it defaults to one. If @var{high} is
  21741. omitted, @var{low} is actually the upper limit and the lower limit
  21742. is one. If @var{low} is also omitted, the limits are @samp{-inf}
  21743. and @samp{inf}, respectively.
  21744. Infinite sums can sometimes be evaluated: @samp{sum(.5^k, k, 1, inf)}
  21745. returns @expr{1}. This is done by evaluating the sum in closed
  21746. form (to @samp{1. - 0.5^n} in this case), then evaluating this
  21747. formula with @code{n} set to @code{inf}. Calc's usual rules
  21748. for ``infinite'' arithmetic can find the answer from there. If
  21749. infinite arithmetic yields a @samp{nan}, or if the sum cannot be
  21750. solved in closed form, Calc leaves the @code{sum} function in
  21751. symbolic form. @xref{Infinities}.
  21752. As a special feature, if the limits are infinite (or omitted, as
  21753. described above) but the formula includes vectors subscripted by
  21754. expressions that involve the iteration variable, Calc narrows
  21755. the limits to include only the range of integers which result in
  21756. valid subscripts for the vector. For example, the sum
  21757. @samp{sum(k [a,b,c,d,e,f,g]_(2k),k)} evaluates to @samp{b + 2 d + 3 f}.
  21758. The limits of a sum do not need to be integers. For example,
  21759. @samp{sum(a_k, k, 0, 2 n, n)} produces @samp{a_0 + a_n + a_(2 n)}.
  21760. Calc computes the number of iterations using the formula
  21761. @samp{1 + (@var{high} - @var{low}) / @var{step}}, which must,
  21762. after algebraic simplification, evaluate to an integer.
  21763. If the number of iterations according to the above formula does
  21764. not come out to an integer, the sum is invalid and will be left
  21765. in symbolic form. However, closed forms are still supplied, and
  21766. you are on your honor not to misuse the resulting formulas by
  21767. substituting mismatched bounds into them. For example,
  21768. @samp{sum(k, k, 1, 10, 2)} is invalid, but Calc will go ahead and
  21769. evaluate the closed form solution for the limits 1 and 10 to get
  21770. the rather dubious answer, 29.25.
  21771. If the lower limit is greater than the upper limit (assuming a
  21772. positive step size), the result is generally zero. However,
  21773. Calc only guarantees a zero result when the upper limit is
  21774. exactly one step less than the lower limit, i.e., if the number
  21775. of iterations is @mathit{-1}. Thus @samp{sum(f(k), k, n, n-1)} is zero
  21776. but the sum from @samp{n} to @samp{n-2} may report a nonzero value
  21777. if Calc used a closed form solution.
  21778. Calc's logical predicates like @expr{a < b} return 1 for ``true''
  21779. and 0 for ``false.'' @xref{Logical Operations}. This can be
  21780. used to advantage for building conditional sums. For example,
  21781. @samp{sum(prime(k)*k^2, k, 1, 20)} is the sum of the squares of all
  21782. prime numbers from 1 to 20; the @code{prime} predicate returns 1 if
  21783. its argument is prime and 0 otherwise. You can read this expression
  21784. as ``the sum of @expr{k^2}, where @expr{k} is prime.'' Indeed,
  21785. @samp{sum(prime(k)*k^2, k)} would represent the sum of @emph{all} primes
  21786. squared, since the limits default to plus and minus infinity, but
  21787. there are no such sums that Calc's built-in rules can do in
  21788. closed form.
  21789. As another example, @samp{sum((k != k_0) * f(k), k, 1, n)} is the
  21790. sum of @expr{f(k)} for all @expr{k} from 1 to @expr{n}, excluding
  21791. one value @expr{k_0}. Slightly more tricky is the summand
  21792. @samp{(k != k_0) / (k - k_0)}, which is an attempt to describe
  21793. the sum of all @expr{1/(k-k_0)} except at @expr{k = k_0}, where
  21794. this would be a division by zero. But at @expr{k = k_0}, this
  21795. formula works out to the indeterminate form @expr{0 / 0}, which
  21796. Calc will not assume is zero. Better would be to use
  21797. @samp{(k != k_0) ? 1/(k-k_0) : 0}; the @samp{? :} operator does
  21798. an ``if-then-else'' test: This expression says, ``if
  21799. @texline @math{k \ne k_0},
  21800. @infoline @expr{k != k_0},
  21801. then @expr{1/(k-k_0)}, else zero.'' Now the formula @expr{1/(k-k_0)}
  21802. will not even be evaluated by Calc when @expr{k = k_0}.
  21803. @cindex Alternating sums
  21804. @kindex a -
  21805. @pindex calc-alt-summation
  21806. @tindex asum
  21807. The @kbd{a -} (@code{calc-alt-summation}) [@code{asum}] command
  21808. computes an alternating sum. Successive terms of the sequence
  21809. are given alternating signs, with the first term (corresponding
  21810. to the lower index value) being positive. Alternating sums
  21811. are converted to normal sums with an extra term of the form
  21812. @samp{(-1)^(k-@var{low})}. This formula is adjusted appropriately
  21813. if the step value is other than one. For example, the Taylor
  21814. series for the sine function is @samp{asum(x^k / k!, k, 1, inf, 2)}.
  21815. (Calc cannot evaluate this infinite series, but it can approximate
  21816. it if you replace @code{inf} with any particular odd number.)
  21817. Calc converts this series to a regular sum with a step of one,
  21818. namely @samp{sum((-1)^k x^(2k+1) / (2k+1)!, k, 0, inf)}.
  21819. @cindex Product of a sequence
  21820. @kindex a *
  21821. @pindex calc-product
  21822. @tindex prod
  21823. The @kbd{a *} (@code{calc-product}) [@code{prod}] command is
  21824. the analogous way to take a product of many terms. Calc also knows
  21825. some closed forms for products, such as @samp{prod(k, k, 1, n) = n!}.
  21826. Conditional products can be written @samp{prod(k^prime(k), k, 1, n)}
  21827. or @samp{prod(prime(k) ? k : 1, k, 1, n)}.
  21828. @kindex a T
  21829. @pindex calc-tabulate
  21830. @tindex table
  21831. The @kbd{a T} (@code{calc-tabulate}) [@code{table}] command
  21832. evaluates a formula at a series of iterated index values, just
  21833. like @code{sum} and @code{prod}, but its result is simply a
  21834. vector of the results. For example, @samp{table(a_i, i, 1, 7, 2)}
  21835. produces @samp{[a_1, a_3, a_5, a_7]}.
  21836. @node Logical Operations, Rewrite Rules, Summations, Algebra
  21837. @section Logical Operations
  21838. @noindent
  21839. The following commands and algebraic functions return true/false values,
  21840. where 1 represents ``true'' and 0 represents ``false.'' In cases where
  21841. a truth value is required (such as for the condition part of a rewrite
  21842. rule, or as the condition for a @w{@kbd{Z [ Z ]}} control structure), any
  21843. nonzero value is accepted to mean ``true.'' (Specifically, anything
  21844. for which @code{dnonzero} returns 1 is ``true,'' and anything for
  21845. which @code{dnonzero} returns 0 or cannot decide is assumed ``false.''
  21846. Note that this means that @w{@kbd{Z [ Z ]}} will execute the ``then''
  21847. portion if its condition is provably true, but it will execute the
  21848. ``else'' portion for any condition like @expr{a = b} that is not
  21849. provably true, even if it might be true. Algebraic functions that
  21850. have conditions as arguments, like @code{? :} and @code{&&}, remain
  21851. unevaluated if the condition is neither provably true nor provably
  21852. false. @xref{Declarations}.)
  21853. @kindex a =
  21854. @pindex calc-equal-to
  21855. @tindex eq
  21856. @tindex =
  21857. @tindex ==
  21858. The @kbd{a =} (@code{calc-equal-to}) command, or @samp{eq(a,b)} function
  21859. (which can also be written @samp{a = b} or @samp{a == b} in an algebraic
  21860. formula) is true if @expr{a} and @expr{b} are equal, either because they
  21861. are identical expressions, or because they are numbers which are
  21862. numerically equal. (Thus the integer 1 is considered equal to the float
  21863. 1.0.) If the equality of @expr{a} and @expr{b} cannot be determined,
  21864. the comparison is left in symbolic form. Note that as a command, this
  21865. operation pops two values from the stack and pushes back either a 1 or
  21866. a 0, or a formula @samp{a = b} if the values' equality cannot be determined.
  21867. Many Calc commands use @samp{=} formulas to represent @dfn{equations}.
  21868. For example, the @kbd{a S} (@code{calc-solve-for}) command rearranges
  21869. an equation to solve for a given variable. The @kbd{a M}
  21870. (@code{calc-map-equation}) command can be used to apply any
  21871. function to both sides of an equation; for example, @kbd{2 a M *}
  21872. multiplies both sides of the equation by two. Note that just
  21873. @kbd{2 *} would not do the same thing; it would produce the formula
  21874. @samp{2 (a = b)} which represents 2 if the equality is true or
  21875. zero if not.
  21876. The @code{eq} function with more than two arguments (e.g., @kbd{C-u 3 a =}
  21877. or @samp{a = b = c}) tests if all of its arguments are equal. In
  21878. algebraic notation, the @samp{=} operator is unusual in that it is
  21879. neither left- nor right-associative: @samp{a = b = c} is not the
  21880. same as @samp{(a = b) = c} or @samp{a = (b = c)} (which each compare
  21881. one variable with the 1 or 0 that results from comparing two other
  21882. variables).
  21883. @kindex a #
  21884. @pindex calc-not-equal-to
  21885. @tindex neq
  21886. @tindex !=
  21887. The @kbd{a #} (@code{calc-not-equal-to}) command, or @samp{neq(a,b)} or
  21888. @samp{a != b} function, is true if @expr{a} and @expr{b} are not equal.
  21889. This also works with more than two arguments; @samp{a != b != c != d}
  21890. tests that all four of @expr{a}, @expr{b}, @expr{c}, and @expr{d} are
  21891. distinct numbers.
  21892. @kindex a <
  21893. @tindex lt
  21894. @ignore
  21895. @mindex @idots
  21896. @end ignore
  21897. @kindex a >
  21898. @ignore
  21899. @mindex @null
  21900. @end ignore
  21901. @kindex a [
  21902. @ignore
  21903. @mindex @null
  21904. @end ignore
  21905. @kindex a ]
  21906. @pindex calc-less-than
  21907. @pindex calc-greater-than
  21908. @pindex calc-less-equal
  21909. @pindex calc-greater-equal
  21910. @ignore
  21911. @mindex @null
  21912. @end ignore
  21913. @tindex gt
  21914. @ignore
  21915. @mindex @null
  21916. @end ignore
  21917. @tindex leq
  21918. @ignore
  21919. @mindex @null
  21920. @end ignore
  21921. @tindex geq
  21922. @ignore
  21923. @mindex @null
  21924. @end ignore
  21925. @tindex <
  21926. @ignore
  21927. @mindex @null
  21928. @end ignore
  21929. @tindex >
  21930. @ignore
  21931. @mindex @null
  21932. @end ignore
  21933. @tindex <=
  21934. @ignore
  21935. @mindex @null
  21936. @end ignore
  21937. @tindex >=
  21938. The @kbd{a <} (@code{calc-less-than}) [@samp{lt(a,b)} or @samp{a < b}]
  21939. operation is true if @expr{a} is less than @expr{b}. Similar functions
  21940. are @kbd{a >} (@code{calc-greater-than}) [@samp{gt(a,b)} or @samp{a > b}],
  21941. @kbd{a [} (@code{calc-less-equal}) [@samp{leq(a,b)} or @samp{a <= b}], and
  21942. @kbd{a ]} (@code{calc-greater-equal}) [@samp{geq(a,b)} or @samp{a >= b}].
  21943. While the inequality functions like @code{lt} do not accept more
  21944. than two arguments, the syntax @w{@samp{a <= b < c}} is translated to an
  21945. equivalent expression involving intervals: @samp{b in [a .. c)}.
  21946. (See the description of @code{in} below.) All four combinations
  21947. of @samp{<} and @samp{<=} are allowed, or any of the four combinations
  21948. of @samp{>} and @samp{>=}. Four-argument constructions like
  21949. @samp{a < b < c < d}, and mixtures like @w{@samp{a < b = c}} that
  21950. involve both equations and inequalities, are not allowed.
  21951. @kindex a .
  21952. @pindex calc-remove-equal
  21953. @tindex rmeq
  21954. The @kbd{a .} (@code{calc-remove-equal}) [@code{rmeq}] command extracts
  21955. the righthand side of the equation or inequality on the top of the
  21956. stack. It also works elementwise on vectors. For example, if
  21957. @samp{[x = 2.34, y = z / 2]} is on the stack, then @kbd{a .} produces
  21958. @samp{[2.34, z / 2]}. As a special case, if the righthand side is a
  21959. variable and the lefthand side is a number (as in @samp{2.34 = x}), then
  21960. Calc keeps the lefthand side instead. Finally, this command works with
  21961. assignments @samp{x := 2.34} as well as equations, always taking the
  21962. righthand side, and for @samp{=>} (evaluates-to) operators, always
  21963. taking the lefthand side.
  21964. @kindex a &
  21965. @pindex calc-logical-and
  21966. @tindex land
  21967. @tindex &&
  21968. The @kbd{a &} (@code{calc-logical-and}) [@samp{land(a,b)} or @samp{a && b}]
  21969. function is true if both of its arguments are true, i.e., are
  21970. non-zero numbers. In this case, the result will be either @expr{a} or
  21971. @expr{b}, chosen arbitrarily. If either argument is zero, the result is
  21972. zero. Otherwise, the formula is left in symbolic form.
  21973. @kindex a |
  21974. @pindex calc-logical-or
  21975. @tindex lor
  21976. @tindex ||
  21977. The @kbd{a |} (@code{calc-logical-or}) [@samp{lor(a,b)} or @samp{a || b}]
  21978. function is true if either or both of its arguments are true (nonzero).
  21979. The result is whichever argument was nonzero, choosing arbitrarily if both
  21980. are nonzero. If both @expr{a} and @expr{b} are zero, the result is
  21981. zero.
  21982. @kindex a !
  21983. @pindex calc-logical-not
  21984. @tindex lnot
  21985. @tindex !
  21986. The @kbd{a !} (@code{calc-logical-not}) [@samp{lnot(a)} or @samp{!@: a}]
  21987. function is true if @expr{a} is false (zero), or false if @expr{a} is
  21988. true (nonzero). It is left in symbolic form if @expr{a} is not a
  21989. number.
  21990. @kindex a :
  21991. @pindex calc-logical-if
  21992. @tindex if
  21993. @ignore
  21994. @mindex ? :
  21995. @end ignore
  21996. @tindex ?
  21997. @ignore
  21998. @mindex @null
  21999. @end ignore
  22000. @tindex :
  22001. @cindex Arguments, not evaluated
  22002. The @kbd{a :} (@code{calc-logical-if}) [@samp{if(a,b,c)} or @samp{a ? b :@: c}]
  22003. function is equal to either @expr{b} or @expr{c} if @expr{a} is a nonzero
  22004. number or zero, respectively. If @expr{a} is not a number, the test is
  22005. left in symbolic form and neither @expr{b} nor @expr{c} is evaluated in
  22006. any way. In algebraic formulas, this is one of the few Calc functions
  22007. whose arguments are not automatically evaluated when the function itself
  22008. is evaluated. The others are @code{lambda}, @code{quote}, and
  22009. @code{condition}.
  22010. One minor surprise to watch out for is that the formula @samp{a?3:4}
  22011. will not work because the @samp{3:4} is parsed as a fraction instead of
  22012. as three separate symbols. Type something like @samp{a ? 3 : 4} or
  22013. @samp{a?(3):4} instead.
  22014. As a special case, if @expr{a} evaluates to a vector, then both @expr{b}
  22015. and @expr{c} are evaluated; the result is a vector of the same length
  22016. as @expr{a} whose elements are chosen from corresponding elements of
  22017. @expr{b} and @expr{c} according to whether each element of @expr{a}
  22018. is zero or nonzero. Each of @expr{b} and @expr{c} must be either a
  22019. vector of the same length as @expr{a}, or a non-vector which is matched
  22020. with all elements of @expr{a}.
  22021. @kindex a @{
  22022. @pindex calc-in-set
  22023. @tindex in
  22024. The @kbd{a @{} (@code{calc-in-set}) [@samp{in(a,b)}] function is true if
  22025. the number @expr{a} is in the set of numbers represented by @expr{b}.
  22026. If @expr{b} is an interval form, @expr{a} must be one of the values
  22027. encompassed by the interval. If @expr{b} is a vector, @expr{a} must be
  22028. equal to one of the elements of the vector. (If any vector elements are
  22029. intervals, @expr{a} must be in any of the intervals.) If @expr{b} is a
  22030. plain number, @expr{a} must be numerically equal to @expr{b}.
  22031. @xref{Set Operations}, for a group of commands that manipulate sets
  22032. of this sort.
  22033. @ignore
  22034. @starindex
  22035. @end ignore
  22036. @tindex typeof
  22037. The @samp{typeof(a)} function produces an integer or variable which
  22038. characterizes @expr{a}. If @expr{a} is a number, vector, or variable,
  22039. the result will be one of the following numbers:
  22040. @example
  22041. 1 Integer
  22042. 2 Fraction
  22043. 3 Floating-point number
  22044. 4 HMS form
  22045. 5 Rectangular complex number
  22046. 6 Polar complex number
  22047. 7 Error form
  22048. 8 Interval form
  22049. 9 Modulo form
  22050. 10 Date-only form
  22051. 11 Date/time form
  22052. 12 Infinity (inf, uinf, or nan)
  22053. 100 Variable
  22054. 101 Vector (but not a matrix)
  22055. 102 Matrix
  22056. @end example
  22057. Otherwise, @expr{a} is a formula, and the result is a variable which
  22058. represents the name of the top-level function call.
  22059. @ignore
  22060. @starindex
  22061. @end ignore
  22062. @tindex integer
  22063. @ignore
  22064. @starindex
  22065. @end ignore
  22066. @tindex real
  22067. @ignore
  22068. @starindex
  22069. @end ignore
  22070. @tindex constant
  22071. The @samp{integer(a)} function returns true if @expr{a} is an integer.
  22072. The @samp{real(a)} function
  22073. is true if @expr{a} is a real number, either integer, fraction, or
  22074. float. The @samp{constant(a)} function returns true if @expr{a} is
  22075. any of the objects for which @code{typeof} would produce an integer
  22076. code result except for variables, and provided that the components of
  22077. an object like a vector or error form are themselves constant.
  22078. Note that infinities do not satisfy any of these tests, nor do
  22079. special constants like @code{pi} and @code{e}.
  22080. @xref{Declarations}, for a set of similar functions that recognize
  22081. formulas as well as actual numbers. For example, @samp{dint(floor(x))}
  22082. is true because @samp{floor(x)} is provably integer-valued, but
  22083. @samp{integer(floor(x))} does not because @samp{floor(x)} is not
  22084. literally an integer constant.
  22085. @ignore
  22086. @starindex
  22087. @end ignore
  22088. @tindex refers
  22089. The @samp{refers(a,b)} function is true if the variable (or sub-expression)
  22090. @expr{b} appears in @expr{a}, or false otherwise. Unlike the other
  22091. tests described here, this function returns a definite ``no'' answer
  22092. even if its arguments are still in symbolic form. The only case where
  22093. @code{refers} will be left unevaluated is if @expr{a} is a plain
  22094. variable (different from @expr{b}).
  22095. @ignore
  22096. @starindex
  22097. @end ignore
  22098. @tindex negative
  22099. The @samp{negative(a)} function returns true if @expr{a} ``looks'' negative,
  22100. because it is a negative number, because it is of the form @expr{-x},
  22101. or because it is a product or quotient with a term that looks negative.
  22102. This is most useful in rewrite rules. Beware that @samp{negative(a)}
  22103. evaluates to 1 or 0 for @emph{any} argument @expr{a}, so it can only
  22104. be stored in a formula if the default simplifications are turned off
  22105. first with @kbd{m O} (or if it appears in an unevaluated context such
  22106. as a rewrite rule condition).
  22107. @ignore
  22108. @starindex
  22109. @end ignore
  22110. @tindex variable
  22111. The @samp{variable(a)} function is true if @expr{a} is a variable,
  22112. or false if not. If @expr{a} is a function call, this test is left
  22113. in symbolic form. Built-in variables like @code{pi} and @code{inf}
  22114. are considered variables like any others by this test.
  22115. @ignore
  22116. @starindex
  22117. @end ignore
  22118. @tindex nonvar
  22119. The @samp{nonvar(a)} function is true if @expr{a} is a non-variable.
  22120. If its argument is a variable it is left unsimplified; it never
  22121. actually returns zero. However, since Calc's condition-testing
  22122. commands consider ``false'' anything not provably true, this is
  22123. often good enough.
  22124. @ignore
  22125. @starindex
  22126. @end ignore
  22127. @tindex lin
  22128. @ignore
  22129. @starindex
  22130. @end ignore
  22131. @tindex linnt
  22132. @ignore
  22133. @starindex
  22134. @end ignore
  22135. @tindex islin
  22136. @ignore
  22137. @starindex
  22138. @end ignore
  22139. @tindex islinnt
  22140. @cindex Linearity testing
  22141. The functions @code{lin}, @code{linnt}, @code{islin}, and @code{islinnt}
  22142. check if an expression is ``linear,'' i.e., can be written in the form
  22143. @expr{a + b x} for some constants @expr{a} and @expr{b}, and some
  22144. variable or subformula @expr{x}. The function @samp{islin(f,x)} checks
  22145. if formula @expr{f} is linear in @expr{x}, returning 1 if so. For
  22146. example, @samp{islin(x,x)}, @samp{islin(-x,x)}, @samp{islin(3,x)}, and
  22147. @samp{islin(x y / 3 - 2, x)} all return 1. The @samp{lin(f,x)} function
  22148. is similar, except that instead of returning 1 it returns the vector
  22149. @expr{[a, b, x]}. For the above examples, this vector would be
  22150. @expr{[0, 1, x]}, @expr{[0, -1, x]}, @expr{[3, 0, x]}, and
  22151. @expr{[-2, y/3, x]}, respectively. Both @code{lin} and @code{islin}
  22152. generally remain unevaluated for expressions which are not linear,
  22153. e.g., @samp{lin(2 x^2, x)} and @samp{lin(sin(x), x)}. The second
  22154. argument can also be a formula; @samp{islin(2 + 3 sin(x), sin(x))}
  22155. returns true.
  22156. The @code{linnt} and @code{islinnt} functions perform a similar check,
  22157. but require a ``non-trivial'' linear form, which means that the
  22158. @expr{b} coefficient must be non-zero. For example, @samp{lin(2,x)}
  22159. returns @expr{[2, 0, x]} and @samp{lin(y,x)} returns @expr{[y, 0, x]},
  22160. but @samp{linnt(2,x)} and @samp{linnt(y,x)} are left unevaluated
  22161. (in other words, these formulas are considered to be only ``trivially''
  22162. linear in @expr{x}).
  22163. All four linearity-testing functions allow you to omit the second
  22164. argument, in which case the input may be linear in any non-constant
  22165. formula. Here, the @expr{a=0}, @expr{b=1} case is also considered
  22166. trivial, and only constant values for @expr{a} and @expr{b} are
  22167. recognized. Thus, @samp{lin(2 x y)} returns @expr{[0, 2, x y]},
  22168. @samp{lin(2 - x y)} returns @expr{[2, -1, x y]}, and @samp{lin(x y)}
  22169. returns @expr{[0, 1, x y]}. The @code{linnt} function would allow the
  22170. first two cases but not the third. Also, neither @code{lin} nor
  22171. @code{linnt} accept plain constants as linear in the one-argument
  22172. case: @samp{islin(2,x)} is true, but @samp{islin(2)} is false.
  22173. @ignore
  22174. @starindex
  22175. @end ignore
  22176. @tindex istrue
  22177. The @samp{istrue(a)} function returns 1 if @expr{a} is a nonzero
  22178. number or provably nonzero formula, or 0 if @expr{a} is anything else.
  22179. Calls to @code{istrue} can only be manipulated if @kbd{m O} mode is
  22180. used to make sure they are not evaluated prematurely. (Note that
  22181. declarations are used when deciding whether a formula is true;
  22182. @code{istrue} returns 1 when @code{dnonzero} would return 1, and
  22183. it returns 0 when @code{dnonzero} would return 0 or leave itself
  22184. in symbolic form.)
  22185. @node Rewrite Rules, , Logical Operations, Algebra
  22186. @section Rewrite Rules
  22187. @noindent
  22188. @cindex Rewrite rules
  22189. @cindex Transformations
  22190. @cindex Pattern matching
  22191. @kindex a r
  22192. @pindex calc-rewrite
  22193. @tindex rewrite
  22194. The @kbd{a r} (@code{calc-rewrite}) [@code{rewrite}] command makes
  22195. substitutions in a formula according to a specified pattern or patterns
  22196. known as @dfn{rewrite rules}. Whereas @kbd{a b} (@code{calc-substitute})
  22197. matches literally, so that substituting @samp{sin(x)} with @samp{cos(x)}
  22198. matches only the @code{sin} function applied to the variable @code{x},
  22199. rewrite rules match general kinds of formulas; rewriting using the rule
  22200. @samp{sin(x) := cos(x)} matches @code{sin} of any argument and replaces
  22201. it with @code{cos} of that same argument. The only significance of the
  22202. name @code{x} is that the same name is used on both sides of the rule.
  22203. Rewrite rules rearrange formulas already in Calc's memory.
  22204. @xref{Syntax Tables}, to read about @dfn{syntax rules}, which are
  22205. similar to algebraic rewrite rules but operate when new algebraic
  22206. entries are being parsed, converting strings of characters into
  22207. Calc formulas.
  22208. @menu
  22209. * Entering Rewrite Rules::
  22210. * Basic Rewrite Rules::
  22211. * Conditional Rewrite Rules::
  22212. * Algebraic Properties of Rewrite Rules::
  22213. * Other Features of Rewrite Rules::
  22214. * Composing Patterns in Rewrite Rules::
  22215. * Nested Formulas with Rewrite Rules::
  22216. * Multi-Phase Rewrite Rules::
  22217. * Selections with Rewrite Rules::
  22218. * Matching Commands::
  22219. * Automatic Rewrites::
  22220. * Debugging Rewrites::
  22221. * Examples of Rewrite Rules::
  22222. @end menu
  22223. @node Entering Rewrite Rules, Basic Rewrite Rules, Rewrite Rules, Rewrite Rules
  22224. @subsection Entering Rewrite Rules
  22225. @noindent
  22226. Rewrite rules normally use the ``assignment'' operator
  22227. @samp{@var{old} := @var{new}}.
  22228. This operator is equivalent to the function call @samp{assign(old, new)}.
  22229. The @code{assign} function is undefined by itself in Calc, so an
  22230. assignment formula such as a rewrite rule will be left alone by ordinary
  22231. Calc commands. But certain commands, like the rewrite system, interpret
  22232. assignments in special ways.
  22233. For example, the rule @samp{sin(x)^2 := 1-cos(x)^2} says to replace
  22234. every occurrence of the sine of something, squared, with one minus the
  22235. square of the cosine of that same thing. All by itself as a formula
  22236. on the stack it does nothing, but when given to the @kbd{a r} command
  22237. it turns that command into a sine-squared-to-cosine-squared converter.
  22238. To specify a set of rules to be applied all at once, make a vector of
  22239. rules.
  22240. When @kbd{a r} prompts you to enter the rewrite rules, you can answer
  22241. in several ways:
  22242. @enumerate
  22243. @item
  22244. With a rule: @kbd{f(x) := g(x) @key{RET}}.
  22245. @item
  22246. With a vector of rules: @kbd{[f1(x) := g1(x), f2(x) := g2(x)] @key{RET}}.
  22247. (You can omit the enclosing square brackets if you wish.)
  22248. @item
  22249. With the name of a variable that contains the rule or rules vector:
  22250. @kbd{myrules @key{RET}}.
  22251. @item
  22252. With any formula except a rule, a vector, or a variable name; this
  22253. will be interpreted as the @var{old} half of a rewrite rule,
  22254. and you will be prompted a second time for the @var{new} half:
  22255. @kbd{f(x) @key{RET} g(x) @key{RET}}.
  22256. @item
  22257. With a blank line, in which case the rule, rules vector, or variable
  22258. will be taken from the top of the stack (and the formula to be
  22259. rewritten will come from the second-to-top position).
  22260. @end enumerate
  22261. If you enter the rules directly (as opposed to using rules stored
  22262. in a variable), those rules will be put into the Trail so that you
  22263. can retrieve them later. @xref{Trail Commands}.
  22264. It is most convenient to store rules you use often in a variable and
  22265. invoke them by giving the variable name. The @kbd{s e}
  22266. (@code{calc-edit-variable}) command is an easy way to create or edit a
  22267. rule set stored in a variable. You may also wish to use @kbd{s p}
  22268. (@code{calc-permanent-variable}) to save your rules permanently;
  22269. @pxref{Operations on Variables}.
  22270. Rewrite rules are compiled into a special internal form for faster
  22271. matching. If you enter a rule set directly it must be recompiled
  22272. every time. If you store the rules in a variable and refer to them
  22273. through that variable, they will be compiled once and saved away
  22274. along with the variable for later reference. This is another good
  22275. reason to store your rules in a variable.
  22276. Calc also accepts an obsolete notation for rules, as vectors
  22277. @samp{[@var{old}, @var{new}]}. But because it is easily confused with a
  22278. vector of two rules, the use of this notation is no longer recommended.
  22279. @node Basic Rewrite Rules, Conditional Rewrite Rules, Entering Rewrite Rules, Rewrite Rules
  22280. @subsection Basic Rewrite Rules
  22281. @noindent
  22282. To match a particular formula @expr{x} with a particular rewrite rule
  22283. @samp{@var{old} := @var{new}}, Calc compares the structure of @expr{x} with
  22284. the structure of @var{old}. Variables that appear in @var{old} are
  22285. treated as @dfn{meta-variables}; the corresponding positions in @expr{x}
  22286. may contain any sub-formulas. For example, the pattern @samp{f(x,y)}
  22287. would match the expression @samp{f(12, a+1)} with the meta-variable
  22288. @samp{x} corresponding to 12 and with @samp{y} corresponding to
  22289. @samp{a+1}. However, this pattern would not match @samp{f(12)} or
  22290. @samp{g(12, a+1)}, since there is no assignment of the meta-variables
  22291. that will make the pattern match these expressions. Notice that if
  22292. the pattern is a single meta-variable, it will match any expression.
  22293. If a given meta-variable appears more than once in @var{old}, the
  22294. corresponding sub-formulas of @expr{x} must be identical. Thus
  22295. the pattern @samp{f(x,x)} would match @samp{f(12, 12)} and
  22296. @samp{f(a+1, a+1)} but not @samp{f(12, a+1)} or @samp{f(a+b, b+a)}.
  22297. (@xref{Conditional Rewrite Rules}, for a way to match the latter.)
  22298. Things other than variables must match exactly between the pattern
  22299. and the target formula. To match a particular variable exactly, use
  22300. the pseudo-function @samp{quote(v)} in the pattern. For example, the
  22301. pattern @samp{x+quote(y)} matches @samp{x+y}, @samp{2+y}, or
  22302. @samp{sin(a)+y}.
  22303. The special variable names @samp{e}, @samp{pi}, @samp{i}, @samp{phi},
  22304. @samp{gamma}, @samp{inf}, @samp{uinf}, and @samp{nan} always match
  22305. literally. Thus the pattern @samp{sin(d + e + f)} acts exactly like
  22306. @samp{sin(d + quote(e) + f)}.
  22307. If the @var{old} pattern is found to match a given formula, that
  22308. formula is replaced by @var{new}, where any occurrences in @var{new}
  22309. of meta-variables from the pattern are replaced with the sub-formulas
  22310. that they matched. Thus, applying the rule @samp{f(x,y) := g(y+x,x)}
  22311. to @samp{f(12, a+1)} would produce @samp{g(a+13, 12)}.
  22312. The normal @kbd{a r} command applies rewrite rules over and over
  22313. throughout the target formula until no further changes are possible
  22314. (up to a limit of 100 times). Use @kbd{C-u 1 a r} to make only one
  22315. change at a time.
  22316. @node Conditional Rewrite Rules, Algebraic Properties of Rewrite Rules, Basic Rewrite Rules, Rewrite Rules
  22317. @subsection Conditional Rewrite Rules
  22318. @noindent
  22319. A rewrite rule can also be @dfn{conditional}, written in the form
  22320. @samp{@var{old} := @var{new} :: @var{cond}}. (There is also the obsolete
  22321. form @samp{[@var{old}, @var{new}, @var{cond}]}.) If a @var{cond} part
  22322. is present in the
  22323. rule, this is an additional condition that must be satisfied before
  22324. the rule is accepted. Once @var{old} has been successfully matched
  22325. to the target expression, @var{cond} is evaluated (with all the
  22326. meta-variables substituted for the values they matched) and simplified
  22327. with Calc's algebraic simplifications. If the result is a nonzero
  22328. number or any other object known to be nonzero (@pxref{Declarations}),
  22329. the rule is accepted. If the result is zero or if it is a symbolic
  22330. formula that is not known to be nonzero, the rule is rejected.
  22331. @xref{Logical Operations}, for a number of functions that return
  22332. 1 or 0 according to the results of various tests.
  22333. For example, the formula @samp{n > 0} simplifies to 1 or 0 if @expr{n}
  22334. is replaced by a positive or nonpositive number, respectively (or if
  22335. @expr{n} has been declared to be positive or nonpositive). Thus,
  22336. the rule @samp{f(x,y) := g(y+x,x) :: x+y > 0} would apply to
  22337. @samp{f(0, 4)} but not to @samp{f(-3, 2)} or @samp{f(12, a+1)}
  22338. (assuming no outstanding declarations for @expr{a}). In the case of
  22339. @samp{f(-3, 2)}, the condition can be shown not to be satisfied; in
  22340. the case of @samp{f(12, a+1)}, the condition merely cannot be shown
  22341. to be satisfied, but that is enough to reject the rule.
  22342. While Calc will use declarations to reason about variables in the
  22343. formula being rewritten, declarations do not apply to meta-variables.
  22344. For example, the rule @samp{f(a) := g(a+1)} will match for any values
  22345. of @samp{a}, such as complex numbers, vectors, or formulas, even if
  22346. @samp{a} has been declared to be real or scalar. If you want the
  22347. meta-variable @samp{a} to match only literal real numbers, use
  22348. @samp{f(a) := g(a+1) :: real(a)}. If you want @samp{a} to match only
  22349. reals and formulas which are provably real, use @samp{dreal(a)} as
  22350. the condition.
  22351. The @samp{::} operator is a shorthand for the @code{condition}
  22352. function; @samp{@var{old} := @var{new} :: @var{cond}} is equivalent to
  22353. the formula @samp{condition(assign(@var{old}, @var{new}), @var{cond})}.
  22354. If you have several conditions, you can use @samp{... :: c1 :: c2 :: c3}
  22355. or @samp{... :: c1 && c2 && c3}. The two are entirely equivalent.
  22356. It is also possible to embed conditions inside the pattern:
  22357. @samp{f(x :: x>0, y) := g(y+x, x)}. This is purely a notational
  22358. convenience, though; where a condition appears in a rule has no
  22359. effect on when it is tested. The rewrite-rule compiler automatically
  22360. decides when it is best to test each condition while a rule is being
  22361. matched.
  22362. Certain conditions are handled as special cases by the rewrite rule
  22363. system and are tested very efficiently: Where @expr{x} is any
  22364. meta-variable, these conditions are @samp{integer(x)}, @samp{real(x)},
  22365. @samp{constant(x)}, @samp{negative(x)}, @samp{x >= y} where @expr{y}
  22366. is either a constant or another meta-variable and @samp{>=} may be
  22367. replaced by any of the six relational operators, and @samp{x % a = b}
  22368. where @expr{a} and @expr{b} are constants. Other conditions, like
  22369. @samp{x >= y+1} or @samp{dreal(x)}, will be less efficient to check
  22370. since Calc must bring the whole evaluator and simplifier into play.
  22371. An interesting property of @samp{::} is that neither of its arguments
  22372. will be touched by Calc's default simplifications. This is important
  22373. because conditions often are expressions that cannot safely be
  22374. evaluated early. For example, the @code{typeof} function never
  22375. remains in symbolic form; entering @samp{typeof(a)} will put the
  22376. number 100 (the type code for variables like @samp{a}) on the stack.
  22377. But putting the condition @samp{... :: typeof(a) = 6} on the stack
  22378. is safe since @samp{::} prevents the @code{typeof} from being
  22379. evaluated until the condition is actually used by the rewrite system.
  22380. Since @samp{::} protects its lefthand side, too, you can use a dummy
  22381. condition to protect a rule that must itself not evaluate early.
  22382. For example, it's not safe to put @samp{a(f,x) := apply(f, [x])} on
  22383. the stack because it will immediately evaluate to @samp{a(f,x) := f(x)},
  22384. where the meta-variable-ness of @code{f} on the righthand side has been
  22385. lost. But @samp{a(f,x) := apply(f, [x]) :: 1} is safe, and of course
  22386. the condition @samp{1} is always true (nonzero) so it has no effect on
  22387. the functioning of the rule. (The rewrite compiler will ensure that
  22388. it doesn't even impact the speed of matching the rule.)
  22389. @node Algebraic Properties of Rewrite Rules, Other Features of Rewrite Rules, Conditional Rewrite Rules, Rewrite Rules
  22390. @subsection Algebraic Properties of Rewrite Rules
  22391. @noindent
  22392. The rewrite mechanism understands the algebraic properties of functions
  22393. like @samp{+} and @samp{*}. In particular, pattern matching takes
  22394. the associativity and commutativity of the following functions into
  22395. account:
  22396. @smallexample
  22397. + - * = != && || and or xor vint vunion vxor gcd lcm max min beta
  22398. @end smallexample
  22399. For example, the rewrite rule:
  22400. @example
  22401. a x + b x := (a + b) x
  22402. @end example
  22403. @noindent
  22404. will match formulas of the form,
  22405. @example
  22406. a x + b x, x a + x b, a x + x b, x a + b x
  22407. @end example
  22408. Rewrites also understand the relationship between the @samp{+} and @samp{-}
  22409. operators. The above rewrite rule will also match the formulas,
  22410. @example
  22411. a x - b x, x a - x b, a x - x b, x a - b x
  22412. @end example
  22413. @noindent
  22414. by matching @samp{b} in the pattern to @samp{-b} from the formula.
  22415. Applied to a sum of many terms like @samp{r + a x + s + b x + t}, this
  22416. pattern will check all pairs of terms for possible matches. The rewrite
  22417. will take whichever suitable pair it discovers first.
  22418. In general, a pattern using an associative operator like @samp{a + b}
  22419. will try @var{2 n} different ways to match a sum of @var{n} terms
  22420. like @samp{x + y + z - w}. First, @samp{a} is matched against each
  22421. of @samp{x}, @samp{y}, @samp{z}, and @samp{-w} in turn, with @samp{b}
  22422. being matched to the remainders @samp{y + z - w}, @samp{x + z - w}, etc.
  22423. If none of these succeed, then @samp{b} is matched against each of the
  22424. four terms with @samp{a} matching the remainder. Half-and-half matches,
  22425. like @samp{(x + y) + (z - w)}, are not tried.
  22426. Note that @samp{*} is not commutative when applied to matrices, but
  22427. rewrite rules pretend that it is. If you type @kbd{m v} to enable
  22428. Matrix mode (@pxref{Matrix Mode}), rewrite rules will match @samp{*}
  22429. literally, ignoring its usual commutativity property. (In the
  22430. current implementation, the associativity also vanishes---it is as
  22431. if the pattern had been enclosed in a @code{plain} marker; see below.)
  22432. If you are applying rewrites to formulas with matrices, it's best to
  22433. enable Matrix mode first to prevent algebraically incorrect rewrites
  22434. from occurring.
  22435. The pattern @samp{-x} will actually match any expression. For example,
  22436. the rule
  22437. @example
  22438. f(-x) := -f(x)
  22439. @end example
  22440. @noindent
  22441. will rewrite @samp{f(a)} to @samp{-f(-a)}. To avoid this, either use
  22442. a @code{plain} marker as described below, or add a @samp{negative(x)}
  22443. condition. The @code{negative} function is true if its argument
  22444. ``looks'' negative, for example, because it is a negative number or
  22445. because it is a formula like @samp{-x}. The new rule using this
  22446. condition is:
  22447. @example
  22448. f(x) := -f(-x) :: negative(x) @r{or, equivalently,}
  22449. f(-x) := -f(x) :: negative(-x)
  22450. @end example
  22451. In the same way, the pattern @samp{x - y} will match the sum @samp{a + b}
  22452. by matching @samp{y} to @samp{-b}.
  22453. The pattern @samp{a b} will also match the formula @samp{x/y} if
  22454. @samp{y} is a number. Thus the rule @samp{a x + @w{b x} := (a+b) x}
  22455. will also convert @samp{a x + x / 2} to @samp{(a + 0.5) x} (or
  22456. @samp{(a + 1:2) x}, depending on the current fraction mode).
  22457. Calc will @emph{not} take other liberties with @samp{*}, @samp{/}, and
  22458. @samp{^}. For example, the pattern @samp{f(a b)} will not match
  22459. @samp{f(x^2)}, and @samp{f(a + b)} will not match @samp{f(2 x)}, even
  22460. though conceivably these patterns could match with @samp{a = b = x}.
  22461. Nor will @samp{f(a b)} match @samp{f(x / y)} if @samp{y} is not a
  22462. constant, even though it could be considered to match with @samp{a = x}
  22463. and @samp{b = 1/y}. The reasons are partly for efficiency, and partly
  22464. because while few mathematical operations are substantively different
  22465. for addition and subtraction, often it is preferable to treat the cases
  22466. of multiplication, division, and integer powers separately.
  22467. Even more subtle is the rule set
  22468. @example
  22469. [ f(a) + f(b) := f(a + b), -f(a) := f(-a) ]
  22470. @end example
  22471. @noindent
  22472. attempting to match @samp{f(x) - f(y)}. You might think that Calc
  22473. will view this subtraction as @samp{f(x) + (-f(y))} and then apply
  22474. the above two rules in turn, but actually this will not work because
  22475. Calc only does this when considering rules for @samp{+} (like the
  22476. first rule in this set). So it will see first that @samp{f(x) + (-f(y))}
  22477. does not match @samp{f(a) + f(b)} for any assignments of the
  22478. meta-variables, and then it will see that @samp{f(x) - f(y)} does
  22479. not match @samp{-f(a)} for any assignment of @samp{a}. Because Calc
  22480. tries only one rule at a time, it will not be able to rewrite
  22481. @samp{f(x) - f(y)} with this rule set. An explicit @samp{f(a) - f(b)}
  22482. rule will have to be added.
  22483. Another thing patterns will @emph{not} do is break up complex numbers.
  22484. The pattern @samp{myconj(a + @w{b i)} := a - b i} will work for formulas
  22485. involving the special constant @samp{i} (such as @samp{3 - 4 i}), but
  22486. it will not match actual complex numbers like @samp{(3, -4)}. A version
  22487. of the above rule for complex numbers would be
  22488. @example
  22489. myconj(a) := re(a) - im(a) (0,1) :: im(a) != 0
  22490. @end example
  22491. @noindent
  22492. (Because the @code{re} and @code{im} functions understand the properties
  22493. of the special constant @samp{i}, this rule will also work for
  22494. @samp{3 - 4 i}. In fact, this particular rule would probably be better
  22495. without the @samp{im(a) != 0} condition, since if @samp{im(a) = 0} the
  22496. righthand side of the rule will still give the correct answer for the
  22497. conjugate of a real number.)
  22498. It is also possible to specify optional arguments in patterns. The rule
  22499. @example
  22500. opt(a) x + opt(b) (x^opt(c) + opt(d)) := f(a, b, c, d)
  22501. @end example
  22502. @noindent
  22503. will match the formula
  22504. @example
  22505. 5 (x^2 - 4) + 3 x
  22506. @end example
  22507. @noindent
  22508. in a fairly straightforward manner, but it will also match reduced
  22509. formulas like
  22510. @example
  22511. x + x^2, 2(x + 1) - x, x + x
  22512. @end example
  22513. @noindent
  22514. producing, respectively,
  22515. @example
  22516. f(1, 1, 2, 0), f(-1, 2, 1, 1), f(1, 1, 1, 0)
  22517. @end example
  22518. (The latter two formulas can be entered only if default simplifications
  22519. have been turned off with @kbd{m O}.)
  22520. The default value for a term of a sum is zero. The default value
  22521. for a part of a product, for a power, or for the denominator of a
  22522. quotient, is one. Also, @samp{-x} matches the pattern @samp{opt(a) b}
  22523. with @samp{a = -1}.
  22524. In particular, the distributive-law rule can be refined to
  22525. @example
  22526. opt(a) x + opt(b) x := (a + b) x
  22527. @end example
  22528. @noindent
  22529. so that it will convert, e.g., @samp{a x - x}, to @samp{(a - 1) x}.
  22530. The pattern @samp{opt(a) + opt(b) x} matches almost any formulas which
  22531. are linear in @samp{x}. You can also use the @code{lin} and @code{islin}
  22532. functions with rewrite conditions to test for this; @pxref{Logical
  22533. Operations}. These functions are not as convenient to use in rewrite
  22534. rules, but they recognize more kinds of formulas as linear:
  22535. @samp{x/z} is considered linear with @expr{b = 1/z} by @code{lin},
  22536. but it will not match the above pattern because that pattern calls
  22537. for a multiplication, not a division.
  22538. As another example, the obvious rule to replace @samp{sin(x)^2 + cos(x)^2}
  22539. by 1,
  22540. @example
  22541. sin(x)^2 + cos(x)^2 := 1
  22542. @end example
  22543. @noindent
  22544. misses many cases because the sine and cosine may both be multiplied by
  22545. an equal factor. Here's a more successful rule:
  22546. @example
  22547. opt(a) sin(x)^2 + opt(a) cos(x)^2 := a
  22548. @end example
  22549. Note that this rule will @emph{not} match @samp{sin(x)^2 + 6 cos(x)^2}
  22550. because one @expr{a} would have ``matched'' 1 while the other matched 6.
  22551. Calc automatically converts a rule like
  22552. @example
  22553. f(x-1, x) := g(x)
  22554. @end example
  22555. @noindent
  22556. into the form
  22557. @example
  22558. f(temp, x) := g(x) :: temp = x-1
  22559. @end example
  22560. @noindent
  22561. (where @code{temp} stands for a new, invented meta-variable that
  22562. doesn't actually have a name). This modified rule will successfully
  22563. match @samp{f(6, 7)}, binding @samp{temp} and @samp{x} to 6 and 7,
  22564. respectively, then verifying that they differ by one even though
  22565. @samp{6} does not superficially look like @samp{x-1}.
  22566. However, Calc does not solve equations to interpret a rule. The
  22567. following rule,
  22568. @example
  22569. f(x-1, x+1) := g(x)
  22570. @end example
  22571. @noindent
  22572. will not work. That is, it will match @samp{f(a - 1 + b, a + 1 + b)}
  22573. but not @samp{f(6, 8)}. Calc always interprets at least one occurrence
  22574. of a variable by literal matching. If the variable appears ``isolated''
  22575. then Calc is smart enough to use it for literal matching. But in this
  22576. last example, Calc is forced to rewrite the rule to @samp{f(x-1, temp)
  22577. := g(x) :: temp = x+1} where the @samp{x-1} term must correspond to an
  22578. actual ``something-minus-one'' in the target formula.
  22579. A successful way to write this would be @samp{f(x, x+2) := g(x+1)}.
  22580. You could make this resemble the original form more closely by using
  22581. @code{let} notation, which is described in the next section:
  22582. @example
  22583. f(xm1, x+1) := g(x) :: let(x := xm1+1)
  22584. @end example
  22585. Calc does this rewriting or ``conditionalizing'' for any sub-pattern
  22586. which involves only the functions in the following list, operating
  22587. only on constants and meta-variables which have already been matched
  22588. elsewhere in the pattern. When matching a function call, Calc is
  22589. careful to match arguments which are plain variables before arguments
  22590. which are calls to any of the functions below, so that a pattern like
  22591. @samp{f(x-1, x)} can be conditionalized even though the isolated
  22592. @samp{x} comes after the @samp{x-1}.
  22593. @smallexample
  22594. + - * / \ % ^ abs sign round rounde roundu trunc floor ceil
  22595. max min re im conj arg
  22596. @end smallexample
  22597. You can suppress all of the special treatments described in this
  22598. section by surrounding a function call with a @code{plain} marker.
  22599. This marker causes the function call which is its argument to be
  22600. matched literally, without regard to commutativity, associativity,
  22601. negation, or conditionalization. When you use @code{plain}, the
  22602. ``deep structure'' of the formula being matched can show through.
  22603. For example,
  22604. @example
  22605. plain(a - a b) := f(a, b)
  22606. @end example
  22607. @noindent
  22608. will match only literal subtractions. However, the @code{plain}
  22609. marker does not affect its arguments' arguments. In this case,
  22610. commutativity and associativity is still considered while matching
  22611. the @w{@samp{a b}} sub-pattern, so the whole pattern will match
  22612. @samp{x - y x} as well as @samp{x - x y}. We could go still
  22613. further and use
  22614. @example
  22615. plain(a - plain(a b)) := f(a, b)
  22616. @end example
  22617. @noindent
  22618. which would do a completely strict match for the pattern.
  22619. By contrast, the @code{quote} marker means that not only the
  22620. function name but also the arguments must be literally the same.
  22621. The above pattern will match @samp{x - x y} but
  22622. @example
  22623. quote(a - a b) := f(a, b)
  22624. @end example
  22625. @noindent
  22626. will match only the single formula @samp{a - a b}. Also,
  22627. @example
  22628. quote(a - quote(a b)) := f(a, b)
  22629. @end example
  22630. @noindent
  22631. will match only @samp{a - quote(a b)}---probably not the desired
  22632. effect!
  22633. A certain amount of algebra is also done when substituting the
  22634. meta-variables on the righthand side of a rule. For example,
  22635. in the rule
  22636. @example
  22637. a + f(b) := f(a + b)
  22638. @end example
  22639. @noindent
  22640. matching @samp{f(x) - y} would produce @samp{f((-y) + x)} if
  22641. taken literally, but the rewrite mechanism will simplify the
  22642. righthand side to @samp{f(x - y)} automatically. (Of course,
  22643. the default simplifications would do this anyway, so this
  22644. special simplification is only noticeable if you have turned the
  22645. default simplifications off.) This rewriting is done only when
  22646. a meta-variable expands to a ``negative-looking'' expression.
  22647. If this simplification is not desirable, you can use a @code{plain}
  22648. marker on the righthand side:
  22649. @example
  22650. a + f(b) := f(plain(a + b))
  22651. @end example
  22652. @noindent
  22653. In this example, we are still allowing the pattern-matcher to
  22654. use all the algebra it can muster, but the righthand side will
  22655. always simplify to a literal addition like @samp{f((-y) + x)}.
  22656. @node Other Features of Rewrite Rules, Composing Patterns in Rewrite Rules, Algebraic Properties of Rewrite Rules, Rewrite Rules
  22657. @subsection Other Features of Rewrite Rules
  22658. @noindent
  22659. Certain ``function names'' serve as markers in rewrite rules.
  22660. Here is a complete list of these markers. First are listed the
  22661. markers that work inside a pattern; then come the markers that
  22662. work in the righthand side of a rule.
  22663. @ignore
  22664. @starindex
  22665. @end ignore
  22666. @tindex import
  22667. One kind of marker, @samp{import(x)}, takes the place of a whole
  22668. rule. Here @expr{x} is the name of a variable containing another
  22669. rule set; those rules are ``spliced into'' the rule set that
  22670. imports them. For example, if @samp{[f(a+b) := f(a) + f(b),
  22671. f(a b) := a f(b) :: real(a)]} is stored in variable @samp{linearF},
  22672. then the rule set @samp{[f(0) := 0, import(linearF)]} will apply
  22673. all three rules. It is possible to modify the imported rules
  22674. slightly: @samp{import(x, v1, x1, v2, x2, @dots{})} imports
  22675. the rule set @expr{x} with all occurrences of
  22676. @texline @math{v_1},
  22677. @infoline @expr{v1},
  22678. as either a variable name or a function name, replaced with
  22679. @texline @math{x_1}
  22680. @infoline @expr{x1}
  22681. and so on. (If
  22682. @texline @math{v_1}
  22683. @infoline @expr{v1}
  22684. is used as a function name, then
  22685. @texline @math{x_1}
  22686. @infoline @expr{x1}
  22687. must be either a function name itself or a @w{@samp{< >}} nameless
  22688. function; @pxref{Specifying Operators}.) For example, @samp{[g(0) := 0,
  22689. import(linearF, f, g)]} applies the linearity rules to the function
  22690. @samp{g} instead of @samp{f}. Imports can be nested, but the
  22691. import-with-renaming feature may fail to rename sub-imports properly.
  22692. The special functions allowed in patterns are:
  22693. @table @samp
  22694. @item quote(x)
  22695. @ignore
  22696. @starindex
  22697. @end ignore
  22698. @tindex quote
  22699. This pattern matches exactly @expr{x}; variable names in @expr{x} are
  22700. not interpreted as meta-variables. The only flexibility is that
  22701. numbers are compared for numeric equality, so that the pattern
  22702. @samp{f(quote(12))} will match both @samp{f(12)} and @samp{f(12.0)}.
  22703. (Numbers are always treated this way by the rewrite mechanism:
  22704. The rule @samp{f(x,x) := g(x)} will match @samp{f(12, 12.0)}.
  22705. The rewrite may produce either @samp{g(12)} or @samp{g(12.0)}
  22706. as a result in this case.)
  22707. @item plain(x)
  22708. @ignore
  22709. @starindex
  22710. @end ignore
  22711. @tindex plain
  22712. Here @expr{x} must be a function call @samp{f(x1,x2,@dots{})}. This
  22713. pattern matches a call to function @expr{f} with the specified
  22714. argument patterns. No special knowledge of the properties of the
  22715. function @expr{f} is used in this case; @samp{+} is not commutative or
  22716. associative. Unlike @code{quote}, the arguments @samp{x1,x2,@dots{}}
  22717. are treated as patterns. If you wish them to be treated ``plainly''
  22718. as well, you must enclose them with more @code{plain} markers:
  22719. @samp{plain(plain(@w{-a}) + plain(b c))}.
  22720. @item opt(x,def)
  22721. @ignore
  22722. @starindex
  22723. @end ignore
  22724. @tindex opt
  22725. Here @expr{x} must be a variable name. This must appear as an
  22726. argument to a function or an element of a vector; it specifies that
  22727. the argument or element is optional.
  22728. As an argument to @samp{+}, @samp{-}, @samp{*}, @samp{&&}, or @samp{||},
  22729. or as the second argument to @samp{/} or @samp{^}, the value @var{def}
  22730. may be omitted. The pattern @samp{x + opt(y)} matches a sum by
  22731. binding one summand to @expr{x} and the other to @expr{y}, and it
  22732. matches anything else by binding the whole expression to @expr{x} and
  22733. zero to @expr{y}. The other operators above work similarly.
  22734. For general miscellaneous functions, the default value @code{def}
  22735. must be specified. Optional arguments are dropped starting with
  22736. the rightmost one during matching. For example, the pattern
  22737. @samp{f(opt(a,0), b, opt(c,b))} will match @samp{f(b)}, @samp{f(a,b)},
  22738. or @samp{f(a,b,c)}. Default values of zero and @expr{b} are
  22739. supplied in this example for the omitted arguments. Note that
  22740. the literal variable @expr{b} will be the default in the latter
  22741. case, @emph{not} the value that matched the meta-variable @expr{b}.
  22742. In other words, the default @var{def} is effectively quoted.
  22743. @item condition(x,c)
  22744. @ignore
  22745. @starindex
  22746. @end ignore
  22747. @tindex condition
  22748. @tindex ::
  22749. This matches the pattern @expr{x}, with the attached condition
  22750. @expr{c}. It is the same as @samp{x :: c}.
  22751. @item pand(x,y)
  22752. @ignore
  22753. @starindex
  22754. @end ignore
  22755. @tindex pand
  22756. @tindex &&&
  22757. This matches anything that matches both pattern @expr{x} and
  22758. pattern @expr{y}. It is the same as @samp{x &&& y}.
  22759. @pxref{Composing Patterns in Rewrite Rules}.
  22760. @item por(x,y)
  22761. @ignore
  22762. @starindex
  22763. @end ignore
  22764. @tindex por
  22765. @tindex |||
  22766. This matches anything that matches either pattern @expr{x} or
  22767. pattern @expr{y}. It is the same as @w{@samp{x ||| y}}.
  22768. @item pnot(x)
  22769. @ignore
  22770. @starindex
  22771. @end ignore
  22772. @tindex pnot
  22773. @tindex !!!
  22774. This matches anything that does not match pattern @expr{x}.
  22775. It is the same as @samp{!!! x}.
  22776. @item cons(h,t)
  22777. @ignore
  22778. @mindex cons
  22779. @end ignore
  22780. @tindex cons (rewrites)
  22781. This matches any vector of one or more elements. The first
  22782. element is matched to @expr{h}; a vector of the remaining
  22783. elements is matched to @expr{t}. Note that vectors of fixed
  22784. length can also be matched as actual vectors: The rule
  22785. @samp{cons(a,cons(b,[])) := cons(a+b,[])} is equivalent
  22786. to the rule @samp{[a,b] := [a+b]}.
  22787. @item rcons(t,h)
  22788. @ignore
  22789. @mindex rcons
  22790. @end ignore
  22791. @tindex rcons (rewrites)
  22792. This is like @code{cons}, except that the @emph{last} element
  22793. is matched to @expr{h}, with the remaining elements matched
  22794. to @expr{t}.
  22795. @item apply(f,args)
  22796. @ignore
  22797. @mindex apply
  22798. @end ignore
  22799. @tindex apply (rewrites)
  22800. This matches any function call. The name of the function, in
  22801. the form of a variable, is matched to @expr{f}. The arguments
  22802. of the function, as a vector of zero or more objects, are
  22803. matched to @samp{args}. Constants, variables, and vectors
  22804. do @emph{not} match an @code{apply} pattern. For example,
  22805. @samp{apply(f,x)} matches any function call, @samp{apply(quote(f),x)}
  22806. matches any call to the function @samp{f}, @samp{apply(f,[a,b])}
  22807. matches any function call with exactly two arguments, and
  22808. @samp{apply(quote(f), cons(a,cons(b,x)))} matches any call
  22809. to the function @samp{f} with two or more arguments. Another
  22810. way to implement the latter, if the rest of the rule does not
  22811. need to refer to the first two arguments of @samp{f} by name,
  22812. would be @samp{apply(quote(f), x :: vlen(x) >= 2)}.
  22813. Here's a more interesting sample use of @code{apply}:
  22814. @example
  22815. apply(f,[x+n]) := n + apply(f,[x])
  22816. :: in(f, [floor,ceil,round,trunc]) :: integer(n)
  22817. @end example
  22818. Note, however, that this will be slower to match than a rule
  22819. set with four separate rules. The reason is that Calc sorts
  22820. the rules of a rule set according to top-level function name;
  22821. if the top-level function is @code{apply}, Calc must try the
  22822. rule for every single formula and sub-formula. If the top-level
  22823. function in the pattern is, say, @code{floor}, then Calc invokes
  22824. the rule only for sub-formulas which are calls to @code{floor}.
  22825. Formulas normally written with operators like @code{+} are still
  22826. considered function calls: @code{apply(f,x)} matches @samp{a+b}
  22827. with @samp{f = add}, @samp{x = [a,b]}.
  22828. You must use @code{apply} for meta-variables with function names
  22829. on both sides of a rewrite rule: @samp{apply(f, [x]) := f(x+1)}
  22830. is @emph{not} correct, because it rewrites @samp{spam(6)} into
  22831. @samp{f(7)}. The righthand side should be @samp{apply(f, [x+1])}.
  22832. Also note that you will have to use No-Simplify mode (@kbd{m O})
  22833. when entering this rule so that the @code{apply} isn't
  22834. evaluated immediately to get the new rule @samp{f(x) := f(x+1)}.
  22835. Or, use @kbd{s e} to enter the rule without going through the stack,
  22836. or enter the rule as @samp{apply(f, [x]) := apply(f, [x+1]) @w{:: 1}}.
  22837. @xref{Conditional Rewrite Rules}.
  22838. @item select(x)
  22839. @ignore
  22840. @starindex
  22841. @end ignore
  22842. @tindex select
  22843. This is used for applying rules to formulas with selections;
  22844. @pxref{Selections with Rewrite Rules}.
  22845. @end table
  22846. Special functions for the righthand sides of rules are:
  22847. @table @samp
  22848. @item quote(x)
  22849. The notation @samp{quote(x)} is changed to @samp{x} when the
  22850. righthand side is used. As far as the rewrite rule is concerned,
  22851. @code{quote} is invisible. However, @code{quote} has the special
  22852. property in Calc that its argument is not evaluated. Thus,
  22853. while it will not work to put the rule @samp{t(a) := typeof(a)}
  22854. on the stack because @samp{typeof(a)} is evaluated immediately
  22855. to produce @samp{t(a) := 100}, you can use @code{quote} to
  22856. protect the righthand side: @samp{t(a) := quote(typeof(a))}.
  22857. (@xref{Conditional Rewrite Rules}, for another trick for
  22858. protecting rules from evaluation.)
  22859. @item plain(x)
  22860. Special properties of and simplifications for the function call
  22861. @expr{x} are not used. One interesting case where @code{plain}
  22862. is useful is the rule, @samp{q(x) := quote(x)}, trying to expand a
  22863. shorthand notation for the @code{quote} function. This rule will
  22864. not work as shown; instead of replacing @samp{q(foo)} with
  22865. @samp{quote(foo)}, it will replace it with @samp{foo}! The correct
  22866. rule would be @samp{q(x) := plain(quote(x))}.
  22867. @item cons(h,t)
  22868. Where @expr{t} is a vector, this is converted into an expanded
  22869. vector during rewrite processing. Note that @code{cons} is a regular
  22870. Calc function which normally does this anyway; the only way @code{cons}
  22871. is treated specially by rewrites is that @code{cons} on the righthand
  22872. side of a rule will be evaluated even if default simplifications
  22873. have been turned off.
  22874. @item rcons(t,h)
  22875. Analogous to @code{cons} except putting @expr{h} at the @emph{end} of
  22876. the vector @expr{t}.
  22877. @item apply(f,args)
  22878. Where @expr{f} is a variable and @var{args} is a vector, this
  22879. is converted to a function call. Once again, note that @code{apply}
  22880. is also a regular Calc function.
  22881. @item eval(x)
  22882. @ignore
  22883. @starindex
  22884. @end ignore
  22885. @tindex eval
  22886. The formula @expr{x} is handled in the usual way, then the
  22887. default simplifications are applied to it even if they have
  22888. been turned off normally. This allows you to treat any function
  22889. similarly to the way @code{cons} and @code{apply} are always
  22890. treated. However, there is a slight difference: @samp{cons(2+3, [])}
  22891. with default simplifications off will be converted to @samp{[2+3]},
  22892. whereas @samp{eval(cons(2+3, []))} will be converted to @samp{[5]}.
  22893. @item evalsimp(x)
  22894. @ignore
  22895. @starindex
  22896. @end ignore
  22897. @tindex evalsimp
  22898. The formula @expr{x} has meta-variables substituted in the usual
  22899. way, then algebraically simplified.
  22900. @item evalextsimp(x)
  22901. @ignore
  22902. @starindex
  22903. @end ignore
  22904. @tindex evalextsimp
  22905. The formula @expr{x} has meta-variables substituted in the normal
  22906. way, then ``extendedly'' simplified as if by the @kbd{a e} command.
  22907. @item select(x)
  22908. @xref{Selections with Rewrite Rules}.
  22909. @end table
  22910. There are also some special functions you can use in conditions.
  22911. @table @samp
  22912. @item let(v := x)
  22913. @ignore
  22914. @starindex
  22915. @end ignore
  22916. @tindex let
  22917. The expression @expr{x} is evaluated with meta-variables substituted.
  22918. The algebraic simplifications are @emph{not} applied by
  22919. default, but @expr{x} can include calls to @code{evalsimp} or
  22920. @code{evalextsimp} as described above to invoke higher levels
  22921. of simplification. The result of @expr{x} is then bound to the
  22922. meta-variable @expr{v}. As usual, if this meta-variable has already
  22923. been matched to something else the two values must be equal; if the
  22924. meta-variable is new then it is bound to the result of the expression.
  22925. This variable can then appear in later conditions, and on the righthand
  22926. side of the rule.
  22927. In fact, @expr{v} may be any pattern in which case the result of
  22928. evaluating @expr{x} is matched to that pattern, binding any
  22929. meta-variables that appear in that pattern. Note that @code{let}
  22930. can only appear by itself as a condition, or as one term of an
  22931. @samp{&&} which is a whole condition: It cannot be inside
  22932. an @samp{||} term or otherwise buried.
  22933. The alternate, equivalent form @samp{let(v, x)} is also recognized.
  22934. Note that the use of @samp{:=} by @code{let}, while still being
  22935. assignment-like in character, is unrelated to the use of @samp{:=}
  22936. in the main part of a rewrite rule.
  22937. As an example, @samp{f(a) := g(ia) :: let(ia := 1/a) :: constant(ia)}
  22938. replaces @samp{f(a)} with @samp{g} of the inverse of @samp{a}, if
  22939. that inverse exists and is constant. For example, if @samp{a} is a
  22940. singular matrix the operation @samp{1/a} is left unsimplified and
  22941. @samp{constant(ia)} fails, but if @samp{a} is an invertible matrix
  22942. then the rule succeeds. Without @code{let} there would be no way
  22943. to express this rule that didn't have to invert the matrix twice.
  22944. Note that, because the meta-variable @samp{ia} is otherwise unbound
  22945. in this rule, the @code{let} condition itself always ``succeeds''
  22946. because no matter what @samp{1/a} evaluates to, it can successfully
  22947. be bound to @code{ia}.
  22948. Here's another example, for integrating cosines of linear
  22949. terms: @samp{myint(cos(y),x) := sin(y)/b :: let([a,b,x] := lin(y,x))}.
  22950. The @code{lin} function returns a 3-vector if its argument is linear,
  22951. or leaves itself unevaluated if not. But an unevaluated @code{lin}
  22952. call will not match the 3-vector on the lefthand side of the @code{let},
  22953. so this @code{let} both verifies that @code{y} is linear, and binds
  22954. the coefficients @code{a} and @code{b} for use elsewhere in the rule.
  22955. (It would have been possible to use @samp{sin(a x + b)/b} for the
  22956. righthand side instead, but using @samp{sin(y)/b} avoids gratuitous
  22957. rearrangement of the argument of the sine.)
  22958. @ignore
  22959. @starindex
  22960. @end ignore
  22961. @tindex ierf
  22962. Similarly, here is a rule that implements an inverse-@code{erf}
  22963. function. It uses @code{root} to search for a solution. If
  22964. @code{root} succeeds, it will return a vector of two numbers
  22965. where the first number is the desired solution. If no solution
  22966. is found, @code{root} remains in symbolic form. So we use
  22967. @code{let} to check that the result was indeed a vector.
  22968. @example
  22969. ierf(x) := y :: let([y,z] := root(erf(a) = x, a, .5))
  22970. @end example
  22971. @item matches(v,p)
  22972. The meta-variable @var{v}, which must already have been matched
  22973. to something elsewhere in the rule, is compared against pattern
  22974. @var{p}. Since @code{matches} is a standard Calc function, it
  22975. can appear anywhere in a condition. But if it appears alone or
  22976. as a term of a top-level @samp{&&}, then you get the special
  22977. extra feature that meta-variables which are bound to things
  22978. inside @var{p} can be used elsewhere in the surrounding rewrite
  22979. rule.
  22980. The only real difference between @samp{let(p := v)} and
  22981. @samp{matches(v, p)} is that the former evaluates @samp{v} using
  22982. the default simplifications, while the latter does not.
  22983. @item remember
  22984. @vindex remember
  22985. This is actually a variable, not a function. If @code{remember}
  22986. appears as a condition in a rule, then when that rule succeeds
  22987. the original expression and rewritten expression are added to the
  22988. front of the rule set that contained the rule. If the rule set
  22989. was not stored in a variable, @code{remember} is ignored. The
  22990. lefthand side is enclosed in @code{quote} in the added rule if it
  22991. contains any variables.
  22992. For example, the rule @samp{f(n) := n f(n-1) :: remember} applied
  22993. to @samp{f(7)} will add the rule @samp{f(7) := 7 f(6)} to the front
  22994. of the rule set. The rule set @code{EvalRules} works slightly
  22995. differently: There, the evaluation of @samp{f(6)} will complete before
  22996. the result is added to the rule set, in this case as @samp{f(7) := 5040}.
  22997. Thus @code{remember} is most useful inside @code{EvalRules}.
  22998. It is up to you to ensure that the optimization performed by
  22999. @code{remember} is safe. For example, the rule @samp{foo(n) := n
  23000. :: evalv(eatfoo) > 0 :: remember} is a bad idea (@code{evalv} is
  23001. the function equivalent of the @kbd{=} command); if the variable
  23002. @code{eatfoo} ever contains 1, rules like @samp{foo(7) := 7} will
  23003. be added to the rule set and will continue to operate even if
  23004. @code{eatfoo} is later changed to 0.
  23005. @item remember(c)
  23006. @ignore
  23007. @starindex
  23008. @end ignore
  23009. @tindex remember
  23010. Remember the match as described above, but only if condition @expr{c}
  23011. is true. For example, @samp{remember(n % 4 = 0)} in the above factorial
  23012. rule remembers only every fourth result. Note that @samp{remember(1)}
  23013. is equivalent to @samp{remember}, and @samp{remember(0)} has no effect.
  23014. @end table
  23015. @node Composing Patterns in Rewrite Rules, Nested Formulas with Rewrite Rules, Other Features of Rewrite Rules, Rewrite Rules
  23016. @subsection Composing Patterns in Rewrite Rules
  23017. @noindent
  23018. There are three operators, @samp{&&&}, @samp{|||}, and @samp{!!!},
  23019. that combine rewrite patterns to make larger patterns. The
  23020. combinations are ``and,'' ``or,'' and ``not,'' respectively, and
  23021. these operators are the pattern equivalents of @samp{&&}, @samp{||}
  23022. and @samp{!} (which operate on zero-or-nonzero logical values).
  23023. Note that @samp{&&&}, @samp{|||}, and @samp{!!!} are left in symbolic
  23024. form by all regular Calc features; they have special meaning only in
  23025. the context of rewrite rule patterns.
  23026. The pattern @samp{@var{p1} &&& @var{p2}} matches anything that
  23027. matches both @var{p1} and @var{p2}. One especially useful case is
  23028. when one of @var{p1} or @var{p2} is a meta-variable. For example,
  23029. here is a rule that operates on error forms:
  23030. @example
  23031. f(x &&& a +/- b, x) := g(x)
  23032. @end example
  23033. This does the same thing, but is arguably simpler than, the rule
  23034. @example
  23035. f(a +/- b, a +/- b) := g(a +/- b)
  23036. @end example
  23037. @ignore
  23038. @starindex
  23039. @end ignore
  23040. @tindex ends
  23041. Here's another interesting example:
  23042. @example
  23043. ends(cons(a, x) &&& rcons(y, b)) := [a, b]
  23044. @end example
  23045. @noindent
  23046. which effectively clips out the middle of a vector leaving just
  23047. the first and last elements. This rule will change a one-element
  23048. vector @samp{[a]} to @samp{[a, a]}. The similar rule
  23049. @example
  23050. ends(cons(a, rcons(y, b))) := [a, b]
  23051. @end example
  23052. @noindent
  23053. would do the same thing except that it would fail to match a
  23054. one-element vector.
  23055. @tex
  23056. \bigskip
  23057. @end tex
  23058. The pattern @samp{@var{p1} ||| @var{p2}} matches anything that
  23059. matches either @var{p1} or @var{p2}. Calc first tries matching
  23060. against @var{p1}; if that fails, it goes on to try @var{p2}.
  23061. @ignore
  23062. @starindex
  23063. @end ignore
  23064. @tindex curve
  23065. A simple example of @samp{|||} is
  23066. @example
  23067. curve(inf ||| -inf) := 0
  23068. @end example
  23069. @noindent
  23070. which converts both @samp{curve(inf)} and @samp{curve(-inf)} to zero.
  23071. Here is a larger example:
  23072. @example
  23073. log(a, b) ||| (ln(a) :: let(b := e)) := mylog(a, b)
  23074. @end example
  23075. This matches both generalized and natural logarithms in a single rule.
  23076. Note that the @samp{::} term must be enclosed in parentheses because
  23077. that operator has lower precedence than @samp{|||} or @samp{:=}.
  23078. (In practice this rule would probably include a third alternative,
  23079. omitted here for brevity, to take care of @code{log10}.)
  23080. While Calc generally treats interior conditions exactly the same as
  23081. conditions on the outside of a rule, it does guarantee that if all the
  23082. variables in the condition are special names like @code{e}, or already
  23083. bound in the pattern to which the condition is attached (say, if
  23084. @samp{a} had appeared in this condition), then Calc will process this
  23085. condition right after matching the pattern to the left of the @samp{::}.
  23086. Thus, we know that @samp{b} will be bound to @samp{e} only if the
  23087. @code{ln} branch of the @samp{|||} was taken.
  23088. Note that this rule was careful to bind the same set of meta-variables
  23089. on both sides of the @samp{|||}. Calc does not check this, but if
  23090. you bind a certain meta-variable only in one branch and then use that
  23091. meta-variable elsewhere in the rule, results are unpredictable:
  23092. @example
  23093. f(a,b) ||| g(b) := h(a,b)
  23094. @end example
  23095. Here if the pattern matches @samp{g(17)}, Calc makes no promises about
  23096. the value that will be substituted for @samp{a} on the righthand side.
  23097. @tex
  23098. \bigskip
  23099. @end tex
  23100. The pattern @samp{!!! @var{pat}} matches anything that does not
  23101. match @var{pat}. Any meta-variables that are bound while matching
  23102. @var{pat} remain unbound outside of @var{pat}.
  23103. For example,
  23104. @example
  23105. f(x &&& !!! a +/- b, !!![]) := g(x)
  23106. @end example
  23107. @noindent
  23108. converts @code{f} whose first argument is anything @emph{except} an
  23109. error form, and whose second argument is not the empty vector, into
  23110. a similar call to @code{g} (but without the second argument).
  23111. If we know that the second argument will be a vector (empty or not),
  23112. then an equivalent rule would be:
  23113. @example
  23114. f(x, y) := g(x) :: typeof(x) != 7 :: vlen(y) > 0
  23115. @end example
  23116. @noindent
  23117. where of course 7 is the @code{typeof} code for error forms.
  23118. Another final condition, that works for any kind of @samp{y},
  23119. would be @samp{!istrue(y == [])}. (The @code{istrue} function
  23120. returns an explicit 0 if its argument was left in symbolic form;
  23121. plain @samp{!(y == [])} or @samp{y != []} would not work to replace
  23122. @samp{!!![]} since these would be left unsimplified, and thus cause
  23123. the rule to fail, if @samp{y} was something like a variable name.)
  23124. It is possible for a @samp{!!!} to refer to meta-variables bound
  23125. elsewhere in the pattern. For example,
  23126. @example
  23127. f(a, !!!a) := g(a)
  23128. @end example
  23129. @noindent
  23130. matches any call to @code{f} with different arguments, changing
  23131. this to @code{g} with only the first argument.
  23132. If a function call is to be matched and one of the argument patterns
  23133. contains a @samp{!!!} somewhere inside it, that argument will be
  23134. matched last. Thus
  23135. @example
  23136. f(!!!a, a) := g(a)
  23137. @end example
  23138. @noindent
  23139. will be careful to bind @samp{a} to the second argument of @code{f}
  23140. before testing the first argument. If Calc had tried to match the
  23141. first argument of @code{f} first, the results would have been
  23142. disastrous: since @code{a} was unbound so far, the pattern @samp{a}
  23143. would have matched anything at all, and the pattern @samp{!!!a}
  23144. therefore would @emph{not} have matched anything at all!
  23145. @node Nested Formulas with Rewrite Rules, Multi-Phase Rewrite Rules, Composing Patterns in Rewrite Rules, Rewrite Rules
  23146. @subsection Nested Formulas with Rewrite Rules
  23147. @noindent
  23148. When @kbd{a r} (@code{calc-rewrite}) is used, it takes an expression from
  23149. the top of the stack and attempts to match any of the specified rules
  23150. to any part of the expression, starting with the whole expression
  23151. and then, if that fails, trying deeper and deeper sub-expressions.
  23152. For each part of the expression, the rules are tried in the order
  23153. they appear in the rules vector. The first rule to match the first
  23154. sub-expression wins; it replaces the matched sub-expression according
  23155. to the @var{new} part of the rule.
  23156. Often, the rule set will match and change the formula several times.
  23157. The top-level formula is first matched and substituted repeatedly until
  23158. it no longer matches the pattern; then, sub-formulas are tried, and
  23159. so on. Once every part of the formula has gotten its chance, the
  23160. rewrite mechanism starts over again with the top-level formula
  23161. (in case a substitution of one of its arguments has caused it again
  23162. to match). This continues until no further matches can be made
  23163. anywhere in the formula.
  23164. It is possible for a rule set to get into an infinite loop. The
  23165. most obvious case, replacing a formula with itself, is not a problem
  23166. because a rule is not considered to ``succeed'' unless the righthand
  23167. side actually comes out to something different than the original
  23168. formula or sub-formula that was matched. But if you accidentally
  23169. had both @samp{ln(a b) := ln(a) + ln(b)} and the reverse
  23170. @samp{ln(a) + ln(b) := ln(a b)} in your rule set, Calc would
  23171. run forever switching a formula back and forth between the two
  23172. forms.
  23173. To avoid disaster, Calc normally stops after 100 changes have been
  23174. made to the formula. This will be enough for most multiple rewrites,
  23175. but it will keep an endless loop of rewrites from locking up the
  23176. computer forever. (On most systems, you can also type @kbd{C-g} to
  23177. halt any Emacs command prematurely.)
  23178. To change this limit, give a positive numeric prefix argument.
  23179. In particular, @kbd{M-1 a r} applies only one rewrite at a time,
  23180. useful when you are first testing your rule (or just if repeated
  23181. rewriting is not what is called for by your application).
  23182. @ignore
  23183. @starindex
  23184. @end ignore
  23185. @ignore
  23186. @mindex iter@idots
  23187. @end ignore
  23188. @tindex iterations
  23189. You can also put a ``function call'' @samp{iterations(@var{n})}
  23190. in place of a rule anywhere in your rules vector (but usually at
  23191. the top). Then, @var{n} will be used instead of 100 as the default
  23192. number of iterations for this rule set. You can use
  23193. @samp{iterations(inf)} if you want no iteration limit by default.
  23194. A prefix argument will override the @code{iterations} limit in the
  23195. rule set.
  23196. @example
  23197. [ iterations(1),
  23198. f(x) := f(x+1) ]
  23199. @end example
  23200. More precisely, the limit controls the number of ``iterations,''
  23201. where each iteration is a successful matching of a rule pattern whose
  23202. righthand side, after substituting meta-variables and applying the
  23203. default simplifications, is different from the original sub-formula
  23204. that was matched.
  23205. A prefix argument of zero sets the limit to infinity. Use with caution!
  23206. Given a negative numeric prefix argument, @kbd{a r} will match and
  23207. substitute the top-level expression up to that many times, but
  23208. will not attempt to match the rules to any sub-expressions.
  23209. In a formula, @code{rewrite(@var{expr}, @var{rules}, @var{n})}
  23210. does a rewriting operation. Here @var{expr} is the expression
  23211. being rewritten, @var{rules} is the rule, vector of rules, or
  23212. variable containing the rules, and @var{n} is the optional
  23213. iteration limit, which may be a positive integer, a negative
  23214. integer, or @samp{inf} or @samp{-inf}. If @var{n} is omitted
  23215. the @code{iterations} value from the rule set is used; if both
  23216. are omitted, 100 is used.
  23217. @node Multi-Phase Rewrite Rules, Selections with Rewrite Rules, Nested Formulas with Rewrite Rules, Rewrite Rules
  23218. @subsection Multi-Phase Rewrite Rules
  23219. @noindent
  23220. It is possible to separate a rewrite rule set into several @dfn{phases}.
  23221. During each phase, certain rules will be enabled while certain others
  23222. will be disabled. A @dfn{phase schedule} controls the order in which
  23223. phases occur during the rewriting process.
  23224. @ignore
  23225. @starindex
  23226. @end ignore
  23227. @tindex phase
  23228. @vindex all
  23229. If a call to the marker function @code{phase} appears in the rules
  23230. vector in place of a rule, all rules following that point will be
  23231. members of the phase(s) identified in the arguments to @code{phase}.
  23232. Phases are given integer numbers. The markers @samp{phase()} and
  23233. @samp{phase(all)} both mean the following rules belong to all phases;
  23234. this is the default at the start of the rule set.
  23235. If you do not explicitly schedule the phases, Calc sorts all phase
  23236. numbers that appear in the rule set and executes the phases in
  23237. ascending order. For example, the rule set
  23238. @example
  23239. @group
  23240. [ f0(x) := g0(x),
  23241. phase(1),
  23242. f1(x) := g1(x),
  23243. phase(2),
  23244. f2(x) := g2(x),
  23245. phase(3),
  23246. f3(x) := g3(x),
  23247. phase(1,2),
  23248. f4(x) := g4(x) ]
  23249. @end group
  23250. @end example
  23251. @noindent
  23252. has three phases, 1 through 3. Phase 1 consists of the @code{f0},
  23253. @code{f1}, and @code{f4} rules (in that order). Phase 2 consists of
  23254. @code{f0}, @code{f2}, and @code{f4}. Phase 3 consists of @code{f0}
  23255. and @code{f3}.
  23256. When Calc rewrites a formula using this rule set, it first rewrites
  23257. the formula using only the phase 1 rules until no further changes are
  23258. possible. Then it switches to the phase 2 rule set and continues
  23259. until no further changes occur, then finally rewrites with phase 3.
  23260. When no more phase 3 rules apply, rewriting finishes. (This is
  23261. assuming @kbd{a r} with a large enough prefix argument to allow the
  23262. rewriting to run to completion; the sequence just described stops
  23263. early if the number of iterations specified in the prefix argument,
  23264. 100 by default, is reached.)
  23265. During each phase, Calc descends through the nested levels of the
  23266. formula as described previously. (@xref{Nested Formulas with Rewrite
  23267. Rules}.) Rewriting starts at the top of the formula, then works its
  23268. way down to the parts, then goes back to the top and works down again.
  23269. The phase 2 rules do not begin until no phase 1 rules apply anywhere
  23270. in the formula.
  23271. @ignore
  23272. @starindex
  23273. @end ignore
  23274. @tindex schedule
  23275. A @code{schedule} marker appearing in the rule set (anywhere, but
  23276. conventionally at the top) changes the default schedule of phases.
  23277. In the simplest case, @code{schedule} has a sequence of phase numbers
  23278. for arguments; each phase number is invoked in turn until the
  23279. arguments to @code{schedule} are exhausted. Thus adding
  23280. @samp{schedule(3,2,1)} at the top of the above rule set would
  23281. reverse the order of the phases; @samp{schedule(1,2,3)} would have
  23282. no effect since this is the default schedule; and @samp{schedule(1,2,1,3)}
  23283. would give phase 1 a second chance after phase 2 has completed, before
  23284. moving on to phase 3.
  23285. Any argument to @code{schedule} can instead be a vector of phase
  23286. numbers (or even of sub-vectors). Then the sub-sequence of phases
  23287. described by the vector are tried repeatedly until no change occurs
  23288. in any phase in the sequence. For example, @samp{schedule([1, 2], 3)}
  23289. tries phase 1, then phase 2, then, if either phase made any changes
  23290. to the formula, repeats these two phases until they can make no
  23291. further progress. Finally, it goes on to phase 3 for finishing
  23292. touches.
  23293. Also, items in @code{schedule} can be variable names as well as
  23294. numbers. A variable name is interpreted as the name of a function
  23295. to call on the whole formula. For example, @samp{schedule(1, simplify)}
  23296. says to apply the phase-1 rules (presumably, all of them), then to
  23297. call @code{simplify} which is the function name equivalent of @kbd{a s}.
  23298. Likewise, @samp{schedule([1, simplify])} says to alternate between
  23299. phase 1 and @kbd{a s} until no further changes occur.
  23300. Phases can be used purely to improve efficiency; if it is known that
  23301. a certain group of rules will apply only at the beginning of rewriting,
  23302. and a certain other group will apply only at the end, then rewriting
  23303. will be faster if these groups are identified as separate phases.
  23304. Once the phase 1 rules are done, Calc can put them aside and no longer
  23305. spend any time on them while it works on phase 2.
  23306. There are also some problems that can only be solved with several
  23307. rewrite phases. For a real-world example of a multi-phase rule set,
  23308. examine the set @code{FitRules}, which is used by the curve-fitting
  23309. command to convert a model expression to linear form.
  23310. @xref{Curve Fitting Details}. This set is divided into four phases.
  23311. The first phase rewrites certain kinds of expressions to be more
  23312. easily linearizable, but less computationally efficient. After the
  23313. linear components have been picked out, the final phase includes the
  23314. opposite rewrites to put each component back into an efficient form.
  23315. If both sets of rules were included in one big phase, Calc could get
  23316. into an infinite loop going back and forth between the two forms.
  23317. Elsewhere in @code{FitRules}, the components are first isolated,
  23318. then recombined where possible to reduce the complexity of the linear
  23319. fit, then finally packaged one component at a time into vectors.
  23320. If the packaging rules were allowed to begin before the recombining
  23321. rules were finished, some components might be put away into vectors
  23322. before they had a chance to recombine. By putting these rules in
  23323. two separate phases, this problem is neatly avoided.
  23324. @node Selections with Rewrite Rules, Matching Commands, Multi-Phase Rewrite Rules, Rewrite Rules
  23325. @subsection Selections with Rewrite Rules
  23326. @noindent
  23327. If a sub-formula of the current formula is selected (as by @kbd{j s};
  23328. @pxref{Selecting Subformulas}), the @kbd{a r} (@code{calc-rewrite})
  23329. command applies only to that sub-formula. Together with a negative
  23330. prefix argument, you can use this fact to apply a rewrite to one
  23331. specific part of a formula without affecting any other parts.
  23332. @kindex j r
  23333. @pindex calc-rewrite-selection
  23334. The @kbd{j r} (@code{calc-rewrite-selection}) command allows more
  23335. sophisticated operations on selections. This command prompts for
  23336. the rules in the same way as @kbd{a r}, but it then applies those
  23337. rules to the whole formula in question even though a sub-formula
  23338. of it has been selected. However, the selected sub-formula will
  23339. first have been surrounded by a @samp{select( )} function call.
  23340. (Calc's evaluator does not understand the function name @code{select};
  23341. this is only a tag used by the @kbd{j r} command.)
  23342. For example, suppose the formula on the stack is @samp{2 (a + b)^2}
  23343. and the sub-formula @samp{a + b} is selected. This formula will
  23344. be rewritten to @samp{2 select(a + b)^2} and then the rewrite
  23345. rules will be applied in the usual way. The rewrite rules can
  23346. include references to @code{select} to tell where in the pattern
  23347. the selected sub-formula should appear.
  23348. If there is still exactly one @samp{select( )} function call in
  23349. the formula after rewriting is done, it indicates which part of
  23350. the formula should be selected afterwards. Otherwise, the
  23351. formula will be unselected.
  23352. You can make @kbd{j r} act much like @kbd{a r} by enclosing both parts
  23353. of the rewrite rule with @samp{select()}. However, @kbd{j r}
  23354. allows you to use the current selection in more flexible ways.
  23355. Suppose you wished to make a rule which removed the exponent from
  23356. the selected term; the rule @samp{select(a)^x := select(a)} would
  23357. work. In the above example, it would rewrite @samp{2 select(a + b)^2}
  23358. to @samp{2 select(a + b)}. This would then be returned to the
  23359. stack as @samp{2 (a + b)} with the @samp{a + b} selected.
  23360. The @kbd{j r} command uses one iteration by default, unlike
  23361. @kbd{a r} which defaults to 100 iterations. A numeric prefix
  23362. argument affects @kbd{j r} in the same way as @kbd{a r}.
  23363. @xref{Nested Formulas with Rewrite Rules}.
  23364. As with other selection commands, @kbd{j r} operates on the stack
  23365. entry that contains the cursor. (If the cursor is on the top-of-stack
  23366. @samp{.} marker, it works as if the cursor were on the formula
  23367. at stack level 1.)
  23368. If you don't specify a set of rules, the rules are taken from the
  23369. top of the stack, just as with @kbd{a r}. In this case, the
  23370. cursor must indicate stack entry 2 or above as the formula to be
  23371. rewritten (otherwise the same formula would be used as both the
  23372. target and the rewrite rules).
  23373. If the indicated formula has no selection, the cursor position within
  23374. the formula temporarily selects a sub-formula for the purposes of this
  23375. command. If the cursor is not on any sub-formula (e.g., it is in
  23376. the line-number area to the left of the formula), the @samp{select( )}
  23377. markers are ignored by the rewrite mechanism and the rules are allowed
  23378. to apply anywhere in the formula.
  23379. As a special feature, the normal @kbd{a r} command also ignores
  23380. @samp{select( )} calls in rewrite rules. For example, if you used the
  23381. above rule @samp{select(a)^x := select(a)} with @kbd{a r}, it would apply
  23382. the rule as if it were @samp{a^x := a}. Thus, you can write general
  23383. purpose rules with @samp{select( )} hints inside them so that they
  23384. will ``do the right thing'' in both @kbd{a r} and @kbd{j r},
  23385. both with and without selections.
  23386. @node Matching Commands, Automatic Rewrites, Selections with Rewrite Rules, Rewrite Rules
  23387. @subsection Matching Commands
  23388. @noindent
  23389. @kindex a m
  23390. @pindex calc-match
  23391. @tindex match
  23392. The @kbd{a m} (@code{calc-match}) [@code{match}] function takes a
  23393. vector of formulas and a rewrite-rule-style pattern, and produces
  23394. a vector of all formulas which match the pattern. The command
  23395. prompts you to enter the pattern; as for @kbd{a r}, you can enter
  23396. a single pattern (i.e., a formula with meta-variables), or a
  23397. vector of patterns, or a variable which contains patterns, or
  23398. you can give a blank response in which case the patterns are taken
  23399. from the top of the stack. The pattern set will be compiled once
  23400. and saved if it is stored in a variable. If there are several
  23401. patterns in the set, vector elements are kept if they match any
  23402. of the patterns.
  23403. For example, @samp{match(a+b, [x, x+y, x-y, 7, x+y+z])}
  23404. will return @samp{[x+y, x-y, x+y+z]}.
  23405. The @code{import} mechanism is not available for pattern sets.
  23406. The @kbd{a m} command can also be used to extract all vector elements
  23407. which satisfy any condition: The pattern @samp{x :: x>0} will select
  23408. all the positive vector elements.
  23409. @kindex I a m
  23410. @tindex matchnot
  23411. With the Inverse flag [@code{matchnot}], this command extracts all
  23412. vector elements which do @emph{not} match the given pattern.
  23413. @ignore
  23414. @starindex
  23415. @end ignore
  23416. @tindex matches
  23417. There is also a function @samp{matches(@var{x}, @var{p})} which
  23418. evaluates to 1 if expression @var{x} matches pattern @var{p}, or
  23419. to 0 otherwise. This is sometimes useful for including into the
  23420. conditional clauses of other rewrite rules.
  23421. @ignore
  23422. @starindex
  23423. @end ignore
  23424. @tindex vmatches
  23425. The function @code{vmatches} is just like @code{matches}, except
  23426. that if the match succeeds it returns a vector of assignments to
  23427. the meta-variables instead of the number 1. For example,
  23428. @samp{vmatches(f(1,2), f(a,b))} returns @samp{[a := 1, b := 2]}.
  23429. If the match fails, the function returns the number 0.
  23430. @node Automatic Rewrites, Debugging Rewrites, Matching Commands, Rewrite Rules
  23431. @subsection Automatic Rewrites
  23432. @noindent
  23433. @cindex @code{EvalRules} variable
  23434. @vindex EvalRules
  23435. It is possible to get Calc to apply a set of rewrite rules on all
  23436. results, effectively adding to the built-in set of default
  23437. simplifications. To do this, simply store your rule set in the
  23438. variable @code{EvalRules}. There is a convenient @kbd{s E} command
  23439. for editing @code{EvalRules}; @pxref{Operations on Variables}.
  23440. For example, suppose you want @samp{sin(a + b)} to be expanded out
  23441. to @samp{sin(b) cos(a) + cos(b) sin(a)} wherever it appears, and
  23442. similarly for @samp{cos(a + b)}. The corresponding rewrite rule
  23443. set would be,
  23444. @smallexample
  23445. @group
  23446. [ sin(a + b) := cos(a) sin(b) + sin(a) cos(b),
  23447. cos(a + b) := cos(a) cos(b) - sin(a) sin(b) ]
  23448. @end group
  23449. @end smallexample
  23450. To apply these manually, you could put them in a variable called
  23451. @code{trigexp} and then use @kbd{a r trigexp} every time you wanted
  23452. to expand trig functions. But if instead you store them in the
  23453. variable @code{EvalRules}, they will automatically be applied to all
  23454. sines and cosines of sums. Then, with @samp{2 x} and @samp{45} on
  23455. the stack, typing @kbd{+ S} will (assuming Degrees mode) result in
  23456. @samp{0.7071 sin(2 x) + 0.7071 cos(2 x)} automatically.
  23457. As each level of a formula is evaluated, the rules from
  23458. @code{EvalRules} are applied before the default simplifications.
  23459. Rewriting continues until no further @code{EvalRules} apply.
  23460. Note that this is different from the usual order of application of
  23461. rewrite rules: @code{EvalRules} works from the bottom up, simplifying
  23462. the arguments to a function before the function itself, while @kbd{a r}
  23463. applies rules from the top down.
  23464. Because the @code{EvalRules} are tried first, you can use them to
  23465. override the normal behavior of any built-in Calc function.
  23466. It is important not to write a rule that will get into an infinite
  23467. loop. For example, the rule set @samp{[f(0) := 1, f(n) := n f(n-1)]}
  23468. appears to be a good definition of a factorial function, but it is
  23469. unsafe. Imagine what happens if @samp{f(2.5)} is simplified. Calc
  23470. will continue to subtract 1 from this argument forever without reaching
  23471. zero. A safer second rule would be @samp{f(n) := n f(n-1) :: n>0}.
  23472. Another dangerous rule is @samp{g(x, y) := g(y, x)}. Rewriting
  23473. @samp{g(2, 4)}, this would bounce back and forth between that and
  23474. @samp{g(4, 2)} forever. If an infinite loop in @code{EvalRules}
  23475. occurs, Emacs will eventually stop with a ``Computation got stuck
  23476. or ran too long'' message.
  23477. Another subtle difference between @code{EvalRules} and regular rewrites
  23478. concerns rules that rewrite a formula into an identical formula. For
  23479. example, @samp{f(n) := f(floor(n))} ``fails to match'' when @expr{n} is
  23480. already an integer. But in @code{EvalRules} this case is detected only
  23481. if the righthand side literally becomes the original formula before any
  23482. further simplification. This means that @samp{f(n) := f(floor(n))} will
  23483. get into an infinite loop if it occurs in @code{EvalRules}. Calc will
  23484. replace @samp{f(6)} with @samp{f(floor(6))}, which is different from
  23485. @samp{f(6)}, so it will consider the rule to have matched and will
  23486. continue simplifying that formula; first the argument is simplified
  23487. to get @samp{f(6)}, then the rule matches again to get @samp{f(floor(6))}
  23488. again, ad infinitum. A much safer rule would check its argument first,
  23489. say, with @samp{f(n) := f(floor(n)) :: !dint(n)}.
  23490. (What really happens is that the rewrite mechanism substitutes the
  23491. meta-variables in the righthand side of a rule, compares to see if the
  23492. result is the same as the original formula and fails if so, then uses
  23493. the default simplifications to simplify the result and compares again
  23494. (and again fails if the formula has simplified back to its original
  23495. form). The only special wrinkle for the @code{EvalRules} is that the
  23496. same rules will come back into play when the default simplifications
  23497. are used. What Calc wants to do is build @samp{f(floor(6))}, see that
  23498. this is different from the original formula, simplify to @samp{f(6)},
  23499. see that this is the same as the original formula, and thus halt the
  23500. rewriting. But while simplifying, @samp{f(6)} will again trigger
  23501. the same @code{EvalRules} rule and Calc will get into a loop inside
  23502. the rewrite mechanism itself.)
  23503. The @code{phase}, @code{schedule}, and @code{iterations} markers do
  23504. not work in @code{EvalRules}. If the rule set is divided into phases,
  23505. only the phase 1 rules are applied, and the schedule is ignored.
  23506. The rules are always repeated as many times as possible.
  23507. The @code{EvalRules} are applied to all function calls in a formula,
  23508. but not to numbers (and other number-like objects like error forms),
  23509. nor to vectors or individual variable names. (Though they will apply
  23510. to @emph{components} of vectors and error forms when appropriate.) You
  23511. might try to make a variable @code{phihat} which automatically expands
  23512. to its definition without the need to press @kbd{=} by writing the
  23513. rule @samp{quote(phihat) := (1-sqrt(5))/2}, but unfortunately this rule
  23514. will not work as part of @code{EvalRules}.
  23515. Finally, another limitation is that Calc sometimes calls its built-in
  23516. functions directly rather than going through the default simplifications.
  23517. When it does this, @code{EvalRules} will not be able to override those
  23518. functions. For example, when you take the absolute value of the complex
  23519. number @expr{(2, 3)}, Calc computes @samp{sqrt(2*2 + 3*3)} by calling
  23520. the multiplication, addition, and square root functions directly rather
  23521. than applying the default simplifications to this formula. So an
  23522. @code{EvalRules} rule that (perversely) rewrites @samp{sqrt(13) := 6}
  23523. would not apply. (However, if you put Calc into Symbolic mode so that
  23524. @samp{sqrt(13)} will be left in symbolic form by the built-in square
  23525. root function, your rule will be able to apply. But if the complex
  23526. number were @expr{(3,4)}, so that @samp{sqrt(25)} must be calculated,
  23527. then Symbolic mode will not help because @samp{sqrt(25)} can be
  23528. evaluated exactly to 5.)
  23529. One subtle restriction that normally only manifests itself with
  23530. @code{EvalRules} is that while a given rewrite rule is in the process
  23531. of being checked, that same rule cannot be recursively applied. Calc
  23532. effectively removes the rule from its rule set while checking the rule,
  23533. then puts it back once the match succeeds or fails. (The technical
  23534. reason for this is that compiled pattern programs are not reentrant.)
  23535. For example, consider the rule @samp{foo(x) := x :: foo(x/2) > 0}
  23536. attempting to match @samp{foo(8)}. This rule will be inactive while
  23537. the condition @samp{foo(4) > 0} is checked, even though it might be
  23538. an integral part of evaluating that condition. Note that this is not
  23539. a problem for the more usual recursive type of rule, such as
  23540. @samp{foo(x) := foo(x/2)}, because there the rule has succeeded and
  23541. been reactivated by the time the righthand side is evaluated.
  23542. If @code{EvalRules} has no stored value (its default state), or if
  23543. anything but a vector is stored in it, then it is ignored.
  23544. Even though Calc's rewrite mechanism is designed to compare rewrite
  23545. rules to formulas as quickly as possible, storing rules in
  23546. @code{EvalRules} may make Calc run substantially slower. This is
  23547. particularly true of rules where the top-level call is a commonly used
  23548. function, or is not fixed. The rule @samp{f(n) := n f(n-1) :: n>0} will
  23549. only activate the rewrite mechanism for calls to the function @code{f},
  23550. but @samp{lg(n) + lg(m) := lg(n m)} will check every @samp{+} operator.
  23551. @smallexample
  23552. apply(f, [a*b]) := apply(f, [a]) + apply(f, [b]) :: in(f, [ln, log10])
  23553. @end smallexample
  23554. @noindent
  23555. may seem more ``efficient'' than two separate rules for @code{ln} and
  23556. @code{log10}, but actually it is vastly less efficient because rules
  23557. with @code{apply} as the top-level pattern must be tested against
  23558. @emph{every} function call that is simplified.
  23559. @cindex @code{AlgSimpRules} variable
  23560. @vindex AlgSimpRules
  23561. Suppose you want @samp{sin(a + b)} to be expanded out not all the time,
  23562. but only when algebraic simplifications are used to simplify the
  23563. formula. The variable @code{AlgSimpRules} holds rules for this purpose.
  23564. The @kbd{a s} command will apply @code{EvalRules} and
  23565. @code{AlgSimpRules} to the formula, as well as all of its built-in
  23566. simplifications.
  23567. Most of the special limitations for @code{EvalRules} don't apply to
  23568. @code{AlgSimpRules}. Calc simply does an @kbd{a r AlgSimpRules}
  23569. command with an infinite repeat count as the first step of algebraic
  23570. simplifications. It then applies its own built-in simplifications
  23571. throughout the formula, and then repeats these two steps (along with
  23572. applying the default simplifications) until no further changes are
  23573. possible.
  23574. @cindex @code{ExtSimpRules} variable
  23575. @cindex @code{UnitSimpRules} variable
  23576. @vindex ExtSimpRules
  23577. @vindex UnitSimpRules
  23578. There are also @code{ExtSimpRules} and @code{UnitSimpRules} variables
  23579. that are used by @kbd{a e} and @kbd{u s}, respectively; these commands
  23580. also apply @code{EvalRules} and @code{AlgSimpRules}. The variable
  23581. @code{IntegSimpRules} contains simplification rules that are used
  23582. only during integration by @kbd{a i}.
  23583. @node Debugging Rewrites, Examples of Rewrite Rules, Automatic Rewrites, Rewrite Rules
  23584. @subsection Debugging Rewrites
  23585. @noindent
  23586. If a buffer named @file{*Trace*} exists, the rewrite mechanism will
  23587. record some useful information there as it operates. The original
  23588. formula is written there, as is the result of each successful rewrite,
  23589. and the final result of the rewriting. All phase changes are also
  23590. noted.
  23591. Calc always appends to @file{*Trace*}. You must empty this buffer
  23592. yourself periodically if it is in danger of growing unwieldy.
  23593. Note that the rewriting mechanism is substantially slower when the
  23594. @file{*Trace*} buffer exists, even if the buffer is not visible on
  23595. the screen. Once you are done, you will probably want to kill this
  23596. buffer (with @kbd{C-x k *Trace* @key{RET}}). If you leave it in
  23597. existence and forget about it, all your future rewrite commands will
  23598. be needlessly slow.
  23599. @node Examples of Rewrite Rules, , Debugging Rewrites, Rewrite Rules
  23600. @subsection Examples of Rewrite Rules
  23601. @noindent
  23602. Returning to the example of substituting the pattern
  23603. @samp{sin(x)^2 + cos(x)^2} with 1, we saw that the rule
  23604. @samp{opt(a) sin(x)^2 + opt(a) cos(x)^2 := a} does a good job of
  23605. finding suitable cases. Another solution would be to use the rule
  23606. @samp{cos(x)^2 := 1 - sin(x)^2}, followed by algebraic simplification
  23607. if necessary. This rule will be the most effective way to do the job,
  23608. but at the expense of making some changes that you might not desire.
  23609. Another algebraic rewrite rule is @samp{exp(x+y) := exp(x) exp(y)}.
  23610. To make this work with the @w{@kbd{j r}} command so that it can be
  23611. easily targeted to a particular exponential in a large formula,
  23612. you might wish to write the rule as @samp{select(exp(x+y)) :=
  23613. select(exp(x) exp(y))}. The @samp{select} markers will be
  23614. ignored by the regular @kbd{a r} command
  23615. (@pxref{Selections with Rewrite Rules}).
  23616. A surprisingly useful rewrite rule is @samp{a/(b-c) := a*(b+c)/(b^2-c^2)}.
  23617. This will simplify the formula whenever @expr{b} and/or @expr{c} can
  23618. be made simpler by squaring. For example, applying this rule to
  23619. @samp{2 / (sqrt(2) + 3)} yields @samp{6:7 - 2:7 sqrt(2)} (assuming
  23620. Symbolic mode has been enabled to keep the square root from being
  23621. evaluated to a floating-point approximation). This rule is also
  23622. useful when working with symbolic complex numbers, e.g.,
  23623. @samp{(a + b i) / (c + d i)}.
  23624. As another example, we could define our own ``triangular numbers'' function
  23625. with the rules @samp{[tri(0) := 0, tri(n) := n + tri(n-1) :: n>0]}. Enter
  23626. this vector and store it in a variable: @kbd{@w{s t} trirules}. Now, given
  23627. a suitable formula like @samp{tri(5)} on the stack, type @samp{a r trirules}
  23628. to apply these rules repeatedly. After six applications, @kbd{a r} will
  23629. stop with 15 on the stack. Once these rules are debugged, it would probably
  23630. be most useful to add them to @code{EvalRules} so that Calc will evaluate
  23631. the new @code{tri} function automatically. We could then use @kbd{Z K} on
  23632. the keyboard macro @kbd{' tri($) @key{RET}} to make a command that applies
  23633. @code{tri} to the value on the top of the stack. @xref{Programming}.
  23634. @cindex Quaternions
  23635. The following rule set, contributed by François
  23636. Pinard, implements @dfn{quaternions}, a generalization of the concept of
  23637. complex numbers. Quaternions have four components, and are here
  23638. represented by function calls @samp{quat(@var{w}, [@var{x}, @var{y},
  23639. @var{z}])} with ``real part'' @var{w} and the three ``imaginary'' parts
  23640. collected into a vector. Various arithmetical operations on quaternions
  23641. are supported. To use these rules, either add them to @code{EvalRules},
  23642. or create a command based on @kbd{a r} for simplifying quaternion
  23643. formulas. A convenient way to enter quaternions would be a command
  23644. defined by a keyboard macro containing: @kbd{' quat($$$$, [$$$, $$, $])
  23645. @key{RET}}.
  23646. @smallexample
  23647. [ quat(w, x, y, z) := quat(w, [x, y, z]),
  23648. quat(w, [0, 0, 0]) := w,
  23649. abs(quat(w, v)) := hypot(w, v),
  23650. -quat(w, v) := quat(-w, -v),
  23651. r + quat(w, v) := quat(r + w, v) :: real(r),
  23652. r - quat(w, v) := quat(r - w, -v) :: real(r),
  23653. quat(w1, v1) + quat(w2, v2) := quat(w1 + w2, v1 + v2),
  23654. r * quat(w, v) := quat(r * w, r * v) :: real(r),
  23655. plain(quat(w1, v1) * quat(w2, v2))
  23656. := quat(w1 * w2 - v1 * v2, w1 * v2 + w2 * v1 + cross(v1, v2)),
  23657. quat(w1, v1) / r := quat(w1 / r, v1 / r) :: real(r),
  23658. z / quat(w, v) := z * quatinv(quat(w, v)),
  23659. quatinv(quat(w, v)) := quat(w, -v) / (w^2 + v^2),
  23660. quatsqr(quat(w, v)) := quat(w^2 - v^2, 2 * w * v),
  23661. quat(w, v)^k := quatsqr(quat(w, v)^(k / 2))
  23662. :: integer(k) :: k > 0 :: k % 2 = 0,
  23663. quat(w, v)^k := quatsqr(quat(w, v)^((k - 1) / 2)) * quat(w, v)
  23664. :: integer(k) :: k > 2,
  23665. quat(w, v)^-k := quatinv(quat(w, v)^k) :: integer(k) :: k > 0 ]
  23666. @end smallexample
  23667. Quaternions, like matrices, have non-commutative multiplication.
  23668. In other words, @expr{q1 * q2 = q2 * q1} is not necessarily true if
  23669. @expr{q1} and @expr{q2} are @code{quat} forms. The @samp{quat*quat}
  23670. rule above uses @code{plain} to prevent Calc from rearranging the
  23671. product. It may also be wise to add the line @samp{[quat(), matrix]}
  23672. to the @code{Decls} matrix, to ensure that Calc's other algebraic
  23673. operations will not rearrange a quaternion product. @xref{Declarations}.
  23674. These rules also accept a four-argument @code{quat} form, converting
  23675. it to the preferred form in the first rule. If you would rather see
  23676. results in the four-argument form, just append the two items
  23677. @samp{phase(2), quat(w, [x, y, z]) := quat(w, x, y, z)} to the end
  23678. of the rule set. (But remember that multi-phase rule sets don't work
  23679. in @code{EvalRules}.)
  23680. @node Units, Store and Recall, Algebra, Top
  23681. @chapter Operating on Units
  23682. @noindent
  23683. One special interpretation of algebraic formulas is as numbers with units.
  23684. For example, the formula @samp{5 m / s^2} can be read ``five meters
  23685. per second squared.'' The commands in this chapter help you
  23686. manipulate units expressions in this form. Units-related commands
  23687. begin with the @kbd{u} prefix key.
  23688. @menu
  23689. * Basic Operations on Units::
  23690. * The Units Table::
  23691. * Predefined Units::
  23692. * User-Defined Units::
  23693. * Logarithmic Units::
  23694. * Musical Notes::
  23695. @end menu
  23696. @node Basic Operations on Units, The Units Table, Units, Units
  23697. @section Basic Operations on Units
  23698. @noindent
  23699. A @dfn{units expression} is a formula which is basically a number
  23700. multiplied and/or divided by one or more @dfn{unit names}, which may
  23701. optionally be raised to integer powers. Actually, the value part need not
  23702. be a number; any product or quotient involving unit names is a units
  23703. expression. Many of the units commands will also accept any formula,
  23704. where the command applies to all units expressions which appear in the
  23705. formula.
  23706. A unit name is a variable whose name appears in the @dfn{unit table},
  23707. or a variable whose name is a prefix character like @samp{k} (for ``kilo'')
  23708. or @samp{u} (for ``micro'') followed by a name in the unit table.
  23709. A substantial table of built-in units is provided with Calc;
  23710. @pxref{Predefined Units}. You can also define your own unit names;
  23711. @pxref{User-Defined Units}.
  23712. Note that if the value part of a units expression is exactly @samp{1},
  23713. it will be removed by the Calculator's automatic algebra routines: The
  23714. formula @samp{1 mm} is ``simplified'' to @samp{mm}. This is only a
  23715. display anomaly, however; @samp{mm} will work just fine as a
  23716. representation of one millimeter.
  23717. You may find that Algebraic mode (@pxref{Algebraic Entry}) makes working
  23718. with units expressions easier. Otherwise, you will have to remember
  23719. to hit the apostrophe key every time you wish to enter units.
  23720. @kindex u s
  23721. @pindex calc-simplify-units
  23722. @ignore
  23723. @mindex usimpl@idots
  23724. @end ignore
  23725. @tindex usimplify
  23726. The @kbd{u s} (@code{calc-simplify-units}) [@code{usimplify}] command
  23727. simplifies a units
  23728. expression. It uses Calc's algebraic simplifications to simplify the
  23729. expression first as a regular algebraic formula; it then looks for
  23730. features that can be further simplified by converting one object's units
  23731. to be compatible with another's. For example, @samp{5 m + 23 mm} will
  23732. simplify to @samp{5.023 m}. When different but compatible units are
  23733. added, the righthand term's units are converted to match those of the
  23734. lefthand term. @xref{Simplification Modes}, for a way to have this done
  23735. automatically at all times.
  23736. Units simplification also handles quotients of two units with the same
  23737. dimensionality, as in @w{@samp{2 in s/L cm}} to @samp{5.08 s/L}; fractional
  23738. powers of unit expressions, as in @samp{sqrt(9 mm^2)} to @samp{3 mm} and
  23739. @samp{sqrt(9 acre)} to a quantity in meters; and @code{floor},
  23740. @code{ceil}, @code{round}, @code{rounde}, @code{roundu}, @code{trunc},
  23741. @code{float}, @code{frac}, @code{abs}, and @code{clean}
  23742. applied to units expressions, in which case
  23743. the operation in question is applied only to the numeric part of the
  23744. expression. Finally, trigonometric functions of quantities with units
  23745. of angle are evaluated, regardless of the current angular mode.
  23746. @kindex u c
  23747. @pindex calc-convert-units
  23748. The @kbd{u c} (@code{calc-convert-units}) command converts a units
  23749. expression to new, compatible units. For example, given the units
  23750. expression @samp{55 mph}, typing @kbd{u c m/s @key{RET}} produces
  23751. @samp{24.5872 m/s}. If you have previously converted a units expression
  23752. with the same type of units (in this case, distance over time), you will
  23753. be offered the previous choice of new units as a default. Continuing
  23754. the above example, entering the units expression @samp{100 km/hr} and
  23755. typing @kbd{u c @key{RET}} (without specifying new units) produces
  23756. @samp{27.7777777778 m/s}.
  23757. @kindex u t
  23758. @pindex calc-convert-temperature
  23759. @cindex Temperature conversion
  23760. The @kbd{u c} command treats temperature units (like @samp{degC} and
  23761. @samp{K}) as relative temperatures. For example, @kbd{u c} converts
  23762. @samp{10 degC} to @samp{18 degF}: A change of 10 degrees Celsius
  23763. corresponds to a change of 18 degrees Fahrenheit. To convert absolute
  23764. temperatures, you can use the @kbd{u t}
  23765. (@code{calc-convert-temperature}) command. The value on the stack
  23766. must be a simple units expression with units of temperature only.
  23767. This command would convert @samp{10 degC} to @samp{50 degF}, the
  23768. equivalent temperature on the Fahrenheit scale.
  23769. While many of Calc's conversion factors are exact, some are necessarily
  23770. approximate. If Calc is in fraction mode (@pxref{Fraction Mode}), then
  23771. unit conversions will try to give exact, rational conversions, but it
  23772. isn't always possible. Given @samp{55 mph} in fraction mode, typing
  23773. @kbd{u c m/s @key{RET}} produces @samp{15367:625 m/s}, for example,
  23774. while typing @kbd{u c au/yr @key{RET}} produces
  23775. @samp{5.18665819999e-3 au/yr}.
  23776. If the units you request are inconsistent with the original units, the
  23777. number will be converted into your units times whatever ``remainder''
  23778. units are left over. For example, converting @samp{55 mph} into acres
  23779. produces @samp{6.08e-3 acre / (m s)}. Remainder units are expressed in terms of
  23780. ``fundamental'' units like @samp{m} and @samp{s}, regardless of the
  23781. input units.
  23782. @kindex u n
  23783. @pindex calc-convert-exact-units
  23784. If you intend that your new units be consistent with the original
  23785. units, the @kbd{u n} (@code{calc-convert-exact-units}) command will
  23786. check the units before the conversion. For example, to change
  23787. @samp{mi/hr} to @samp{km/hr}, you could type @kbd{u c km @key{RET}},
  23788. but @kbd{u n km @key{RET}} would signal an error.
  23789. You would need to type @kbd{u n km/hr @key{RET}}.
  23790. One special exception is that if you specify a single unit name, and
  23791. a compatible unit appears somewhere in the units expression, then
  23792. that compatible unit will be converted to the new unit and the
  23793. remaining units in the expression will be left alone. For example,
  23794. given the input @samp{980 cm/s^2}, the command @kbd{u c ms} will
  23795. change the @samp{s} to @samp{ms} to get @samp{9.8e-4 cm/ms^2}.
  23796. The ``remainder unit'' @samp{cm} is left alone rather than being
  23797. changed to the base unit @samp{m}.
  23798. You can use explicit unit conversion instead of the @kbd{u s} command
  23799. to gain more control over the units of the result of an expression.
  23800. For example, given @samp{5 m + 23 mm}, you can type @kbd{u c m} or
  23801. @kbd{u c mm} to express the result in either meters or millimeters.
  23802. (For that matter, you could type @kbd{u c fath} to express the result
  23803. in fathoms, if you preferred!)
  23804. In place of a specific set of units, you can also enter one of the
  23805. units system names @code{si}, @code{mks} (equivalent), or @code{cgs}.
  23806. For example, @kbd{u c si @key{RET}} converts the expression into
  23807. International System of Units (SI) base units. Also, @kbd{u c base}
  23808. converts to Calc's base units, which are the same as @code{si} units
  23809. except that @code{base} uses @samp{g} as the fundamental unit of mass
  23810. whereas @code{si} uses @samp{kg}.
  23811. @cindex Composite units
  23812. The @kbd{u c} command also accepts @dfn{composite units}, which
  23813. are expressed as the sum of several compatible unit names. For
  23814. example, converting @samp{30.5 in} to units @samp{mi+ft+in} (miles,
  23815. feet, and inches) produces @samp{2 ft + 6.5 in}. Calc first
  23816. sorts the unit names into order of decreasing relative size.
  23817. It then accounts for as much of the input quantity as it can
  23818. using an integer number times the largest unit, then moves on
  23819. to the next smaller unit, and so on. Only the smallest unit
  23820. may have a non-integer amount attached in the result. A few
  23821. standard unit names exist for common combinations, such as
  23822. @code{mfi} for @samp{mi+ft+in}, and @code{tpo} for @samp{ton+lb+oz}.
  23823. Composite units are expanded as if by @kbd{a x}, so that
  23824. @samp{(ft+in)/hr} is first converted to @samp{ft/hr+in/hr}.
  23825. If the value on the stack does not contain any units, @kbd{u c} will
  23826. prompt first for the old units which this value should be considered
  23827. to have, then for the new units. (If the value on the stack can be
  23828. simplified so that it doesn't contain any units, like @samp{ft/in} can
  23829. be simplified to 12, then @kbd{u c} will still prompt for both old
  23830. units and new units. Assuming the old and new units you give are
  23831. consistent with each other, the result also will not contain any
  23832. units. For example, @kbd{@w{u c} cm @key{RET} in @key{RET}} converts
  23833. the number 2 on the stack to 5.08.
  23834. @kindex u b
  23835. @pindex calc-base-units
  23836. The @kbd{u b} (@code{calc-base-units}) command is shorthand for
  23837. @kbd{u c base}; it converts the units expression on the top of the
  23838. stack into @code{base} units. If @kbd{u s} does not simplify a
  23839. units expression as far as you would like, try @kbd{u b}.
  23840. Like the @kbd{u c} command, the @kbd{u b} command treats temperature
  23841. units as relative temperatures.
  23842. @kindex u r
  23843. @pindex calc-remove-units
  23844. @kindex u x
  23845. @pindex calc-extract-units
  23846. The @kbd{u r} (@code{calc-remove-units}) command removes units from the
  23847. formula at the top of the stack. The @kbd{u x}
  23848. (@code{calc-extract-units}) command extracts only the units portion of a
  23849. formula. These commands essentially replace every term of the formula
  23850. that does or doesn't (respectively) look like a unit name by the
  23851. constant 1, then resimplify the formula.
  23852. @kindex u a
  23853. @pindex calc-autorange-units
  23854. The @kbd{u a} (@code{calc-autorange-units}) command turns on and off a
  23855. mode in which unit prefixes like @code{k} (``kilo'') are automatically
  23856. applied to keep the numeric part of a units expression in a reasonable
  23857. range. This mode affects @kbd{u s} and all units conversion commands
  23858. except @kbd{u b}. For example, with autoranging on, @samp{12345 Hz}
  23859. will be simplified to @samp{12.345 kHz}. Autoranging is useful for
  23860. some kinds of units (like @code{Hz} and @code{m}), but is probably
  23861. undesirable for non-metric units like @code{ft} and @code{tbsp}.
  23862. (Composite units are more appropriate for those; see above.)
  23863. Autoranging always applies the prefix to the leftmost unit name.
  23864. Calc chooses the largest prefix that causes the number to be greater
  23865. than or equal to 1.0. Thus an increasing sequence of adjusted times
  23866. would be @samp{1 ms, 10 ms, 100 ms, 1 s, 10 s, 100 s, 1 ks}.
  23867. Generally the rule of thumb is that the number will be adjusted
  23868. to be in the interval @samp{[1 .. 1000)}, although there are several
  23869. exceptions to this rule. First, if the unit has a power then this
  23870. is not possible; @samp{0.1 s^2} simplifies to @samp{100000 ms^2}.
  23871. Second, the ``centi-'' prefix is allowed to form @code{cm} (centimeters),
  23872. but will not apply to other units. The ``deci-,'' ``deka-,'' and
  23873. ``hecto-'' prefixes are never used. Thus the allowable interval is
  23874. @samp{[1 .. 10)} for millimeters and @samp{[1 .. 100)} for centimeters.
  23875. Finally, a prefix will not be added to a unit if the resulting name
  23876. is also the actual name of another unit; @samp{1e-15 t} would normally
  23877. be considered a ``femto-ton,'' but it is written as @samp{1000 at}
  23878. (1000 atto-tons) instead because @code{ft} would be confused with feet.
  23879. @node The Units Table, Predefined Units, Basic Operations on Units, Units
  23880. @section The Units Table
  23881. @noindent
  23882. @kindex u v
  23883. @pindex calc-enter-units-table
  23884. The @kbd{u v} (@code{calc-enter-units-table}) command displays the units table
  23885. in another buffer called @file{*Units Table*}. Each entry in this table
  23886. gives the unit name as it would appear in an expression, the definition
  23887. of the unit in terms of simpler units, and a full name or description of
  23888. the unit. Fundamental units are defined as themselves; these are the
  23889. units produced by the @kbd{u b} command. The fundamental units are
  23890. meters, seconds, grams, kelvins, amperes, candelas, moles, radians,
  23891. and steradians.
  23892. The Units Table buffer also displays the Unit Prefix Table. Note that
  23893. two prefixes, ``kilo'' and ``hecto,'' accept either upper- or lower-case
  23894. prefix letters. @samp{Meg} is also accepted as a synonym for the @samp{M}
  23895. prefix. Whenever a unit name can be interpreted as either a built-in name
  23896. or a prefix followed by another built-in name, the former interpretation
  23897. wins. For example, @samp{2 pt} means two pints, not two pico-tons.
  23898. The Units Table buffer, once created, is not rebuilt unless you define
  23899. new units. To force the buffer to be rebuilt, give any numeric prefix
  23900. argument to @kbd{u v}.
  23901. @kindex u V
  23902. @pindex calc-view-units-table
  23903. The @kbd{u V} (@code{calc-view-units-table}) command is like @kbd{u v} except
  23904. that the cursor is not moved into the Units Table buffer. You can
  23905. type @kbd{u V} again to remove the Units Table from the display. To
  23906. return from the Units Table buffer after a @kbd{u v}, type @kbd{C-x * c}
  23907. again or use the regular Emacs @w{@kbd{C-x o}} (@code{other-window})
  23908. command. You can also kill the buffer with @kbd{C-x k} if you wish;
  23909. the actual units table is safely stored inside the Calculator.
  23910. @kindex u g
  23911. @pindex calc-get-unit-definition
  23912. The @kbd{u g} (@code{calc-get-unit-definition}) command retrieves a unit's
  23913. defining expression and pushes it onto the Calculator stack. For example,
  23914. @kbd{u g in} will produce the expression @samp{2.54 cm}. This is the
  23915. same definition for the unit that would appear in the Units Table buffer.
  23916. Note that this command works only for actual unit names; @kbd{u g km}
  23917. will report that no such unit exists, for example, because @code{km} is
  23918. really the unit @code{m} with a @code{k} (``kilo'') prefix. To see a
  23919. definition of a unit in terms of base units, it is easier to push the
  23920. unit name on the stack and then reduce it to base units with @kbd{u b}.
  23921. @kindex u e
  23922. @pindex calc-explain-units
  23923. The @kbd{u e} (@code{calc-explain-units}) command displays an English
  23924. description of the units of the expression on the stack. For example,
  23925. for the expression @samp{62 km^2 g / s^2 mol K}, the description is
  23926. ``Square-Kilometer Gram per (Second-squared Mole Degree-Kelvin).'' This
  23927. command uses the English descriptions that appear in the righthand
  23928. column of the Units Table.
  23929. @node Predefined Units, User-Defined Units, The Units Table, Units
  23930. @section Predefined Units
  23931. @noindent
  23932. The definitions of many units have changed over the years. For example,
  23933. the meter was originally defined in 1791 as one ten-millionth of the
  23934. distance from the equator to the north pole. In order to be more
  23935. precise, the definition was adjusted several times, and now a meter is
  23936. defined as the distance that light will travel in a vacuum in
  23937. 1/299792458 of a second; consequently, the speed of light in a
  23938. vacuum is exactly 299792458 m/s. Many other units have been
  23939. redefined in terms of fundamental physical processes; a second, for
  23940. example, is currently defined as 9192631770 periods of a certain
  23941. radiation related to the cesium-133 atom. The only SI unit that is not
  23942. based on a fundamental physical process (although there are efforts to
  23943. change this) is the kilogram, which was originally defined as the mass
  23944. of one liter of water, but is now defined as the mass of the
  23945. international prototype of the kilogram (IPK), a cylinder of platinum-iridium
  23946. kept at the Bureau international des poids et mesures in Sèvres,
  23947. France. (There are several copies of the IPK throughout the world.)
  23948. The British imperial units, once defined in terms of physical objects,
  23949. were redefined in 1963 in terms of SI units. The US customary units,
  23950. which were the same as British units until the British imperial system
  23951. was created in 1824, were also defined in terms of the SI units in 1893.
  23952. Because of these redefinitions, conversions between metric, British
  23953. Imperial, and US customary units can often be done precisely.
  23954. Since the exact definitions of many kinds of units have evolved over the
  23955. years, and since certain countries sometimes have local differences in
  23956. their definitions, it is a good idea to examine Calc's definition of a
  23957. unit before depending on its exact value. For example, there are three
  23958. different units for gallons, corresponding to the US (@code{gal}),
  23959. Canadian (@code{galC}), and British (@code{galUK}) definitions. Also,
  23960. note that @code{oz} is a standard ounce of mass, @code{ozt} is a Troy
  23961. ounce, and @code{ozfl} is a fluid ounce.
  23962. The temperature units corresponding to degrees Kelvin and Centigrade
  23963. (Celsius) are the same in this table, since most units commands treat
  23964. temperatures as being relative. The @code{calc-convert-temperature}
  23965. command has special rules for handling the different absolute magnitudes
  23966. of the various temperature scales.
  23967. The unit of volume ``liters'' can be referred to by either the lower-case
  23968. @code{l} or the upper-case @code{L}.
  23969. The unit @code{A} stands for Amperes; the name @code{Ang} is used
  23970. @tex
  23971. for \AA ngstroms.
  23972. @end tex
  23973. @ifnottex
  23974. for Angstroms.
  23975. @end ifnottex
  23976. The unit @code{pt} stands for pints; the name @code{point} stands for
  23977. a typographical point, defined by @samp{72 point = 1 in}. This is
  23978. slightly different than the point defined by the American Typefounder's
  23979. Association in 1886, but the point used by Calc has become standard
  23980. largely due to its use by the PostScript page description language.
  23981. There is also @code{texpt}, which stands for a printer's point as
  23982. defined by the @TeX{} typesetting system: @samp{72.27 texpt = 1 in}.
  23983. Other units used by @TeX{} are available; they are @code{texpc} (a pica),
  23984. @code{texbp} (a ``big point'', equal to a standard point which is larger
  23985. than the point used by @TeX{}), @code{texdd} (a Didot point),
  23986. @code{texcc} (a Cicero) and @code{texsp} (a scaled @TeX{} point,
  23987. all dimensions representable in @TeX{} are multiples of this value).
  23988. When Calc is using the @TeX{} or @LaTeX{} language mode (@pxref{TeX
  23989. and LaTeX Language Modes}), the @TeX{} specific unit names will not
  23990. use the @samp{tex} prefix; the unit name for a @TeX{} point will be
  23991. @samp{pt} instead of @samp{texpt}, for example. To avoid conflicts,
  23992. the unit names for pint and parsec will simply be @samp{pint} and
  23993. @samp{parsec} instead of @samp{pt} and @samp{pc}.
  23994. The unit @code{e} stands for the elementary (electron) unit of charge;
  23995. because algebra command could mistake this for the special constant
  23996. @expr{e}, Calc provides the alternate unit name @code{ech} which is
  23997. preferable to @code{e}.
  23998. The name @code{g} stands for one gram of mass; there is also @code{gf},
  23999. one gram of force. (Likewise for @kbd{lb}, pounds, and @kbd{lbf}.)
  24000. Meanwhile, one ``@expr{g}'' of acceleration is denoted @code{ga}.
  24001. The unit @code{ton} is a U.S. ton of @samp{2000 lb}, and @code{t} is
  24002. a metric ton of @samp{1000 kg}.
  24003. The names @code{s} (or @code{sec}) and @code{min} refer to units of
  24004. time; @code{arcsec} and @code{arcmin} are units of angle.
  24005. Some ``units'' are really physical constants; for example, @code{c}
  24006. represents the speed of light, and @code{h} represents Planck's
  24007. constant. You can use these just like other units: converting
  24008. @samp{.5 c} to @samp{m/s} expresses one-half the speed of light in
  24009. meters per second. You can also use this merely as a handy reference;
  24010. the @kbd{u g} command gets the definition of one of these constants
  24011. in its normal terms, and @kbd{u b} expresses the definition in base
  24012. units.
  24013. Two units, @code{pi} and @code{alpha} (the fine structure constant,
  24014. approximately @mathit{1/137}) are dimensionless. The units simplification
  24015. commands simply treat these names as equivalent to their corresponding
  24016. values. However you can, for example, use @kbd{u c} to convert a pure
  24017. number into multiples of the fine structure constant, or @kbd{u b} to
  24018. convert this back into a pure number. (When @kbd{u c} prompts for the
  24019. ``old units,'' just enter a blank line to signify that the value
  24020. really is unitless.)
  24021. @c Describe angular units, luminosity vs. steradians problem.
  24022. @node User-Defined Units, Logarithmic Units, Predefined Units, Units
  24023. @section User-Defined Units
  24024. @noindent
  24025. Calc provides ways to get quick access to your selected ``favorite''
  24026. units, as well as ways to define your own new units.
  24027. @kindex u 0-9
  24028. @pindex calc-quick-units
  24029. @vindex Units
  24030. @cindex @code{Units} variable
  24031. @cindex Quick units
  24032. To select your favorite units, store a vector of unit names or
  24033. expressions in the Calc variable @code{Units}. The @kbd{u 1}
  24034. through @kbd{u 9} commands (@code{calc-quick-units}) provide access
  24035. to these units. If the value on the top of the stack is a plain
  24036. number (with no units attached), then @kbd{u 1} gives it the
  24037. specified units. (Basically, it multiplies the number by the
  24038. first item in the @code{Units} vector.) If the number on the
  24039. stack @emph{does} have units, then @kbd{u 1} converts that number
  24040. to the new units. For example, suppose the vector @samp{[in, ft]}
  24041. is stored in @code{Units}. Then @kbd{30 u 1} will create the
  24042. expression @samp{30 in}, and @kbd{u 2} will convert that expression
  24043. to @samp{2.5 ft}.
  24044. The @kbd{u 0} command accesses the tenth element of @code{Units}.
  24045. Only ten quick units may be defined at a time. If the @code{Units}
  24046. variable has no stored value (the default), or if its value is not
  24047. a vector, then the quick-units commands will not function. The
  24048. @kbd{s U} command is a convenient way to edit the @code{Units}
  24049. variable; @pxref{Operations on Variables}.
  24050. @kindex u d
  24051. @pindex calc-define-unit
  24052. @cindex User-defined units
  24053. The @kbd{u d} (@code{calc-define-unit}) command records the units
  24054. expression on the top of the stack as the definition for a new,
  24055. user-defined unit. For example, putting @samp{16.5 ft} on the stack and
  24056. typing @kbd{u d rod} defines the new unit @samp{rod} to be equivalent to
  24057. 16.5 feet. The unit conversion and simplification commands will now
  24058. treat @code{rod} just like any other unit of length. You will also be
  24059. prompted for an optional English description of the unit, which will
  24060. appear in the Units Table. If you wish the definition of this unit to
  24061. be displayed in a special way in the Units Table buffer (such as with an
  24062. asterisk to indicate an approximate value), then you can call this
  24063. command with an argument, @kbd{C-u u d}; you will then also be prompted
  24064. for a string that will be used to display the definition.
  24065. @kindex u u
  24066. @pindex calc-undefine-unit
  24067. The @kbd{u u} (@code{calc-undefine-unit}) command removes a user-defined
  24068. unit. It is not possible to remove one of the predefined units,
  24069. however.
  24070. If you define a unit with an existing unit name, your new definition
  24071. will replace the original definition of that unit. If the unit was a
  24072. predefined unit, the old definition will not be replaced, only
  24073. ``shadowed.'' The built-in definition will reappear if you later use
  24074. @kbd{u u} to remove the shadowing definition.
  24075. To create a new fundamental unit, use either 1 or the unit name itself
  24076. as the defining expression. Otherwise the expression can involve any
  24077. other units that you like (except for composite units like @samp{mfi}).
  24078. You can create a new composite unit with a sum of other units as the
  24079. defining expression. The next unit operation like @kbd{u c} or @kbd{u v}
  24080. will rebuild the internal unit table incorporating your modifications.
  24081. Note that erroneous definitions (such as two units defined in terms of
  24082. each other) will not be detected until the unit table is next rebuilt;
  24083. @kbd{u v} is a convenient way to force this to happen.
  24084. Temperature units are treated specially inside the Calculator; it is not
  24085. possible to create user-defined temperature units.
  24086. @kindex u p
  24087. @pindex calc-permanent-units
  24088. @cindex Calc init file, user-defined units
  24089. The @kbd{u p} (@code{calc-permanent-units}) command stores the user-defined
  24090. units in your Calc init file (the file given by the variable
  24091. @code{calc-settings-file}, typically @file{~/.emacs.d/calc.el}), so that the
  24092. units will still be available in subsequent Emacs sessions. If there
  24093. was already a set of user-defined units in your Calc init file, it
  24094. is replaced by the new set. (@xref{General Mode Commands}, for a way to
  24095. tell Calc to use a different file for the Calc init file.)
  24096. @node Logarithmic Units, Musical Notes, User-Defined Units, Units
  24097. @section Logarithmic Units
  24098. The units @code{dB} (decibels) and @code{Np} (nepers) are logarithmic
  24099. units which are manipulated differently than standard units. Calc
  24100. provides commands to work with these logarithmic units.
  24101. Decibels and nepers are used to measure power quantities as well as
  24102. field quantities (quantities whose squares are proportional to power);
  24103. these two types of quantities are handled slightly different from each
  24104. other. By default the Calc commands work as if power quantities are
  24105. being used; with the @kbd{H} prefix the Calc commands work as if field
  24106. quantities are being used.
  24107. The decibel level of a power
  24108. @infoline @math{P1},
  24109. @texline @math{P_1},
  24110. relative to a reference power
  24111. @infoline @math{P0},
  24112. @texline @math{P_0},
  24113. is defined to be
  24114. @infoline @math{10 log10(P1/P0) dB}.
  24115. @texline @math{10 \log_{10}(P_{1}/P_{0}) {\rm dB}}.
  24116. (The factor of 10 is because a decibel, as its name implies, is
  24117. one-tenth of a bel. The bel, named after Alexander Graham Bell, was
  24118. considered to be too large of a unit and was effectively replaced by
  24119. the decibel.) If @math{F} is a field quantity with power
  24120. @math{P=k F^2}, then a reference quantity of
  24121. @infoline @math{F0}
  24122. @texline @math{F_0}
  24123. would correspond to a power of
  24124. @infoline @math{P0=k F0^2}.
  24125. @texline @math{P_{0}=kF_{0}^2}.
  24126. If
  24127. @infoline @math{P1=k F1^2},
  24128. @texline @math{P_{1}=kF_{1}^2},
  24129. then
  24130. @ifnottex
  24131. @example
  24132. 10 log10(P1/P0) = 10 log10(F1^2/F0^2) = 20 log10(F1/F0).
  24133. @end example
  24134. @end ifnottex
  24135. @tex
  24136. $$ 10 \log_{10}(P_1/P_0) = 10 \log_{10}(F_1^2/F_0^2) = 20
  24137. \log_{10}(F_1/F_0)$$
  24138. @end tex
  24139. @noindent
  24140. In order to get the same decibel level regardless of whether a field
  24141. quantity or the corresponding power quantity is used, the decibel
  24142. level of a field quantity
  24143. @infoline @math{F1},
  24144. @texline @math{F_1},
  24145. relative to a reference
  24146. @infoline @math{F0},
  24147. @texline @math{F_0},
  24148. is defined as
  24149. @infoline @math{20 log10(F1/F0) dB}.
  24150. @texline @math{20 \log_{10}(F_{1}/F_{0}) {\rm dB}}.
  24151. For example, the decibel value of a sound pressure level of
  24152. @infoline @math{60 uPa}
  24153. @texline @math{60 \mu{\rm Pa}}
  24154. relative to
  24155. @infoline @math{20 uPa}
  24156. @texline @math{20 \mu{\rm Pa}}
  24157. (the threshold of human hearing) is
  24158. @infoline @math{20 log10(60 uPa/ 20 uPa) dB = 20 log10(3) dB},
  24159. @texline @math{20 \log_{10}(60 \mu{\rm Pa}/20 \mu{\rm Pa}) {\rm dB} = 20 \log_{10}(3) {\rm dB}},
  24160. which is about
  24161. @infoline @math{9.54 dB}.
  24162. @texline @math{9.54 {\rm dB}}.
  24163. Note that in taking the ratio, the original units cancel and so these
  24164. logarithmic units are dimensionless.
  24165. Nepers (named after John Napier, who is credited with inventing the
  24166. logarithm) are similar to bels except they use natural logarithms instead
  24167. of common logarithms. The neper level of a power
  24168. @infoline @math{P1},
  24169. @texline @math{P_1},
  24170. relative to a reference power
  24171. @infoline @math{P0},
  24172. @texline @math{P_0},
  24173. is
  24174. @infoline @math{(1/2) ln(P1/P0) Np}.
  24175. @texline @math{(1/2) \ln(P_1/P_0) {\rm Np}}.
  24176. The neper level of a field
  24177. @infoline @math{F1},
  24178. @texline @math{F_1},
  24179. relative to a reference field
  24180. @infoline @math{F0},
  24181. @texline @math{F_0},
  24182. is
  24183. @infoline @math{ln(F1/F0) Np}.
  24184. @texline @math{\ln(F_1/F_0) {\rm Np}}.
  24185. @vindex calc-lu-power-reference
  24186. @vindex calc-lu-field-reference
  24187. For power quantities, Calc uses
  24188. @infoline @math{1 mW}
  24189. @texline @math{1 {\rm mW}}
  24190. as the default reference quantity; this default can be changed by changing
  24191. the value of the customizable variable
  24192. @code{calc-lu-power-reference} (@pxref{Customizing Calc}).
  24193. For field quantities, Calc uses
  24194. @infoline @math{20 uPa}
  24195. @texline @math{20 \mu{\rm Pa}}
  24196. as the default reference quantity; this is the value used in acoustics
  24197. which is where decibels are commonly encountered. This default can be
  24198. changed by changing the value of the customizable variable
  24199. @code{calc-lu-field-reference} (@pxref{Customizing Calc}). A
  24200. non-default reference quantity will be read from the stack if the
  24201. capital @kbd{O} prefix is used.
  24202. @kindex l q
  24203. @pindex calc-lu-quant
  24204. @tindex lupquant
  24205. @tindex lufquant
  24206. The @kbd{l q} (@code{calc-lu-quant}) [@code{lupquant}]
  24207. command computes the power quantity corresponding to a given number of
  24208. logarithmic units. With the capital @kbd{O} prefix, @kbd{O l q}, the
  24209. reference level will be read from the top of the stack. (In an
  24210. algebraic formula, @code{lupquant} can be given an optional second
  24211. argument which will be used for the reference level.) For example,
  24212. @code{20 dB @key{RET} l q} will return @code{100 mW};
  24213. @code{20 dB @key{RET} 4 W @key{RET} O l q} will return @code{400 W}.
  24214. The @kbd{H l q} [@code{lufquant}] command behaves like @kbd{l q} but
  24215. computes field quantities instead of power quantities.
  24216. @kindex l d
  24217. @pindex calc-db
  24218. @tindex dbpower
  24219. @tindex dbfield
  24220. @kindex l n
  24221. @pindex calc-np
  24222. @tindex nppower
  24223. @tindex npfield
  24224. The @kbd{l d} (@code{calc-db}) [@code{dbpower}] command will compute
  24225. the decibel level of a power quantity using the default reference
  24226. level; @kbd{H l d} [@code{dbfield}] will compute the decibel level of
  24227. a field quantity. The commands @kbd{l n} (@code{calc-np})
  24228. [@code{nppower}] and @kbd{H l n} [@code{npfield}] will similarly
  24229. compute neper levels. With the capital @kbd{O} prefix these commands
  24230. will read a reference level from the stack; in an algebraic formula
  24231. the reference level can be given as an optional second argument.
  24232. @kindex l +
  24233. @pindex calc-lu-plus
  24234. @tindex lupadd
  24235. @tindex lufadd
  24236. @kindex l -
  24237. @pindex calc-lu-minus
  24238. @tindex lupsub
  24239. @tindex lufsub
  24240. @kindex l *
  24241. @pindex calc-lu-times
  24242. @tindex lupmul
  24243. @tindex lufmul
  24244. @kindex l /
  24245. @pindex calc-lu-divide
  24246. @tindex lupdiv
  24247. @tindex lufdiv
  24248. The sum of two power or field quantities doesn't correspond to the sum
  24249. of the corresponding decibel or neper levels. If the powers
  24250. corresponding to decibel levels
  24251. @infoline @math{D1}
  24252. @texline @math{D_1}
  24253. and
  24254. @infoline @math{D2}
  24255. @texline @math{D_2}
  24256. are added, the corresponding decibel level ``sum'' will be
  24257. @ifnottex
  24258. @example
  24259. 10 log10(10^(D1/10) + 10^(D2/10)) dB.
  24260. @end example
  24261. @end ifnottex
  24262. @tex
  24263. $$ 10 \log_{10}(10^{D_1/10} + 10^{D_2/10}) {\rm dB}.$$
  24264. @end tex
  24265. @noindent
  24266. When field quantities are combined, it often means the corresponding
  24267. powers are added and so the above formula might be used. In
  24268. acoustics, for example, the sound pressure level is a field quantity
  24269. and so the decibels are often defined using the field formula, but the
  24270. sound pressure levels are combined as the sound power levels, and so
  24271. the above formula should be used. If two field quantities themselves
  24272. are added, the new decibel level will be
  24273. @ifnottex
  24274. @example
  24275. 20 log10(10^(D1/20) + 10^(D2/20)) dB.
  24276. @end example
  24277. @end ifnottex
  24278. @tex
  24279. $$ 20 \log_{10}(10^{D_1/20} + 10^{D_2/20}) {\rm dB}.$$
  24280. @end tex
  24281. @noindent
  24282. If the power corresponding to @math{D} dB is multiplied by a number @math{N},
  24283. then the corresponding decibel level will be
  24284. @ifnottex
  24285. @example
  24286. D + 10 log10(N) dB,
  24287. @end example
  24288. @end ifnottex
  24289. @tex
  24290. $$ D + 10 \log_{10}(N) {\rm dB},$$
  24291. @end tex
  24292. @noindent
  24293. if a field quantity is multiplied by @math{N} the corresponding decibel level
  24294. will be
  24295. @ifnottex
  24296. @example
  24297. D + 20 log10(N) dB.
  24298. @end example
  24299. @end ifnottex
  24300. @tex
  24301. $$ D + 20 \log_{10}(N) {\rm dB}.$$
  24302. @end tex
  24303. @noindent
  24304. There are similar formulas for combining nepers. The @kbd{l +}
  24305. (@code{calc-lu-plus}) [@code{lupadd}] command will ``add'' two
  24306. logarithmic unit power levels this way; with the @kbd{H} prefix,
  24307. @kbd{H l +} [@code{lufadd}] will add logarithmic unit field levels.
  24308. Similarly, logarithmic units can be ``subtracted'' with @kbd{l -}
  24309. (@code{calc-lu-minus}) [@code{lupsub}] or @kbd{H l -} [@code{lufsub}].
  24310. The @kbd{l *} (@code{calc-lu-times}) [@code{lupmul}] and @kbd{H l *}
  24311. [@code{lufmul}] commands will ``multiply'' a logarithmic unit by a
  24312. number; the @kbd{l /} (@code{calc-lu-divide}) [@code{lupdiv}] and
  24313. @kbd{H l /} [@code{lufdiv}] commands will ``divide'' a logarithmic
  24314. unit by a number. Note that the reference quantities don't play a role
  24315. in this arithmetic.
  24316. @node Musical Notes, , Logarithmic Units, Units
  24317. @section Musical Notes
  24318. Calc can convert between musical notes and their associated
  24319. frequencies. Notes can be given using either scientific pitch
  24320. notation or midi numbers. Since these note systems are basically
  24321. logarithmic scales, Calc uses the @kbd{l} prefix for functions
  24322. operating on notes.
  24323. Scientific pitch notation refers to a note by giving a letter
  24324. A through G, possibly followed by a flat or sharp) with a subscript
  24325. indicating an octave number. Each octave starts with C and ends with
  24326. B and
  24327. @c increasing each note by a semitone will result
  24328. @c in the sequence @expr{C}, @expr{C} sharp, @expr{D}, @expr{E} flat, @expr{E},
  24329. @c @expr{F}, @expr{F} sharp, @expr{G}, @expr{A} flat, @expr{A}, @expr{B}
  24330. @c flat and @expr{B}.
  24331. the octave numbered 0 was chosen to correspond to the lowest
  24332. audible frequency. Using this system, middle C (about 261.625 Hz)
  24333. corresponds to the note @expr{C} in octave 4 and is denoted
  24334. @expr{C_4}. Any frequency can be described by giving a note plus an
  24335. offset in cents (where a cent is a ratio of frequencies so that a
  24336. semitone consists of 100 cents).
  24337. The midi note number system assigns numbers to notes so that
  24338. @expr{C_(-1)} corresponds to the midi note number 0 and @expr{G_9}
  24339. corresponds to the midi note number 127. A midi controller can have
  24340. up to 128 keys and each midi note number from 0 to 127 corresponds to
  24341. a possible key.
  24342. @kindex l s
  24343. @pindex calc-spn
  24344. @tindex spn
  24345. The @kbd{l s} (@code{calc-spn}) [@code{spn}] command converts either
  24346. a frequency or a midi number to scientific pitch notation. For
  24347. example, @code{500 Hz} gets converted to
  24348. @code{B_4 + 21.3094853649 cents} and @code{84} to @code{C_6}.
  24349. @kindex l m
  24350. @pindex calc-midi
  24351. @tindex midi
  24352. The @kbd{l m} (@code{calc-midi}) [@code{midi}] command converts either
  24353. a frequency or a note given in scientific pitch notation to the
  24354. corresponding midi number. For example, @code{C_6} gets converted to 84
  24355. and @code{440 Hz} to 69.
  24356. @kindex l f
  24357. @pindex calc-freq
  24358. @tindex freq
  24359. The @kbd{l f} (@code{calc-freq}) [@code{freq}] command converts either
  24360. either a midi number or a note given in scientific pitch notation to
  24361. the corresponding frequency. For example, @code{Asharp_2 + 30 cents}
  24362. gets converted to @code{118.578040134 Hz} and @code{55} to
  24363. @code{195.99771799 Hz}.
  24364. Since the frequencies of notes are not usually given exactly (and are
  24365. typically irrational), the customizable variable
  24366. @code{calc-note-threshold} determines how close (in cents) a frequency
  24367. needs to be to a note to be recognized as that note
  24368. (@pxref{Customizing Calc}). This variable has a default value of
  24369. @code{1}. For example, middle @var{C} is approximately
  24370. @expr{261.625565302 Hz}; this frequency is often shortened to
  24371. @expr{261.625 Hz}. Without @code{calc-note-threshold} (or a value of
  24372. @expr{0}), Calc would convert @code{261.625 Hz} to scientific pitch
  24373. notation @code{B_3 + 99.9962592773 cents}; with the default value of
  24374. @code{1}, Calc converts @code{261.625 Hz} to @code{C_4}.
  24375. @node Store and Recall, Graphics, Units, Top
  24376. @chapter Storing and Recalling
  24377. @noindent
  24378. Calculator variables are really just Lisp variables that contain numbers
  24379. or formulas in a form that Calc can understand. The commands in this
  24380. section allow you to manipulate variables conveniently. Commands related
  24381. to variables use the @kbd{s} prefix key.
  24382. @menu
  24383. * Storing Variables::
  24384. * Recalling Variables::
  24385. * Operations on Variables::
  24386. * Let Command::
  24387. * Evaluates-To Operator::
  24388. @end menu
  24389. @node Storing Variables, Recalling Variables, Store and Recall, Store and Recall
  24390. @section Storing Variables
  24391. @noindent
  24392. @kindex s s
  24393. @pindex calc-store
  24394. @cindex Storing variables
  24395. @cindex Quick variables
  24396. @vindex q0
  24397. @vindex q9
  24398. The @kbd{s s} (@code{calc-store}) command stores the value at the top of
  24399. the stack into a specified variable. It prompts you to enter the
  24400. name of the variable. If you press a single digit, the value is stored
  24401. immediately in one of the ``quick'' variables @code{q0} through
  24402. @code{q9}. Or you can enter any variable name.
  24403. @kindex s t
  24404. @pindex calc-store-into
  24405. The @kbd{s s} command leaves the stored value on the stack. There is
  24406. also an @kbd{s t} (@code{calc-store-into}) command, which removes a
  24407. value from the stack and stores it in a variable.
  24408. If the top of stack value is an equation @samp{a = 7} or assignment
  24409. @samp{a := 7} with a variable on the lefthand side, then Calc will
  24410. assign that variable with that value by default, i.e., if you type
  24411. @kbd{s s @key{RET}} or @kbd{s t @key{RET}}. In this example, the
  24412. value 7 would be stored in the variable @samp{a}. (If you do type
  24413. a variable name at the prompt, the top-of-stack value is stored in
  24414. its entirety, even if it is an equation: @samp{s s b @key{RET}}
  24415. with @samp{a := 7} on the stack stores @samp{a := 7} in @code{b}.)
  24416. In fact, the top of stack value can be a vector of equations or
  24417. assignments with different variables on their lefthand sides; the
  24418. default will be to store all the variables with their corresponding
  24419. righthand sides simultaneously.
  24420. It is also possible to type an equation or assignment directly at
  24421. the prompt for the @kbd{s s} or @kbd{s t} command: @kbd{s s foo = 7}.
  24422. In this case the expression to the right of the @kbd{=} or @kbd{:=}
  24423. symbol is evaluated as if by the @kbd{=} command, and that value is
  24424. stored in the variable. No value is taken from the stack; @kbd{s s}
  24425. and @kbd{s t} are equivalent when used in this way.
  24426. @kindex s 0-9
  24427. @kindex t 0-9
  24428. The prefix keys @kbd{s} and @kbd{t} may be followed immediately by a
  24429. digit; @kbd{s 9} is equivalent to @kbd{s s 9}, and @kbd{t 9} is
  24430. equivalent to @kbd{s t 9}. (The @kbd{t} prefix is otherwise used
  24431. for trail and time/date commands.)
  24432. @kindex s +
  24433. @kindex s -
  24434. @ignore
  24435. @mindex @idots
  24436. @end ignore
  24437. @kindex s *
  24438. @ignore
  24439. @mindex @null
  24440. @end ignore
  24441. @kindex s /
  24442. @ignore
  24443. @mindex @null
  24444. @end ignore
  24445. @kindex s ^
  24446. @ignore
  24447. @mindex @null
  24448. @end ignore
  24449. @kindex s |
  24450. @ignore
  24451. @mindex @null
  24452. @end ignore
  24453. @kindex s n
  24454. @ignore
  24455. @mindex @null
  24456. @end ignore
  24457. @kindex s &
  24458. @ignore
  24459. @mindex @null
  24460. @end ignore
  24461. @kindex s [
  24462. @ignore
  24463. @mindex @null
  24464. @end ignore
  24465. @kindex s ]
  24466. @pindex calc-store-plus
  24467. @pindex calc-store-minus
  24468. @pindex calc-store-times
  24469. @pindex calc-store-div
  24470. @pindex calc-store-power
  24471. @pindex calc-store-concat
  24472. @pindex calc-store-neg
  24473. @pindex calc-store-inv
  24474. @pindex calc-store-decr
  24475. @pindex calc-store-incr
  24476. There are also several ``arithmetic store'' commands. For example,
  24477. @kbd{s +} removes a value from the stack and adds it to the specified
  24478. variable. The other arithmetic stores are @kbd{s -}, @kbd{s *}, @kbd{s /},
  24479. @kbd{s ^}, and @w{@kbd{s |}} (vector concatenation), plus @kbd{s n} and
  24480. @kbd{s &} which negate or invert the value in a variable, and @w{@kbd{s [}}
  24481. and @kbd{s ]} which decrease or increase a variable by one.
  24482. All the arithmetic stores accept the Inverse prefix to reverse the
  24483. order of the operands. If @expr{v} represents the contents of the
  24484. variable, and @expr{a} is the value drawn from the stack, then regular
  24485. @w{@kbd{s -}} assigns
  24486. @texline @math{v \coloneq v - a},
  24487. @infoline @expr{v := v - a},
  24488. but @kbd{I s -} assigns
  24489. @texline @math{v \coloneq a - v}.
  24490. @infoline @expr{v := a - v}.
  24491. While @kbd{I s *} might seem pointless, it is
  24492. useful if matrix multiplication is involved. Actually, all the
  24493. arithmetic stores use formulas designed to behave usefully both
  24494. forwards and backwards:
  24495. @example
  24496. @group
  24497. s + v := v + a v := a + v
  24498. s - v := v - a v := a - v
  24499. s * v := v * a v := a * v
  24500. s / v := v / a v := a / v
  24501. s ^ v := v ^ a v := a ^ v
  24502. s | v := v | a v := a | v
  24503. s n v := v / (-1) v := (-1) / v
  24504. s & v := v ^ (-1) v := (-1) ^ v
  24505. s [ v := v - 1 v := 1 - v
  24506. s ] v := v - (-1) v := (-1) - v
  24507. @end group
  24508. @end example
  24509. In the last four cases, a numeric prefix argument will be used in
  24510. place of the number one. (For example, @kbd{M-2 s ]} increases
  24511. a variable by 2, and @kbd{M-2 I s ]} replaces a variable by
  24512. minus-two minus the variable.
  24513. The first six arithmetic stores can also be typed @kbd{s t +}, @kbd{s t -},
  24514. etc. The commands @kbd{s s +}, @kbd{s s -}, and so on are analogous
  24515. arithmetic stores that don't remove the value @expr{a} from the stack.
  24516. All arithmetic stores report the new value of the variable in the
  24517. Trail for your information. They signal an error if the variable
  24518. previously had no stored value. If default simplifications have been
  24519. turned off, the arithmetic stores temporarily turn them on for numeric
  24520. arguments only (i.e., they temporarily do an @kbd{m N} command).
  24521. @xref{Simplification Modes}. Large vectors put in the trail by
  24522. these commands always use abbreviated (@kbd{t .}) mode.
  24523. @kindex s m
  24524. @pindex calc-store-map
  24525. The @kbd{s m} command is a general way to adjust a variable's value
  24526. using any Calc function. It is a ``mapping'' command analogous to
  24527. @kbd{V M}, @kbd{V R}, etc. @xref{Reducing and Mapping}, to see
  24528. how to specify a function for a mapping command. Basically,
  24529. all you do is type the Calc command key that would invoke that
  24530. function normally. For example, @kbd{s m n} applies the @kbd{n}
  24531. key to negate the contents of the variable, so @kbd{s m n} is
  24532. equivalent to @kbd{s n}. Also, @kbd{s m Q} takes the square root
  24533. of the value stored in a variable, @kbd{s m v v} uses @kbd{v v} to
  24534. reverse the vector stored in the variable, and @kbd{s m H I S}
  24535. takes the hyperbolic arcsine of the variable contents.
  24536. If the mapping function takes two or more arguments, the additional
  24537. arguments are taken from the stack; the old value of the variable
  24538. is provided as the first argument. Thus @kbd{s m -} with @expr{a}
  24539. on the stack computes @expr{v - a}, just like @kbd{s -}. With the
  24540. Inverse prefix, the variable's original value becomes the @emph{last}
  24541. argument instead of the first. Thus @kbd{I s m -} is also
  24542. equivalent to @kbd{I s -}.
  24543. @kindex s x
  24544. @pindex calc-store-exchange
  24545. The @kbd{s x} (@code{calc-store-exchange}) command exchanges the value
  24546. of a variable with the value on the top of the stack. Naturally, the
  24547. variable must already have a stored value for this to work.
  24548. You can type an equation or assignment at the @kbd{s x} prompt. The
  24549. command @kbd{s x a=6} takes no values from the stack; instead, it
  24550. pushes the old value of @samp{a} on the stack and stores @samp{a = 6}.
  24551. @kindex s u
  24552. @pindex calc-unstore
  24553. @cindex Void variables
  24554. @cindex Un-storing variables
  24555. Until you store something in them, most variables are ``void,'' that is,
  24556. they contain no value at all. If they appear in an algebraic formula
  24557. they will be left alone even if you press @kbd{=} (@code{calc-evaluate}).
  24558. The @kbd{s u} (@code{calc-unstore}) command returns a variable to the
  24559. void state.
  24560. @kindex s c
  24561. @pindex calc-copy-variable
  24562. The @kbd{s c} (@code{calc-copy-variable}) command copies the stored
  24563. value of one variable to another. One way it differs from a simple
  24564. @kbd{s r} followed by an @kbd{s t} (aside from saving keystrokes) is
  24565. that the value never goes on the stack and thus is never rounded,
  24566. evaluated, or simplified in any way; it is not even rounded down to the
  24567. current precision.
  24568. The only variables with predefined values are the ``special constants''
  24569. @code{pi}, @code{e}, @code{i}, @code{phi}, and @code{gamma}. You are free
  24570. to unstore these variables or to store new values into them if you like,
  24571. although some of the algebraic-manipulation functions may assume these
  24572. variables represent their standard values. Calc displays a warning if
  24573. you change the value of one of these variables, or of one of the other
  24574. special variables @code{inf}, @code{uinf}, and @code{nan} (which are
  24575. normally void).
  24576. Note that @code{pi} doesn't actually have 3.14159265359 stored in it,
  24577. but rather a special magic value that evaluates to @cpi{} at the current
  24578. precision. Likewise @code{e}, @code{i}, and @code{phi} evaluate
  24579. according to the current precision or polar mode. If you recall a value
  24580. from @code{pi} and store it back, this magic property will be lost. The
  24581. magic property is preserved, however, when a variable is copied with
  24582. @kbd{s c}.
  24583. @kindex s k
  24584. @pindex calc-copy-special-constant
  24585. If one of the ``special constants'' is redefined (or undefined) so that
  24586. it no longer has its magic property, the property can be restored with
  24587. @kbd{s k} (@code{calc-copy-special-constant}). This command will prompt
  24588. for a special constant and a variable to store it in, and so a special
  24589. constant can be stored in any variable. Here, the special constant that
  24590. you enter doesn't depend on the value of the corresponding variable;
  24591. @code{pi} will represent 3.14159@dots{} regardless of what is currently
  24592. stored in the Calc variable @code{pi}. If one of the other special
  24593. variables, @code{inf}, @code{uinf} or @code{nan}, is given a value, its
  24594. original behavior can be restored by voiding it with @kbd{s u}.
  24595. @node Recalling Variables, Operations on Variables, Storing Variables, Store and Recall
  24596. @section Recalling Variables
  24597. @noindent
  24598. @kindex s r
  24599. @pindex calc-recall
  24600. @cindex Recalling variables
  24601. The most straightforward way to extract the stored value from a variable
  24602. is to use the @kbd{s r} (@code{calc-recall}) command. This command prompts
  24603. for a variable name (similarly to @code{calc-store}), looks up the value
  24604. of the specified variable, and pushes that value onto the stack. It is
  24605. an error to try to recall a void variable.
  24606. It is also possible to recall the value from a variable by evaluating a
  24607. formula containing that variable. For example, @kbd{' a @key{RET} =} is
  24608. the same as @kbd{s r a @key{RET}} except that if the variable is void, the
  24609. former will simply leave the formula @samp{a} on the stack whereas the
  24610. latter will produce an error message.
  24611. @kindex r 0-9
  24612. The @kbd{r} prefix may be followed by a digit, so that @kbd{r 9} is
  24613. equivalent to @kbd{s r 9}.
  24614. @node Operations on Variables, Let Command, Recalling Variables, Store and Recall
  24615. @section Other Operations on Variables
  24616. @noindent
  24617. @kindex s e
  24618. @pindex calc-edit-variable
  24619. The @kbd{s e} (@code{calc-edit-variable}) command edits the stored
  24620. value of a variable without ever putting that value on the stack
  24621. or simplifying or evaluating the value. It prompts for the name of
  24622. the variable to edit. If the variable has no stored value, the
  24623. editing buffer will start out empty. If the editing buffer is
  24624. empty when you press @kbd{C-c C-c} to finish, the variable will
  24625. be made void. @xref{Editing Stack Entries}, for a general
  24626. description of editing.
  24627. The @kbd{s e} command is especially useful for creating and editing
  24628. rewrite rules which are stored in variables. Sometimes these rules
  24629. contain formulas which must not be evaluated until the rules are
  24630. actually used. (For example, they may refer to @samp{deriv(x,y)},
  24631. where @code{x} will someday become some expression involving @code{y};
  24632. if you let Calc evaluate the rule while you are defining it, Calc will
  24633. replace @samp{deriv(x,y)} with 0 because the formula @code{x} does
  24634. not itself refer to @code{y}.) By contrast, recalling the variable,
  24635. editing with @kbd{`}, and storing will evaluate the variable's value
  24636. as a side effect of putting the value on the stack.
  24637. @kindex s A
  24638. @kindex s D
  24639. @ignore
  24640. @mindex @idots
  24641. @end ignore
  24642. @kindex s E
  24643. @ignore
  24644. @mindex @null
  24645. @end ignore
  24646. @kindex s F
  24647. @ignore
  24648. @mindex @null
  24649. @end ignore
  24650. @kindex s G
  24651. @ignore
  24652. @mindex @null
  24653. @end ignore
  24654. @kindex s H
  24655. @ignore
  24656. @mindex @null
  24657. @end ignore
  24658. @kindex s I
  24659. @ignore
  24660. @mindex @null
  24661. @end ignore
  24662. @kindex s L
  24663. @ignore
  24664. @mindex @null
  24665. @end ignore
  24666. @kindex s P
  24667. @ignore
  24668. @mindex @null
  24669. @end ignore
  24670. @kindex s R
  24671. @ignore
  24672. @mindex @null
  24673. @end ignore
  24674. @kindex s T
  24675. @ignore
  24676. @mindex @null
  24677. @end ignore
  24678. @kindex s U
  24679. @ignore
  24680. @mindex @null
  24681. @end ignore
  24682. @kindex s X
  24683. @pindex calc-store-AlgSimpRules
  24684. @pindex calc-store-Decls
  24685. @pindex calc-store-EvalRules
  24686. @pindex calc-store-FitRules
  24687. @pindex calc-store-GenCount
  24688. @pindex calc-store-Holidays
  24689. @pindex calc-store-IntegLimit
  24690. @pindex calc-store-LineStyles
  24691. @pindex calc-store-PointStyles
  24692. @pindex calc-store-PlotRejects
  24693. @pindex calc-store-TimeZone
  24694. @pindex calc-store-Units
  24695. @pindex calc-store-ExtSimpRules
  24696. There are several special-purpose variable-editing commands that
  24697. use the @kbd{s} prefix followed by a shifted letter:
  24698. @table @kbd
  24699. @item s A
  24700. Edit @code{AlgSimpRules}. @xref{Algebraic Simplifications}.
  24701. @item s D
  24702. Edit @code{Decls}. @xref{Declarations}.
  24703. @item s E
  24704. Edit @code{EvalRules}. @xref{Basic Simplifications}.
  24705. @item s F
  24706. Edit @code{FitRules}. @xref{Curve Fitting}.
  24707. @item s G
  24708. Edit @code{GenCount}. @xref{Solving Equations}.
  24709. @item s H
  24710. Edit @code{Holidays}. @xref{Business Days}.
  24711. @item s I
  24712. Edit @code{IntegLimit}. @xref{Calculus}.
  24713. @item s L
  24714. Edit @code{LineStyles}. @xref{Graphics}.
  24715. @item s P
  24716. Edit @code{PointStyles}. @xref{Graphics}.
  24717. @item s R
  24718. Edit @code{PlotRejects}. @xref{Graphics}.
  24719. @item s T
  24720. Edit @code{TimeZone}. @xref{Time Zones}.
  24721. @item s U
  24722. Edit @code{Units}. @xref{User-Defined Units}.
  24723. @item s X
  24724. Edit @code{ExtSimpRules}. @xref{Unsafe Simplifications}.
  24725. @end table
  24726. These commands are just versions of @kbd{s e} that use fixed variable
  24727. names rather than prompting for the variable name.
  24728. @kindex s p
  24729. @pindex calc-permanent-variable
  24730. @cindex Storing variables
  24731. @cindex Permanent variables
  24732. @cindex Calc init file, variables
  24733. The @kbd{s p} (@code{calc-permanent-variable}) command saves a
  24734. variable's value permanently in your Calc init file (the file given by
  24735. the variable @code{calc-settings-file}, typically @file{~/.emacs.d/calc.el}), so
  24736. that its value will still be available in future Emacs sessions. You
  24737. can re-execute @w{@kbd{s p}} later on to update the saved value, but the
  24738. only way to remove a saved variable is to edit your calc init file
  24739. by hand. (@xref{General Mode Commands}, for a way to tell Calc to
  24740. use a different file for the Calc init file.)
  24741. If you do not specify the name of a variable to save (i.e.,
  24742. @kbd{s p @key{RET}}), all Calc variables with defined values
  24743. are saved except for the special constants @code{pi}, @code{e},
  24744. @code{i}, @code{phi}, and @code{gamma}; the variables @code{TimeZone}
  24745. and @code{PlotRejects};
  24746. @code{FitRules}, @code{DistribRules}, and other built-in rewrite
  24747. rules; and @code{PlotData@var{n}} variables generated
  24748. by the graphics commands. (You can still save these variables by
  24749. explicitly naming them in an @kbd{s p} command.)
  24750. @kindex s i
  24751. @pindex calc-insert-variables
  24752. The @kbd{s i} (@code{calc-insert-variables}) command writes
  24753. the values of all Calc variables into a specified buffer.
  24754. The variables are written with the prefix @code{var-} in the form of
  24755. Lisp @code{setq} commands
  24756. which store the values in string form. You can place these commands
  24757. in your Calc init file (or @file{.emacs}) if you wish, though in this case it
  24758. would be easier to use @kbd{s p @key{RET}}. (Note that @kbd{s i}
  24759. omits the same set of variables as @w{@kbd{s p @key{RET}}}; the difference
  24760. is that @kbd{s i} will store the variables in any buffer, and it also
  24761. stores in a more human-readable format.)
  24762. @node Let Command, Evaluates-To Operator, Operations on Variables, Store and Recall
  24763. @section The Let Command
  24764. @noindent
  24765. @kindex s l
  24766. @pindex calc-let
  24767. @cindex Variables, temporary assignment
  24768. @cindex Temporary assignment to variables
  24769. If you have an expression like @samp{a+b^2} on the stack and you wish to
  24770. compute its value where @expr{b=3}, you can simply store 3 in @expr{b} and
  24771. then press @kbd{=} to reevaluate the formula. This has the side-effect
  24772. of leaving the stored value of 3 in @expr{b} for future operations.
  24773. The @kbd{s l} (@code{calc-let}) command evaluates a formula under a
  24774. @emph{temporary} assignment of a variable. It stores the value on the
  24775. top of the stack into the specified variable, then evaluates the
  24776. second-to-top stack entry, then restores the original value (or lack of one)
  24777. in the variable. Thus after @kbd{'@w{ }a+b^2 @key{RET} 3 s l b @key{RET}},
  24778. the stack will contain the formula @samp{a + 9}. The subsequent command
  24779. @kbd{@w{5 s l a} @key{RET}} will replace this formula with the number 14.
  24780. The variables @samp{a} and @samp{b} are not permanently affected in any way
  24781. by these commands.
  24782. The value on the top of the stack may be an equation or assignment, or
  24783. a vector of equations or assignments, in which case the default will be
  24784. analogous to the case of @kbd{s t @key{RET}}. @xref{Storing Variables}.
  24785. Also, you can answer the variable-name prompt with an equation or
  24786. assignment: @kbd{s l b=3 @key{RET}} is the same as storing 3 on the stack
  24787. and typing @kbd{s l b @key{RET}}.
  24788. The @kbd{a b} (@code{calc-substitute}) command is another way to substitute
  24789. a variable with a value in a formula. It does an actual substitution
  24790. rather than temporarily assigning the variable and evaluating. For
  24791. example, letting @expr{n=2} in @samp{f(n pi)} with @kbd{a b} will
  24792. produce @samp{f(2 pi)}, whereas @kbd{s l} would give @samp{f(6.28)}
  24793. since the evaluation step will also evaluate @code{pi}.
  24794. @node Evaluates-To Operator, , Let Command, Store and Recall
  24795. @section The Evaluates-To Operator
  24796. @noindent
  24797. @tindex evalto
  24798. @tindex =>
  24799. @cindex Evaluates-to operator
  24800. @cindex @samp{=>} operator
  24801. The special algebraic symbol @samp{=>} is known as the @dfn{evaluates-to
  24802. operator}. (It will show up as an @code{evalto} function call in
  24803. other language modes like Pascal and @LaTeX{}.) This is a binary
  24804. operator, that is, it has a lefthand and a righthand argument,
  24805. although it can be entered with the righthand argument omitted.
  24806. A formula like @samp{@var{a} => @var{b}} is evaluated by Calc as
  24807. follows: First, @var{a} is not simplified or modified in any
  24808. way. The previous value of argument @var{b} is thrown away; the
  24809. formula @var{a} is then copied and evaluated as if by the @kbd{=}
  24810. command according to all current modes and stored variable values,
  24811. and the result is installed as the new value of @var{b}.
  24812. For example, suppose you enter the algebraic formula @samp{2 + 3 => 17}.
  24813. The number 17 is ignored, and the lefthand argument is left in its
  24814. unevaluated form; the result is the formula @samp{2 + 3 => 5}.
  24815. @kindex s =
  24816. @pindex calc-evalto
  24817. You can enter an @samp{=>} formula either directly using algebraic
  24818. entry (in which case the righthand side may be omitted since it is
  24819. going to be replaced right away anyhow), or by using the @kbd{s =}
  24820. (@code{calc-evalto}) command, which takes @var{a} from the stack
  24821. and replaces it with @samp{@var{a} => @var{b}}.
  24822. Calc keeps track of all @samp{=>} operators on the stack, and
  24823. recomputes them whenever anything changes that might affect their
  24824. values, i.e., a mode setting or variable value. This occurs only
  24825. if the @samp{=>} operator is at the top level of the formula, or
  24826. if it is part of a top-level vector. In other words, pushing
  24827. @samp{2 + (a => 17)} will change the 17 to the actual value of
  24828. @samp{a} when you enter the formula, but the result will not be
  24829. dynamically updated when @samp{a} is changed later because the
  24830. @samp{=>} operator is buried inside a sum. However, a vector
  24831. of @samp{=>} operators will be recomputed, since it is convenient
  24832. to push a vector like @samp{[a =>, b =>, c =>]} on the stack to
  24833. make a concise display of all the variables in your problem.
  24834. (Another way to do this would be to use @samp{[a, b, c] =>},
  24835. which provides a slightly different format of display. You
  24836. can use whichever you find easiest to read.)
  24837. @kindex m C
  24838. @pindex calc-auto-recompute
  24839. The @kbd{m C} (@code{calc-auto-recompute}) command allows you to
  24840. turn this automatic recomputation on or off. If you turn
  24841. recomputation off, you must explicitly recompute an @samp{=>}
  24842. operator on the stack in one of the usual ways, such as by
  24843. pressing @kbd{=}. Turning recomputation off temporarily can save
  24844. a lot of time if you will be changing several modes or variables
  24845. before you look at the @samp{=>} entries again.
  24846. Most commands are not especially useful with @samp{=>} operators
  24847. as arguments. For example, given @samp{x + 2 => 17}, it won't
  24848. work to type @kbd{1 +} to get @samp{x + 3 => 18}. If you want
  24849. to operate on the lefthand side of the @samp{=>} operator on
  24850. the top of the stack, type @kbd{j 1} (that's the digit ``one'')
  24851. to select the lefthand side, execute your commands, then type
  24852. @kbd{j u} to unselect.
  24853. All current modes apply when an @samp{=>} operator is computed,
  24854. including the current simplification mode. Recall that the
  24855. formula @samp{arcsin(sin(x))} will not be handled by Calc's algebraic
  24856. simplifications, but Calc's unsafe simplifications will reduce it to
  24857. @samp{x}. If you enter @samp{arcsin(sin(x)) =>} normally, the result
  24858. will be @samp{arcsin(sin(x)) => arcsin(sin(x))}. If you change to
  24859. Extended Simplification mode, the result will be
  24860. @samp{arcsin(sin(x)) => x}. However, just pressing @kbd{a e}
  24861. once will have no effect on @samp{arcsin(sin(x)) => arcsin(sin(x))},
  24862. because the righthand side depends only on the lefthand side
  24863. and the current mode settings, and the lefthand side is not
  24864. affected by commands like @kbd{a e}.
  24865. The ``let'' command (@kbd{s l}) has an interesting interaction
  24866. with the @samp{=>} operator. The @kbd{s l} command evaluates the
  24867. second-to-top stack entry with the top stack entry supplying
  24868. a temporary value for a given variable. As you might expect,
  24869. if that stack entry is an @samp{=>} operator its righthand
  24870. side will temporarily show this value for the variable. In
  24871. fact, all @samp{=>}s on the stack will be updated if they refer
  24872. to that variable. But this change is temporary in the sense
  24873. that the next command that causes Calc to look at those stack
  24874. entries will make them revert to the old variable value.
  24875. @smallexample
  24876. @group
  24877. 2: a => a 2: a => 17 2: a => a
  24878. 1: a + 1 => a + 1 1: a + 1 => 18 1: a + 1 => a + 1
  24879. . . .
  24880. 17 s l a @key{RET} p 8 @key{RET}
  24881. @end group
  24882. @end smallexample
  24883. Here the @kbd{p 8} command changes the current precision,
  24884. thus causing the @samp{=>} forms to be recomputed after the
  24885. influence of the ``let'' is gone. The @kbd{d @key{SPC}} command
  24886. (@code{calc-refresh}) is a handy way to force the @samp{=>}
  24887. operators on the stack to be recomputed without any other
  24888. side effects.
  24889. @kindex s :
  24890. @pindex calc-assign
  24891. @tindex assign
  24892. @tindex :=
  24893. Embedded mode also uses @samp{=>} operators. In Embedded mode,
  24894. the lefthand side of an @samp{=>} operator can refer to variables
  24895. assigned elsewhere in the file by @samp{:=} operators. The
  24896. assignment operator @samp{a := 17} does not actually do anything
  24897. by itself. But Embedded mode recognizes it and marks it as a sort
  24898. of file-local definition of the variable. You can enter @samp{:=}
  24899. operators in Algebraic mode, or by using the @kbd{s :}
  24900. (@code{calc-assign}) [@code{assign}] command which takes a variable
  24901. and value from the stack and replaces them with an assignment.
  24902. @xref{TeX and LaTeX Language Modes}, for the way @samp{=>} appears in
  24903. @TeX{} language output. The @dfn{eqn} mode gives similar
  24904. treatment to @samp{=>}.
  24905. @node Graphics, Kill and Yank, Store and Recall, Top
  24906. @chapter Graphics
  24907. @noindent
  24908. The commands for graphing data begin with the @kbd{g} prefix key. Calc
  24909. uses GNUPLOT 2.0 or later to do graphics. These commands will only work
  24910. if GNUPLOT is available on your system. (While GNUPLOT sounds like
  24911. a relative of GNU Emacs, it is actually completely unrelated.
  24912. However, it is free software. It can be obtained from
  24913. @samp{http://www.gnuplot.info}.)
  24914. @vindex calc-gnuplot-name
  24915. If you have GNUPLOT installed on your system but Calc is unable to
  24916. find it, you may need to set the @code{calc-gnuplot-name} variable in
  24917. your Calc init file or @file{.emacs}. You may also need to set some
  24918. Lisp variables to show Calc how to run GNUPLOT on your system; these
  24919. are described under @kbd{g D} and @kbd{g O} below. If you are using
  24920. the X window system or MS-Windows, Calc will configure GNUPLOT for you
  24921. automatically. If you have GNUPLOT 3.0 or later and you are using a
  24922. Unix or GNU system without X, Calc will configure GNUPLOT to display
  24923. graphs using simple character graphics that will work on any
  24924. Posix-compatible terminal.
  24925. @menu
  24926. * Basic Graphics::
  24927. * Three Dimensional Graphics::
  24928. * Managing Curves::
  24929. * Graphics Options::
  24930. * Devices::
  24931. @end menu
  24932. @node Basic Graphics, Three Dimensional Graphics, Graphics, Graphics
  24933. @section Basic Graphics
  24934. @noindent
  24935. @kindex g f
  24936. @pindex calc-graph-fast
  24937. The easiest graphics command is @kbd{g f} (@code{calc-graph-fast}).
  24938. This command takes two vectors of equal length from the stack.
  24939. The vector at the top of the stack represents the ``y'' values of
  24940. the various data points. The vector in the second-to-top position
  24941. represents the corresponding ``x'' values. This command runs
  24942. GNUPLOT (if it has not already been started by previous graphing
  24943. commands) and displays the set of data points. The points will
  24944. be connected by lines, and there will also be some kind of symbol
  24945. to indicate the points themselves.
  24946. The ``x'' entry may instead be an interval form, in which case suitable
  24947. ``x'' values are interpolated between the minimum and maximum values of
  24948. the interval (whether the interval is open or closed is ignored).
  24949. The ``x'' entry may also be a number, in which case Calc uses the
  24950. sequence of ``x'' values @expr{x}, @expr{x+1}, @expr{x+2}, etc.
  24951. (Generally the number 0 or 1 would be used for @expr{x} in this case.)
  24952. The ``y'' entry may be any formula instead of a vector. Calc effectively
  24953. uses @kbd{N} (@code{calc-eval-num}) to evaluate variables in the formula;
  24954. the result of this must be a formula in a single (unassigned) variable.
  24955. The formula is plotted with this variable taking on the various ``x''
  24956. values. Graphs of formulas by default use lines without symbols at the
  24957. computed data points. Note that if neither ``x'' nor ``y'' is a vector,
  24958. Calc guesses at a reasonable number of data points to use. See the
  24959. @kbd{g N} command below. (The ``x'' values must be either a vector
  24960. or an interval if ``y'' is a formula.)
  24961. @ignore
  24962. @starindex
  24963. @end ignore
  24964. @tindex xy
  24965. If ``y'' is (or evaluates to) a formula of the form
  24966. @samp{xy(@var{x}, @var{y})} then the result is a
  24967. parametric plot. The two arguments of the fictitious @code{xy} function
  24968. are used as the ``x'' and ``y'' coordinates of the curve, respectively.
  24969. In this case the ``x'' vector or interval you specified is not directly
  24970. visible in the graph. For example, if ``x'' is the interval @samp{[0..360]}
  24971. and ``y'' is the formula @samp{xy(sin(t), cos(t))}, the resulting graph
  24972. will be a circle.
  24973. Also, ``x'' and ``y'' may each be variable names, in which case Calc
  24974. looks for suitable vectors, intervals, or formulas stored in those
  24975. variables.
  24976. The ``x'' and ``y'' values for the data points (as pulled from the vectors,
  24977. calculated from the formulas, or interpolated from the intervals) should
  24978. be real numbers (integers, fractions, or floats). One exception to this
  24979. is that the ``y'' entry can consist of a vector of numbers combined with
  24980. error forms, in which case the points will be plotted with the
  24981. appropriate error bars. Other than this, if either the ``x''
  24982. value or the ``y'' value of a given data point is not a real number, that
  24983. data point will be omitted from the graph. The points on either side
  24984. of the invalid point will @emph{not} be connected by a line.
  24985. See the documentation for @kbd{g a} below for a description of the way
  24986. numeric prefix arguments affect @kbd{g f}.
  24987. @cindex @code{PlotRejects} variable
  24988. @vindex PlotRejects
  24989. If you store an empty vector in the variable @code{PlotRejects}
  24990. (i.e., @kbd{[ ] s t PlotRejects}), Calc will append information to
  24991. this vector for every data point which was rejected because its
  24992. ``x'' or ``y'' values were not real numbers. The result will be
  24993. a matrix where each row holds the curve number, data point number,
  24994. ``x'' value, and ``y'' value for a rejected data point.
  24995. @xref{Evaluates-To Operator}, for a handy way to keep tabs on the
  24996. current value of @code{PlotRejects}. @xref{Operations on Variables},
  24997. for the @kbd{s R} command which is another easy way to examine
  24998. @code{PlotRejects}.
  24999. @kindex g c
  25000. @pindex calc-graph-clear
  25001. To clear the graphics display, type @kbd{g c} (@code{calc-graph-clear}).
  25002. If the GNUPLOT output device is an X window, the window will go away.
  25003. Effects on other kinds of output devices will vary. You don't need
  25004. to use @kbd{g c} if you don't want to---if you give another @kbd{g f}
  25005. or @kbd{g p} command later on, it will reuse the existing graphics
  25006. window if there is one.
  25007. @node Three Dimensional Graphics, Managing Curves, Basic Graphics, Graphics
  25008. @section Three-Dimensional Graphics
  25009. @kindex g F
  25010. @pindex calc-graph-fast-3d
  25011. The @kbd{g F} (@code{calc-graph-fast-3d}) command makes a three-dimensional
  25012. graph. It works only if you have GNUPLOT 3.0 or later; with GNUPLOT 2.0,
  25013. you will see a GNUPLOT error message if you try this command.
  25014. The @kbd{g F} command takes three values from the stack, called ``x'',
  25015. ``y'', and ``z'', respectively. As was the case for 2D graphs, there
  25016. are several options for these values.
  25017. In the first case, ``x'' and ``y'' are each vectors (not necessarily of
  25018. the same length); either or both may instead be interval forms. The
  25019. ``z'' value must be a matrix with the same number of rows as elements
  25020. in ``x'', and the same number of columns as elements in ``y''. The
  25021. result is a surface plot where
  25022. @texline @math{z_{ij}}
  25023. @infoline @expr{z_ij}
  25024. is the height of the point
  25025. at coordinate @expr{(x_i, y_j)} on the surface. The 3D graph will
  25026. be displayed from a certain default viewpoint; you can change this
  25027. viewpoint by adding a @samp{set view} to the @file{*Gnuplot Commands*}
  25028. buffer as described later. See the GNUPLOT documentation for a
  25029. description of the @samp{set view} command.
  25030. Each point in the matrix will be displayed as a dot in the graph,
  25031. and these points will be connected by a grid of lines (@dfn{isolines}).
  25032. In the second case, ``x'', ``y'', and ``z'' are all vectors of equal
  25033. length. The resulting graph displays a 3D line instead of a surface,
  25034. where the coordinates of points along the line are successive triplets
  25035. of values from the input vectors.
  25036. In the third case, ``x'' and ``y'' are vectors or interval forms, and
  25037. ``z'' is any formula involving two variables (not counting variables
  25038. with assigned values). These variables are sorted into alphabetical
  25039. order; the first takes on values from ``x'' and the second takes on
  25040. values from ``y'' to form a matrix of results that are graphed as a
  25041. 3D surface.
  25042. @ignore
  25043. @starindex
  25044. @end ignore
  25045. @tindex xyz
  25046. If the ``z'' formula evaluates to a call to the fictitious function
  25047. @samp{xyz(@var{x}, @var{y}, @var{z})}, then the result is a
  25048. ``parametric surface.'' In this case, the axes of the graph are
  25049. taken from the @var{x} and @var{y} values in these calls, and the
  25050. ``x'' and ``y'' values from the input vectors or intervals are used only
  25051. to specify the range of inputs to the formula. For example, plotting
  25052. @samp{[0..360], [0..180], xyz(sin(x)*sin(y), cos(x)*sin(y), cos(y))}
  25053. will draw a sphere. (Since the default resolution for 3D plots is
  25054. 5 steps in each of ``x'' and ``y'', this will draw a very crude
  25055. sphere. You could use the @kbd{g N} command, described below, to
  25056. increase this resolution, or specify the ``x'' and ``y'' values as
  25057. vectors with more than 5 elements.
  25058. It is also possible to have a function in a regular @kbd{g f} plot
  25059. evaluate to an @code{xyz} call. Since @kbd{g f} plots a line, not
  25060. a surface, the result will be a 3D parametric line. For example,
  25061. @samp{[[0..720], xyz(sin(x), cos(x), x)]} will plot two turns of a
  25062. helix (a three-dimensional spiral).
  25063. As for @kbd{g f}, each of ``x'', ``y'', and ``z'' may instead be
  25064. variables containing the relevant data.
  25065. @node Managing Curves, Graphics Options, Three Dimensional Graphics, Graphics
  25066. @section Managing Curves
  25067. @noindent
  25068. The @kbd{g f} command is really shorthand for the following commands:
  25069. @kbd{C-u g d g a g p}. Likewise, @w{@kbd{g F}} is shorthand for
  25070. @kbd{C-u g d g A g p}. You can gain more control over your graph
  25071. by using these commands directly.
  25072. @kindex g a
  25073. @pindex calc-graph-add
  25074. The @kbd{g a} (@code{calc-graph-add}) command adds the ``curve''
  25075. represented by the two values on the top of the stack to the current
  25076. graph. You can have any number of curves in the same graph. When
  25077. you give the @kbd{g p} command, all the curves will be drawn superimposed
  25078. on the same axes.
  25079. The @kbd{g a} command (and many others that affect the current graph)
  25080. will cause a special buffer, @file{*Gnuplot Commands*}, to be displayed
  25081. in another window. This buffer is a template of the commands that will
  25082. be sent to GNUPLOT when it is time to draw the graph. The first
  25083. @kbd{g a} command adds a @code{plot} command to this buffer. Succeeding
  25084. @kbd{g a} commands add extra curves onto that @code{plot} command.
  25085. Other graph-related commands put other GNUPLOT commands into this
  25086. buffer. In normal usage you never need to work with this buffer
  25087. directly, but you can if you wish. The only constraint is that there
  25088. must be only one @code{plot} command, and it must be the last command
  25089. in the buffer. If you want to save and later restore a complete graph
  25090. configuration, you can use regular Emacs commands to save and restore
  25091. the contents of the @file{*Gnuplot Commands*} buffer.
  25092. @vindex PlotData1
  25093. @vindex PlotData2
  25094. If the values on the stack are not variable names, @kbd{g a} will invent
  25095. variable names for them (of the form @samp{PlotData@var{n}}) and store
  25096. the values in those variables. The ``x'' and ``y'' variables are what
  25097. go into the @code{plot} command in the template. If you add a curve
  25098. that uses a certain variable and then later change that variable, you
  25099. can replot the graph without having to delete and re-add the curve.
  25100. That's because the variable name, not the vector, interval or formula
  25101. itself, is what was added by @kbd{g a}.
  25102. A numeric prefix argument on @kbd{g a} or @kbd{g f} changes the way
  25103. stack entries are interpreted as curves. With a positive prefix
  25104. argument @expr{n}, the top @expr{n} stack entries are ``y'' values
  25105. for @expr{n} different curves which share a common ``x'' value in
  25106. the @expr{n+1}st stack entry. (Thus @kbd{g a} with no prefix
  25107. argument is equivalent to @kbd{C-u 1 g a}.)
  25108. A prefix of zero or plain @kbd{C-u} means to take two stack entries,
  25109. ``x'' and ``y'' as usual, but to interpret ``y'' as a vector of
  25110. ``y'' values for several curves that share a common ``x''.
  25111. A negative prefix argument tells Calc to read @expr{n} vectors from
  25112. the stack; each vector @expr{[x, y]} describes an independent curve.
  25113. This is the only form of @kbd{g a} that creates several curves at once
  25114. that don't have common ``x'' values. (Of course, the range of ``x''
  25115. values covered by all the curves ought to be roughly the same if
  25116. they are to look nice on the same graph.)
  25117. For example, to plot
  25118. @texline @math{\sin n x}
  25119. @infoline @expr{sin(n x)}
  25120. for integers @expr{n}
  25121. from 1 to 5, you could use @kbd{v x} to create a vector of integers
  25122. (@expr{n}), then @kbd{V M '} or @kbd{V M $} to map @samp{sin(n x)}
  25123. across this vector. The resulting vector of formulas is suitable
  25124. for use as the ``y'' argument to a @kbd{C-u g a} or @kbd{C-u g f}
  25125. command.
  25126. @kindex g A
  25127. @pindex calc-graph-add-3d
  25128. The @kbd{g A} (@code{calc-graph-add-3d}) command adds a 3D curve
  25129. to the graph. It is not valid to intermix 2D and 3D curves in a
  25130. single graph. This command takes three arguments, ``x'', ``y'',
  25131. and ``z'', from the stack. With a positive prefix @expr{n}, it
  25132. takes @expr{n+2} arguments (common ``x'' and ``y'', plus @expr{n}
  25133. separate ``z''s). With a zero prefix, it takes three stack entries
  25134. but the ``z'' entry is a vector of curve values. With a negative
  25135. prefix @expr{-n}, it takes @expr{n} vectors of the form @expr{[x, y, z]}.
  25136. The @kbd{g A} command works by adding a @code{splot} (surface-plot)
  25137. command to the @file{*Gnuplot Commands*} buffer.
  25138. (Although @kbd{g a} adds a 2D @code{plot} command to the
  25139. @file{*Gnuplot Commands*} buffer, Calc changes this to @code{splot}
  25140. before sending it to GNUPLOT if it notices that the data points are
  25141. evaluating to @code{xyz} calls. It will not work to mix 2D and 3D
  25142. @kbd{g a} curves in a single graph, although Calc does not currently
  25143. check for this.)
  25144. @kindex g d
  25145. @pindex calc-graph-delete
  25146. The @kbd{g d} (@code{calc-graph-delete}) command deletes the most
  25147. recently added curve from the graph. It has no effect if there are
  25148. no curves in the graph. With a numeric prefix argument of any kind,
  25149. it deletes all of the curves from the graph.
  25150. @kindex g H
  25151. @pindex calc-graph-hide
  25152. The @kbd{g H} (@code{calc-graph-hide}) command ``hides'' or ``unhides''
  25153. the most recently added curve. A hidden curve will not appear in
  25154. the actual plot, but information about it such as its name and line and
  25155. point styles will be retained.
  25156. @kindex g j
  25157. @pindex calc-graph-juggle
  25158. The @kbd{g j} (@code{calc-graph-juggle}) command moves the curve
  25159. at the end of the list (the ``most recently added curve'') to the
  25160. front of the list. The next-most-recent curve is thus exposed for
  25161. @w{@kbd{g d}} or similar commands to use. With @kbd{g j} you can work
  25162. with any curve in the graph even though curve-related commands only
  25163. affect the last curve in the list.
  25164. @kindex g p
  25165. @pindex calc-graph-plot
  25166. The @kbd{g p} (@code{calc-graph-plot}) command uses GNUPLOT to draw
  25167. the graph described in the @file{*Gnuplot Commands*} buffer. Any
  25168. GNUPLOT parameters which are not defined by commands in this buffer
  25169. are reset to their default values. The variables named in the @code{plot}
  25170. command are written to a temporary data file and the variable names
  25171. are then replaced by the file name in the template. The resulting
  25172. plotting commands are fed to the GNUPLOT program. See the documentation
  25173. for the GNUPLOT program for more specific information. All temporary
  25174. files are removed when Emacs or GNUPLOT exits.
  25175. If you give a formula for ``y'', Calc will remember all the values that
  25176. it calculates for the formula so that later plots can reuse these values.
  25177. Calc throws out these saved values when you change any circumstances
  25178. that may affect the data, such as switching from Degrees to Radians
  25179. mode, or changing the value of a parameter in the formula. You can
  25180. force Calc to recompute the data from scratch by giving a negative
  25181. numeric prefix argument to @kbd{g p}.
  25182. Calc uses a fairly rough step size when graphing formulas over intervals.
  25183. This is to ensure quick response. You can ``refine'' a plot by giving
  25184. a positive numeric prefix argument to @kbd{g p}. Calc goes through
  25185. the data points it has computed and saved from previous plots of the
  25186. function, and computes and inserts a new data point midway between
  25187. each of the existing points. You can refine a plot any number of times,
  25188. but beware that the amount of calculation involved doubles each time.
  25189. Calc does not remember computed values for 3D graphs. This means the
  25190. numerix prefix argument, if any, to @kbd{g p} is effectively ignored if
  25191. the current graph is three-dimensional.
  25192. @kindex g P
  25193. @pindex calc-graph-print
  25194. The @kbd{g P} (@code{calc-graph-print}) command is like @kbd{g p},
  25195. except that it sends the output to a printer instead of to the
  25196. screen. More precisely, @kbd{g p} looks for @samp{set terminal}
  25197. or @samp{set output} commands in the @file{*Gnuplot Commands*} buffer;
  25198. lacking these it uses the default settings. However, @kbd{g P}
  25199. ignores @samp{set terminal} and @samp{set output} commands and
  25200. uses a different set of default values. All of these values are
  25201. controlled by the @kbd{g D} and @kbd{g O} commands discussed below.
  25202. Provided everything is set up properly, @kbd{g p} will plot to
  25203. the screen unless you have specified otherwise and @kbd{g P} will
  25204. always plot to the printer.
  25205. @node Graphics Options, Devices, Managing Curves, Graphics
  25206. @section Graphics Options
  25207. @noindent
  25208. @kindex g g
  25209. @pindex calc-graph-grid
  25210. The @kbd{g g} (@code{calc-graph-grid}) command turns the ``grid''
  25211. on and off. It is off by default; tick marks appear only at the
  25212. edges of the graph. With the grid turned on, dotted lines appear
  25213. across the graph at each tick mark. Note that this command only
  25214. changes the setting in @file{*Gnuplot Commands*}; to see the effects
  25215. of the change you must give another @kbd{g p} command.
  25216. @kindex g b
  25217. @pindex calc-graph-border
  25218. The @kbd{g b} (@code{calc-graph-border}) command turns the border
  25219. (the box that surrounds the graph) on and off. It is on by default.
  25220. This command will only work with GNUPLOT 3.0 and later versions.
  25221. @kindex g k
  25222. @pindex calc-graph-key
  25223. The @kbd{g k} (@code{calc-graph-key}) command turns the ``key''
  25224. on and off. The key is a chart in the corner of the graph that
  25225. shows the correspondence between curves and line styles. It is
  25226. off by default, and is only really useful if you have several
  25227. curves on the same graph.
  25228. @kindex g N
  25229. @pindex calc-graph-num-points
  25230. The @kbd{g N} (@code{calc-graph-num-points}) command allows you
  25231. to select the number of data points in the graph. This only affects
  25232. curves where neither ``x'' nor ``y'' is specified as a vector.
  25233. Enter a blank line to revert to the default value (initially 15).
  25234. With no prefix argument, this command affects only the current graph.
  25235. With a positive prefix argument this command changes or, if you enter
  25236. a blank line, displays the default number of points used for all
  25237. graphs created by @kbd{g a} that don't specify the resolution explicitly.
  25238. With a negative prefix argument, this command changes or displays
  25239. the default value (initially 5) used for 3D graphs created by @kbd{g A}.
  25240. Note that a 3D setting of 5 means that a total of @expr{5^2 = 25} points
  25241. will be computed for the surface.
  25242. Data values in the graph of a function are normally computed to a
  25243. precision of five digits, regardless of the current precision at the
  25244. time. This is usually more than adequate, but there are cases where
  25245. it will not be. For example, plotting @expr{1 + x} with @expr{x} in the
  25246. interval @samp{[0 ..@: 1e-6]} will round all the data points down
  25247. to 1.0! Putting the command @samp{set precision @var{n}} in the
  25248. @file{*Gnuplot Commands*} buffer will cause the data to be computed
  25249. at precision @var{n} instead of 5. Since this is such a rare case,
  25250. there is no keystroke-based command to set the precision.
  25251. @kindex g h
  25252. @pindex calc-graph-header
  25253. The @kbd{g h} (@code{calc-graph-header}) command sets the title
  25254. for the graph. This will show up centered above the graph.
  25255. The default title is blank (no title).
  25256. @kindex g n
  25257. @pindex calc-graph-name
  25258. The @kbd{g n} (@code{calc-graph-name}) command sets the title of an
  25259. individual curve. Like the other curve-manipulating commands, it
  25260. affects the most recently added curve, i.e., the last curve on the
  25261. list in the @file{*Gnuplot Commands*} buffer. To set the title of
  25262. the other curves you must first juggle them to the end of the list
  25263. with @kbd{g j}, or edit the @file{*Gnuplot Commands*} buffer by hand.
  25264. Curve titles appear in the key; if the key is turned off they are
  25265. not used.
  25266. @kindex g t
  25267. @kindex g T
  25268. @pindex calc-graph-title-x
  25269. @pindex calc-graph-title-y
  25270. The @kbd{g t} (@code{calc-graph-title-x}) and @kbd{g T}
  25271. (@code{calc-graph-title-y}) commands set the titles on the ``x''
  25272. and ``y'' axes, respectively. These titles appear next to the
  25273. tick marks on the left and bottom edges of the graph, respectively.
  25274. Calc does not have commands to control the tick marks themselves,
  25275. but you can edit them into the @file{*Gnuplot Commands*} buffer if
  25276. you wish. See the GNUPLOT documentation for details.
  25277. @kindex g r
  25278. @kindex g R
  25279. @pindex calc-graph-range-x
  25280. @pindex calc-graph-range-y
  25281. The @kbd{g r} (@code{calc-graph-range-x}) and @kbd{g R}
  25282. (@code{calc-graph-range-y}) commands set the range of values on the
  25283. ``x'' and ``y'' axes, respectively. You are prompted to enter a
  25284. suitable range. This should be either a pair of numbers of the
  25285. form, @samp{@var{min}:@var{max}}, or a blank line to revert to the
  25286. default behavior of setting the range based on the range of values
  25287. in the data, or @samp{$} to take the range from the top of the stack.
  25288. Ranges on the stack can be represented as either interval forms or
  25289. vectors: @samp{[@var{min} ..@: @var{max}]} or @samp{[@var{min}, @var{max}]}.
  25290. @kindex g l
  25291. @kindex g L
  25292. @pindex calc-graph-log-x
  25293. @pindex calc-graph-log-y
  25294. The @kbd{g l} (@code{calc-graph-log-x}) and @kbd{g L} (@code{calc-graph-log-y})
  25295. commands allow you to set either or both of the axes of the graph to
  25296. be logarithmic instead of linear.
  25297. @kindex g C-l
  25298. @kindex g C-r
  25299. @kindex g C-t
  25300. @pindex calc-graph-log-z
  25301. @pindex calc-graph-range-z
  25302. @pindex calc-graph-title-z
  25303. For 3D plots, @kbd{g C-t}, @kbd{g C-r}, and @kbd{g C-l} (those are
  25304. letters with the Control key held down) are the corresponding commands
  25305. for the ``z'' axis.
  25306. @kindex g z
  25307. @kindex g Z
  25308. @pindex calc-graph-zero-x
  25309. @pindex calc-graph-zero-y
  25310. The @kbd{g z} (@code{calc-graph-zero-x}) and @kbd{g Z}
  25311. (@code{calc-graph-zero-y}) commands control whether a dotted line is
  25312. drawn to indicate the ``x'' and/or ``y'' zero axes. (These are the same
  25313. dotted lines that would be drawn there anyway if you used @kbd{g g} to
  25314. turn the ``grid'' feature on.) Zero-axis lines are on by default, and
  25315. may be turned off only in GNUPLOT 3.0 and later versions. They are
  25316. not available for 3D plots.
  25317. @kindex g s
  25318. @pindex calc-graph-line-style
  25319. The @kbd{g s} (@code{calc-graph-line-style}) command turns the connecting
  25320. lines on or off for the most recently added curve, and optionally selects
  25321. the style of lines to be used for that curve. Plain @kbd{g s} simply
  25322. toggles the lines on and off. With a numeric prefix argument, @kbd{g s}
  25323. turns lines on and sets a particular line style. Line style numbers
  25324. start at one and their meanings vary depending on the output device.
  25325. GNUPLOT guarantees that there will be at least six different line styles
  25326. available for any device.
  25327. @kindex g S
  25328. @pindex calc-graph-point-style
  25329. The @kbd{g S} (@code{calc-graph-point-style}) command similarly turns
  25330. the symbols at the data points on or off, or sets the point style.
  25331. If you turn both lines and points off, the data points will show as
  25332. tiny dots. If the ``y'' values being plotted contain error forms and
  25333. the connecting lines are turned off, then this command will also turn
  25334. the error bars on or off.
  25335. @cindex @code{LineStyles} variable
  25336. @cindex @code{PointStyles} variable
  25337. @vindex LineStyles
  25338. @vindex PointStyles
  25339. Another way to specify curve styles is with the @code{LineStyles} and
  25340. @code{PointStyles} variables. These variables initially have no stored
  25341. values, but if you store a vector of integers in one of these variables,
  25342. the @kbd{g a} and @kbd{g f} commands will use those style numbers
  25343. instead of the defaults for new curves that are added to the graph.
  25344. An entry should be a positive integer for a specific style, or 0 to let
  25345. the style be chosen automatically, or @mathit{-1} to turn off lines or points
  25346. altogether. If there are more curves than elements in the vector, the
  25347. last few curves will continue to have the default styles. Of course,
  25348. you can later use @kbd{g s} and @kbd{g S} to change any of these styles.
  25349. For example, @kbd{'[2 -1 3] @key{RET} s t LineStyles} causes the first curve
  25350. to have lines in style number 2, the second curve to have no connecting
  25351. lines, and the third curve to have lines in style 3. Point styles will
  25352. still be assigned automatically, but you could store another vector in
  25353. @code{PointStyles} to define them, too.
  25354. @node Devices, , Graphics Options, Graphics
  25355. @section Graphical Devices
  25356. @noindent
  25357. @kindex g D
  25358. @pindex calc-graph-device
  25359. The @kbd{g D} (@code{calc-graph-device}) command sets the device name
  25360. (or ``terminal name'' in GNUPLOT lingo) to be used by @kbd{g p} commands
  25361. on this graph. It does not affect the permanent default device name.
  25362. If you enter a blank name, the device name reverts to the default.
  25363. Enter @samp{?} to see a list of supported devices.
  25364. With a positive numeric prefix argument, @kbd{g D} instead sets
  25365. the default device name, used by all plots in the future which do
  25366. not override it with a plain @kbd{g D} command. If you enter a
  25367. blank line this command shows you the current default. The special
  25368. name @code{default} signifies that Calc should choose @code{x11} if
  25369. the X window system is in use (as indicated by the presence of a
  25370. @code{DISPLAY} environment variable), @code{windows} on MS-Windows, or
  25371. otherwise @code{dumb} under GNUPLOT 3.0 and later, or
  25372. @code{postscript} under GNUPLOT 2.0. This is the initial default
  25373. value.
  25374. The @code{dumb} device is an interface to ``dumb terminals,'' i.e.,
  25375. terminals with no special graphics facilities. It writes a crude
  25376. picture of the graph composed of characters like @code{-} and @code{|}
  25377. to a buffer called @file{*Gnuplot Trail*}, which Calc then displays.
  25378. The graph is made the same size as the Emacs screen, which on most
  25379. dumb terminals will be
  25380. @texline @math{80\times24}
  25381. @infoline 80x24
  25382. characters. The graph is displayed in
  25383. an Emacs ``recursive edit''; type @kbd{q} or @kbd{C-c C-c} to exit
  25384. the recursive edit and return to Calc. Note that the @code{dumb}
  25385. device is present only in GNUPLOT 3.0 and later versions.
  25386. The word @code{dumb} may be followed by two numbers separated by
  25387. spaces. These are the desired width and height of the graph in
  25388. characters. Also, the device name @code{big} is like @code{dumb}
  25389. but creates a graph four times the width and height of the Emacs
  25390. screen. You will then have to scroll around to view the entire
  25391. graph. In the @file{*Gnuplot Trail*} buffer, @key{SPC}, @key{DEL},
  25392. @kbd{<}, and @kbd{>} are defined to scroll by one screenful in each
  25393. of the four directions.
  25394. With a negative numeric prefix argument, @kbd{g D} sets or displays
  25395. the device name used by @kbd{g P} (@code{calc-graph-print}). This
  25396. is initially @code{postscript}. If you don't have a PostScript
  25397. printer, you may decide once again to use @code{dumb} to create a
  25398. plot on any text-only printer.
  25399. @kindex g O
  25400. @pindex calc-graph-output
  25401. The @kbd{g O} (@code{calc-graph-output}) command sets the name of the
  25402. output file used by GNUPLOT@. For some devices, notably @code{x11} and
  25403. @code{windows}, there is no output file and this information is not
  25404. used. Many other ``devices'' are really file formats like
  25405. @code{postscript}; in these cases the output in the desired format
  25406. goes into the file you name with @kbd{g O}. Type @kbd{g O stdout
  25407. @key{RET}} to set GNUPLOT to write to its standard output stream,
  25408. i.e., to @file{*Gnuplot Trail*}. This is the default setting.
  25409. Another special output name is @code{tty}, which means that GNUPLOT
  25410. is going to write graphics commands directly to its standard output,
  25411. which you wish Emacs to pass through to your terminal. Tektronix
  25412. graphics terminals, among other devices, operate this way. Calc does
  25413. this by telling GNUPLOT to write to a temporary file, then running a
  25414. sub-shell executing the command @samp{cat tempfile >/dev/tty}. On
  25415. typical Unix systems, this will copy the temporary file directly to
  25416. the terminal, bypassing Emacs entirely. You will have to type @kbd{C-l}
  25417. to Emacs afterwards to refresh the screen.
  25418. Once again, @kbd{g O} with a positive or negative prefix argument
  25419. sets the default or printer output file names, respectively. In each
  25420. case you can specify @code{auto}, which causes Calc to invent a temporary
  25421. file name for each @kbd{g p} (or @kbd{g P}) command. This temporary file
  25422. will be deleted once it has been displayed or printed. If the output file
  25423. name is not @code{auto}, the file is not automatically deleted.
  25424. The default and printer devices and output files can be saved
  25425. permanently by the @kbd{m m} (@code{calc-save-modes}) command. The
  25426. default number of data points (see @kbd{g N}) and the X geometry
  25427. (see @kbd{g X}) are also saved. Other graph information is @emph{not}
  25428. saved; you can save a graph's configuration simply by saving the contents
  25429. of the @file{*Gnuplot Commands*} buffer.
  25430. @vindex calc-gnuplot-plot-command
  25431. @vindex calc-gnuplot-default-device
  25432. @vindex calc-gnuplot-default-output
  25433. @vindex calc-gnuplot-print-command
  25434. @vindex calc-gnuplot-print-device
  25435. @vindex calc-gnuplot-print-output
  25436. You may wish to configure the default and
  25437. printer devices and output files for the whole system. The relevant
  25438. Lisp variables are @code{calc-gnuplot-default-device} and @code{-output},
  25439. and @code{calc-gnuplot-print-device} and @code{-output}. The output
  25440. file names must be either strings as described above, or Lisp
  25441. expressions which are evaluated on the fly to get the output file names.
  25442. Other important Lisp variables are @code{calc-gnuplot-plot-command} and
  25443. @code{calc-gnuplot-print-command}, which give the system commands to
  25444. display or print the output of GNUPLOT, respectively. These may be
  25445. @code{nil} if no command is necessary, or strings which can include
  25446. @samp{%s} to signify the name of the file to be displayed or printed.
  25447. Or, these variables may contain Lisp expressions which are evaluated
  25448. to display or print the output. These variables are customizable
  25449. (@pxref{Customizing Calc}).
  25450. @kindex g x
  25451. @pindex calc-graph-display
  25452. The @kbd{g x} (@code{calc-graph-display}) command lets you specify
  25453. on which X window system display your graphs should be drawn. Enter
  25454. a blank line to see the current display name. This command has no
  25455. effect unless the current device is @code{x11}.
  25456. @kindex g X
  25457. @pindex calc-graph-geometry
  25458. The @kbd{g X} (@code{calc-graph-geometry}) command is a similar
  25459. command for specifying the position and size of the X window.
  25460. The normal value is @code{default}, which generally means your
  25461. window manager will let you place the window interactively.
  25462. Entering @samp{800x500+0+0} would create an 800-by-500 pixel
  25463. window in the upper-left corner of the screen. This command has no
  25464. effect if the current device is @code{windows}.
  25465. The buffer called @file{*Gnuplot Trail*} holds a transcript of the
  25466. session with GNUPLOT@. This shows the commands Calc has ``typed'' to
  25467. GNUPLOT and the responses it has received. Calc tries to notice when an
  25468. error message has appeared here and display the buffer for you when
  25469. this happens. You can check this buffer yourself if you suspect
  25470. something has gone wrong@footnote{
  25471. On MS-Windows, due to the peculiarities of how the Windows version of
  25472. GNUPLOT (called @command{wgnuplot}) works, the GNUPLOT responses are
  25473. not communicated back to Calc. Instead, you need to look them up in
  25474. the GNUPLOT command window that is displayed as in normal interactive
  25475. usage of GNUPLOT.
  25476. }.
  25477. @kindex g C
  25478. @pindex calc-graph-command
  25479. The @kbd{g C} (@code{calc-graph-command}) command prompts you to
  25480. enter any line of text, then simply sends that line to the current
  25481. GNUPLOT process. The @file{*Gnuplot Trail*} buffer looks deceptively
  25482. like a Shell buffer but you can't type commands in it yourself.
  25483. Instead, you must use @kbd{g C} for this purpose.
  25484. @kindex g v
  25485. @kindex g V
  25486. @pindex calc-graph-view-commands
  25487. @pindex calc-graph-view-trail
  25488. The @kbd{g v} (@code{calc-graph-view-commands}) and @kbd{g V}
  25489. (@code{calc-graph-view-trail}) commands display the @file{*Gnuplot Commands*}
  25490. and @file{*Gnuplot Trail*} buffers, respectively, in another window.
  25491. This happens automatically when Calc thinks there is something you
  25492. will want to see in either of these buffers. If you type @kbd{g v}
  25493. or @kbd{g V} when the relevant buffer is already displayed, the
  25494. buffer is hidden again. (Note that on MS-Windows, the @file{*Gnuplot
  25495. Trail*} buffer will usually show nothing of interest, because
  25496. GNUPLOT's responses are not communicated back to Calc.)
  25497. One reason to use @kbd{g v} is to add your own commands to the
  25498. @file{*Gnuplot Commands*} buffer. Press @kbd{g v}, then use
  25499. @kbd{C-x o} to switch into that window. For example, GNUPLOT has
  25500. @samp{set label} and @samp{set arrow} commands that allow you to
  25501. annotate your plots. Since Calc doesn't understand these commands,
  25502. you have to add them to the @file{*Gnuplot Commands*} buffer
  25503. yourself, then use @w{@kbd{g p}} to replot using these new commands. Note
  25504. that your commands must appear @emph{before} the @code{plot} command.
  25505. To get help on any GNUPLOT feature, type, e.g., @kbd{g C help set label}.
  25506. You may have to type @kbd{g C @key{RET}} a few times to clear the
  25507. ``press return for more'' or ``subtopic of @dots{}'' requests.
  25508. Note that Calc always sends commands (like @samp{set nolabel}) to
  25509. reset all plotting parameters to the defaults before each plot, so
  25510. to delete a label all you need to do is delete the @samp{set label}
  25511. line you added (or comment it out with @samp{#}) and then replot
  25512. with @kbd{g p}.
  25513. @kindex g q
  25514. @pindex calc-graph-quit
  25515. You can use @kbd{g q} (@code{calc-graph-quit}) to kill the GNUPLOT
  25516. process that is running. The next graphing command you give will
  25517. start a fresh GNUPLOT process. The word @samp{Graph} appears in
  25518. the Calc window's mode line whenever a GNUPLOT process is currently
  25519. running. The GNUPLOT process is automatically killed when you
  25520. exit Emacs if you haven't killed it manually by then.
  25521. @kindex g K
  25522. @pindex calc-graph-kill
  25523. The @kbd{g K} (@code{calc-graph-kill}) command is like @kbd{g q}
  25524. except that it also views the @file{*Gnuplot Trail*} buffer so that
  25525. you can see the process being killed. This is better if you are
  25526. killing GNUPLOT because you think it has gotten stuck.
  25527. @node Kill and Yank, Keypad Mode, Graphics, Top
  25528. @chapter Kill and Yank Functions
  25529. @noindent
  25530. The commands in this chapter move information between the Calculator and
  25531. other Emacs editing buffers.
  25532. In many cases Embedded mode is an easier and more natural way to
  25533. work with Calc from a regular editing buffer. @xref{Embedded Mode}.
  25534. @menu
  25535. * Killing From Stack::
  25536. * Yanking Into Stack::
  25537. * Saving Into Registers::
  25538. * Inserting From Registers::
  25539. * Grabbing From Buffers::
  25540. * Yanking Into Buffers::
  25541. * X Cut and Paste::
  25542. @end menu
  25543. @node Killing From Stack, Yanking Into Stack, Kill and Yank, Kill and Yank
  25544. @section Killing from the Stack
  25545. @noindent
  25546. @kindex C-k
  25547. @pindex calc-kill
  25548. @kindex M-k
  25549. @pindex calc-copy-as-kill
  25550. @kindex C-w
  25551. @pindex calc-kill-region
  25552. @kindex M-w
  25553. @pindex calc-copy-region-as-kill
  25554. @kindex M-C-w
  25555. @cindex Kill ring
  25556. @dfn{Kill} commands are Emacs commands that insert text into the ``kill
  25557. ring,'' from which it can later be ``yanked'' by a @kbd{C-y} command.
  25558. Three common kill commands in normal Emacs are @kbd{C-k}, which kills
  25559. one line, @kbd{C-w}, which kills the region between mark and point, and
  25560. @kbd{M-w}, which puts the region into the kill ring without actually
  25561. deleting it. All of these commands work in the Calculator, too,
  25562. although in the Calculator they operate on whole stack entries, so they
  25563. ``round up'' the specified region to encompass full lines. (To copy
  25564. only parts of lines, the @kbd{M-C-w} command in the Calculator will copy
  25565. the region to the kill ring without any ``rounding up'', just like the
  25566. @kbd{M-w} command in normal Emacs.) Also, @kbd{M-k} has been provided
  25567. to complete the set; it puts the current line into the kill ring without
  25568. deleting anything.
  25569. The kill commands are unusual in that they pay attention to the location
  25570. of the cursor in the Calculator buffer. If the cursor is on or below
  25571. the bottom line, the kill commands operate on the top of the stack.
  25572. Otherwise, they operate on whatever stack element the cursor is on. The
  25573. text is copied into the kill ring exactly as it appears on the screen,
  25574. including line numbers if they are enabled.
  25575. A numeric prefix argument to @kbd{C-k} or @kbd{M-k} affects the number
  25576. of lines killed. A positive argument kills the current line and @expr{n-1}
  25577. lines below it. A negative argument kills the @expr{-n} lines above the
  25578. current line. Again this mirrors the behavior of the standard Emacs
  25579. @kbd{C-k} command. Although a whole line is always deleted, @kbd{C-k}
  25580. with no argument copies only the number itself into the kill ring, whereas
  25581. @kbd{C-k} with a prefix argument of 1 copies the number with its trailing
  25582. newline.
  25583. @node Yanking Into Stack, Saving Into Registers, Killing From Stack, Kill and Yank
  25584. @section Yanking into the Stack
  25585. @noindent
  25586. @kindex C-y
  25587. @pindex calc-yank
  25588. The @kbd{C-y} command yanks the most recently killed text back into the
  25589. Calculator. It pushes this value onto the top of the stack regardless of
  25590. the cursor position. In general it re-parses the killed text as a number
  25591. or formula (or a list of these separated by commas or newlines). However if
  25592. the thing being yanked is something that was just killed from the Calculator
  25593. itself, its full internal structure is yanked. For example, if you have
  25594. set the floating-point display mode to show only four significant digits,
  25595. then killing and re-yanking 3.14159 (which displays as 3.142) will yank the
  25596. full 3.14159, even though yanking it into any other buffer would yank the
  25597. number in its displayed form, 3.142. (Since the default display modes
  25598. show all objects to their full precision, this feature normally makes no
  25599. difference.)
  25600. The @kbd{C-y} command can be given a prefix, which will interpret the
  25601. text being yanked with a different radix. If the text being yanked can be
  25602. interpreted as a binary, octal, hexadecimal, or decimal number, then a
  25603. prefix of @kbd{2}, @kbd{8}, @kbd{6} or @kbd{0} will have Calc
  25604. interpret the yanked text as a number in the appropriate base. For example,
  25605. if @samp{111} has just been killed and is yanked into Calc with a command
  25606. of @kbd{C-2 C-y}, then the number @samp{7} will be put on the stack.
  25607. If you use the plain prefix @kbd{C-u}, then you will be prompted for a
  25608. base to use, which can be any integer from 2 to 36. If Calc doesn't
  25609. allow the text being yanked to be read in a different base (such as if
  25610. the text is an algebraic expression), then the prefix will have no
  25611. effect.
  25612. @node Saving Into Registers, Inserting From Registers, Yanking Into Stack, Kill and Yank
  25613. @section Saving into Registers
  25614. @noindent
  25615. @kindex r s
  25616. @pindex calc-copy-to-register
  25617. @pindex calc-prepend-to-register
  25618. @pindex calc-append-to-register
  25619. @cindex Registers
  25620. An alternative to killing and yanking stack entries is using
  25621. registers in Calc. Saving stack entries in registers is like
  25622. saving text in normal Emacs registers; although, like Calc's kill
  25623. commands, register commands always operate on whole stack
  25624. entries.
  25625. Registers in Calc are places to store stack entries for later use;
  25626. each register is indexed by a single character. To store the current
  25627. region (rounded up, of course, to include full stack entries) into a
  25628. register, use the command @kbd{r s} (@code{calc-copy-to-register}).
  25629. You will then be prompted for a register to use, the next character
  25630. you type will be the index for the register. To store the region in
  25631. register @var{r}, the full command will be @kbd{r s @var{r}}. With an
  25632. argument, @kbd{C-u r s @var{r}}, the region being copied to the
  25633. register will be deleted from the Calc buffer.
  25634. It is possible to add additional stack entries to a register. The
  25635. command @kbd{M-x calc-append-to-register} will prompt for a register,
  25636. then add the stack entries in the region to the end of the register
  25637. contents. The command @kbd{M-x calc-prepend-to-register} will
  25638. similarly prompt for a register and add the stack entries in the
  25639. region to the beginning of the register contents. Both commands take
  25640. @kbd{C-u} arguments, which will cause the region to be deleted after being
  25641. added to the register.
  25642. @node Inserting From Registers, Grabbing From Buffers, Saving Into Registers, Kill and Yank
  25643. @section Inserting from Registers
  25644. @noindent
  25645. @kindex r i
  25646. @pindex calc-insert-register
  25647. The command @kbd{r i} (@code{calc-insert-register}) will prompt for a
  25648. register, then insert the contents of that register into the
  25649. Calculator. If the contents of the register were placed there from
  25650. within Calc, then the full internal structure of the contents will be
  25651. inserted into the Calculator, otherwise whatever text is in the
  25652. register is reparsed and then inserted into the Calculator.
  25653. @node Grabbing From Buffers, Yanking Into Buffers, Inserting From Registers, Kill and Yank
  25654. @section Grabbing from Other Buffers
  25655. @noindent
  25656. @kindex C-x * g
  25657. @pindex calc-grab-region
  25658. The @kbd{C-x * g} (@code{calc-grab-region}) command takes the text between
  25659. point and mark in the current buffer and attempts to parse it as a
  25660. vector of values. Basically, it wraps the text in vector brackets
  25661. @samp{[ ]} unless the text already is enclosed in vector brackets,
  25662. then reads the text as if it were an algebraic entry. The contents
  25663. of the vector may be numbers, formulas, or any other Calc objects.
  25664. If the @kbd{C-x * g} command works successfully, it does an automatic
  25665. @kbd{C-x * c} to enter the Calculator buffer.
  25666. A numeric prefix argument grabs the specified number of lines around
  25667. point, ignoring the mark. A positive prefix grabs from point to the
  25668. @expr{n}th following newline (so that @kbd{M-1 C-x * g} grabs from point
  25669. to the end of the current line); a negative prefix grabs from point
  25670. back to the @expr{n+1}st preceding newline. In these cases the text
  25671. that is grabbed is exactly the same as the text that @kbd{C-k} would
  25672. delete given that prefix argument.
  25673. A prefix of zero grabs the current line; point may be anywhere on the
  25674. line.
  25675. A plain @kbd{C-u} prefix interprets the region between point and mark
  25676. as a single number or formula rather than a vector. For example,
  25677. @kbd{C-x * g} on the text @samp{2 a b} produces the vector of three
  25678. values @samp{[2, a, b]}, but @kbd{C-u C-x * g} on the same region
  25679. reads a formula which is a product of three things: @samp{2 a b}.
  25680. (The text @samp{a + b}, on the other hand, will be grabbed as a
  25681. vector of one element by plain @kbd{C-x * g} because the interpretation
  25682. @samp{[a, +, b]} would be a syntax error.)
  25683. If a different language has been specified (@pxref{Language Modes}),
  25684. the grabbed text will be interpreted according to that language.
  25685. @kindex C-x * r
  25686. @pindex calc-grab-rectangle
  25687. The @kbd{C-x * r} (@code{calc-grab-rectangle}) command takes the text between
  25688. point and mark and attempts to parse it as a matrix. If point and mark
  25689. are both in the leftmost column, the lines in between are parsed in their
  25690. entirety. Otherwise, point and mark define the corners of a rectangle
  25691. whose contents are parsed.
  25692. Each line of the grabbed area becomes a row of the matrix. The result
  25693. will actually be a vector of vectors, which Calc will treat as a matrix
  25694. only if every row contains the same number of values.
  25695. If a line contains a portion surrounded by square brackets (or curly
  25696. braces), that portion is interpreted as a vector which becomes a row
  25697. of the matrix. Any text surrounding the bracketed portion on the line
  25698. is ignored.
  25699. Otherwise, the entire line is interpreted as a row vector as if it
  25700. were surrounded by square brackets. Leading line numbers (in the
  25701. format used in the Calc stack buffer) are ignored. If you wish to
  25702. force this interpretation (even if the line contains bracketed
  25703. portions), give a negative numeric prefix argument to the
  25704. @kbd{C-x * r} command.
  25705. If you give a numeric prefix argument of zero or plain @kbd{C-u}, each
  25706. line is instead interpreted as a single formula which is converted into
  25707. a one-element vector. Thus the result of @kbd{C-u C-x * r} will be a
  25708. one-column matrix. For example, suppose one line of the data is the
  25709. expression @samp{2 a}. A plain @w{@kbd{C-x * r}} will interpret this as
  25710. @samp{[2 a]}, which in turn is read as a two-element vector that forms
  25711. one row of the matrix. But a @kbd{C-u C-x * r} will interpret this row
  25712. as @samp{[2*a]}.
  25713. If you give a positive numeric prefix argument @var{n}, then each line
  25714. will be split up into columns of width @var{n}; each column is parsed
  25715. separately as a matrix element. If a line contained
  25716. @w{@samp{2 +/- 3 4 +/- 5}}, then grabbing with a prefix argument of 8
  25717. would correctly split the line into two error forms.
  25718. @xref{Matrix Functions}, to see how to pull the matrix apart into its
  25719. constituent rows and columns. (If it is a
  25720. @texline @math{1\times1}
  25721. @infoline 1x1
  25722. matrix, just hit @kbd{v u} (@code{calc-unpack}) twice.)
  25723. @kindex C-x * :
  25724. @kindex C-x * _
  25725. @pindex calc-grab-sum-across
  25726. @pindex calc-grab-sum-down
  25727. @cindex Summing rows and columns of data
  25728. The @kbd{C-x * :} (@code{calc-grab-sum-down}) command is a handy way to
  25729. grab a rectangle of data and sum its columns. It is equivalent to
  25730. typing @kbd{C-x * r}, followed by @kbd{V R : +} (the vector reduction
  25731. command that sums the columns of a matrix; @pxref{Reducing}). The
  25732. result of the command will be a vector of numbers, one for each column
  25733. in the input data. The @kbd{C-x * _} (@code{calc-grab-sum-across}) command
  25734. similarly grabs a rectangle and sums its rows by executing @w{@kbd{V R _ +}}.
  25735. As well as being more convenient, @kbd{C-x * :} and @kbd{C-x * _} are also
  25736. much faster because they don't actually place the grabbed vector on
  25737. the stack. In a @kbd{C-x * r V R : +} sequence, formatting the vector
  25738. for display on the stack takes a large fraction of the total time
  25739. (unless you have planned ahead and used @kbd{v .} and @kbd{t .} modes).
  25740. For example, suppose we have a column of numbers in a file which we
  25741. wish to sum. Go to one corner of the column and press @kbd{C-@@} to
  25742. set the mark; go to the other corner and type @kbd{C-x * :}. Since there
  25743. is only one column, the result will be a vector of one number, the sum.
  25744. (You can type @kbd{v u} to unpack this vector into a plain number if
  25745. you want to do further arithmetic with it.)
  25746. To compute the product of the column of numbers, we would have to do
  25747. it ``by hand'' since there's no special grab-and-multiply command.
  25748. Use @kbd{C-x * r} to grab the column of numbers into the calculator in
  25749. the form of a column matrix. The statistics command @kbd{u *} is a
  25750. handy way to find the product of a vector or matrix of numbers.
  25751. @xref{Statistical Operations}. Another approach would be to use
  25752. an explicit column reduction command, @kbd{V R : *}.
  25753. @node Yanking Into Buffers, X Cut and Paste, Grabbing From Buffers, Kill and Yank
  25754. @section Yanking into Other Buffers
  25755. @noindent
  25756. @kindex y
  25757. @pindex calc-copy-to-buffer
  25758. The plain @kbd{y} (@code{calc-copy-to-buffer}) command inserts the number
  25759. at the top of the stack into the most recently used normal editing buffer.
  25760. (More specifically, this is the most recently used buffer which is displayed
  25761. in a window and whose name does not begin with @samp{*}. If there is no
  25762. such buffer, this is the most recently used buffer except for Calculator
  25763. and Calc Trail buffers.) The number is inserted exactly as it appears and
  25764. without a newline. (If line-numbering is enabled, the line number is
  25765. normally not included.) The number is @emph{not} removed from the stack.
  25766. With a prefix argument, @kbd{y} inserts several numbers, one per line.
  25767. A positive argument inserts the specified number of values from the top
  25768. of the stack. A negative argument inserts the @expr{n}th value from the
  25769. top of the stack. An argument of zero inserts the entire stack. Note
  25770. that @kbd{y} with an argument of 1 is slightly different from @kbd{y}
  25771. with no argument; the former always copies full lines, whereas the
  25772. latter strips off the trailing newline.
  25773. With a lone @kbd{C-u} as a prefix argument, @kbd{y} @emph{replaces} the
  25774. region in the other buffer with the yanked text, then quits the
  25775. Calculator, leaving you in that buffer. A typical use would be to use
  25776. @kbd{C-x * g} to read a region of data into the Calculator, operate on the
  25777. data to produce a new matrix, then type @kbd{C-u y} to replace the
  25778. original data with the new data. One might wish to alter the matrix
  25779. display style (@pxref{Vector and Matrix Formats}) or change the current
  25780. display language (@pxref{Language Modes}) before doing this. Also, note
  25781. that this command replaces a linear region of text (as grabbed by
  25782. @kbd{C-x * g}), not a rectangle (as grabbed by @kbd{C-x * r}).
  25783. If the editing buffer is in overwrite (as opposed to insert) mode,
  25784. and the @kbd{C-u} prefix was not used, then the yanked number will
  25785. overwrite the characters following point rather than being inserted
  25786. before those characters. The usual conventions of overwrite mode
  25787. are observed; for example, characters will be inserted at the end of
  25788. a line rather than overflowing onto the next line. Yanking a multi-line
  25789. object such as a matrix in overwrite mode overwrites the next @var{n}
  25790. lines in the buffer, lengthening or shortening each line as necessary.
  25791. Finally, if the thing being yanked is a simple integer or floating-point
  25792. number (like @samp{-1.2345e-3}) and the characters following point also
  25793. make up such a number, then Calc will replace that number with the new
  25794. number, lengthening or shortening as necessary. The concept of
  25795. ``overwrite mode'' has thus been generalized from overwriting characters
  25796. to overwriting one complete number with another.
  25797. @kindex C-x * y
  25798. The @kbd{C-x * y} key sequence is equivalent to @kbd{y} except that
  25799. it can be typed anywhere, not just in Calc. This provides an easy
  25800. way to guarantee that Calc knows which editing buffer you want to use!
  25801. @node X Cut and Paste, , Yanking Into Buffers, Kill and Yank
  25802. @section X Cut and Paste
  25803. @noindent
  25804. If you are using Emacs with the X window system, there is an easier
  25805. way to move small amounts of data into and out of the calculator:
  25806. Use the mouse-oriented cut and paste facilities of X.
  25807. The default bindings for a three-button mouse cause the left button
  25808. to move the Emacs cursor to the given place, the right button to
  25809. select the text between the cursor and the clicked location, and
  25810. the middle button to yank the selection into the buffer at the
  25811. clicked location. So, if you have a Calc window and an editing
  25812. window on your Emacs screen, you can use left-click/right-click
  25813. to select a number, vector, or formula from one window, then
  25814. middle-click to paste that value into the other window. When you
  25815. paste text into the Calc window, Calc interprets it as an algebraic
  25816. entry. It doesn't matter where you click in the Calc window; the
  25817. new value is always pushed onto the top of the stack.
  25818. The @code{xterm} program that is typically used for general-purpose
  25819. shell windows in X interprets the mouse buttons in the same way.
  25820. So you can use the mouse to move data between Calc and any other
  25821. Unix program. One nice feature of @code{xterm} is that a double
  25822. left-click selects one word, and a triple left-click selects a
  25823. whole line. So you can usually transfer a single number into Calc
  25824. just by double-clicking on it in the shell, then middle-clicking
  25825. in the Calc window.
  25826. @node Keypad Mode, Embedded Mode, Kill and Yank, Top
  25827. @chapter Keypad Mode
  25828. @noindent
  25829. @kindex C-x * k
  25830. @pindex calc-keypad
  25831. The @kbd{C-x * k} (@code{calc-keypad}) command starts the Calculator
  25832. and displays a picture of a calculator-style keypad. If you are using
  25833. the X window system, you can click on any of the ``keys'' in the
  25834. keypad using the left mouse button to operate the calculator.
  25835. The original window remains the selected window; in Keypad mode
  25836. you can type in your file while simultaneously performing
  25837. calculations with the mouse.
  25838. @pindex full-calc-keypad
  25839. If you have used @kbd{C-x * b} first, @kbd{C-x * k} instead invokes
  25840. the @code{full-calc-keypad} command, which takes over the whole
  25841. Emacs screen and displays the keypad, the Calc stack, and the Calc
  25842. trail all at once. This mode would normally be used when running
  25843. Calc standalone (@pxref{Standalone Operation}).
  25844. If you aren't using the X window system, you must switch into
  25845. the @file{*Calc Keypad*} window, place the cursor on the desired
  25846. ``key,'' and type @key{SPC} or @key{RET}. If you think this
  25847. is easier than using Calc normally, go right ahead.
  25848. Calc commands are more or less the same in Keypad mode. Certain
  25849. keypad keys differ slightly from the corresponding normal Calc
  25850. keystrokes; all such deviations are described below.
  25851. Keypad mode includes many more commands than will fit on the keypad
  25852. at once. Click the right mouse button [@code{calc-keypad-menu}]
  25853. to switch to the next menu. The bottom five rows of the keypad
  25854. stay the same; the top three rows change to a new set of commands.
  25855. To return to earlier menus, click the middle mouse button
  25856. [@code{calc-keypad-menu-back}] or simply advance through the menus
  25857. until you wrap around. Typing @key{TAB} inside the keypad window
  25858. is equivalent to clicking the right mouse button there.
  25859. You can always click the @key{EXEC} button and type any normal
  25860. Calc key sequence. This is equivalent to switching into the
  25861. Calc buffer, typing the keys, then switching back to your
  25862. original buffer.
  25863. @menu
  25864. * Keypad Main Menu::
  25865. * Keypad Functions Menu::
  25866. * Keypad Binary Menu::
  25867. * Keypad Vectors Menu::
  25868. * Keypad Modes Menu::
  25869. @end menu
  25870. @node Keypad Main Menu, Keypad Functions Menu, Keypad Mode, Keypad Mode
  25871. @section Main Menu
  25872. @smallexample
  25873. @group
  25874. |----+----+--Calc---+----+----1
  25875. |FLR |CEIL|RND |TRNC|CLN2|FLT |
  25876. |----+----+----+----+----+----|
  25877. | LN |EXP | |ABS |IDIV|MOD |
  25878. |----+----+----+----+----+----|
  25879. |SIN |COS |TAN |SQRT|y^x |1/x |
  25880. |----+----+----+----+----+----|
  25881. | ENTER |+/- |EEX |UNDO| <- |
  25882. |-----+---+-+--+--+-+---++----|
  25883. | INV | 7 | 8 | 9 | / |
  25884. |-----+-----+-----+-----+-----|
  25885. | HYP | 4 | 5 | 6 | * |
  25886. |-----+-----+-----+-----+-----|
  25887. |EXEC | 1 | 2 | 3 | - |
  25888. |-----+-----+-----+-----+-----|
  25889. | OFF | 0 | . | PI | + |
  25890. |-----+-----+-----+-----+-----+
  25891. @end group
  25892. @end smallexample
  25893. @noindent
  25894. This is the menu that appears the first time you start Keypad mode.
  25895. It will show up in a vertical window on the right side of your screen.
  25896. Above this menu is the traditional Calc stack display. On a 24-line
  25897. screen you will be able to see the top three stack entries.
  25898. The ten digit keys, decimal point, and @key{EEX} key are used for
  25899. entering numbers in the obvious way. @key{EEX} begins entry of an
  25900. exponent in scientific notation. Just as with regular Calc, the
  25901. number is pushed onto the stack as soon as you press @key{ENTER}
  25902. or any other function key.
  25903. The @key{+/-} key corresponds to normal Calc's @kbd{n} key. During
  25904. numeric entry it changes the sign of the number or of the exponent.
  25905. At other times it changes the sign of the number on the top of the
  25906. stack.
  25907. The @key{INV} and @key{HYP} keys modify other keys. As well as
  25908. having the effects described elsewhere in this manual, Keypad mode
  25909. defines several other ``inverse'' operations. These are described
  25910. below and in the following sections.
  25911. The @key{ENTER} key finishes the current numeric entry, or otherwise
  25912. duplicates the top entry on the stack.
  25913. The @key{UNDO} key undoes the most recent Calc operation.
  25914. @kbd{INV UNDO} is the ``redo'' command, and @kbd{HYP UNDO} is
  25915. ``last arguments'' (@kbd{M-@key{RET}}).
  25916. The @key{<-} key acts as a ``backspace'' during numeric entry.
  25917. At other times it removes the top stack entry. @kbd{INV <-}
  25918. clears the entire stack. @kbd{HYP <-} takes an integer from
  25919. the stack, then removes that many additional stack elements.
  25920. The @key{EXEC} key prompts you to enter any keystroke sequence
  25921. that would normally work in Calc mode. This can include a
  25922. numeric prefix if you wish. It is also possible simply to
  25923. switch into the Calc window and type commands in it; there is
  25924. nothing ``magic'' about this window when Keypad mode is active.
  25925. The other keys in this display perform their obvious calculator
  25926. functions. @key{CLN2} rounds the top-of-stack by temporarily
  25927. reducing the precision by 2 digits. @key{FLT} converts an
  25928. integer or fraction on the top of the stack to floating-point.
  25929. The @key{INV} and @key{HYP} keys combined with several of these keys
  25930. give you access to some common functions even if the appropriate menu
  25931. is not displayed. Obviously you don't need to learn these keys
  25932. unless you find yourself wasting time switching among the menus.
  25933. @table @kbd
  25934. @item INV +/-
  25935. is the same as @key{1/x}.
  25936. @item INV +
  25937. is the same as @key{SQRT}.
  25938. @item INV -
  25939. is the same as @key{CONJ}.
  25940. @item INV *
  25941. is the same as @key{y^x}.
  25942. @item INV /
  25943. is the same as @key{INV y^x} (the @expr{x}th root of @expr{y}).
  25944. @item HYP/INV 1
  25945. are the same as @key{SIN} / @kbd{INV SIN}.
  25946. @item HYP/INV 2
  25947. are the same as @key{COS} / @kbd{INV COS}.
  25948. @item HYP/INV 3
  25949. are the same as @key{TAN} / @kbd{INV TAN}.
  25950. @item INV/HYP 4
  25951. are the same as @key{LN} / @kbd{HYP LN}.
  25952. @item INV/HYP 5
  25953. are the same as @key{EXP} / @kbd{HYP EXP}.
  25954. @item INV 6
  25955. is the same as @key{ABS}.
  25956. @item INV 7
  25957. is the same as @key{RND} (@code{calc-round}).
  25958. @item INV 8
  25959. is the same as @key{CLN2}.
  25960. @item INV 9
  25961. is the same as @key{FLT} (@code{calc-float}).
  25962. @item INV 0
  25963. is the same as @key{IMAG}.
  25964. @item INV .
  25965. is the same as @key{PREC}.
  25966. @item INV ENTER
  25967. is the same as @key{SWAP}.
  25968. @item HYP ENTER
  25969. is the same as @key{RLL3}.
  25970. @item INV HYP ENTER
  25971. is the same as @key{OVER}.
  25972. @item HYP +/-
  25973. packs the top two stack entries as an error form.
  25974. @item HYP EEX
  25975. packs the top two stack entries as a modulo form.
  25976. @item INV EEX
  25977. creates an interval form; this removes an integer which is one
  25978. of 0 @samp{[]}, 1 @samp{[)}, 2 @samp{(]} or 3 @samp{()}, followed
  25979. by the two limits of the interval.
  25980. @end table
  25981. The @kbd{OFF} key turns Calc off; typing @kbd{C-x * k} or @kbd{C-x * *}
  25982. again has the same effect. This is analogous to typing @kbd{q} or
  25983. hitting @kbd{C-x * c} again in the normal calculator. If Calc is
  25984. running standalone (the @code{full-calc-keypad} command appeared in the
  25985. command line that started Emacs), then @kbd{OFF} is replaced with
  25986. @kbd{EXIT}; clicking on this actually exits Emacs itself.
  25987. @node Keypad Functions Menu, Keypad Binary Menu, Keypad Main Menu, Keypad Mode
  25988. @section Functions Menu
  25989. @smallexample
  25990. @group
  25991. |----+----+----+----+----+----2
  25992. |IGAM|BETA|IBET|ERF |BESJ|BESY|
  25993. |----+----+----+----+----+----|
  25994. |IMAG|CONJ| RE |ATN2|RAND|RAGN|
  25995. |----+----+----+----+----+----|
  25996. |GCD |FACT|DFCT|BNOM|PERM|NXTP|
  25997. |----+----+----+----+----+----|
  25998. @end group
  25999. @end smallexample
  26000. @noindent
  26001. This menu provides various operations from the @kbd{f} and @kbd{k}
  26002. prefix keys.
  26003. @key{IMAG} multiplies the number on the stack by the imaginary
  26004. number @expr{i = (0, 1)}.
  26005. @key{RE} extracts the real part a complex number. @kbd{INV RE}
  26006. extracts the imaginary part.
  26007. @key{RAND} takes a number from the top of the stack and computes
  26008. a random number greater than or equal to zero but less than that
  26009. number. (@xref{Random Numbers}.) @key{RAGN} is the ``random
  26010. again'' command; it computes another random number using the
  26011. same limit as last time.
  26012. @key{INV GCD} computes the LCM (least common multiple) function.
  26013. @key{INV FACT} is the gamma function.
  26014. @texline @math{\Gamma(x) = (x-1)!}.
  26015. @infoline @expr{gamma(x) = (x-1)!}.
  26016. @key{PERM} is the number-of-permutations function, which is on the
  26017. @kbd{H k c} key in normal Calc.
  26018. @key{NXTP} finds the next prime after a number. @kbd{INV NXTP}
  26019. finds the previous prime.
  26020. @node Keypad Binary Menu, Keypad Vectors Menu, Keypad Functions Menu, Keypad Mode
  26021. @section Binary Menu
  26022. @smallexample
  26023. @group
  26024. |----+----+----+----+----+----3
  26025. |AND | OR |XOR |NOT |LSH |RSH |
  26026. |----+----+----+----+----+----|
  26027. |DEC |HEX |OCT |BIN |WSIZ|ARSH|
  26028. |----+----+----+----+----+----|
  26029. | A | B | C | D | E | F |
  26030. |----+----+----+----+----+----|
  26031. @end group
  26032. @end smallexample
  26033. @noindent
  26034. The keys in this menu perform operations on binary integers.
  26035. Note that both logical and arithmetic right-shifts are provided.
  26036. @key{INV LSH} rotates one bit to the left.
  26037. The ``difference'' function (normally on @kbd{b d}) is on @key{INV AND}.
  26038. The ``clip'' function (normally on @w{@kbd{b c}}) is on @key{INV NOT}.
  26039. The @key{DEC}, @key{HEX}, @key{OCT}, and @key{BIN} keys select the
  26040. current radix for display and entry of numbers: Decimal, hexadecimal,
  26041. octal, or binary. The six letter keys @key{A} through @key{F} are used
  26042. for entering hexadecimal numbers.
  26043. The @key{WSIZ} key displays the current word size for binary operations
  26044. and allows you to enter a new word size. You can respond to the prompt
  26045. using either the keyboard or the digits and @key{ENTER} from the keypad.
  26046. The initial word size is 32 bits.
  26047. @node Keypad Vectors Menu, Keypad Modes Menu, Keypad Binary Menu, Keypad Mode
  26048. @section Vectors Menu
  26049. @smallexample
  26050. @group
  26051. |----+----+----+----+----+----4
  26052. |SUM |PROD|MAX |MAP*|MAP^|MAP$|
  26053. |----+----+----+----+----+----|
  26054. |MINV|MDET|MTRN|IDNT|CRSS|"x" |
  26055. |----+----+----+----+----+----|
  26056. |PACK|UNPK|INDX|BLD |LEN |... |
  26057. |----+----+----+----+----+----|
  26058. @end group
  26059. @end smallexample
  26060. @noindent
  26061. The keys in this menu operate on vectors and matrices.
  26062. @key{PACK} removes an integer @var{n} from the top of the stack;
  26063. the next @var{n} stack elements are removed and packed into a vector,
  26064. which is replaced onto the stack. Thus the sequence
  26065. @kbd{1 ENTER 3 ENTER 5 ENTER 3 PACK} enters the vector
  26066. @samp{[1, 3, 5]} onto the stack. To enter a matrix, build each row
  26067. on the stack as a vector, then use a final @key{PACK} to collect the
  26068. rows into a matrix.
  26069. @key{UNPK} unpacks the vector on the stack, pushing each of its
  26070. components separately.
  26071. @key{INDX} removes an integer @var{n}, then builds a vector of
  26072. integers from 1 to @var{n}. @kbd{INV INDX} takes three numbers
  26073. from the stack: The vector size @var{n}, the starting number,
  26074. and the increment. @kbd{BLD} takes an integer @var{n} and any
  26075. value @var{x} and builds a vector of @var{n} copies of @var{x}.
  26076. @key{IDNT} removes an integer @var{n}, then builds an @var{n}-by-@var{n}
  26077. identity matrix.
  26078. @key{LEN} replaces a vector by its length, an integer.
  26079. @key{...} turns on or off ``abbreviated'' display mode for large vectors.
  26080. @key{MINV}, @key{MDET}, @key{MTRN}, and @key{CROSS} are the matrix
  26081. inverse, determinant, and transpose, and vector cross product.
  26082. @key{SUM} replaces a vector by the sum of its elements. It is
  26083. equivalent to @kbd{u +} in normal Calc (@pxref{Statistical Operations}).
  26084. @key{PROD} computes the product of the elements of a vector, and
  26085. @key{MAX} computes the maximum of all the elements of a vector.
  26086. @key{INV SUM} computes the alternating sum of the first element
  26087. minus the second, plus the third, minus the fourth, and so on.
  26088. @key{INV MAX} computes the minimum of the vector elements.
  26089. @key{HYP SUM} computes the mean of the vector elements.
  26090. @key{HYP PROD} computes the sample standard deviation.
  26091. @key{HYP MAX} computes the median.
  26092. @key{MAP*} multiplies two vectors elementwise. It is equivalent
  26093. to the @kbd{V M *} command. @key{MAP^} computes powers elementwise.
  26094. The arguments must be vectors of equal length, or one must be a vector
  26095. and the other must be a plain number. For example, @kbd{2 MAP^} squares
  26096. all the elements of a vector.
  26097. @key{MAP$} maps the formula on the top of the stack across the
  26098. vector in the second-to-top position. If the formula contains
  26099. several variables, Calc takes that many vectors starting at the
  26100. second-to-top position and matches them to the variables in
  26101. alphabetical order. The result is a vector of the same size as
  26102. the input vectors, whose elements are the formula evaluated with
  26103. the variables set to the various sets of numbers in those vectors.
  26104. For example, you could simulate @key{MAP^} using @key{MAP$} with
  26105. the formula @samp{x^y}.
  26106. The @kbd{"x"} key pushes the variable name @expr{x} onto the
  26107. stack. To build the formula @expr{x^2 + 6}, you would use the
  26108. key sequence @kbd{"x" 2 y^x 6 +}. This formula would then be
  26109. suitable for use with the @key{MAP$} key described above.
  26110. With @key{INV}, @key{HYP}, or @key{INV} and @key{HYP}, the
  26111. @kbd{"x"} key pushes the variable names @expr{y}, @expr{z}, and
  26112. @expr{t}, respectively.
  26113. @node Keypad Modes Menu, , Keypad Vectors Menu, Keypad Mode
  26114. @section Modes Menu
  26115. @smallexample
  26116. @group
  26117. |----+----+----+----+----+----5
  26118. |FLT |FIX |SCI |ENG |GRP | |
  26119. |----+----+----+----+----+----|
  26120. |RAD |DEG |FRAC|POLR|SYMB|PREC|
  26121. |----+----+----+----+----+----|
  26122. |SWAP|RLL3|RLL4|OVER|STO |RCL |
  26123. |----+----+----+----+----+----|
  26124. @end group
  26125. @end smallexample
  26126. @noindent
  26127. The keys in this menu manipulate modes, variables, and the stack.
  26128. The @key{FLT}, @key{FIX}, @key{SCI}, and @key{ENG} keys select
  26129. floating-point, fixed-point, scientific, or engineering notation.
  26130. @key{FIX} displays two digits after the decimal by default; the
  26131. others display full precision. With the @key{INV} prefix, these
  26132. keys pop a number-of-digits argument from the stack.
  26133. The @key{GRP} key turns grouping of digits with commas on or off.
  26134. @kbd{INV GRP} enables grouping to the right of the decimal point as
  26135. well as to the left.
  26136. The @key{RAD} and @key{DEG} keys switch between radians and degrees
  26137. for trigonometric functions.
  26138. The @key{FRAC} key turns Fraction mode on or off. This affects
  26139. whether commands like @kbd{/} with integer arguments produce
  26140. fractional or floating-point results.
  26141. The @key{POLR} key turns Polar mode on or off, determining whether
  26142. polar or rectangular complex numbers are used by default.
  26143. The @key{SYMB} key turns Symbolic mode on or off, in which
  26144. operations that would produce inexact floating-point results
  26145. are left unevaluated as algebraic formulas.
  26146. The @key{PREC} key selects the current precision. Answer with
  26147. the keyboard or with the keypad digit and @key{ENTER} keys.
  26148. The @key{SWAP} key exchanges the top two stack elements.
  26149. The @key{RLL3} key rotates the top three stack elements upwards.
  26150. The @key{RLL4} key rotates the top four stack elements upwards.
  26151. The @key{OVER} key duplicates the second-to-top stack element.
  26152. The @key{STO} and @key{RCL} keys are analogous to @kbd{s t} and
  26153. @kbd{s r} in regular Calc. @xref{Store and Recall}. Click the
  26154. @key{STO} or @key{RCL} key, then one of the ten digits. (Named
  26155. variables are not available in Keypad mode.) You can also use,
  26156. for example, @kbd{STO + 3} to add to register 3.
  26157. @node Embedded Mode, Programming, Keypad Mode, Top
  26158. @chapter Embedded Mode
  26159. @noindent
  26160. Embedded mode in Calc provides an alternative to copying numbers
  26161. and formulas back and forth between editing buffers and the Calc
  26162. stack. In Embedded mode, your editing buffer becomes temporarily
  26163. linked to the stack and this copying is taken care of automatically.
  26164. @menu
  26165. * Basic Embedded Mode::
  26166. * More About Embedded Mode::
  26167. * Assignments in Embedded Mode::
  26168. * Mode Settings in Embedded Mode::
  26169. * Customizing Embedded Mode::
  26170. @end menu
  26171. @node Basic Embedded Mode, More About Embedded Mode, Embedded Mode, Embedded Mode
  26172. @section Basic Embedded Mode
  26173. @noindent
  26174. @kindex C-x * e
  26175. @pindex calc-embedded
  26176. To enter Embedded mode, position the Emacs point (cursor) on a
  26177. formula in any buffer and press @kbd{C-x * e} (@code{calc-embedded}).
  26178. Note that @kbd{C-x * e} is not to be used in the Calc stack buffer
  26179. like most Calc commands, but rather in regular editing buffers that
  26180. are visiting your own files.
  26181. Calc will try to guess an appropriate language based on the major mode
  26182. of the editing buffer. (@xref{Language Modes}.) If the current buffer is
  26183. in @code{latex-mode}, for example, Calc will set its language to @LaTeX{}.
  26184. Similarly, Calc will use @TeX{} language for @code{tex-mode},
  26185. @code{plain-tex-mode} and @code{context-mode}, C language for
  26186. @code{c-mode} and @code{c++-mode}, FORTRAN language for
  26187. @code{fortran-mode} and @code{f90-mode}, Pascal for @code{pascal-mode},
  26188. and eqn for @code{nroff-mode} (@pxref{Customizing Calc}).
  26189. These can be overridden with Calc's mode
  26190. changing commands (@pxref{Mode Settings in Embedded Mode}). If no
  26191. suitable language is available, Calc will continue with its current language.
  26192. Calc normally scans backward and forward in the buffer for the
  26193. nearest opening and closing @dfn{formula delimiters}. The simplest
  26194. delimiters are blank lines. Other delimiters that Embedded mode
  26195. understands are:
  26196. @enumerate
  26197. @item
  26198. The @TeX{} and @LaTeX{} math delimiters @samp{$ $}, @samp{$$ $$},
  26199. @samp{\[ \]}, and @samp{\( \)};
  26200. @item
  26201. Lines beginning with @samp{\begin} and @samp{\end} (except matrix delimiters);
  26202. @item
  26203. Lines beginning with @samp{@@} (Texinfo delimiters).
  26204. @item
  26205. Lines beginning with @samp{.EQ} and @samp{.EN} (@dfn{eqn} delimiters);
  26206. @item
  26207. Lines containing a single @samp{%} or @samp{.\"} symbol and nothing else.
  26208. @end enumerate
  26209. @xref{Customizing Embedded Mode}, to see how to make Calc recognize
  26210. your own favorite delimiters. Delimiters like @samp{$ $} can appear
  26211. on their own separate lines or in-line with the formula.
  26212. If you give a positive or negative numeric prefix argument, Calc
  26213. instead uses the current point as one end of the formula, and includes
  26214. that many lines forward or backward (respectively, including the current
  26215. line). Explicit delimiters are not necessary in this case.
  26216. With a prefix argument of zero, Calc uses the current region (delimited
  26217. by point and mark) instead of formula delimiters. With a prefix
  26218. argument of @kbd{C-u} only, Calc uses the current line as the formula.
  26219. @kindex C-x * w
  26220. @pindex calc-embedded-word
  26221. The @kbd{C-x * w} (@code{calc-embedded-word}) command will start Embedded
  26222. mode on the current ``word''; in this case Calc will scan for the first
  26223. non-numeric character (i.e., the first character that is not a digit,
  26224. sign, decimal point, or upper- or lower-case @samp{e}) forward and
  26225. backward to delimit the formula.
  26226. When you enable Embedded mode for a formula, Calc reads the text
  26227. between the delimiters and tries to interpret it as a Calc formula.
  26228. Calc can generally identify @TeX{} formulas and
  26229. Big-style formulas even if the language mode is wrong. If Calc
  26230. can't make sense of the formula, it beeps and refuses to enter
  26231. Embedded mode. But if the current language is wrong, Calc can
  26232. sometimes parse the formula successfully (but incorrectly);
  26233. for example, the C expression @samp{atan(a[1])} can be parsed
  26234. in Normal language mode, but the @code{atan} won't correspond to
  26235. the built-in @code{arctan} function, and the @samp{a[1]} will be
  26236. interpreted as @samp{a} times the vector @samp{[1]}!
  26237. If you press @kbd{C-x * e} or @kbd{C-x * w} to activate an embedded
  26238. formula which is blank, say with the cursor on the space between
  26239. the two delimiters @samp{$ $}, Calc will immediately prompt for
  26240. an algebraic entry.
  26241. Only one formula in one buffer can be enabled at a time. If you
  26242. move to another area of the current buffer and give Calc commands,
  26243. Calc turns Embedded mode off for the old formula and then tries
  26244. to restart Embedded mode at the new position. Other buffers are
  26245. not affected by Embedded mode.
  26246. When Embedded mode begins, Calc pushes the current formula onto
  26247. the stack. No Calc stack window is created; however, Calc copies
  26248. the top-of-stack position into the original buffer at all times.
  26249. You can create a Calc window by hand with @kbd{C-x * o} if you
  26250. find you need to see the entire stack.
  26251. For example, typing @kbd{C-x * e} while somewhere in the formula
  26252. @samp{n>2} in the following line enables Embedded mode on that
  26253. inequality:
  26254. @example
  26255. We define $F_n = F_(n-1)+F_(n-2)$ for all $n>2$.
  26256. @end example
  26257. @noindent
  26258. The formula @expr{n>2} will be pushed onto the Calc stack, and
  26259. the top of stack will be copied back into the editing buffer.
  26260. This means that spaces will appear around the @samp{>} symbol
  26261. to match Calc's usual display style:
  26262. @example
  26263. We define $F_n = F_(n-1)+F_(n-2)$ for all $n > 2$.
  26264. @end example
  26265. @noindent
  26266. No spaces have appeared around the @samp{+} sign because it's
  26267. in a different formula, one which we have not yet touched with
  26268. Embedded mode.
  26269. Now that Embedded mode is enabled, keys you type in this buffer
  26270. are interpreted as Calc commands. At this point we might use
  26271. the ``commute'' command @kbd{j C} to reverse the inequality.
  26272. This is a selection-based command for which we first need to
  26273. move the cursor onto the operator (@samp{>} in this case) that
  26274. needs to be commuted.
  26275. @example
  26276. We define $F_n = F_(n-1)+F_(n-2)$ for all $2 < n$.
  26277. @end example
  26278. The @kbd{C-x * o} command is a useful way to open a Calc window
  26279. without actually selecting that window. Giving this command
  26280. verifies that @samp{2 < n} is also on the Calc stack. Typing
  26281. @kbd{17 @key{RET}} would produce:
  26282. @example
  26283. We define $F_n = F_(n-1)+F_(n-2)$ for all $17$.
  26284. @end example
  26285. @noindent
  26286. with @samp{2 < n} and @samp{17} on the stack; typing @key{TAB}
  26287. at this point will exchange the two stack values and restore
  26288. @samp{2 < n} to the embedded formula. Even though you can't
  26289. normally see the stack in Embedded mode, it is still there and
  26290. it still operates in the same way. But, as with old-fashioned
  26291. RPN calculators, you can only see the value at the top of the
  26292. stack at any given time (unless you use @kbd{C-x * o}).
  26293. Typing @kbd{C-x * e} again turns Embedded mode off. The Calc
  26294. window reveals that the formula @w{@samp{2 < n}} is automatically
  26295. removed from the stack, but the @samp{17} is not. Entering
  26296. Embedded mode always pushes one thing onto the stack, and
  26297. leaving Embedded mode always removes one thing. Anything else
  26298. that happens on the stack is entirely your business as far as
  26299. Embedded mode is concerned.
  26300. If you press @kbd{C-x * e} in the wrong place by accident, it is
  26301. possible that Calc will be able to parse the nearby text as a
  26302. formula and will mangle that text in an attempt to redisplay it
  26303. ``properly'' in the current language mode. If this happens,
  26304. press @kbd{C-x * e} again to exit Embedded mode, then give the
  26305. regular Emacs ``undo'' command (@kbd{C-_} or @kbd{C-x u}) to put
  26306. the text back the way it was before Calc edited it. Note that Calc's
  26307. own Undo command (typed before you turn Embedded mode back off)
  26308. will not do you any good, because as far as Calc is concerned
  26309. you haven't done anything with this formula yet.
  26310. @node More About Embedded Mode, Assignments in Embedded Mode, Basic Embedded Mode, Embedded Mode
  26311. @section More About Embedded Mode
  26312. @noindent
  26313. When Embedded mode ``activates'' a formula, i.e., when it examines
  26314. the formula for the first time since the buffer was created or
  26315. loaded, Calc tries to sense the language in which the formula was
  26316. written. If the formula contains any @LaTeX{}-like @samp{\} sequences,
  26317. it is parsed (i.e., read) in @LaTeX{} mode. If the formula appears to
  26318. be written in multi-line Big mode, it is parsed in Big mode. Otherwise,
  26319. it is parsed according to the current language mode.
  26320. Note that Calc does not change the current language mode according
  26321. the formula it reads in. Even though it can read a @LaTeX{} formula when
  26322. not in @LaTeX{} mode, it will immediately rewrite this formula using
  26323. whatever language mode is in effect.
  26324. @tex
  26325. \bigskip
  26326. @end tex
  26327. @kindex d p
  26328. @pindex calc-show-plain
  26329. Calc's parser is unable to read certain kinds of formulas. For
  26330. example, with @kbd{v ]} (@code{calc-matrix-brackets}) you can
  26331. specify matrix display styles which the parser is unable to
  26332. recognize as matrices. The @kbd{d p} (@code{calc-show-plain})
  26333. command turns on a mode in which a ``plain'' version of a
  26334. formula is placed in front of the fully-formatted version.
  26335. When Calc reads a formula that has such a plain version in
  26336. front, it reads the plain version and ignores the formatted
  26337. version.
  26338. Plain formulas are preceded and followed by @samp{%%%} signs
  26339. by default. This notation has the advantage that the @samp{%}
  26340. character begins a comment in @TeX{} and @LaTeX{}, so if your formula is
  26341. embedded in a @TeX{} or @LaTeX{} document its plain version will be
  26342. invisible in the final printed copy. Certain major modes have different
  26343. delimiters to ensure that the ``plain'' version will be
  26344. in a comment for those modes, also.
  26345. See @ref{Customizing Embedded Mode} to see how to change the ``plain''
  26346. formula delimiters.
  26347. There are several notations which Calc's parser for ``big''
  26348. formatted formulas can't yet recognize. In particular, it can't
  26349. read the large symbols for @code{sum}, @code{prod}, and @code{integ},
  26350. and it can't handle @samp{=>} with the righthand argument omitted.
  26351. Also, Calc won't recognize special formats you have defined with
  26352. the @kbd{Z C} command (@pxref{User-Defined Compositions}). In
  26353. these cases it is important to use ``plain'' mode to make sure
  26354. Calc will be able to read your formula later.
  26355. Another example where ``plain'' mode is important is if you have
  26356. specified a float mode with few digits of precision. Normally
  26357. any digits that are computed but not displayed will simply be
  26358. lost when you save and re-load your embedded buffer, but ``plain''
  26359. mode allows you to make sure that the complete number is present
  26360. in the file as well as the rounded-down number.
  26361. @tex
  26362. \bigskip
  26363. @end tex
  26364. Embedded buffers remember active formulas for as long as they
  26365. exist in Emacs memory. Suppose you have an embedded formula
  26366. which is @cpi{} to the normal 12 decimal places, and then
  26367. type @w{@kbd{C-u 5 d n}} to display only five decimal places.
  26368. If you then type @kbd{d n}, all 12 places reappear because the
  26369. full number is still there on the Calc stack. More surprisingly,
  26370. even if you exit Embedded mode and later re-enter it for that
  26371. formula, typing @kbd{d n} will restore all 12 places because
  26372. each buffer remembers all its active formulas. However, if you
  26373. save the buffer in a file and reload it in a new Emacs session,
  26374. all non-displayed digits will have been lost unless you used
  26375. ``plain'' mode.
  26376. @tex
  26377. \bigskip
  26378. @end tex
  26379. In some applications of Embedded mode, you will want to have a
  26380. sequence of copies of a formula that show its evolution as you
  26381. work on it. For example, you might want to have a sequence
  26382. like this in your file (elaborating here on the example from
  26383. the ``Getting Started'' chapter):
  26384. @smallexample
  26385. The derivative of
  26386. ln(ln(x))
  26387. is
  26388. @r{(the derivative of }ln(ln(x))@r{)}
  26389. whose value at x = 2 is
  26390. @r{(the value)}
  26391. and at x = 3 is
  26392. @r{(the value)}
  26393. @end smallexample
  26394. @kindex C-x * d
  26395. @pindex calc-embedded-duplicate
  26396. The @kbd{C-x * d} (@code{calc-embedded-duplicate}) command is a
  26397. handy way to make sequences like this. If you type @kbd{C-x * d},
  26398. the formula under the cursor (which may or may not have Embedded
  26399. mode enabled for it at the time) is copied immediately below and
  26400. Embedded mode is then enabled for that copy.
  26401. For this example, you would start with just
  26402. @smallexample
  26403. The derivative of
  26404. ln(ln(x))
  26405. @end smallexample
  26406. @noindent
  26407. and press @kbd{C-x * d} with the cursor on this formula. The result
  26408. is
  26409. @smallexample
  26410. The derivative of
  26411. ln(ln(x))
  26412. ln(ln(x))
  26413. @end smallexample
  26414. @noindent
  26415. with the second copy of the formula enabled in Embedded mode.
  26416. You can now press @kbd{a d x @key{RET}} to take the derivative, and
  26417. @kbd{C-x * d C-x * d} to make two more copies of the derivative.
  26418. To complete the computations, type @kbd{3 s l x @key{RET}} to evaluate
  26419. the last formula, then move up to the second-to-last formula
  26420. and type @kbd{2 s l x @key{RET}}.
  26421. Finally, you would want to press @kbd{C-x * e} to exit Embedded
  26422. mode, then go up and insert the necessary text in between the
  26423. various formulas and numbers.
  26424. @tex
  26425. \bigskip
  26426. @end tex
  26427. @kindex C-x * f
  26428. @kindex C-x * '
  26429. @pindex calc-embedded-new-formula
  26430. The @kbd{C-x * f} (@code{calc-embedded-new-formula}) command
  26431. creates a new embedded formula at the current point. It inserts
  26432. some default delimiters, which are usually just blank lines,
  26433. and then does an algebraic entry to get the formula (which is
  26434. then enabled for Embedded mode). This is just shorthand for
  26435. typing the delimiters yourself, positioning the cursor between
  26436. the new delimiters, and pressing @kbd{C-x * e}. The key sequence
  26437. @kbd{C-x * '} is equivalent to @kbd{C-x * f}.
  26438. @kindex C-x * n
  26439. @kindex C-x * p
  26440. @pindex calc-embedded-next
  26441. @pindex calc-embedded-previous
  26442. The @kbd{C-x * n} (@code{calc-embedded-next}) and @kbd{C-x * p}
  26443. (@code{calc-embedded-previous}) commands move the cursor to the
  26444. next or previous active embedded formula in the buffer. They
  26445. can take positive or negative prefix arguments to move by several
  26446. formulas. Note that these commands do not actually examine the
  26447. text of the buffer looking for formulas; they only see formulas
  26448. which have previously been activated in Embedded mode. In fact,
  26449. @kbd{C-x * n} and @kbd{C-x * p} are a useful way to tell which
  26450. embedded formulas are currently active. Also, note that these
  26451. commands do not enable Embedded mode on the next or previous
  26452. formula, they just move the cursor.
  26453. @kindex C-x * `
  26454. @pindex calc-embedded-edit
  26455. The @kbd{C-x * `} (@code{calc-embedded-edit}) command edits the
  26456. embedded formula at the current point as if by @kbd{`} (@code{calc-edit}).
  26457. Embedded mode does not have to be enabled for this to work. Press
  26458. @kbd{C-c C-c} to finish the edit, or @kbd{C-x k} to cancel.
  26459. @node Assignments in Embedded Mode, Mode Settings in Embedded Mode, More About Embedded Mode, Embedded Mode
  26460. @section Assignments in Embedded Mode
  26461. @noindent
  26462. The @samp{:=} (assignment) and @samp{=>} (``evaluates-to'') operators
  26463. are especially useful in Embedded mode. They allow you to make
  26464. a definition in one formula, then refer to that definition in
  26465. other formulas embedded in the same buffer.
  26466. An embedded formula which is an assignment to a variable, as in
  26467. @example
  26468. foo := 5
  26469. @end example
  26470. @noindent
  26471. records @expr{5} as the stored value of @code{foo} for the
  26472. purposes of Embedded mode operations in the current buffer. It
  26473. does @emph{not} actually store @expr{5} as the ``global'' value
  26474. of @code{foo}, however. Regular Calc operations, and Embedded
  26475. formulas in other buffers, will not see this assignment.
  26476. One way to use this assigned value is simply to create an
  26477. Embedded formula elsewhere that refers to @code{foo}, and to press
  26478. @kbd{=} in that formula. However, this permanently replaces the
  26479. @code{foo} in the formula with its current value. More interesting
  26480. is to use @samp{=>} elsewhere:
  26481. @example
  26482. foo + 7 => 12
  26483. @end example
  26484. @xref{Evaluates-To Operator}, for a general discussion of @samp{=>}.
  26485. If you move back and change the assignment to @code{foo}, any
  26486. @samp{=>} formulas which refer to it are automatically updated.
  26487. @example
  26488. foo := 17
  26489. foo + 7 => 24
  26490. @end example
  26491. The obvious question then is, @emph{how} can one easily change the
  26492. assignment to @code{foo}? If you simply select the formula in
  26493. Embedded mode and type 17, the assignment itself will be replaced
  26494. by the 17. The effect on the other formula will be that the
  26495. variable @code{foo} becomes unassigned:
  26496. @example
  26497. 17
  26498. foo + 7 => foo + 7
  26499. @end example
  26500. The right thing to do is first to use a selection command (@kbd{j 2}
  26501. will do the trick) to select the righthand side of the assignment.
  26502. Then, @kbd{17 @key{TAB} @key{DEL}} will swap the 17 into place (@pxref{Selecting
  26503. Subformulas}, to see how this works).
  26504. @kindex C-x * j
  26505. @pindex calc-embedded-select
  26506. The @kbd{C-x * j} (@code{calc-embedded-select}) command provides an
  26507. easy way to operate on assignments. It is just like @kbd{C-x * e},
  26508. except that if the enabled formula is an assignment, it uses
  26509. @kbd{j 2} to select the righthand side. If the enabled formula
  26510. is an evaluates-to, it uses @kbd{j 1} to select the lefthand side.
  26511. A formula can also be a combination of both:
  26512. @example
  26513. bar := foo + 3 => 20
  26514. @end example
  26515. @noindent
  26516. in which case @kbd{C-x * j} will select the middle part (@samp{foo + 3}).
  26517. The formula is automatically deselected when you leave Embedded
  26518. mode.
  26519. @kindex C-x * u
  26520. @pindex calc-embedded-update-formula
  26521. Another way to change the assignment to @code{foo} would simply be
  26522. to edit the number using regular Emacs editing rather than Embedded
  26523. mode. Then, we have to find a way to get Embedded mode to notice
  26524. the change. The @kbd{C-x * u} (@code{calc-embedded-update-formula})
  26525. command is a convenient way to do this.
  26526. @example
  26527. foo := 6
  26528. foo + 7 => 13
  26529. @end example
  26530. Pressing @kbd{C-x * u} is much like pressing @kbd{C-x * e = C-x * e}, that
  26531. is, temporarily enabling Embedded mode for the formula under the
  26532. cursor and then evaluating it with @kbd{=}. But @kbd{C-x * u} does
  26533. not actually use @kbd{C-x * e}, and in fact another formula somewhere
  26534. else can be enabled in Embedded mode while you use @kbd{C-x * u} and
  26535. that formula will not be disturbed.
  26536. With a numeric prefix argument, @kbd{C-x * u} updates all active
  26537. @samp{=>} formulas in the buffer. Formulas which have not yet
  26538. been activated in Embedded mode, and formulas which do not have
  26539. @samp{=>} as their top-level operator, are not affected by this.
  26540. (This is useful only if you have used @kbd{m C}; see below.)
  26541. With a plain @kbd{C-u} prefix, @kbd{C-u C-x * u} updates only in the
  26542. region between mark and point rather than in the whole buffer.
  26543. @kbd{C-x * u} is also a handy way to activate a formula, such as an
  26544. @samp{=>} formula that has freshly been typed in or loaded from a
  26545. file.
  26546. @kindex C-x * a
  26547. @pindex calc-embedded-activate
  26548. The @kbd{C-x * a} (@code{calc-embedded-activate}) command scans
  26549. through the current buffer and activates all embedded formulas
  26550. that contain @samp{:=} or @samp{=>} symbols. This does not mean
  26551. that Embedded mode is actually turned on, but only that the
  26552. formulas' positions are registered with Embedded mode so that
  26553. the @samp{=>} values can be properly updated as assignments are
  26554. changed.
  26555. It is a good idea to type @kbd{C-x * a} right after loading a file
  26556. that uses embedded @samp{=>} operators. Emacs includes a nifty
  26557. ``buffer-local variables'' feature that you can use to do this
  26558. automatically. The idea is to place near the end of your file
  26559. a few lines that look like this:
  26560. @example
  26561. --- Local Variables: ---
  26562. --- eval:(calc-embedded-activate) ---
  26563. --- End: ---
  26564. @end example
  26565. @noindent
  26566. where the leading and trailing @samp{---} can be replaced by
  26567. any suitable strings (which must be the same on all three lines)
  26568. or omitted altogether; in a @TeX{} or @LaTeX{} file, @samp{%} would be a good
  26569. leading string and no trailing string would be necessary. In a
  26570. C program, @samp{/*} and @samp{*/} would be good leading and
  26571. trailing strings.
  26572. When Emacs loads a file into memory, it checks for a Local Variables
  26573. section like this one at the end of the file. If it finds this
  26574. section, it does the specified things (in this case, running
  26575. @kbd{C-x * a} automatically) before editing of the file begins.
  26576. The Local Variables section must be within 3000 characters of the
  26577. end of the file for Emacs to find it, and it must be in the last
  26578. page of the file if the file has any page separators.
  26579. @xref{File Variables, , Local Variables in Files, emacs, the
  26580. Emacs manual}.
  26581. Note that @kbd{C-x * a} does not update the formulas it finds.
  26582. To do this, type, say, @kbd{M-1 C-x * u} after @w{@kbd{C-x * a}}.
  26583. Generally this should not be a problem, though, because the
  26584. formulas will have been up-to-date already when the file was
  26585. saved.
  26586. Normally, @kbd{C-x * a} activates all the formulas it finds, but
  26587. any previous active formulas remain active as well. With a
  26588. positive numeric prefix argument, @kbd{C-x * a} first deactivates
  26589. all current active formulas, then actives the ones it finds in
  26590. its scan of the buffer. With a negative prefix argument,
  26591. @kbd{C-x * a} simply deactivates all formulas.
  26592. Embedded mode has two symbols, @samp{Active} and @samp{~Active},
  26593. which it puts next to the major mode name in a buffer's mode line.
  26594. It puts @samp{Active} if it has reason to believe that all
  26595. formulas in the buffer are active, because you have typed @kbd{C-x * a}
  26596. and Calc has not since had to deactivate any formulas (which can
  26597. happen if Calc goes to update an @samp{=>} formula somewhere because
  26598. a variable changed, and finds that the formula is no longer there
  26599. due to some kind of editing outside of Embedded mode). Calc puts
  26600. @samp{~Active} in the mode line if some, but probably not all,
  26601. formulas in the buffer are active. This happens if you activate
  26602. a few formulas one at a time but never use @kbd{C-x * a}, or if you
  26603. used @kbd{C-x * a} but then Calc had to deactivate a formula
  26604. because it lost track of it. If neither of these symbols appears
  26605. in the mode line, no embedded formulas are active in the buffer
  26606. (e.g., before Embedded mode has been used, or after a @kbd{M-- C-x * a}).
  26607. Embedded formulas can refer to assignments both before and after them
  26608. in the buffer. If there are several assignments to a variable, the
  26609. nearest preceding assignment is used if there is one, otherwise the
  26610. following assignment is used.
  26611. @example
  26612. x => 1
  26613. x := 1
  26614. x => 1
  26615. x := 2
  26616. x => 2
  26617. @end example
  26618. As well as simple variables, you can also assign to subscript
  26619. expressions of the form @samp{@var{var}_@var{number}} (as in
  26620. @code{x_0}), or @samp{@var{var}_@var{var}} (as in @code{x_max}).
  26621. Assignments to other kinds of objects can be represented by Calc,
  26622. but the automatic linkage between assignments and references works
  26623. only for plain variables and these two kinds of subscript expressions.
  26624. If there are no assignments to a given variable, the global
  26625. stored value for the variable is used (@pxref{Storing Variables}),
  26626. or, if no value is stored, the variable is left in symbolic form.
  26627. Note that global stored values will be lost when the file is saved
  26628. and loaded in a later Emacs session, unless you have used the
  26629. @kbd{s p} (@code{calc-permanent-variable}) command to save them;
  26630. @pxref{Operations on Variables}.
  26631. The @kbd{m C} (@code{calc-auto-recompute}) command turns automatic
  26632. recomputation of @samp{=>} forms on and off. If you turn automatic
  26633. recomputation off, you will have to use @kbd{C-x * u} to update these
  26634. formulas manually after an assignment has been changed. If you
  26635. plan to change several assignments at once, it may be more efficient
  26636. to type @kbd{m C}, change all the assignments, then use @kbd{M-1 C-x * u}
  26637. to update the entire buffer afterwards. The @kbd{m C} command also
  26638. controls @samp{=>} formulas on the stack; @pxref{Evaluates-To
  26639. Operator}. When you turn automatic recomputation back on, the
  26640. stack will be updated but the Embedded buffer will not; you must
  26641. use @kbd{C-x * u} to update the buffer by hand.
  26642. @node Mode Settings in Embedded Mode, Customizing Embedded Mode, Assignments in Embedded Mode, Embedded Mode
  26643. @section Mode Settings in Embedded Mode
  26644. @kindex m e
  26645. @pindex calc-embedded-preserve-modes
  26646. @noindent
  26647. The mode settings can be changed while Calc is in embedded mode, but
  26648. by default they will revert to their original values when embedded mode
  26649. is ended. However, the modes saved when the mode-recording mode is
  26650. @code{Save} (see below) and the modes in effect when the @kbd{m e}
  26651. (@code{calc-embedded-preserve-modes}) command is given
  26652. will be preserved when embedded mode is ended.
  26653. Embedded mode has a rather complicated mechanism for handling mode
  26654. settings in Embedded formulas. It is possible to put annotations
  26655. in the file that specify mode settings either global to the entire
  26656. file or local to a particular formula or formulas. In the latter
  26657. case, different modes can be specified for use when a formula
  26658. is the enabled Embedded mode formula.
  26659. When you give any mode-setting command, like @kbd{m f} (for Fraction
  26660. mode) or @kbd{d s} (for scientific notation), Embedded mode adds
  26661. a line like the following one to the file just before the opening
  26662. delimiter of the formula.
  26663. @example
  26664. % [calc-mode: fractions: t]
  26665. % [calc-mode: float-format: (sci 0)]
  26666. @end example
  26667. When Calc interprets an embedded formula, it scans the text before
  26668. the formula for mode-setting annotations like these and sets the
  26669. Calc buffer to match these modes. Modes not explicitly described
  26670. in the file are not changed. Calc scans all the way to the top of
  26671. the file, or up to a line of the form
  26672. @example
  26673. % [calc-defaults]
  26674. @end example
  26675. @noindent
  26676. which you can insert at strategic places in the file if this backward
  26677. scan is getting too slow, or just to provide a barrier between one
  26678. ``zone'' of mode settings and another.
  26679. If the file contains several annotations for the same mode, the
  26680. closest one before the formula is used. Annotations after the
  26681. formula are never used (except for global annotations, described
  26682. below).
  26683. The scan does not look for the leading @samp{% }, only for the
  26684. square brackets and the text they enclose. In fact, the leading
  26685. characters are different for different major modes. You can edit the
  26686. mode annotations to a style that works better in context if you wish.
  26687. @xref{Customizing Embedded Mode}, to see how to change the style
  26688. that Calc uses when it generates the annotations. You can write
  26689. mode annotations into the file yourself if you know the syntax;
  26690. the easiest way to find the syntax for a given mode is to let
  26691. Calc write the annotation for it once and see what it does.
  26692. If you give a mode-changing command for a mode that already has
  26693. a suitable annotation just above the current formula, Calc will
  26694. modify that annotation rather than generating a new, conflicting
  26695. one.
  26696. Mode annotations have three parts, separated by colons. (Spaces
  26697. after the colons are optional.) The first identifies the kind
  26698. of mode setting, the second is a name for the mode itself, and
  26699. the third is the value in the form of a Lisp symbol, number,
  26700. or list. Annotations with unrecognizable text in the first or
  26701. second parts are ignored. The third part is not checked to make
  26702. sure the value is of a valid type or range; if you write an
  26703. annotation by hand, be sure to give a proper value or results
  26704. will be unpredictable. Mode-setting annotations are case-sensitive.
  26705. While Embedded mode is enabled, the word @code{Local} appears in
  26706. the mode line. This is to show that mode setting commands generate
  26707. annotations that are ``local'' to the current formula or set of
  26708. formulas. The @kbd{m R} (@code{calc-mode-record-mode}) command
  26709. causes Calc to generate different kinds of annotations. Pressing
  26710. @kbd{m R} repeatedly cycles through the possible modes.
  26711. @code{LocEdit} and @code{LocPerm} modes generate annotations
  26712. that look like this, respectively:
  26713. @example
  26714. % [calc-edit-mode: float-format: (sci 0)]
  26715. % [calc-perm-mode: float-format: (sci 5)]
  26716. @end example
  26717. The first kind of annotation will be used only while a formula
  26718. is enabled in Embedded mode. The second kind will be used only
  26719. when the formula is @emph{not} enabled. (Whether the formula
  26720. is ``active'' or not, i.e., whether Calc has seen this formula
  26721. yet, is not relevant here.)
  26722. @code{Global} mode generates an annotation like this at the end
  26723. of the file:
  26724. @example
  26725. % [calc-global-mode: fractions t]
  26726. @end example
  26727. Global mode annotations affect all formulas throughout the file,
  26728. and may appear anywhere in the file. This allows you to tuck your
  26729. mode annotations somewhere out of the way, say, on a new page of
  26730. the file, as long as those mode settings are suitable for all
  26731. formulas in the file.
  26732. Enabling a formula with @kbd{C-x * e} causes a fresh scan for local
  26733. mode annotations; you will have to use this after adding annotations
  26734. above a formula by hand to get the formula to notice them. Updating
  26735. a formula with @kbd{C-x * u} will also re-scan the local modes, but
  26736. global modes are only re-scanned by @kbd{C-x * a}.
  26737. Another way that modes can get out of date is if you add a local
  26738. mode annotation to a formula that has another formula after it.
  26739. In this example, we have used the @kbd{d s} command while the
  26740. first of the two embedded formulas is active. But the second
  26741. formula has not changed its style to match, even though by the
  26742. rules of reading annotations the @samp{(sci 0)} applies to it, too.
  26743. @example
  26744. % [calc-mode: float-format: (sci 0)]
  26745. 1.23e2
  26746. 456.
  26747. @end example
  26748. We would have to go down to the other formula and press @kbd{C-x * u}
  26749. on it in order to get it to notice the new annotation.
  26750. Two more mode-recording modes selectable by @kbd{m R} are available
  26751. which are also available outside of Embedded mode.
  26752. (@pxref{General Mode Commands}.) They are @code{Save}, in which mode
  26753. settings are recorded permanently in your Calc init file (the file given
  26754. by the variable @code{calc-settings-file}, typically @file{~/.emacs.d/calc.el})
  26755. rather than by annotating the current document, and no-recording
  26756. mode (where there is no symbol like @code{Save} or @code{Local} in
  26757. the mode line), in which mode-changing commands do not leave any
  26758. annotations at all.
  26759. When Embedded mode is not enabled, mode-recording modes except
  26760. for @code{Save} have no effect.
  26761. @node Customizing Embedded Mode, , Mode Settings in Embedded Mode, Embedded Mode
  26762. @section Customizing Embedded Mode
  26763. @noindent
  26764. You can modify Embedded mode's behavior by setting various Lisp
  26765. variables described here. These variables are customizable
  26766. (@pxref{Customizing Calc}), or you can use @kbd{M-x set-variable}
  26767. or @kbd{M-x edit-options} to adjust a variable on the fly.
  26768. (Another possibility would be to use a file-local variable annotation at
  26769. the end of the file;
  26770. @pxref{File Variables, , Local Variables in Files, emacs, the Emacs manual}.)
  26771. Many of the variables given mentioned here can be set to depend on the
  26772. major mode of the editing buffer (@pxref{Customizing Calc}).
  26773. @vindex calc-embedded-open-formula
  26774. The @code{calc-embedded-open-formula} variable holds a regular
  26775. expression for the opening delimiter of a formula. @xref{Regexp Search,
  26776. , Regular Expression Search, emacs, the Emacs manual}, to see
  26777. how regular expressions work. Basically, a regular expression is a
  26778. pattern that Calc can search for. A regular expression that considers
  26779. blank lines, @samp{$}, and @samp{$$} to be opening delimiters is
  26780. @code{"\\`\\|^\n\\|\\$\\$?"}. Just in case the meaning of this
  26781. regular expression is not completely plain, let's go through it
  26782. in detail.
  26783. The surrounding @samp{" "} marks quote the text between them as a
  26784. Lisp string. If you left them off, @code{set-variable} or
  26785. @code{edit-options} would try to read the regular expression as a
  26786. Lisp program.
  26787. The most obvious property of this regular expression is that it
  26788. contains indecently many backslashes. There are actually two levels
  26789. of backslash usage going on here. First, when Lisp reads a quoted
  26790. string, all pairs of characters beginning with a backslash are
  26791. interpreted as special characters. Here, @code{\n} changes to a
  26792. new-line character, and @code{\\} changes to a single backslash.
  26793. So the actual regular expression seen by Calc is
  26794. @samp{\`\|^ @r{(newline)} \|\$\$?}.
  26795. Regular expressions also consider pairs beginning with backslash
  26796. to have special meanings. Sometimes the backslash is used to quote
  26797. a character that otherwise would have a special meaning in a regular
  26798. expression, like @samp{$}, which normally means ``end-of-line,''
  26799. or @samp{?}, which means that the preceding item is optional. So
  26800. @samp{\$\$?} matches either one or two dollar signs.
  26801. The other codes in this regular expression are @samp{^}, which matches
  26802. ``beginning-of-line,'' @samp{\|}, which means ``or,'' and @samp{\`},
  26803. which matches ``beginning-of-buffer.'' So the whole pattern means
  26804. that a formula begins at the beginning of the buffer, or on a newline
  26805. that occurs at the beginning of a line (i.e., a blank line), or at
  26806. one or two dollar signs.
  26807. The default value of @code{calc-embedded-open-formula} looks just
  26808. like this example, with several more alternatives added on to
  26809. recognize various other common kinds of delimiters.
  26810. By the way, the reason to use @samp{^\n} rather than @samp{^$}
  26811. or @samp{\n\n}, which also would appear to match blank lines,
  26812. is that the former expression actually ``consumes'' only one
  26813. newline character as @emph{part of} the delimiter, whereas the
  26814. latter expressions consume zero or two newlines, respectively.
  26815. The former choice gives the most natural behavior when Calc
  26816. must operate on a whole formula including its delimiters.
  26817. See the Emacs manual for complete details on regular expressions.
  26818. But just for your convenience, here is a list of all characters
  26819. which must be quoted with backslash (like @samp{\$}) to avoid
  26820. some special interpretation: @samp{. * + ? [ ] ^ $ \}. (Note
  26821. the backslash in this list; for example, to match @samp{\[} you
  26822. must use @code{"\\\\\\["}. An exercise for the reader is to
  26823. account for each of these six backslashes!)
  26824. @vindex calc-embedded-close-formula
  26825. The @code{calc-embedded-close-formula} variable holds a regular
  26826. expression for the closing delimiter of a formula. A closing
  26827. regular expression to match the above example would be
  26828. @code{"\\'\\|\n$\\|\\$\\$?"}. This is almost the same as the
  26829. other one, except it now uses @samp{\'} (``end-of-buffer'') and
  26830. @samp{\n$} (newline occurring at end of line, yet another way
  26831. of describing a blank line that is more appropriate for this
  26832. case).
  26833. @vindex calc-embedded-word-regexp
  26834. The @code{calc-embedded-word-regexp} variable holds a regular expression
  26835. used to define an expression to look for (a ``word'') when you type
  26836. @kbd{C-x * w} to enable Embedded mode.
  26837. @vindex calc-embedded-open-plain
  26838. The @code{calc-embedded-open-plain} variable is a string which
  26839. begins a ``plain'' formula written in front of the formatted
  26840. formula when @kbd{d p} mode is turned on. Note that this is an
  26841. actual string, not a regular expression, because Calc must be able
  26842. to write this string into a buffer as well as to recognize it.
  26843. The default string is @code{"%%% "} (note the trailing space), but may
  26844. be different for certain major modes.
  26845. @vindex calc-embedded-close-plain
  26846. The @code{calc-embedded-close-plain} variable is a string which
  26847. ends a ``plain'' formula. The default is @code{" %%%\n"}, but may be
  26848. different for different major modes. Without
  26849. the trailing newline here, the first line of a Big mode formula
  26850. that followed might be shifted over with respect to the other lines.
  26851. @vindex calc-embedded-open-new-formula
  26852. The @code{calc-embedded-open-new-formula} variable is a string
  26853. which is inserted at the front of a new formula when you type
  26854. @kbd{C-x * f}. Its default value is @code{"\n\n"}. If this
  26855. string begins with a newline character and the @kbd{C-x * f} is
  26856. typed at the beginning of a line, @kbd{C-x * f} will skip this
  26857. first newline to avoid introducing unnecessary blank lines in
  26858. the file.
  26859. @vindex calc-embedded-close-new-formula
  26860. The @code{calc-embedded-close-new-formula} variable is the corresponding
  26861. string which is inserted at the end of a new formula. Its default
  26862. value is also @code{"\n\n"}. The final newline is omitted by
  26863. @w{@kbd{C-x * f}} if typed at the end of a line. (It follows that if
  26864. @kbd{C-x * f} is typed on a blank line, both a leading opening
  26865. newline and a trailing closing newline are omitted.)
  26866. @vindex calc-embedded-announce-formula
  26867. The @code{calc-embedded-announce-formula} variable is a regular
  26868. expression which is sure to be followed by an embedded formula.
  26869. The @kbd{C-x * a} command searches for this pattern as well as for
  26870. @samp{=>} and @samp{:=} operators. Note that @kbd{C-x * a} will
  26871. not activate just anything surrounded by formula delimiters; after
  26872. all, blank lines are considered formula delimiters by default!
  26873. But if your language includes a delimiter which can only occur
  26874. actually in front of a formula, you can take advantage of it here.
  26875. The default pattern is @code{"%Embed\n\\(% .*\n\\)*"}, but may be
  26876. different for different major modes.
  26877. This pattern will check for @samp{%Embed} followed by any number of
  26878. lines beginning with @samp{%} and a space. This last is important to
  26879. make Calc consider mode annotations part of the pattern, so that the
  26880. formula's opening delimiter really is sure to follow the pattern.
  26881. @vindex calc-embedded-open-mode
  26882. The @code{calc-embedded-open-mode} variable is a string (not a
  26883. regular expression) which should precede a mode annotation.
  26884. Calc never scans for this string; Calc always looks for the
  26885. annotation itself. But this is the string that is inserted before
  26886. the opening bracket when Calc adds an annotation on its own.
  26887. The default is @code{"% "}, but may be different for different major
  26888. modes.
  26889. @vindex calc-embedded-close-mode
  26890. The @code{calc-embedded-close-mode} variable is a string which
  26891. follows a mode annotation written by Calc. Its default value
  26892. is simply a newline, @code{"\n"}, but may be different for different
  26893. major modes. If you change this, it is a good idea still to end with a
  26894. newline so that mode annotations will appear on lines by themselves.
  26895. @node Programming, Copying, Embedded Mode, Top
  26896. @chapter Programming
  26897. @noindent
  26898. There are several ways to ``program'' the Emacs Calculator, depending
  26899. on the nature of the problem you need to solve.
  26900. @enumerate
  26901. @item
  26902. @dfn{Keyboard macros} allow you to record a sequence of keystrokes
  26903. and play them back at a later time. This is just the standard Emacs
  26904. keyboard macro mechanism, dressed up with a few more features such
  26905. as loops and conditionals.
  26906. @item
  26907. @dfn{Algebraic definitions} allow you to use any formula to define a
  26908. new function. This function can then be used in algebraic formulas or
  26909. as an interactive command.
  26910. @item
  26911. @dfn{Rewrite rules} are discussed in the section on algebra commands.
  26912. @xref{Rewrite Rules}. If you put your rewrite rules in the variable
  26913. @code{EvalRules}, they will be applied automatically to all Calc
  26914. results in just the same way as an internal ``rule'' is applied to
  26915. evaluate @samp{sqrt(9)} to 3 and so on. @xref{Automatic Rewrites}.
  26916. @item
  26917. @dfn{Lisp} is the programming language that Calc (and most of Emacs)
  26918. is written in. If the above techniques aren't powerful enough, you
  26919. can write Lisp functions to do anything that built-in Calc commands
  26920. can do. Lisp code is also somewhat faster than keyboard macros or
  26921. rewrite rules.
  26922. @end enumerate
  26923. @kindex z
  26924. Programming features are available through the @kbd{z} and @kbd{Z}
  26925. prefix keys. New commands that you define are two-key sequences
  26926. beginning with @kbd{z}. Commands for managing these definitions
  26927. use the shift-@kbd{Z} prefix. (The @kbd{Z T} (@code{calc-timing})
  26928. command is described elsewhere; @pxref{Troubleshooting Commands}.
  26929. The @kbd{Z C} (@code{calc-user-define-composition}) command is also
  26930. described elsewhere; @pxref{User-Defined Compositions}.)
  26931. @menu
  26932. * Creating User Keys::
  26933. * Keyboard Macros::
  26934. * Invocation Macros::
  26935. * Algebraic Definitions::
  26936. * Lisp Definitions::
  26937. @end menu
  26938. @node Creating User Keys, Keyboard Macros, Programming, Programming
  26939. @section Creating User Keys
  26940. @noindent
  26941. @kindex Z D
  26942. @pindex calc-user-define
  26943. Any Calculator command may be bound to a key using the @kbd{Z D}
  26944. (@code{calc-user-define}) command. Actually, it is bound to a two-key
  26945. sequence beginning with the lower-case @kbd{z} prefix.
  26946. The @kbd{Z D} command first prompts for the key to define. For example,
  26947. press @kbd{Z D a} to define the new key sequence @kbd{z a}. You are then
  26948. prompted for the name of the Calculator command that this key should
  26949. run. For example, the @code{calc-sincos} command is not normally
  26950. available on a key. Typing @kbd{Z D s sincos @key{RET}} programs the
  26951. @kbd{z s} key sequence to run @code{calc-sincos}. This definition will remain
  26952. in effect for the rest of this Emacs session, or until you redefine
  26953. @kbd{z s} to be something else.
  26954. You can actually bind any Emacs command to a @kbd{z} key sequence by
  26955. backspacing over the @samp{calc-} when you are prompted for the command name.
  26956. As with any other prefix key, you can type @kbd{z ?} to see a list of
  26957. all the two-key sequences you have defined that start with @kbd{z}.
  26958. Initially, no @kbd{z} sequences (except @kbd{z ?} itself) are defined.
  26959. User keys are typically letters, but may in fact be any key.
  26960. (@key{META}-keys are not permitted, nor are a terminal's special
  26961. function keys which generate multi-character sequences when pressed.)
  26962. You can define different commands on the shifted and unshifted versions
  26963. of a letter if you wish.
  26964. @kindex Z U
  26965. @pindex calc-user-undefine
  26966. The @kbd{Z U} (@code{calc-user-undefine}) command unbinds a user key.
  26967. For example, the key sequence @kbd{Z U s} will undefine the @code{sincos}
  26968. key we defined above.
  26969. @kindex Z P
  26970. @pindex calc-user-define-permanent
  26971. @cindex Storing user definitions
  26972. @cindex Permanent user definitions
  26973. @cindex Calc init file, user-defined commands
  26974. The @kbd{Z P} (@code{calc-user-define-permanent}) command makes a key
  26975. binding permanent so that it will remain in effect even in future Emacs
  26976. sessions. (It does this by adding a suitable bit of Lisp code into
  26977. your Calc init file; that is, the file given by the variable
  26978. @code{calc-settings-file}, typically @file{~/.emacs.d/calc.el}.) For example,
  26979. @kbd{Z P s} would register our @code{sincos} command permanently. If
  26980. you later wish to unregister this command you must edit your Calc init
  26981. file by hand. (@xref{General Mode Commands}, for a way to tell Calc to
  26982. use a different file for the Calc init file.)
  26983. The @kbd{Z P} command also saves the user definition, if any, for the
  26984. command bound to the key. After @kbd{Z F} and @kbd{Z C}, a given user
  26985. key could invoke a command, which in turn calls an algebraic function,
  26986. which might have one or more special display formats. A single @kbd{Z P}
  26987. command will save all of these definitions.
  26988. To save an algebraic function, type @kbd{'} (the apostrophe)
  26989. when prompted for a key, and type the function name. To save a command
  26990. without its key binding, type @kbd{M-x} and enter a function name. (The
  26991. @samp{calc-} prefix will automatically be inserted for you.)
  26992. (If the command you give implies a function, the function will be saved,
  26993. and if the function has any display formats, those will be saved, but
  26994. not the other way around: Saving a function will not save any commands
  26995. or key bindings associated with the function.)
  26996. @kindex Z E
  26997. @pindex calc-user-define-edit
  26998. @cindex Editing user definitions
  26999. The @kbd{Z E} (@code{calc-user-define-edit}) command edits the definition
  27000. of a user key. This works for keys that have been defined by either
  27001. keyboard macros or formulas; further details are contained in the relevant
  27002. following sections.
  27003. @node Keyboard Macros, Invocation Macros, Creating User Keys, Programming
  27004. @section Programming with Keyboard Macros
  27005. @noindent
  27006. @kindex X
  27007. @cindex Programming with keyboard macros
  27008. @cindex Keyboard macros
  27009. The easiest way to ``program'' the Emacs Calculator is to use standard
  27010. keyboard macros. Press @w{@kbd{C-x (}} to begin recording a macro. From
  27011. this point on, keystrokes you type will be saved away as well as
  27012. performing their usual functions. Press @kbd{C-x )} to end recording.
  27013. Press shift-@kbd{X} (or the standard Emacs key sequence @kbd{C-x e}) to
  27014. execute your keyboard macro by replaying the recorded keystrokes.
  27015. @xref{Keyboard Macros, , , emacs, the Emacs Manual}, for further
  27016. information.
  27017. When you use @kbd{X} to invoke a keyboard macro, the entire macro is
  27018. treated as a single command by the undo and trail features. The stack
  27019. display buffer is not updated during macro execution, but is instead
  27020. fixed up once the macro completes. Thus, commands defined with keyboard
  27021. macros are convenient and efficient. The @kbd{C-x e} command, on the
  27022. other hand, invokes the keyboard macro with no special treatment: Each
  27023. command in the macro will record its own undo information and trail entry,
  27024. and update the stack buffer accordingly. If your macro uses features
  27025. outside of Calc's control to operate on the contents of the Calc stack
  27026. buffer, or if it includes Undo, Redo, or last-arguments commands, you
  27027. must use @kbd{C-x e} to make sure the buffer and undo list are up-to-date
  27028. at all times. You could also consider using @kbd{K} (@code{calc-keep-args})
  27029. instead of @kbd{M-@key{RET}} (@code{calc-last-args}).
  27030. Calc extends the standard Emacs keyboard macros in several ways.
  27031. Keyboard macros can be used to create user-defined commands. Keyboard
  27032. macros can include conditional and iteration structures, somewhat
  27033. analogous to those provided by a traditional programmable calculator.
  27034. @menu
  27035. * Naming Keyboard Macros::
  27036. * Conditionals in Macros::
  27037. * Loops in Macros::
  27038. * Local Values in Macros::
  27039. * Queries in Macros::
  27040. @end menu
  27041. @node Naming Keyboard Macros, Conditionals in Macros, Keyboard Macros, Keyboard Macros
  27042. @subsection Naming Keyboard Macros
  27043. @noindent
  27044. @kindex Z K
  27045. @pindex calc-user-define-kbd-macro
  27046. Once you have defined a keyboard macro, you can bind it to a @kbd{z}
  27047. key sequence with the @kbd{Z K} (@code{calc-user-define-kbd-macro}) command.
  27048. This command prompts first for a key, then for a command name. For
  27049. example, if you type @kbd{C-x ( n @key{TAB} n @key{TAB} C-x )} you will
  27050. define a keyboard macro which negates the top two numbers on the stack
  27051. (@key{TAB} swaps the top two stack elements). Now you can type
  27052. @kbd{Z K n @key{RET}} to define this keyboard macro onto the @kbd{z n} key
  27053. sequence. The default command name (if you answer the second prompt with
  27054. just the @key{RET} key as in this example) will be something like
  27055. @samp{calc-User-n}. The keyboard macro will now be available as both
  27056. @kbd{z n} and @kbd{M-x calc-User-n}. You can backspace and enter a more
  27057. descriptive command name if you wish.
  27058. Macros defined by @kbd{Z K} act like single commands; they are executed
  27059. in the same way as by the @kbd{X} key. If you wish to define the macro
  27060. as a standard no-frills Emacs macro (to be executed as if by @kbd{C-x e}),
  27061. give a negative prefix argument to @kbd{Z K}.
  27062. Once you have bound your keyboard macro to a key, you can use
  27063. @kbd{Z P} to register it permanently with Emacs. @xref{Creating User Keys}.
  27064. @cindex Keyboard macros, editing
  27065. The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
  27066. been defined by a keyboard macro tries to use the @code{edmacro} package
  27067. edit the macro. Type @kbd{C-c C-c} to finish editing and update
  27068. the definition stored on the key, or, to cancel the edit, kill the
  27069. buffer with @kbd{C-x k}.
  27070. The special characters @code{RET}, @code{LFD}, @code{TAB}, @code{SPC},
  27071. @code{DEL}, and @code{NUL} must be entered as these three character
  27072. sequences, written in all uppercase, as must the prefixes @code{C-} and
  27073. @code{M-}. Spaces and line breaks are ignored. Other characters are
  27074. copied verbatim into the keyboard macro. Basically, the notation is the
  27075. same as is used in all of this manual's examples, except that the manual
  27076. takes some liberties with spaces: When we say @kbd{' [1 2 3] @key{RET}},
  27077. we take it for granted that it is clear we really mean
  27078. @kbd{' [1 @key{SPC} 2 @key{SPC} 3] @key{RET}}.
  27079. @kindex C-x * m
  27080. @pindex read-kbd-macro
  27081. The @kbd{C-x * m} (@code{read-kbd-macro}) command reads an Emacs ``region''
  27082. of spelled-out keystrokes and defines it as the current keyboard macro.
  27083. It is a convenient way to define a keyboard macro that has been stored
  27084. in a file, or to define a macro without executing it at the same time.
  27085. @node Conditionals in Macros, Loops in Macros, Naming Keyboard Macros, Keyboard Macros
  27086. @subsection Conditionals in Keyboard Macros
  27087. @noindent
  27088. @kindex Z [
  27089. @kindex Z ]
  27090. @pindex calc-kbd-if
  27091. @pindex calc-kbd-else
  27092. @pindex calc-kbd-else-if
  27093. @pindex calc-kbd-end-if
  27094. @cindex Conditional structures
  27095. The @kbd{Z [} (@code{calc-kbd-if}) and @kbd{Z ]} (@code{calc-kbd-end-if})
  27096. commands allow you to put simple tests in a keyboard macro. When Calc
  27097. sees the @kbd{Z [}, it pops an object from the stack and, if the object is
  27098. a non-zero value, continues executing keystrokes. But if the object is
  27099. zero, or if it is not provably nonzero, Calc skips ahead to the matching
  27100. @kbd{Z ]} keystroke. @xref{Logical Operations}, for a set of commands for
  27101. performing tests which conveniently produce 1 for true and 0 for false.
  27102. For example, @kbd{@key{RET} 0 a < Z [ n Z ]} implements an absolute-value
  27103. function in the form of a keyboard macro. This macro duplicates the
  27104. number on the top of the stack, pushes zero and compares using @kbd{a <}
  27105. (@code{calc-less-than}), then, if the number was less than zero,
  27106. executes @kbd{n} (@code{calc-change-sign}). Otherwise, the change-sign
  27107. command is skipped.
  27108. To program this macro, type @kbd{C-x (}, type the above sequence of
  27109. keystrokes, then type @kbd{C-x )}. Note that the keystrokes will be
  27110. executed while you are making the definition as well as when you later
  27111. re-execute the macro by typing @kbd{X}. Thus you should make sure a
  27112. suitable number is on the stack before defining the macro so that you
  27113. don't get a stack-underflow error during the definition process.
  27114. Conditionals can be nested arbitrarily. However, there should be exactly
  27115. one @kbd{Z ]} for each @kbd{Z [} in a keyboard macro.
  27116. @kindex Z :
  27117. The @kbd{Z :} (@code{calc-kbd-else}) command allows you to choose between
  27118. two keystroke sequences. The general format is @kbd{@var{cond} Z [
  27119. @var{then-part} Z : @var{else-part} Z ]}. If @var{cond} is true
  27120. (i.e., if the top of stack contains a non-zero number after @var{cond}
  27121. has been executed), the @var{then-part} will be executed and the
  27122. @var{else-part} will be skipped. Otherwise, the @var{then-part} will
  27123. be skipped and the @var{else-part} will be executed.
  27124. @kindex Z |
  27125. The @kbd{Z |} (@code{calc-kbd-else-if}) command allows you to choose
  27126. between any number of alternatives. For example,
  27127. @kbd{@var{cond1} Z [ @var{part1} Z : @var{cond2} Z | @var{part2} Z :
  27128. @var{part3} Z ]} will execute @var{part1} if @var{cond1} is true,
  27129. otherwise it will execute @var{part2} if @var{cond2} is true, otherwise
  27130. it will execute @var{part3}.
  27131. More precisely, @kbd{Z [} pops a number and conditionally skips to the
  27132. next matching @kbd{Z :} or @kbd{Z ]} key. @w{@kbd{Z ]}} has no effect when
  27133. actually executed. @kbd{Z :} skips to the next matching @kbd{Z ]}.
  27134. @kbd{Z |} pops a number and conditionally skips to the next matching
  27135. @kbd{Z :} or @kbd{Z ]}; thus, @kbd{Z [} and @kbd{Z |} are functionally
  27136. equivalent except that @kbd{Z [} participates in nesting but @kbd{Z |}
  27137. does not.
  27138. Calc's conditional and looping constructs work by scanning the
  27139. keyboard macro for occurrences of character sequences like @samp{Z:}
  27140. and @samp{Z]}. One side-effect of this is that if you use these
  27141. constructs you must be careful that these character pairs do not
  27142. occur by accident in other parts of the macros. Since Calc rarely
  27143. uses shift-@kbd{Z} for any purpose except as a prefix character, this
  27144. is not likely to be a problem. Another side-effect is that it will
  27145. not work to define your own custom key bindings for these commands.
  27146. Only the standard shift-@kbd{Z} bindings will work correctly.
  27147. @kindex Z C-g
  27148. If Calc gets stuck while skipping characters during the definition of a
  27149. macro, type @kbd{Z C-g} to cancel the definition. (Typing plain @kbd{C-g}
  27150. actually adds a @kbd{C-g} keystroke to the macro.)
  27151. @node Loops in Macros, Local Values in Macros, Conditionals in Macros, Keyboard Macros
  27152. @subsection Loops in Keyboard Macros
  27153. @noindent
  27154. @kindex Z <
  27155. @kindex Z >
  27156. @pindex calc-kbd-repeat
  27157. @pindex calc-kbd-end-repeat
  27158. @cindex Looping structures
  27159. @cindex Iterative structures
  27160. The @kbd{Z <} (@code{calc-kbd-repeat}) and @kbd{Z >}
  27161. (@code{calc-kbd-end-repeat}) commands pop a number from the stack,
  27162. which must be an integer, then repeat the keystrokes between the brackets
  27163. the specified number of times. If the integer is zero or negative, the
  27164. body is skipped altogether. For example, @kbd{1 @key{TAB} Z < 2 * Z >}
  27165. computes two to a nonnegative integer power. First, we push 1 on the
  27166. stack and then swap the integer argument back to the top. The @kbd{Z <}
  27167. pops that argument leaving the 1 back on top of the stack. Then, we
  27168. repeat a multiply-by-two step however many times.
  27169. Once again, the keyboard macro is executed as it is being entered.
  27170. In this case it is especially important to set up reasonable initial
  27171. conditions before making the definition: Suppose the integer 1000 just
  27172. happened to be sitting on the stack before we typed the above definition!
  27173. Another approach is to enter a harmless dummy definition for the macro,
  27174. then go back and edit in the real one with a @kbd{Z E} command. Yet
  27175. another approach is to type the macro as written-out keystroke names
  27176. in a buffer, then use @kbd{C-x * m} (@code{read-kbd-macro}) to read the
  27177. macro.
  27178. @kindex Z /
  27179. @pindex calc-break
  27180. The @kbd{Z /} (@code{calc-kbd-break}) command allows you to break out
  27181. of a keyboard macro loop prematurely. It pops an object from the stack;
  27182. if that object is true (a non-zero number), control jumps out of the
  27183. innermost enclosing @kbd{Z <} @dots{} @kbd{Z >} loop and continues
  27184. after the @kbd{Z >}. If the object is false, the @kbd{Z /} has no
  27185. effect. Thus @kbd{@var{cond} Z /} is similar to @samp{if (@var{cond}) break;}
  27186. in the C language.
  27187. @kindex Z (
  27188. @kindex Z )
  27189. @pindex calc-kbd-for
  27190. @pindex calc-kbd-end-for
  27191. The @kbd{Z (} (@code{calc-kbd-for}) and @kbd{Z )} (@code{calc-kbd-end-for})
  27192. commands are similar to @kbd{Z <} and @kbd{Z >}, except that they make the
  27193. value of the counter available inside the loop. The general layout is
  27194. @kbd{@var{init} @var{final} Z ( @var{body} @var{step} Z )}. The @kbd{Z (}
  27195. command pops initial and final values from the stack. It then creates
  27196. a temporary internal counter and initializes it with the value @var{init}.
  27197. The @kbd{Z (} command then repeatedly pushes the counter value onto the
  27198. stack and executes @var{body} and @var{step}, adding @var{step} to the
  27199. counter each time until the loop finishes.
  27200. @cindex Summations (by keyboard macros)
  27201. By default, the loop finishes when the counter becomes greater than (or
  27202. less than) @var{final}, assuming @var{initial} is less than (greater
  27203. than) @var{final}. If @var{initial} is equal to @var{final}, the body
  27204. executes exactly once. The body of the loop always executes at least
  27205. once. For example, @kbd{0 1 10 Z ( 2 ^ + 1 Z )} computes the sum of the
  27206. squares of the integers from 1 to 10, in steps of 1.
  27207. If you give a numeric prefix argument of 1 to @kbd{Z (}, the loop is
  27208. forced to use upward-counting conventions. In this case, if @var{initial}
  27209. is greater than @var{final} the body will not be executed at all.
  27210. Note that @var{step} may still be negative in this loop; the prefix
  27211. argument merely constrains the loop-finished test. Likewise, a prefix
  27212. argument of @mathit{-1} forces downward-counting conventions.
  27213. @kindex Z @{
  27214. @kindex Z @}
  27215. @pindex calc-kbd-loop
  27216. @pindex calc-kbd-end-loop
  27217. The @kbd{Z @{} (@code{calc-kbd-loop}) and @kbd{Z @}}
  27218. (@code{calc-kbd-end-loop}) commands are similar to @kbd{Z <} and
  27219. @kbd{Z >}, except that they do not pop a count from the stack---they
  27220. effectively create an infinite loop. Every @kbd{Z @{} @dots{} @kbd{Z @}}
  27221. loop ought to include at least one @kbd{Z /} to make sure the loop
  27222. doesn't run forever. (If any error message occurs which causes Emacs
  27223. to beep, the keyboard macro will also be halted; this is a standard
  27224. feature of Emacs. You can also generally press @kbd{C-g} to halt a
  27225. running keyboard macro, although not all versions of Unix support
  27226. this feature.)
  27227. The conditional and looping constructs are not actually tied to
  27228. keyboard macros, but they are most often used in that context.
  27229. For example, the keystrokes @kbd{10 Z < 23 @key{RET} Z >} push
  27230. ten copies of 23 onto the stack. This can be typed ``live'' just
  27231. as easily as in a macro definition.
  27232. @xref{Conditionals in Macros}, for some additional notes about
  27233. conditional and looping commands.
  27234. @node Local Values in Macros, Queries in Macros, Loops in Macros, Keyboard Macros
  27235. @subsection Local Values in Macros
  27236. @noindent
  27237. @cindex Local variables
  27238. @cindex Restoring saved modes
  27239. Keyboard macros sometimes want to operate under known conditions
  27240. without affecting surrounding conditions. For example, a keyboard
  27241. macro may wish to turn on Fraction mode, or set a particular
  27242. precision, independent of the user's normal setting for those
  27243. modes.
  27244. @kindex Z `
  27245. @kindex Z '
  27246. @pindex calc-kbd-push
  27247. @pindex calc-kbd-pop
  27248. Macros also sometimes need to use local variables. Assignments to
  27249. local variables inside the macro should not affect any variables
  27250. outside the macro. The @kbd{Z `} (@code{calc-kbd-push}) and @kbd{Z '}
  27251. (@code{calc-kbd-pop}) commands give you both of these capabilities.
  27252. When you type @kbd{Z `} (with a grave accent),
  27253. the values of various mode settings are saved away. The ten ``quick''
  27254. variables @code{q0} through @code{q9} are also saved. When
  27255. you type @w{@kbd{Z '}} (with an apostrophe), these values are restored.
  27256. Pairs of @kbd{Z `} and @kbd{Z '} commands may be nested.
  27257. If a keyboard macro halts due to an error in between a @kbd{Z `} and
  27258. a @kbd{Z '}, the saved values will be restored correctly even though
  27259. the macro never reaches the @kbd{Z '} command. Thus you can use
  27260. @kbd{Z `} and @kbd{Z '} without having to worry about what happens
  27261. in exceptional conditions.
  27262. If you type @kbd{Z `} ``live'' (not in a keyboard macro), Calc puts
  27263. you into a ``recursive edit.'' You can tell you are in a recursive
  27264. edit because there will be extra square brackets in the mode line,
  27265. as in @samp{[(Calculator)]}. These brackets will go away when you
  27266. type the matching @kbd{Z '} command. The modes and quick variables
  27267. will be saved and restored in just the same way as if actual keyboard
  27268. macros were involved.
  27269. The modes saved by @kbd{Z `} and @kbd{Z '} are the current precision
  27270. and binary word size, the angular mode (Deg, Rad, or HMS), the
  27271. simplification mode, Algebraic mode, Symbolic mode, Infinite mode,
  27272. Matrix or Scalar mode, Fraction mode, and the current complex mode
  27273. (Polar or Rectangular). The ten ``quick'' variables' values (or lack
  27274. thereof) are also saved.
  27275. Most mode-setting commands act as toggles, but with a numeric prefix
  27276. they force the mode either on (positive prefix) or off (negative
  27277. or zero prefix). Since you don't know what the environment might
  27278. be when you invoke your macro, it's best to use prefix arguments
  27279. for all mode-setting commands inside the macro.
  27280. In fact, @kbd{C-u Z `} is like @kbd{Z `} except that it sets the modes
  27281. listed above to their default values. As usual, the matching @kbd{Z '}
  27282. will restore the modes to their settings from before the @kbd{C-u Z `}.
  27283. Also, @w{@kbd{Z `}} with a negative prefix argument resets the algebraic mode
  27284. to its default (off) but leaves the other modes the same as they were
  27285. outside the construct.
  27286. The contents of the stack and trail, values of non-quick variables, and
  27287. other settings such as the language mode and the various display modes,
  27288. are @emph{not} affected by @kbd{Z `} and @kbd{Z '}.
  27289. @node Queries in Macros, , Local Values in Macros, Keyboard Macros
  27290. @subsection Queries in Keyboard Macros
  27291. @c @noindent
  27292. @c @kindex Z =
  27293. @c @pindex calc-kbd-report
  27294. @c The @kbd{Z =} (@code{calc-kbd-report}) command displays an informative
  27295. @c message including the value on the top of the stack. You are prompted
  27296. @c to enter a string. That string, along with the top-of-stack value,
  27297. @c is displayed unless @kbd{m w} (@code{calc-working}) has been used
  27298. @c to turn such messages off.
  27299. @noindent
  27300. @kindex Z #
  27301. @pindex calc-kbd-query
  27302. The @kbd{Z #} (@code{calc-kbd-query}) command prompts for an algebraic
  27303. entry which takes its input from the keyboard, even during macro
  27304. execution. All the normal conventions of algebraic input, including the
  27305. use of @kbd{$} characters, are supported. The prompt message itself is
  27306. taken from the top of the stack, and so must be entered (as a string)
  27307. before the @kbd{Z #} command. (Recall, as a string it can be entered by
  27308. pressing the @kbd{"} key and will appear as a vector when it is put on
  27309. the stack. The prompt message is only put on the stack to provide a
  27310. prompt for the @kbd{Z #} command; it will not play any role in any
  27311. subsequent calculations.) This command allows your keyboard macros to
  27312. accept numbers or formulas as interactive input.
  27313. As an example,
  27314. @kbd{2 @key{RET} "Power: " @key{RET} Z # 3 @key{RET} ^} will prompt for
  27315. input with ``Power: '' in the minibuffer, then return 2 to the provided
  27316. power. (The response to the prompt that's given, 3 in this example,
  27317. will not be part of the macro.)
  27318. @xref{Keyboard Macro Query, , , emacs, the Emacs Manual}, for a description of
  27319. @kbd{C-x q} (@code{kbd-macro-query}), the standard Emacs way to accept
  27320. keyboard input during a keyboard macro. In particular, you can use
  27321. @kbd{C-x q} to enter a recursive edit, which allows the user to perform
  27322. any Calculator operations interactively before pressing @kbd{C-M-c} to
  27323. return control to the keyboard macro.
  27324. @node Invocation Macros, Algebraic Definitions, Keyboard Macros, Programming
  27325. @section Invocation Macros
  27326. @kindex C-x * z
  27327. @kindex Z I
  27328. @pindex calc-user-invocation
  27329. @pindex calc-user-define-invocation
  27330. Calc provides one special keyboard macro, called up by @kbd{C-x * z}
  27331. (@code{calc-user-invocation}), that is intended to allow you to define
  27332. your own special way of starting Calc. To define this ``invocation
  27333. macro,'' create the macro in the usual way with @kbd{C-x (} and
  27334. @kbd{C-x )}, then type @kbd{Z I} (@code{calc-user-define-invocation}).
  27335. There is only one invocation macro, so you don't need to type any
  27336. additional letters after @kbd{Z I}. From now on, you can type
  27337. @kbd{C-x * z} at any time to execute your invocation macro.
  27338. For example, suppose you find yourself often grabbing rectangles of
  27339. numbers into Calc and multiplying their columns. You can do this
  27340. by typing @kbd{C-x * r} to grab, and @kbd{V R : *} to multiply columns.
  27341. To make this into an invocation macro, just type @kbd{C-x ( C-x * r
  27342. V R : * C-x )}, then @kbd{Z I}. Then, to multiply a rectangle of data,
  27343. just mark the data in its buffer in the usual way and type @kbd{C-x * z}.
  27344. Invocation macros are treated like regular Emacs keyboard macros;
  27345. all the special features described above for @kbd{Z K}-style macros
  27346. do not apply. @kbd{C-x * z} is just like @kbd{C-x e}, except that it
  27347. uses the macro that was last stored by @kbd{Z I}. (In fact, the
  27348. macro does not even have to have anything to do with Calc!)
  27349. The @kbd{m m} command saves the last invocation macro defined by
  27350. @kbd{Z I} along with all the other Calc mode settings.
  27351. @xref{General Mode Commands}.
  27352. @node Algebraic Definitions, Lisp Definitions, Invocation Macros, Programming
  27353. @section Programming with Formulas
  27354. @noindent
  27355. @kindex Z F
  27356. @pindex calc-user-define-formula
  27357. @cindex Programming with algebraic formulas
  27358. Another way to create a new Calculator command uses algebraic formulas.
  27359. The @kbd{Z F} (@code{calc-user-define-formula}) command stores the
  27360. formula at the top of the stack as the definition for a key. This
  27361. command prompts for five things: The key, the command name, the function
  27362. name, the argument list, and the behavior of the command when given
  27363. non-numeric arguments.
  27364. For example, suppose we type @kbd{' a+2b @key{RET}} to push the formula
  27365. @samp{a + 2*b} onto the stack. We now type @kbd{Z F m} to define this
  27366. formula on the @kbd{z m} key sequence. The next prompt is for a command
  27367. name, beginning with @samp{calc-}, which should be the long (@kbd{M-x}) form
  27368. for the new command. If you simply press @key{RET}, a default name like
  27369. @code{calc-User-m} will be constructed. In our example, suppose we enter
  27370. @kbd{spam @key{RET}} to define the new command as @code{calc-spam}.
  27371. If you want to give the formula a long-style name only, you can press
  27372. @key{SPC} or @key{RET} when asked which single key to use. For example
  27373. @kbd{Z F @key{RET} spam @key{RET}} defines the new command as
  27374. @kbd{M-x calc-spam}, with no keyboard equivalent.
  27375. The third prompt is for an algebraic function name. The default is to
  27376. use the same name as the command name but without the @samp{calc-}
  27377. prefix. (If this is of the form @samp{User-m}, the hyphen is removed so
  27378. it won't be taken for a minus sign in algebraic formulas.)
  27379. This is the name you will use if you want to enter your
  27380. new function in an algebraic formula. Suppose we enter @kbd{yow @key{RET}}.
  27381. Then the new function can be invoked by pushing two numbers on the
  27382. stack and typing @kbd{z m} or @kbd{x spam}, or by entering the algebraic
  27383. formula @samp{yow(x,y)}.
  27384. The fourth prompt is for the function's argument list. This is used to
  27385. associate values on the stack with the variables that appear in the formula.
  27386. The default is a list of all variables which appear in the formula, sorted
  27387. into alphabetical order. In our case, the default would be @samp{(a b)}.
  27388. This means that, when the user types @kbd{z m}, the Calculator will remove
  27389. two numbers from the stack, substitute these numbers for @samp{a} and
  27390. @samp{b} (respectively) in the formula, then simplify the formula and
  27391. push the result on the stack. In other words, @kbd{10 @key{RET} 100 z m}
  27392. would replace the 10 and 100 on the stack with the number 210, which is
  27393. @expr{a + 2 b} with @expr{a=10} and @expr{b=100}. Likewise, the formula
  27394. @samp{yow(10, 100)} will be evaluated by substituting @expr{a=10} and
  27395. @expr{b=100} in the definition.
  27396. You can rearrange the order of the names before pressing @key{RET} to
  27397. control which stack positions go to which variables in the formula. If
  27398. you remove a variable from the argument list, that variable will be left
  27399. in symbolic form by the command. Thus using an argument list of @samp{(b)}
  27400. for our function would cause @kbd{10 z m} to replace the 10 on the stack
  27401. with the formula @samp{a + 20}. If we had used an argument list of
  27402. @samp{(b a)}, the result with inputs 10 and 100 would have been 120.
  27403. You can also put a nameless function on the stack instead of just a
  27404. formula, as in @samp{<a, b : a + 2 b>}. @xref{Specifying Operators}.
  27405. In this example, the command will be defined by the formula @samp{a + 2 b}
  27406. using the argument list @samp{(a b)}.
  27407. The final prompt is a y-or-n question concerning what to do if symbolic
  27408. arguments are given to your function. If you answer @kbd{y}, then
  27409. executing @kbd{z m} (using the original argument list @samp{(a b)}) with
  27410. arguments @expr{10} and @expr{x} will leave the function in symbolic
  27411. form, i.e., @samp{yow(10,x)}. On the other hand, if you answer @kbd{n},
  27412. then the formula will always be expanded, even for non-constant
  27413. arguments: @samp{10 + 2 x}. If you never plan to feed algebraic
  27414. formulas to your new function, it doesn't matter how you answer this
  27415. question.
  27416. If you answered @kbd{y} to this question you can still cause a function
  27417. call to be expanded by typing @kbd{a "} (@code{calc-expand-formula}).
  27418. Also, Calc will expand the function if necessary when you take a
  27419. derivative or integral or solve an equation involving the function.
  27420. @kindex Z G
  27421. @pindex calc-get-user-defn
  27422. Once you have defined a formula on a key, you can retrieve this formula
  27423. with the @kbd{Z G} (@code{calc-user-define-get-defn}) command. Press a
  27424. key, and this command pushes the formula that was used to define that
  27425. key onto the stack. Actually, it pushes a nameless function that
  27426. specifies both the argument list and the defining formula. You will get
  27427. an error message if the key is undefined, or if the key was not defined
  27428. by a @kbd{Z F} command.
  27429. The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
  27430. been defined by a formula uses a variant of the @code{calc-edit} command
  27431. to edit the defining formula. Press @kbd{C-c C-c} to finish editing and
  27432. store the new formula back in the definition, or kill the buffer with
  27433. @kbd{C-x k} to
  27434. cancel the edit. (The argument list and other properties of the
  27435. definition are unchanged; to adjust the argument list, you can use
  27436. @kbd{Z G} to grab the function onto the stack, edit with @kbd{`}, and
  27437. then re-execute the @kbd{Z F} command.)
  27438. As usual, the @kbd{Z P} command records your definition permanently.
  27439. In this case it will permanently record all three of the relevant
  27440. definitions: the key, the command, and the function.
  27441. You may find it useful to turn off the default simplifications with
  27442. @kbd{m O} (@code{calc-no-simplify-mode}) when entering a formula to be
  27443. used as a function definition. For example, the formula @samp{deriv(a^2,v)}
  27444. which might be used to define a new function @samp{dsqr(a,v)} will be
  27445. ``simplified'' to 0 immediately upon entry since @code{deriv} considers
  27446. @expr{a} to be constant with respect to @expr{v}. Turning off
  27447. default simplifications cures this problem: The definition will be stored
  27448. in symbolic form without ever activating the @code{deriv} function. Press
  27449. @kbd{m D} to turn the default simplifications back on afterwards.
  27450. @node Lisp Definitions, , Algebraic Definitions, Programming
  27451. @section Programming with Lisp
  27452. @noindent
  27453. The Calculator can be programmed quite extensively in Lisp. All you
  27454. do is write a normal Lisp function definition, but with @code{defmath}
  27455. in place of @code{defun}. This has the same form as @code{defun}, but it
  27456. automagically replaces calls to standard Lisp functions like @code{+} and
  27457. @code{zerop} with calls to the corresponding functions in Calc's own library.
  27458. Thus you can write natural-looking Lisp code which operates on all of the
  27459. standard Calculator data types. You can then use @kbd{Z D} if you wish to
  27460. bind your new command to a @kbd{z}-prefix key sequence. The @kbd{Z E} command
  27461. will not edit a Lisp-based definition.
  27462. Emacs Lisp is described in the GNU Emacs Lisp Reference Manual. This section
  27463. assumes a familiarity with Lisp programming concepts; if you do not know
  27464. Lisp, you may find keyboard macros or rewrite rules to be an easier way
  27465. to program the Calculator.
  27466. This section first discusses ways to write commands, functions, or
  27467. small programs to be executed inside of Calc. Then it discusses how
  27468. your own separate programs are able to call Calc from the outside.
  27469. Finally, there is a list of internal Calc functions and data structures
  27470. for the true Lisp enthusiast.
  27471. @menu
  27472. * Defining Functions::
  27473. * Defining Simple Commands::
  27474. * Defining Stack Commands::
  27475. * Argument Qualifiers::
  27476. * Example Definitions::
  27477. * Calling Calc from Your Programs::
  27478. * Internals::
  27479. @end menu
  27480. @node Defining Functions, Defining Simple Commands, Lisp Definitions, Lisp Definitions
  27481. @subsection Defining New Functions
  27482. @noindent
  27483. @findex defmath
  27484. The @code{defmath} function (actually a Lisp macro) is like @code{defun}
  27485. except that code in the body of the definition can make use of the full
  27486. range of Calculator data types. The prefix @samp{calcFunc-} is added
  27487. to the specified name to get the actual Lisp function name. As a simple
  27488. example,
  27489. @example
  27490. (defmath myfact (n)
  27491. (if (> n 0)
  27492. (* n (myfact (1- n)))
  27493. 1))
  27494. @end example
  27495. @noindent
  27496. This actually expands to the code,
  27497. @example
  27498. (defun calcFunc-myfact (n)
  27499. (if (math-posp n)
  27500. (math-mul n (calcFunc-myfact (math-add n -1)))
  27501. 1))
  27502. @end example
  27503. @noindent
  27504. This function can be used in algebraic expressions, e.g., @samp{myfact(5)}.
  27505. The @samp{myfact} function as it is defined above has the bug that an
  27506. expression @samp{myfact(a+b)} will be simplified to 1 because the
  27507. formula @samp{a+b} is not considered to be @code{posp}. A robust
  27508. factorial function would be written along the following lines:
  27509. @smallexample
  27510. (defmath myfact (n)
  27511. (if (> n 0)
  27512. (* n (myfact (1- n)))
  27513. (if (= n 0)
  27514. 1
  27515. nil))) ; this could be simplified as: (and (= n 0) 1)
  27516. @end smallexample
  27517. If a function returns @code{nil}, it is left unsimplified by the Calculator
  27518. (except that its arguments will be simplified). Thus, @samp{myfact(a+1+2)}
  27519. will be simplified to @samp{myfact(a+3)} but no further. Beware that every
  27520. time the Calculator reexamines this formula it will attempt to resimplify
  27521. it, so your function ought to detect the returning-@code{nil} case as
  27522. efficiently as possible.
  27523. The following standard Lisp functions are treated by @code{defmath}:
  27524. @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^} or
  27525. @code{expt}, @code{=}, @code{<}, @code{>}, @code{<=}, @code{>=},
  27526. @code{/=}, @code{1+}, @code{1-}, @code{logand}, @code{logior}, @code{logxor},
  27527. @code{logandc2}, @code{lognot}. Also, @code{~=} is an abbreviation for
  27528. @code{math-nearly-equal}, which is useful in implementing Taylor series.
  27529. For other functions @var{func}, if a function by the name
  27530. @samp{calcFunc-@var{func}} exists it is used, otherwise if a function by the
  27531. name @samp{math-@var{func}} exists it is used, otherwise if @var{func} itself
  27532. is defined as a function it is used, otherwise @samp{calcFunc-@var{func}} is
  27533. used on the assumption that this is a to-be-defined math function. Also, if
  27534. the function name is quoted as in @samp{('integerp a)} the function name is
  27535. always used exactly as written (but not quoted).
  27536. Variable names have @samp{var-} prepended to them unless they appear in
  27537. the function's argument list or in an enclosing @code{let}, @code{let*},
  27538. @code{for}, or @code{foreach} form,
  27539. or their names already contain a @samp{-} character. Thus a reference to
  27540. @samp{foo} is the same as a reference to @samp{var-foo}.
  27541. A few other Lisp extensions are available in @code{defmath} definitions:
  27542. @itemize @bullet
  27543. @item
  27544. The @code{elt} function accepts any number of index variables.
  27545. Note that Calc vectors are stored as Lisp lists whose first
  27546. element is the symbol @code{vec}; thus, @samp{(elt v 2)} yields
  27547. the second element of vector @code{v}, and @samp{(elt m i j)}
  27548. yields one element of a Calc matrix.
  27549. @item
  27550. The @code{setq} function has been extended to act like the Common
  27551. Lisp @code{setf} function. (The name @code{setf} is recognized as
  27552. a synonym of @code{setq}.) Specifically, the first argument of
  27553. @code{setq} can be an @code{nth}, @code{elt}, @code{car}, or @code{cdr} form,
  27554. in which case the effect is to store into the specified
  27555. element of a list. Thus, @samp{(setq (elt m i j) x)} stores @expr{x}
  27556. into one element of a matrix.
  27557. @item
  27558. A @code{for} looping construct is available. For example,
  27559. @samp{(for ((i 0 10)) body)} executes @code{body} once for each
  27560. binding of @expr{i} from zero to 10. This is like a @code{let}
  27561. form in that @expr{i} is temporarily bound to the loop count
  27562. without disturbing its value outside the @code{for} construct.
  27563. Nested loops, as in @samp{(for ((i 0 10) (j 0 (1- i) 2)) body)},
  27564. are also available. For each value of @expr{i} from zero to 10,
  27565. @expr{j} counts from 0 to @expr{i-1} in steps of two. Note that
  27566. @code{for} has the same general outline as @code{let*}, except
  27567. that each element of the header is a list of three or four
  27568. things, not just two.
  27569. @item
  27570. The @code{foreach} construct loops over elements of a list.
  27571. For example, @samp{(foreach ((x (cdr v))) body)} executes
  27572. @code{body} with @expr{x} bound to each element of Calc vector
  27573. @expr{v} in turn. The purpose of @code{cdr} here is to skip over
  27574. the initial @code{vec} symbol in the vector.
  27575. @item
  27576. The @code{break} function breaks out of the innermost enclosing
  27577. @code{while}, @code{for}, or @code{foreach} loop. If given a
  27578. value, as in @samp{(break x)}, this value is returned by the
  27579. loop. (Lisp loops otherwise always return @code{nil}.)
  27580. @item
  27581. The @code{return} function prematurely returns from the enclosing
  27582. function. For example, @samp{(return (+ x y))} returns @expr{x+y}
  27583. as the value of a function. You can use @code{return} anywhere
  27584. inside the body of the function.
  27585. @end itemize
  27586. Non-integer numbers (and extremely large integers) cannot be included
  27587. directly into a @code{defmath} definition. This is because the Lisp
  27588. reader will fail to parse them long before @code{defmath} ever gets control.
  27589. Instead, use the notation, @samp{:"3.1415"}. In fact, any algebraic
  27590. formula can go between the quotes. For example,
  27591. @smallexample
  27592. (defmath sqexp (x) ; sqexp(x) == sqrt(exp(x)) == exp(x*0.5)
  27593. (and (numberp x)
  27594. (exp :"x * 0.5")))
  27595. @end smallexample
  27596. expands to
  27597. @smallexample
  27598. (defun calcFunc-sqexp (x)
  27599. (and (math-numberp x)
  27600. (calcFunc-exp (math-mul x '(float 5 -1)))))
  27601. @end smallexample
  27602. Note the use of @code{numberp} as a guard to ensure that the argument is
  27603. a number first, returning @code{nil} if not. The exponential function
  27604. could itself have been included in the expression, if we had preferred:
  27605. @samp{:"exp(x * 0.5)"}. As another example, the multiplication-and-recursion
  27606. step of @code{myfact} could have been written
  27607. @example
  27608. :"n * myfact(n-1)"
  27609. @end example
  27610. A good place to put your @code{defmath} commands is your Calc init file
  27611. (the file given by @code{calc-settings-file}, typically
  27612. @file{~/.emacs.d/calc.el}), which will not be loaded until Calc starts.
  27613. If a file named @file{.emacs} exists in your home directory, Emacs reads
  27614. and executes the Lisp forms in this file as it starts up. While it may
  27615. seem reasonable to put your favorite @code{defmath} commands there,
  27616. this has the unfortunate side-effect that parts of the Calculator must be
  27617. loaded in to process the @code{defmath} commands whether or not you will
  27618. actually use the Calculator! If you want to put the @code{defmath}
  27619. commands there (for example, if you redefine @code{calc-settings-file}
  27620. to be @file{.emacs}), a better effect can be had by writing
  27621. @example
  27622. (put 'calc-define 'thing '(progn
  27623. (defmath ... )
  27624. (defmath ... )
  27625. ))
  27626. @end example
  27627. @noindent
  27628. @vindex calc-define
  27629. The @code{put} function adds a @dfn{property} to a symbol. Each Lisp
  27630. symbol has a list of properties associated with it. Here we add a
  27631. property with a name of @code{thing} and a @samp{(progn ...)} form as
  27632. its value. When Calc starts up, and at the start of every Calc command,
  27633. the property list for the symbol @code{calc-define} is checked and the
  27634. values of any properties found are evaluated as Lisp forms. The
  27635. properties are removed as they are evaluated. The property names
  27636. (like @code{thing}) are not used; you should choose something like the
  27637. name of your project so as not to conflict with other properties.
  27638. The net effect is that you can put the above code in your @file{.emacs}
  27639. file and it will not be executed until Calc is loaded. Or, you can put
  27640. that same code in another file which you load by hand either before or
  27641. after Calc itself is loaded.
  27642. The properties of @code{calc-define} are evaluated in the same order
  27643. that they were added. They can assume that the Calc modules @file{calc.el},
  27644. @file{calc-ext.el}, and @file{calc-macs.el} have been fully loaded, and
  27645. that the @file{*Calculator*} buffer will be the current buffer.
  27646. If your @code{calc-define} property only defines algebraic functions,
  27647. you can be sure that it will have been evaluated before Calc tries to
  27648. call your function, even if the file defining the property is loaded
  27649. after Calc is loaded. But if the property defines commands or key
  27650. sequences, it may not be evaluated soon enough. (Suppose it defines the
  27651. new command @code{tweak-calc}; the user can load your file, then type
  27652. @kbd{M-x tweak-calc} before Calc has had chance to do anything.) To
  27653. protect against this situation, you can put
  27654. @example
  27655. (run-hooks 'calc-check-defines)
  27656. @end example
  27657. @findex calc-check-defines
  27658. @noindent
  27659. at the end of your file. The @code{calc-check-defines} function is what
  27660. looks for and evaluates properties on @code{calc-define}; @code{run-hooks}
  27661. has the advantage that it is quietly ignored if @code{calc-check-defines}
  27662. is not yet defined because Calc has not yet been loaded.
  27663. Examples of things that ought to be enclosed in a @code{calc-define}
  27664. property are @code{defmath} calls, @code{define-key} calls that modify
  27665. the Calc key map, and any calls that redefine things defined inside Calc.
  27666. Ordinary @code{defun}s need not be enclosed with @code{calc-define}.
  27667. @node Defining Simple Commands, Defining Stack Commands, Defining Functions, Lisp Definitions
  27668. @subsection Defining New Simple Commands
  27669. @noindent
  27670. @findex interactive
  27671. If a @code{defmath} form contains an @code{interactive} clause, it defines
  27672. a Calculator command. Actually such a @code{defmath} results in @emph{two}
  27673. function definitions: One, a @samp{calcFunc-} function as was just described,
  27674. with the @code{interactive} clause removed. Two, a @samp{calc-} function
  27675. with a suitable @code{interactive} clause and some sort of wrapper to make
  27676. the command work in the Calc environment.
  27677. In the simple case, the @code{interactive} clause has the same form as
  27678. for normal Emacs Lisp commands:
  27679. @smallexample
  27680. (defmath increase-precision (delta)
  27681. "Increase precision by DELTA." ; This is the "documentation string"
  27682. (interactive "p") ; Register this as a M-x-able command
  27683. (setq calc-internal-prec (+ calc-internal-prec delta)))
  27684. @end smallexample
  27685. This expands to the pair of definitions,
  27686. @smallexample
  27687. (defun calc-increase-precision (delta)
  27688. "Increase precision by DELTA."
  27689. (interactive "p")
  27690. (calc-wrapper
  27691. (setq calc-internal-prec (math-add calc-internal-prec delta))))
  27692. (defun calcFunc-increase-precision (delta)
  27693. "Increase precision by DELTA."
  27694. (setq calc-internal-prec (math-add calc-internal-prec delta)))
  27695. @end smallexample
  27696. @noindent
  27697. where in this case the latter function would never really be used! Note
  27698. that since the Calculator stores small integers as plain Lisp integers,
  27699. the @code{math-add} function will work just as well as the native
  27700. @code{+} even when the intent is to operate on native Lisp integers.
  27701. @findex calc-wrapper
  27702. The @samp{calc-wrapper} call invokes a macro which surrounds the body of
  27703. the function with code that looks roughly like this:
  27704. @smallexample
  27705. (let ((calc-command-flags nil))
  27706. (unwind-protect
  27707. (save-current-buffer
  27708. (calc-select-buffer)
  27709. @emph{body of function}
  27710. @emph{renumber stack}
  27711. @emph{clear} Working @emph{message})
  27712. @emph{realign cursor and window}
  27713. @emph{clear Inverse, Hyperbolic, and Keep Args flags}
  27714. @emph{update Emacs mode line}))
  27715. @end smallexample
  27716. @findex calc-select-buffer
  27717. The @code{calc-select-buffer} function selects the @file{*Calculator*}
  27718. buffer if necessary, say, because the command was invoked from inside
  27719. the @file{*Calc Trail*} window.
  27720. @findex calc-set-command-flag
  27721. You can call, for example, @code{(calc-set-command-flag 'no-align)} to
  27722. set the above-mentioned command flags. Calc routines recognize the
  27723. following command flags:
  27724. @table @code
  27725. @item renum-stack
  27726. Stack line numbers @samp{1:}, @samp{2:}, and so on must be renumbered
  27727. after this command completes. This is set by routines like
  27728. @code{calc-push}.
  27729. @item clear-message
  27730. Calc should call @samp{(message "")} if this command completes normally
  27731. (to clear a ``Working@dots{}'' message out of the echo area).
  27732. @item no-align
  27733. Do not move the cursor back to the @samp{.} top-of-stack marker.
  27734. @item position-point
  27735. Use the variables @code{calc-position-point-line} and
  27736. @code{calc-position-point-column} to position the cursor after
  27737. this command finishes.
  27738. @item keep-flags
  27739. Do not clear @code{calc-inverse-flag}, @code{calc-hyperbolic-flag},
  27740. and @code{calc-keep-args-flag} at the end of this command.
  27741. @item do-edit
  27742. Switch to buffer @file{*Calc Edit*} after this command.
  27743. @item hold-trail
  27744. Do not move trail pointer to end of trail when something is recorded
  27745. there.
  27746. @end table
  27747. @kindex Y
  27748. @kindex Y ?
  27749. @vindex calc-Y-help-msgs
  27750. Calc reserves a special prefix key, shift-@kbd{Y}, for user-written
  27751. extensions to Calc. There are no built-in commands that work with
  27752. this prefix key; you must call @code{define-key} from Lisp (probably
  27753. from inside a @code{calc-define} property) to add to it. Initially only
  27754. @kbd{Y ?} is defined; it takes help messages from a list of strings
  27755. (initially @code{nil}) in the variable @code{calc-Y-help-msgs}. All
  27756. other undefined keys except for @kbd{Y} are reserved for use by
  27757. future versions of Calc.
  27758. If you are writing a Calc enhancement which you expect to give to
  27759. others, it is best to minimize the number of @kbd{Y}-key sequences
  27760. you use. In fact, if you have more than one key sequence you should
  27761. consider defining three-key sequences with a @kbd{Y}, then a key that
  27762. stands for your package, then a third key for the particular command
  27763. within your package.
  27764. Users may wish to install several Calc enhancements, and it is possible
  27765. that several enhancements will choose to use the same key. In the
  27766. example below, a variable @code{inc-prec-base-key} has been defined
  27767. to contain the key that identifies the @code{inc-prec} package. Its
  27768. value is initially @code{"P"}, but a user can change this variable
  27769. if necessary without having to modify the file.
  27770. Here is a complete file, @file{inc-prec.el}, which makes a @kbd{Y P I}
  27771. command that increases the precision, and a @kbd{Y P D} command that
  27772. decreases the precision.
  27773. @smallexample
  27774. ;;; Increase and decrease Calc precision. Dave Gillespie, 5/31/91.
  27775. ;; (Include copyright or copyleft stuff here.)
  27776. (defvar inc-prec-base-key "P"
  27777. "Base key for inc-prec.el commands.")
  27778. (put 'calc-define 'inc-prec '(progn
  27779. (define-key calc-mode-map (format "Y%sI" inc-prec-base-key)
  27780. 'increase-precision)
  27781. (define-key calc-mode-map (format "Y%sD" inc-prec-base-key)
  27782. 'decrease-precision)
  27783. (setq calc-Y-help-msgs
  27784. (cons (format "%s + Inc-prec, Dec-prec" inc-prec-base-key)
  27785. calc-Y-help-msgs))
  27786. (defmath increase-precision (delta)
  27787. "Increase precision by DELTA."
  27788. (interactive "p")
  27789. (setq calc-internal-prec (+ calc-internal-prec delta)))
  27790. (defmath decrease-precision (delta)
  27791. "Decrease precision by DELTA."
  27792. (interactive "p")
  27793. (setq calc-internal-prec (- calc-internal-prec delta)))
  27794. )) ; end of calc-define property
  27795. (run-hooks 'calc-check-defines)
  27796. @end smallexample
  27797. @node Defining Stack Commands, Argument Qualifiers, Defining Simple Commands, Lisp Definitions
  27798. @subsection Defining New Stack-Based Commands
  27799. @noindent
  27800. To define a new computational command which takes and/or leaves arguments
  27801. on the stack, a special form of @code{interactive} clause is used.
  27802. @example
  27803. (interactive @var{num} @var{tag})
  27804. @end example
  27805. @noindent
  27806. where @var{num} is an integer, and @var{tag} is a string. The effect is
  27807. to pop @var{num} values off the stack, resimplify them by calling
  27808. @code{calc-normalize}, and hand them to your function according to the
  27809. function's argument list. Your function may include @code{&optional} and
  27810. @code{&rest} parameters, so long as calling the function with @var{num}
  27811. parameters is valid.
  27812. Your function must return either a number or a formula in a form
  27813. acceptable to Calc, or a list of such numbers or formulas. These value(s)
  27814. are pushed onto the stack when the function completes. They are also
  27815. recorded in the Calc Trail buffer on a line beginning with @var{tag},
  27816. a string of (normally) four characters or less. If you omit @var{tag}
  27817. or use @code{nil} as a tag, the result is not recorded in the trail.
  27818. As an example, the definition
  27819. @smallexample
  27820. (defmath myfact (n)
  27821. "Compute the factorial of the integer at the top of the stack."
  27822. (interactive 1 "fact")
  27823. (if (> n 0)
  27824. (* n (myfact (1- n)))
  27825. (and (= n 0) 1)))
  27826. @end smallexample
  27827. @noindent
  27828. is a version of the factorial function shown previously which can be used
  27829. as a command as well as an algebraic function. It expands to
  27830. @smallexample
  27831. (defun calc-myfact ()
  27832. "Compute the factorial of the integer at the top of the stack."
  27833. (interactive)
  27834. (calc-slow-wrapper
  27835. (calc-enter-result 1 "fact"
  27836. (cons 'calcFunc-myfact (calc-top-list-n 1)))))
  27837. (defun calcFunc-myfact (n)
  27838. "Compute the factorial of the integer at the top of the stack."
  27839. (if (math-posp n)
  27840. (math-mul n (calcFunc-myfact (math-add n -1)))
  27841. (and (math-zerop n) 1)))
  27842. @end smallexample
  27843. @findex calc-slow-wrapper
  27844. The @code{calc-slow-wrapper} function is a version of @code{calc-wrapper}
  27845. that automatically puts up a @samp{Working...} message before the
  27846. computation begins. (This message can be turned off by the user
  27847. with an @kbd{m w} (@code{calc-working}) command.)
  27848. @findex calc-top-list-n
  27849. The @code{calc-top-list-n} function returns a list of the specified number
  27850. of values from the top of the stack. It resimplifies each value by
  27851. calling @code{calc-normalize}. If its argument is zero it returns an
  27852. empty list. It does not actually remove these values from the stack.
  27853. @findex calc-enter-result
  27854. The @code{calc-enter-result} function takes an integer @var{num} and string
  27855. @var{tag} as described above, plus a third argument which is either a
  27856. Calculator data object or a list of such objects. These objects are
  27857. resimplified and pushed onto the stack after popping the specified number
  27858. of values from the stack. If @var{tag} is non-@code{nil}, the values
  27859. being pushed are also recorded in the trail.
  27860. Note that if @code{calcFunc-myfact} returns @code{nil} this represents
  27861. ``leave the function in symbolic form.'' To return an actual empty list,
  27862. in the sense that @code{calc-enter-result} will push zero elements back
  27863. onto the stack, you should return the special value @samp{'(nil)}, a list
  27864. containing the single symbol @code{nil}.
  27865. The @code{interactive} declaration can actually contain a limited
  27866. Emacs-style code string as well which comes just before @var{num} and
  27867. @var{tag}. Currently the only Emacs code supported is @samp{"p"}, as in
  27868. @example
  27869. (defmath foo (a b &optional c)
  27870. (interactive "p" 2 "foo")
  27871. @var{body})
  27872. @end example
  27873. In this example, the command @code{calc-foo} will evaluate the expression
  27874. @samp{foo(a,b)} if executed with no argument, or @samp{foo(a,b,n)} if
  27875. executed with a numeric prefix argument of @expr{n}.
  27876. The other code string allowed is @samp{"m"} (unrelated to the usual @samp{"m"}
  27877. code as used with @code{defun}). It uses the numeric prefix argument as the
  27878. number of objects to remove from the stack and pass to the function.
  27879. In this case, the integer @var{num} serves as a default number of
  27880. arguments to be used when no prefix is supplied.
  27881. @node Argument Qualifiers, Example Definitions, Defining Stack Commands, Lisp Definitions
  27882. @subsection Argument Qualifiers
  27883. @noindent
  27884. Anywhere a parameter name can appear in the parameter list you can also use
  27885. an @dfn{argument qualifier}. Thus the general form of a definition is:
  27886. @example
  27887. (defmath @var{name} (@var{param} @var{param...}
  27888. &optional @var{param} @var{param...}
  27889. &rest @var{param})
  27890. @var{body})
  27891. @end example
  27892. @noindent
  27893. where each @var{param} is either a symbol or a list of the form
  27894. @example
  27895. (@var{qual} @var{param})
  27896. @end example
  27897. The following qualifiers are recognized:
  27898. @table @samp
  27899. @item complete
  27900. @findex complete
  27901. The argument must not be an incomplete vector, interval, or complex number.
  27902. (This is rarely needed since the Calculator itself will never call your
  27903. function with an incomplete argument. But there is nothing stopping your
  27904. own Lisp code from calling your function with an incomplete argument.)
  27905. @item integer
  27906. @findex integer
  27907. The argument must be an integer. If it is an integer-valued float
  27908. it will be accepted but converted to integer form. Non-integers and
  27909. formulas are rejected.
  27910. @item natnum
  27911. @findex natnum
  27912. Like @samp{integer}, but the argument must be non-negative.
  27913. @item fixnum
  27914. @findex fixnum
  27915. Like @samp{integer}, but the argument must fit into a native Lisp integer,
  27916. which on most systems means less than 2^23 in absolute value. The
  27917. argument is converted into Lisp-integer form if necessary.
  27918. @item float
  27919. @findex float
  27920. The argument is converted to floating-point format if it is a number or
  27921. vector. If it is a formula it is left alone. (The argument is never
  27922. actually rejected by this qualifier.)
  27923. @item @var{pred}
  27924. The argument must satisfy predicate @var{pred}, which is one of the
  27925. standard Calculator predicates. @xref{Predicates}.
  27926. @item not-@var{pred}
  27927. The argument must @emph{not} satisfy predicate @var{pred}.
  27928. @end table
  27929. For example,
  27930. @example
  27931. (defmath foo (a (constp (not-matrixp b)) &optional (float c)
  27932. &rest (integer d))
  27933. @var{body})
  27934. @end example
  27935. @noindent
  27936. expands to
  27937. @example
  27938. (defun calcFunc-foo (a b &optional c &rest d)
  27939. (and (math-matrixp b)
  27940. (math-reject-arg b 'not-matrixp))
  27941. (or (math-constp b)
  27942. (math-reject-arg b 'constp))
  27943. (and c (setq c (math-check-float c)))
  27944. (setq d (mapcar 'math-check-integer d))
  27945. @var{body})
  27946. @end example
  27947. @noindent
  27948. which performs the necessary checks and conversions before executing the
  27949. body of the function.
  27950. @node Example Definitions, Calling Calc from Your Programs, Argument Qualifiers, Lisp Definitions
  27951. @subsection Example Definitions
  27952. @noindent
  27953. This section includes some Lisp programming examples on a larger scale.
  27954. These programs make use of some of the Calculator's internal functions;
  27955. @pxref{Internals}.
  27956. @menu
  27957. * Bit Counting Example::
  27958. * Sine Example::
  27959. @end menu
  27960. @node Bit Counting Example, Sine Example, Example Definitions, Example Definitions
  27961. @subsubsection Bit-Counting
  27962. @noindent
  27963. @ignore
  27964. @starindex
  27965. @end ignore
  27966. @tindex bcount
  27967. Calc does not include a built-in function for counting the number of
  27968. ``one'' bits in a binary integer. It's easy to invent one using @kbd{b u}
  27969. to convert the integer to a set, and @kbd{V #} to count the elements of
  27970. that set; let's write a function that counts the bits without having to
  27971. create an intermediate set.
  27972. @smallexample
  27973. (defmath bcount ((natnum n))
  27974. (interactive 1 "bcnt")
  27975. (let ((count 0))
  27976. (while (> n 0)
  27977. (if (oddp n)
  27978. (setq count (1+ count)))
  27979. (setq n (lsh n -1)))
  27980. count))
  27981. @end smallexample
  27982. @noindent
  27983. When this is expanded by @code{defmath}, it will become the following
  27984. Emacs Lisp function:
  27985. @smallexample
  27986. (defun calcFunc-bcount (n)
  27987. (setq n (math-check-natnum n))
  27988. (let ((count 0))
  27989. (while (math-posp n)
  27990. (if (math-oddp n)
  27991. (setq count (math-add count 1)))
  27992. (setq n (calcFunc-lsh n -1)))
  27993. count))
  27994. @end smallexample
  27995. If the input numbers are large, this function involves a fair amount
  27996. of arithmetic. A binary right shift is essentially a division by two;
  27997. recall that Calc stores integers in decimal form so bit shifts must
  27998. involve actual division.
  27999. To gain a bit more efficiency, we could divide the integer into
  28000. @var{n}-bit chunks, each of which can be handled quickly because
  28001. they fit into Lisp integers. It turns out that Calc's arithmetic
  28002. routines are especially fast when dividing by an integer less than
  28003. 1000, so we can set @var{n = 9} bits and use repeated division by 512:
  28004. @smallexample
  28005. (defmath bcount ((natnum n))
  28006. (interactive 1 "bcnt")
  28007. (let ((count 0))
  28008. (while (not (fixnump n))
  28009. (let ((qr (idivmod n 512)))
  28010. (setq count (+ count (bcount-fixnum (cdr qr)))
  28011. n (car qr))))
  28012. (+ count (bcount-fixnum n))))
  28013. (defun bcount-fixnum (n)
  28014. (let ((count 0))
  28015. (while (> n 0)
  28016. (setq count (+ count (logand n 1))
  28017. n (lsh n -1)))
  28018. count))
  28019. @end smallexample
  28020. @noindent
  28021. Note that the second function uses @code{defun}, not @code{defmath}.
  28022. Because this function deals only with native Lisp integers (``fixnums''),
  28023. it can use the actual Emacs @code{+} and related functions rather
  28024. than the slower but more general Calc equivalents which @code{defmath}
  28025. uses.
  28026. The @code{idivmod} function does an integer division, returning both
  28027. the quotient and the remainder at once. Again, note that while it
  28028. might seem that @samp{(logand n 511)} and @samp{(lsh n -9)} are
  28029. more efficient ways to split off the bottom nine bits of @code{n},
  28030. actually they are less efficient because each operation is really
  28031. a division by 512 in disguise; @code{idivmod} allows us to do the
  28032. same thing with a single division by 512.
  28033. @node Sine Example, , Bit Counting Example, Example Definitions
  28034. @subsubsection The Sine Function
  28035. @noindent
  28036. @ignore
  28037. @starindex
  28038. @end ignore
  28039. @tindex mysin
  28040. A somewhat limited sine function could be defined as follows, using the
  28041. well-known Taylor series expansion for
  28042. @texline @math{\sin x}:
  28043. @infoline @samp{sin(x)}:
  28044. @smallexample
  28045. (defmath mysin ((float (anglep x)))
  28046. (interactive 1 "mysn")
  28047. (setq x (to-radians x)) ; Convert from current angular mode.
  28048. (let ((sum x) ; Initial term of Taylor expansion of sin.
  28049. newsum
  28050. (nfact 1) ; "nfact" equals "n" factorial at all times.
  28051. (xnegsqr :"-(x^2)")) ; "xnegsqr" equals -x^2.
  28052. (for ((n 3 100 2)) ; Upper limit of 100 is a good precaution.
  28053. (working "mysin" sum) ; Display "Working" message, if enabled.
  28054. (setq nfact (* nfact (1- n) n)
  28055. x (* x xnegsqr)
  28056. newsum (+ sum (/ x nfact)))
  28057. (if (~= newsum sum) ; If newsum is "nearly equal to" sum,
  28058. (break)) ; then we are done.
  28059. (setq sum newsum))
  28060. sum))
  28061. @end smallexample
  28062. The actual @code{sin} function in Calc works by first reducing the problem
  28063. to a sine or cosine of a nonnegative number less than @cpiover{4}. This
  28064. ensures that the Taylor series will converge quickly. Also, the calculation
  28065. is carried out with two extra digits of precision to guard against cumulative
  28066. round-off in @samp{sum}. Finally, complex arguments are allowed and handled
  28067. by a separate algorithm.
  28068. @smallexample
  28069. (defmath mysin ((float (scalarp x)))
  28070. (interactive 1 "mysn")
  28071. (setq x (to-radians x)) ; Convert from current angular mode.
  28072. (with-extra-prec 2 ; Evaluate with extra precision.
  28073. (cond ((complexp x)
  28074. (mysin-complex x))
  28075. ((< x 0)
  28076. (- (mysin-raw (- x))) ; Always call mysin-raw with x >= 0.
  28077. (t (mysin-raw x))))))
  28078. (defmath mysin-raw (x)
  28079. (cond ((>= x 7)
  28080. (mysin-raw (% x (two-pi)))) ; Now x < 7.
  28081. ((> x (pi-over-2))
  28082. (- (mysin-raw (- x (pi))))) ; Now -pi/2 <= x <= pi/2.
  28083. ((> x (pi-over-4))
  28084. (mycos-raw (- x (pi-over-2)))) ; Now -pi/2 <= x <= pi/4.
  28085. ((< x (- (pi-over-4)))
  28086. (- (mycos-raw (+ x (pi-over-2))))) ; Now -pi/4 <= x <= pi/4,
  28087. (t (mysin-series x)))) ; so the series will be efficient.
  28088. @end smallexample
  28089. @noindent
  28090. where @code{mysin-complex} is an appropriate function to handle complex
  28091. numbers, @code{mysin-series} is the routine to compute the sine Taylor
  28092. series as before, and @code{mycos-raw} is a function analogous to
  28093. @code{mysin-raw} for cosines.
  28094. The strategy is to ensure that @expr{x} is nonnegative before calling
  28095. @code{mysin-raw}. This function then recursively reduces its argument
  28096. to a suitable range, namely, plus-or-minus @cpiover{4}. Note that each
  28097. test, and particularly the first comparison against 7, is designed so
  28098. that small roundoff errors cannot produce an infinite loop. (Suppose
  28099. we compared with @samp{(two-pi)} instead; if due to roundoff problems
  28100. the modulo operator ever returned @samp{(two-pi)} exactly, an infinite
  28101. recursion could result!) We use modulo only for arguments that will
  28102. clearly get reduced, knowing that the next rule will catch any reductions
  28103. that this rule misses.
  28104. If a program is being written for general use, it is important to code
  28105. it carefully as shown in this second example. For quick-and-dirty programs,
  28106. when you know that your own use of the sine function will never encounter
  28107. a large argument, a simpler program like the first one shown is fine.
  28108. @node Calling Calc from Your Programs, Internals, Example Definitions, Lisp Definitions
  28109. @subsection Calling Calc from Your Lisp Programs
  28110. @noindent
  28111. A later section (@pxref{Internals}) gives a full description of
  28112. Calc's internal Lisp functions. It's not hard to call Calc from
  28113. inside your programs, but the number of these functions can be daunting.
  28114. So Calc provides one special ``programmer-friendly'' function called
  28115. @code{calc-eval} that can be made to do just about everything you
  28116. need. It's not as fast as the low-level Calc functions, but it's
  28117. much simpler to use!
  28118. It may seem that @code{calc-eval} itself has a daunting number of
  28119. options, but they all stem from one simple operation.
  28120. In its simplest manifestation, @samp{(calc-eval "1+2")} parses the
  28121. string @code{"1+2"} as if it were a Calc algebraic entry and returns
  28122. the result formatted as a string: @code{"3"}.
  28123. Since @code{calc-eval} is on the list of recommended @code{autoload}
  28124. functions, you don't need to make any special preparations to load
  28125. Calc before calling @code{calc-eval} the first time. Calc will be
  28126. loaded and initialized for you.
  28127. All the Calc modes that are currently in effect will be used when
  28128. evaluating the expression and formatting the result.
  28129. @ifinfo
  28130. @example
  28131. @end example
  28132. @end ifinfo
  28133. @subsubsection Additional Arguments to @code{calc-eval}
  28134. @noindent
  28135. If the input string parses to a list of expressions, Calc returns
  28136. the results separated by @code{", "}. You can specify a different
  28137. separator by giving a second string argument to @code{calc-eval}:
  28138. @samp{(calc-eval "1+2,3+4" ";")} returns @code{"3;7"}.
  28139. The ``separator'' can also be any of several Lisp symbols which
  28140. request other behaviors from @code{calc-eval}. These are discussed
  28141. one by one below.
  28142. You can give additional arguments to be substituted for
  28143. @samp{$}, @samp{$$}, and so on in the main expression. For
  28144. example, @samp{(calc-eval "$/$$" nil "7" "1+1")} evaluates the
  28145. expression @code{"7/(1+1)"} to yield the result @code{"3.5"}
  28146. (assuming Fraction mode is not in effect). Note the @code{nil}
  28147. used as a placeholder for the item-separator argument.
  28148. @ifinfo
  28149. @example
  28150. @end example
  28151. @end ifinfo
  28152. @subsubsection Error Handling
  28153. @noindent
  28154. If @code{calc-eval} encounters an error, it returns a list containing
  28155. the character position of the error, plus a suitable message as a
  28156. string. Note that @samp{1 / 0} is @emph{not} an error by Calc's
  28157. standards; it simply returns the string @code{"1 / 0"} which is the
  28158. division left in symbolic form. But @samp{(calc-eval "1/")} will
  28159. return the list @samp{(2 "Expected a number")}.
  28160. If you bind the variable @code{calc-eval-error} to @code{t}
  28161. using a @code{let} form surrounding the call to @code{calc-eval},
  28162. errors instead call the Emacs @code{error} function which aborts
  28163. to the Emacs command loop with a beep and an error message.
  28164. If you bind this variable to the symbol @code{string}, error messages
  28165. are returned as strings instead of lists. The character position is
  28166. ignored.
  28167. As a courtesy to other Lisp code which may be using Calc, be sure
  28168. to bind @code{calc-eval-error} using @code{let} rather than changing
  28169. it permanently with @code{setq}.
  28170. @ifinfo
  28171. @example
  28172. @end example
  28173. @end ifinfo
  28174. @subsubsection Numbers Only
  28175. @noindent
  28176. Sometimes it is preferable to treat @samp{1 / 0} as an error
  28177. rather than returning a symbolic result. If you pass the symbol
  28178. @code{num} as the second argument to @code{calc-eval}, results
  28179. that are not constants are treated as errors. The error message
  28180. reported is the first @code{calc-why} message if there is one,
  28181. or otherwise ``Number expected.''
  28182. A result is ``constant'' if it is a number, vector, or other
  28183. object that does not include variables or function calls. If it
  28184. is a vector, the components must themselves be constants.
  28185. @ifinfo
  28186. @example
  28187. @end example
  28188. @end ifinfo
  28189. @subsubsection Default Modes
  28190. @noindent
  28191. If the first argument to @code{calc-eval} is a list whose first
  28192. element is a formula string, then @code{calc-eval} sets all the
  28193. various Calc modes to their default values while the formula is
  28194. evaluated and formatted. For example, the precision is set to 12
  28195. digits, digit grouping is turned off, and the Normal language
  28196. mode is used.
  28197. This same principle applies to the other options discussed below.
  28198. If the first argument would normally be @var{x}, then it can also
  28199. be the list @samp{(@var{x})} to use the default mode settings.
  28200. If there are other elements in the list, they are taken as
  28201. variable-name/value pairs which override the default mode
  28202. settings. Look at the documentation at the front of the
  28203. @file{calc.el} file to find the names of the Lisp variables for
  28204. the various modes. The mode settings are restored to their
  28205. original values when @code{calc-eval} is done.
  28206. For example, @samp{(calc-eval '("$+$$" calc-internal-prec 8) 'num a b)}
  28207. computes the sum of two numbers, requiring a numeric result, and
  28208. using default mode settings except that the precision is 8 instead
  28209. of the default of 12.
  28210. It's usually best to use this form of @code{calc-eval} unless your
  28211. program actually considers the interaction with Calc's mode settings
  28212. to be a feature. This will avoid all sorts of potential ``gotchas'';
  28213. consider what happens with @samp{(calc-eval "sqrt(2)" 'num)}
  28214. when the user has left Calc in Symbolic mode or No-Simplify mode.
  28215. As another example, @samp{(equal (calc-eval '("$<$$") nil a b) "1")}
  28216. checks if the number in string @expr{a} is less than the one in
  28217. string @expr{b}. Without using a list, the integer 1 might
  28218. come out in a variety of formats which would be hard to test for
  28219. conveniently: @code{"1"}, @code{"8#1"}, @code{"00001"}. (But
  28220. see ``Predicates'' mode, below.)
  28221. @ifinfo
  28222. @example
  28223. @end example
  28224. @end ifinfo
  28225. @subsubsection Raw Numbers
  28226. @noindent
  28227. Normally all input and output for @code{calc-eval} is done with strings.
  28228. You can do arithmetic with, say, @samp{(calc-eval "$+$$" nil a b)}
  28229. in place of @samp{(+ a b)}, but this is very inefficient since the
  28230. numbers must be converted to and from string format as they are passed
  28231. from one @code{calc-eval} to the next.
  28232. If the separator is the symbol @code{raw}, the result will be returned
  28233. as a raw Calc data structure rather than a string. You can read about
  28234. how these objects look in the following sections, but usually you can
  28235. treat them as ``black box'' objects with no important internal
  28236. structure.
  28237. There is also a @code{rawnum} symbol, which is a combination of
  28238. @code{raw} (returning a raw Calc object) and @code{num} (signaling
  28239. an error if that object is not a constant).
  28240. You can pass a raw Calc object to @code{calc-eval} in place of a
  28241. string, either as the formula itself or as one of the @samp{$}
  28242. arguments. Thus @samp{(calc-eval "$+$$" 'raw a b)} is an
  28243. addition function that operates on raw Calc objects. Of course
  28244. in this case it would be easier to call the low-level @code{math-add}
  28245. function in Calc, if you can remember its name.
  28246. In particular, note that a plain Lisp integer is acceptable to Calc
  28247. as a raw object. (All Lisp integers are accepted on input, but
  28248. integers of more than six decimal digits are converted to ``big-integer''
  28249. form for output. @xref{Data Type Formats}.)
  28250. When it comes time to display the object, just use @samp{(calc-eval a)}
  28251. to format it as a string.
  28252. It is an error if the input expression evaluates to a list of
  28253. values. The separator symbol @code{list} is like @code{raw}
  28254. except that it returns a list of one or more raw Calc objects.
  28255. Note that a Lisp string is not a valid Calc object, nor is a list
  28256. containing a string. Thus you can still safely distinguish all the
  28257. various kinds of error returns discussed above.
  28258. @ifinfo
  28259. @example
  28260. @end example
  28261. @end ifinfo
  28262. @subsubsection Predicates
  28263. @noindent
  28264. If the separator symbol is @code{pred}, the result of the formula is
  28265. treated as a true/false value; @code{calc-eval} returns @code{t} or
  28266. @code{nil}, respectively. A value is considered ``true'' if it is a
  28267. non-zero number, or false if it is zero or if it is not a number.
  28268. For example, @samp{(calc-eval "$<$$" 'pred a b)} tests whether
  28269. one value is less than another.
  28270. As usual, it is also possible for @code{calc-eval} to return one of
  28271. the error indicators described above. Lisp will interpret such an
  28272. indicator as ``true'' if you don't check for it explicitly. If you
  28273. wish to have an error register as ``false'', use something like
  28274. @samp{(eq (calc-eval ...) t)}.
  28275. @ifinfo
  28276. @example
  28277. @end example
  28278. @end ifinfo
  28279. @subsubsection Variable Values
  28280. @noindent
  28281. Variables in the formula passed to @code{calc-eval} are not normally
  28282. replaced by their values. If you wish this, you can use the
  28283. @code{evalv} function (@pxref{Algebraic Manipulation}). For example,
  28284. if 4 is stored in Calc variable @code{a} (i.e., in Lisp variable
  28285. @code{var-a}), then @samp{(calc-eval "a+pi")} will return the
  28286. formula @code{"a + pi"}, but @samp{(calc-eval "evalv(a+pi)")}
  28287. will return @code{"7.14159265359"}.
  28288. To store in a Calc variable, just use @code{setq} to store in the
  28289. corresponding Lisp variable. (This is obtained by prepending
  28290. @samp{var-} to the Calc variable name.) Calc routines will
  28291. understand either string or raw form values stored in variables,
  28292. although raw data objects are much more efficient. For example,
  28293. to increment the Calc variable @code{a}:
  28294. @example
  28295. (setq var-a (calc-eval "evalv(a+1)" 'raw))
  28296. @end example
  28297. @ifinfo
  28298. @example
  28299. @end example
  28300. @end ifinfo
  28301. @subsubsection Stack Access
  28302. @noindent
  28303. If the separator symbol is @code{push}, the formula argument is
  28304. evaluated (with possible @samp{$} expansions, as usual). The
  28305. result is pushed onto the Calc stack. The return value is @code{nil}
  28306. (unless there is an error from evaluating the formula, in which
  28307. case the return value depends on @code{calc-eval-error} in the
  28308. usual way).
  28309. If the separator symbol is @code{pop}, the first argument to
  28310. @code{calc-eval} must be an integer instead of a string. That
  28311. many values are popped from the stack and thrown away. A negative
  28312. argument deletes the entry at that stack level. The return value
  28313. is the number of elements remaining in the stack after popping;
  28314. @samp{(calc-eval 0 'pop)} is a good way to measure the size of
  28315. the stack.
  28316. If the separator symbol is @code{top}, the first argument to
  28317. @code{calc-eval} must again be an integer. The value at that
  28318. stack level is formatted as a string and returned. Thus
  28319. @samp{(calc-eval 1 'top)} returns the top-of-stack value. If the
  28320. integer is out of range, @code{nil} is returned.
  28321. The separator symbol @code{rawtop} is just like @code{top} except
  28322. that the stack entry is returned as a raw Calc object instead of
  28323. as a string.
  28324. In all of these cases the first argument can be made a list in
  28325. order to force the default mode settings, as described above.
  28326. Thus @samp{(calc-eval '(2 calc-number-radix 16) 'top)} returns the
  28327. second-to-top stack entry, formatted as a string using the default
  28328. instead of current display modes, except that the radix is
  28329. hexadecimal instead of decimal.
  28330. It is, of course, polite to put the Calc stack back the way you
  28331. found it when you are done, unless the user of your program is
  28332. actually expecting it to affect the stack.
  28333. Note that you do not actually have to switch into the @file{*Calculator*}
  28334. buffer in order to use @code{calc-eval}; it temporarily switches into
  28335. the stack buffer if necessary.
  28336. @ifinfo
  28337. @example
  28338. @end example
  28339. @end ifinfo
  28340. @subsubsection Keyboard Macros
  28341. @noindent
  28342. If the separator symbol is @code{macro}, the first argument must be a
  28343. string of characters which Calc can execute as a sequence of keystrokes.
  28344. This switches into the Calc buffer for the duration of the macro.
  28345. For example, @samp{(calc-eval "vx5\rVR+" 'macro)} pushes the
  28346. vector @samp{[1,2,3,4,5]} on the stack and then replaces it
  28347. with the sum of those numbers. Note that @samp{\r} is the Lisp
  28348. notation for the carriage-return, @key{RET}, character.
  28349. If your keyboard macro wishes to pop the stack, @samp{\C-d} is
  28350. safer than @samp{\177} (the @key{DEL} character) because some
  28351. installations may have switched the meanings of @key{DEL} and
  28352. @kbd{C-h}. Calc always interprets @kbd{C-d} as a synonym for
  28353. ``pop-stack'' regardless of key mapping.
  28354. If you provide a third argument to @code{calc-eval}, evaluation
  28355. of the keyboard macro will leave a record in the Trail using
  28356. that argument as a tag string. Normally the Trail is unaffected.
  28357. The return value in this case is always @code{nil}.
  28358. @ifinfo
  28359. @example
  28360. @end example
  28361. @end ifinfo
  28362. @subsubsection Lisp Evaluation
  28363. @noindent
  28364. Finally, if the separator symbol is @code{eval}, then the Lisp
  28365. @code{eval} function is called on the first argument, which must
  28366. be a Lisp expression rather than a Calc formula. Remember to
  28367. quote the expression so that it is not evaluated until inside
  28368. @code{calc-eval}.
  28369. The difference from plain @code{eval} is that @code{calc-eval}
  28370. switches to the Calc buffer before evaluating the expression.
  28371. For example, @samp{(calc-eval '(setq calc-internal-prec 17) 'eval)}
  28372. will correctly affect the buffer-local Calc precision variable.
  28373. An alternative would be @samp{(calc-eval '(calc-precision 17) 'eval)}.
  28374. This is evaluating a call to the function that is normally invoked
  28375. by the @kbd{p} key, giving it 17 as its ``numeric prefix argument.''
  28376. Note that this function will leave a message in the echo area as
  28377. a side effect. Also, all Calc functions switch to the Calc buffer
  28378. automatically if not invoked from there, so the above call is
  28379. also equivalent to @samp{(calc-precision 17)} by itself.
  28380. In all cases, Calc uses @code{save-excursion} to switch back to
  28381. your original buffer when it is done.
  28382. As usual the first argument can be a list that begins with a Lisp
  28383. expression to use default instead of current mode settings.
  28384. The result of @code{calc-eval} in this usage is just the result
  28385. returned by the evaluated Lisp expression.
  28386. @ifinfo
  28387. @example
  28388. @end example
  28389. @end ifinfo
  28390. @subsubsection Example
  28391. @noindent
  28392. @findex convert-temp
  28393. Here is a sample Emacs command that uses @code{calc-eval}. Suppose
  28394. you have a document with lots of references to temperatures on the
  28395. Fahrenheit scale, say ``98.6 F'', and you wish to convert these
  28396. references to Centigrade. The following command does this conversion.
  28397. Place the Emacs cursor right after the letter ``F'' and invoke the
  28398. command to change ``98.6 F'' to ``37 C''. Or, if the temperature is
  28399. already in Centigrade form, the command changes it back to Fahrenheit.
  28400. @example
  28401. (defun convert-temp ()
  28402. (interactive)
  28403. (save-excursion
  28404. (re-search-backward "[^-.0-9]\\([-.0-9]+\\) *\\([FC]\\)")
  28405. (let* ((top1 (match-beginning 1))
  28406. (bot1 (match-end 1))
  28407. (number (buffer-substring top1 bot1))
  28408. (top2 (match-beginning 2))
  28409. (bot2 (match-end 2))
  28410. (type (buffer-substring top2 bot2)))
  28411. (if (equal type "F")
  28412. (setq type "C"
  28413. number (calc-eval "($ - 32)*5/9" nil number))
  28414. (setq type "F"
  28415. number (calc-eval "$*9/5 + 32" nil number)))
  28416. (goto-char top2)
  28417. (delete-region top2 bot2)
  28418. (insert-before-markers type)
  28419. (goto-char top1)
  28420. (delete-region top1 bot1)
  28421. (if (string-match "\\.$" number) ; change "37." to "37"
  28422. (setq number (substring number 0 -1)))
  28423. (insert number))))
  28424. @end example
  28425. Note the use of @code{insert-before-markers} when changing between
  28426. ``F'' and ``C'', so that the character winds up before the cursor
  28427. instead of after it.
  28428. @node Internals, , Calling Calc from Your Programs, Lisp Definitions
  28429. @subsection Calculator Internals
  28430. @noindent
  28431. This section describes the Lisp functions defined by the Calculator that
  28432. may be of use to user-written Calculator programs (as described in the
  28433. rest of this chapter). These functions are shown by their names as they
  28434. conventionally appear in @code{defmath}. Their full Lisp names are
  28435. generally gotten by prepending @samp{calcFunc-} or @samp{math-} to their
  28436. apparent names. (Names that begin with @samp{calc-} are already in
  28437. their full Lisp form.) You can use the actual full names instead if you
  28438. prefer them, or if you are calling these functions from regular Lisp.
  28439. The functions described here are scattered throughout the various
  28440. Calc component files. Note that @file{calc.el} includes @code{autoload}s
  28441. for only a few component files; when Calc wants to call an advanced
  28442. function it calls @samp{(calc-extensions)} first; this function
  28443. autoloads @file{calc-ext.el}, which in turn autoloads all the functions
  28444. in the remaining component files.
  28445. Because @code{defmath} itself uses the extensions, user-written code
  28446. generally always executes with the extensions already loaded, so
  28447. normally you can use any Calc function and be confident that it will
  28448. be autoloaded for you when necessary. If you are doing something
  28449. special, check carefully to make sure each function you are using is
  28450. from @file{calc.el} or its components, and call @samp{(calc-extensions)}
  28451. before using any function based in @file{calc-ext.el} if you can't
  28452. prove this file will already be loaded.
  28453. @menu
  28454. * Data Type Formats::
  28455. * Interactive Lisp Functions::
  28456. * Stack Lisp Functions::
  28457. * Predicates::
  28458. * Computational Lisp Functions::
  28459. * Vector Lisp Functions::
  28460. * Symbolic Lisp Functions::
  28461. * Formatting Lisp Functions::
  28462. * Hooks::
  28463. @end menu
  28464. @node Data Type Formats, Interactive Lisp Functions, Internals, Internals
  28465. @subsubsection Data Type Formats
  28466. @noindent
  28467. Integers are stored in either of two ways, depending on their magnitude.
  28468. Integers less than one million in absolute value are stored as standard
  28469. Lisp integers. This is the only storage format for Calc data objects
  28470. which is not a Lisp list.
  28471. Large integers are stored as lists of the form @samp{(bigpos @var{d0}
  28472. @var{d1} @var{d2} @dots{})} for sufficiently large positive integers
  28473. (where ``sufficiently large'' depends on the machine), or
  28474. @samp{(bigneg @var{d0} @var{d1} @var{d2} @dots{})} for negative
  28475. integers. Each @var{d} is a base-@expr{10^n} ``digit'' (where again,
  28476. @expr{n} depends on the machine), a Lisp integer from 0 to
  28477. 99@dots{}9. The least significant digit is @var{d0}; the last digit,
  28478. @var{dn}, which is always nonzero, is the most significant digit. For
  28479. example, the integer @mathit{-12345678} might be stored as
  28480. @samp{(bigneg 678 345 12)}.
  28481. The distinction between small and large integers is entirely hidden from
  28482. the user. In @code{defmath} definitions, the Lisp predicate @code{integerp}
  28483. returns true for either kind of integer, and in general both big and small
  28484. integers are accepted anywhere the word ``integer'' is used in this manual.
  28485. If the distinction must be made, native Lisp integers are called @dfn{fixnums}
  28486. and large integers are called @dfn{bignums}.
  28487. Fractions are stored as a list of the form, @samp{(frac @var{n} @var{d})}
  28488. where @var{n} is an integer (big or small) numerator, @var{d} is an
  28489. integer denominator greater than one, and @var{n} and @var{d} are relatively
  28490. prime. Note that fractions where @var{d} is one are automatically converted
  28491. to plain integers by all math routines; fractions where @var{d} is negative
  28492. are normalized by negating the numerator and denominator.
  28493. Floating-point numbers are stored in the form, @samp{(float @var{mant}
  28494. @var{exp})}, where @var{mant} (the ``mantissa'') is an integer less than
  28495. @samp{10^@var{p}} in absolute value (@var{p} represents the current
  28496. precision), and @var{exp} (the ``exponent'') is a fixnum. The value of
  28497. the float is @samp{@var{mant} * 10^@var{exp}}. For example, the number
  28498. @mathit{-3.14} is stored as @samp{(float -314 -2) = -314*10^-2}. Other constraints
  28499. are that the number 0.0 is always stored as @samp{(float 0 0)}, and,
  28500. except for the 0.0 case, the rightmost base-10 digit of @var{mant} is
  28501. always nonzero. (If the rightmost digit is zero, the number is
  28502. rearranged by dividing @var{mant} by ten and incrementing @var{exp}.)
  28503. Rectangular complex numbers are stored in the form @samp{(cplx @var{re}
  28504. @var{im})}, where @var{re} and @var{im} are each real numbers, either
  28505. integers, fractions, or floats. The value is @samp{@var{re} + @var{im}i}.
  28506. The @var{im} part is nonzero; complex numbers with zero imaginary
  28507. components are converted to real numbers automatically.
  28508. Polar complex numbers are stored in the form @samp{(polar @var{r}
  28509. @var{theta})}, where @var{r} is a positive real value and @var{theta}
  28510. is a real value or HMS form representing an angle. This angle is
  28511. usually normalized to lie in the interval @samp{(-180 ..@: 180)} degrees,
  28512. or @samp{(-pi ..@: pi)} radians, according to the current angular mode.
  28513. If the angle is 0 the value is converted to a real number automatically.
  28514. (If the angle is 180 degrees, the value is usually also converted to a
  28515. negative real number.)
  28516. Hours-minutes-seconds forms are stored as @samp{(hms @var{h} @var{m}
  28517. @var{s})}, where @var{h} is an integer or an integer-valued float (i.e.,
  28518. a float with @samp{@var{exp} >= 0}), @var{m} is an integer or integer-valued
  28519. float in the range @w{@samp{[0 ..@: 60)}}, and @var{s} is any real number
  28520. in the range @samp{[0 ..@: 60)}.
  28521. Date forms are stored as @samp{(date @var{n})}, where @var{n} is
  28522. a real number that counts days since midnight on the morning of
  28523. January 1, 1 AD@. If @var{n} is an integer, this is a pure date
  28524. form. If @var{n} is a fraction or float, this is a date/time form.
  28525. Modulo forms are stored as @samp{(mod @var{n} @var{m})}, where @var{m} is a
  28526. positive real number or HMS form, and @var{n} is a real number or HMS
  28527. form in the range @samp{[0 ..@: @var{m})}.
  28528. Error forms are stored as @samp{(sdev @var{x} @var{sigma})}, where @var{x}
  28529. is the mean value and @var{sigma} is the standard deviation. Each
  28530. component is either a number, an HMS form, or a symbolic object
  28531. (a variable or function call). If @var{sigma} is zero, the value is
  28532. converted to a plain real number. If @var{sigma} is negative or
  28533. complex, it is automatically normalized to be a positive real.
  28534. Interval forms are stored as @samp{(intv @var{mask} @var{lo} @var{hi})},
  28535. where @var{mask} is one of the integers 0, 1, 2, or 3, and @var{lo} and
  28536. @var{hi} are real numbers, HMS forms, or symbolic objects. The @var{mask}
  28537. is a binary integer where 1 represents the fact that the interval is
  28538. closed on the high end, and 2 represents the fact that it is closed on
  28539. the low end. (Thus 3 represents a fully closed interval.) The interval
  28540. @w{@samp{(intv 3 @var{x} @var{x})}} is converted to the plain number @var{x};
  28541. intervals @samp{(intv @var{mask} @var{x} @var{x})} for any other @var{mask}
  28542. represent empty intervals. If @var{hi} is less than @var{lo}, the interval
  28543. is converted to a standard empty interval by replacing @var{hi} with @var{lo}.
  28544. Vectors are stored as @samp{(vec @var{v1} @var{v2} @dots{})}, where @var{v1}
  28545. is the first element of the vector, @var{v2} is the second, and so on.
  28546. An empty vector is stored as @samp{(vec)}. A matrix is simply a vector
  28547. where all @var{v}'s are themselves vectors of equal lengths. Note that
  28548. Calc vectors are unrelated to the Emacs Lisp ``vector'' type, which is
  28549. generally unused by Calc data structures.
  28550. Variables are stored as @samp{(var @var{name} @var{sym})}, where
  28551. @var{name} is a Lisp symbol whose print name is used as the visible name
  28552. of the variable, and @var{sym} is a Lisp symbol in which the variable's
  28553. value is actually stored. Thus, @samp{(var pi var-pi)} represents the
  28554. special constant @samp{pi}. Almost always, the form is @samp{(var
  28555. @var{v} var-@var{v})}. If the variable name was entered with @code{#}
  28556. signs (which are converted to hyphens internally), the form is
  28557. @samp{(var @var{u} @var{v})}, where @var{u} is a symbol whose name
  28558. contains @code{#} characters, and @var{v} is a symbol that contains
  28559. @code{-} characters instead. The value of a variable is the Calc
  28560. object stored in its @var{sym} symbol's value cell. If the symbol's
  28561. value cell is void or if it contains @code{nil}, the variable has no
  28562. value. Special constants have the form @samp{(special-const
  28563. @var{value})} stored in their value cell, where @var{value} is a formula
  28564. which is evaluated when the constant's value is requested. Variables
  28565. which represent units are not stored in any special way; they are units
  28566. only because their names appear in the units table. If the value
  28567. cell contains a string, it is parsed to get the variable's value when
  28568. the variable is used.
  28569. A Lisp list with any other symbol as the first element is a function call.
  28570. The symbols @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^},
  28571. and @code{|} represent special binary operators; these lists are always
  28572. of the form @samp{(@var{op} @var{lhs} @var{rhs})} where @var{lhs} is the
  28573. sub-formula on the lefthand side and @var{rhs} is the sub-formula on the
  28574. right. The symbol @code{neg} represents unary negation; this list is always
  28575. of the form @samp{(neg @var{arg})}. Any other symbol @var{func} represents a
  28576. function that would be displayed in function-call notation; the symbol
  28577. @var{func} is in general always of the form @samp{calcFunc-@var{name}}.
  28578. The function cell of the symbol @var{func} should contain a Lisp function
  28579. for evaluating a call to @var{func}. This function is passed the remaining
  28580. elements of the list (themselves already evaluated) as arguments; such
  28581. functions should return @code{nil} or call @code{reject-arg} to signify
  28582. that they should be left in symbolic form, or they should return a Calc
  28583. object which represents their value, or a list of such objects if they
  28584. wish to return multiple values. (The latter case is allowed only for
  28585. functions which are the outer-level call in an expression whose value is
  28586. about to be pushed on the stack; this feature is considered obsolete
  28587. and is not used by any built-in Calc functions.)
  28588. @node Interactive Lisp Functions, Stack Lisp Functions, Data Type Formats, Internals
  28589. @subsubsection Interactive Functions
  28590. @noindent
  28591. The functions described here are used in implementing interactive Calc
  28592. commands. Note that this list is not exhaustive! If there is an
  28593. existing command that behaves similarly to the one you want to define,
  28594. you may find helpful tricks by checking the source code for that command.
  28595. @defun calc-set-command-flag flag
  28596. Set the command flag @var{flag}. This is generally a Lisp symbol, but
  28597. may in fact be anything. The effect is to add @var{flag} to the list
  28598. stored in the variable @code{calc-command-flags}, unless it is already
  28599. there. @xref{Defining Simple Commands}.
  28600. @end defun
  28601. @defun calc-clear-command-flag flag
  28602. If @var{flag} appears among the list of currently-set command flags,
  28603. remove it from that list.
  28604. @end defun
  28605. @defun calc-record-undo rec
  28606. Add the ``undo record'' @var{rec} to the list of steps to take if the
  28607. current operation should need to be undone. Stack push and pop functions
  28608. automatically call @code{calc-record-undo}, so the kinds of undo records
  28609. you might need to create take the form @samp{(set @var{sym} @var{value})},
  28610. which says that the Lisp variable @var{sym} was changed and had previously
  28611. contained @var{value}; @samp{(store @var{var} @var{value})} which says that
  28612. the Calc variable @var{var} (a string which is the name of the symbol that
  28613. contains the variable's value) was stored and its previous value was
  28614. @var{value} (either a Calc data object, or @code{nil} if the variable was
  28615. previously void); or @samp{(eval @var{undo} @var{redo} @var{args} @dots{})},
  28616. which means that to undo requires calling the function @samp{(@var{undo}
  28617. @var{args} @dots{})} and, if the undo is later redone, calling
  28618. @samp{(@var{redo} @var{args} @dots{})}.
  28619. @end defun
  28620. @defun calc-record-why msg args
  28621. Record the error or warning message @var{msg}, which is normally a string.
  28622. This message will be replayed if the user types @kbd{w} (@code{calc-why});
  28623. if the message string begins with a @samp{*}, it is considered important
  28624. enough to display even if the user doesn't type @kbd{w}. If one or more
  28625. @var{args} are present, the displayed message will be of the form,
  28626. @samp{@var{msg}: @var{arg1}, @var{arg2}, @dots{}}, where the arguments are
  28627. formatted on the assumption that they are either strings or Calc objects of
  28628. some sort. If @var{msg} is a symbol, it is the name of a Calc predicate
  28629. (such as @code{integerp} or @code{numvecp}) which the arguments did not
  28630. satisfy; it is expanded to a suitable string such as ``Expected an
  28631. integer.'' The @code{reject-arg} function calls @code{calc-record-why}
  28632. automatically; @pxref{Predicates}.
  28633. @end defun
  28634. @defun calc-is-inverse
  28635. This predicate returns true if the current command is inverse,
  28636. i.e., if the Inverse (@kbd{I} key) flag was set.
  28637. @end defun
  28638. @defun calc-is-hyperbolic
  28639. This predicate is the analogous function for the @kbd{H} key.
  28640. @end defun
  28641. @node Stack Lisp Functions, Predicates, Interactive Lisp Functions, Internals
  28642. @subsubsection Stack-Oriented Functions
  28643. @noindent
  28644. The functions described here perform various operations on the Calc
  28645. stack and trail. They are to be used in interactive Calc commands.
  28646. @defun calc-push-list vals n
  28647. Push the Calc objects in list @var{vals} onto the stack at stack level
  28648. @var{n}. If @var{n} is omitted it defaults to 1, so that the elements
  28649. are pushed at the top of the stack. If @var{n} is greater than 1, the
  28650. elements will be inserted into the stack so that the last element will
  28651. end up at level @var{n}, the next-to-last at level @var{n}+1, etc.
  28652. The elements of @var{vals} are assumed to be valid Calc objects, and
  28653. are not evaluated, rounded, or renormalized in any way. If @var{vals}
  28654. is an empty list, nothing happens.
  28655. The stack elements are pushed without any sub-formula selections.
  28656. You can give an optional third argument to this function, which must
  28657. be a list the same size as @var{vals} of selections. Each selection
  28658. must be @code{eq} to some sub-formula of the corresponding formula
  28659. in @var{vals}, or @code{nil} if that formula should have no selection.
  28660. @end defun
  28661. @defun calc-top-list n m
  28662. Return a list of the @var{n} objects starting at level @var{m} of the
  28663. stack. If @var{m} is omitted it defaults to 1, so that the elements are
  28664. taken from the top of the stack. If @var{n} is omitted, it also
  28665. defaults to 1, so that the top stack element (in the form of a
  28666. one-element list) is returned. If @var{m} is greater than 1, the
  28667. @var{m}th stack element will be at the end of the list, the @var{m}+1st
  28668. element will be next-to-last, etc. If @var{n} or @var{m} are out of
  28669. range, the command is aborted with a suitable error message. If @var{n}
  28670. is zero, the function returns an empty list. The stack elements are not
  28671. evaluated, rounded, or renormalized.
  28672. If any stack elements contain selections, and selections have not
  28673. been disabled by the @kbd{j e} (@code{calc-enable-selections}) command,
  28674. this function returns the selected portions rather than the entire
  28675. stack elements. It can be given a third ``selection-mode'' argument
  28676. which selects other behaviors. If it is the symbol @code{t}, then
  28677. a selection in any of the requested stack elements produces an
  28678. ``invalid operation on selections'' error. If it is the symbol @code{full},
  28679. the whole stack entry is always returned regardless of selections.
  28680. If it is the symbol @code{sel}, the selected portion is always returned,
  28681. or @code{nil} if there is no selection. (This mode ignores the @kbd{j e}
  28682. command.) If the symbol is @code{entry}, the complete stack entry in
  28683. list form is returned; the first element of this list will be the whole
  28684. formula, and the third element will be the selection (or @code{nil}).
  28685. @end defun
  28686. @defun calc-pop-stack n m
  28687. Remove the specified elements from the stack. The parameters @var{n}
  28688. and @var{m} are defined the same as for @code{calc-top-list}. The return
  28689. value of @code{calc-pop-stack} is uninteresting.
  28690. If there are any selected sub-formulas among the popped elements, and
  28691. @kbd{j e} has not been used to disable selections, this produces an
  28692. error without changing the stack. If you supply an optional third
  28693. argument of @code{t}, the stack elements are popped even if they
  28694. contain selections.
  28695. @end defun
  28696. @defun calc-record-list vals tag
  28697. This function records one or more results in the trail. The @var{vals}
  28698. are a list of strings or Calc objects. The @var{tag} is the four-character
  28699. tag string to identify the values. If @var{tag} is omitted, a blank tag
  28700. will be used.
  28701. @end defun
  28702. @defun calc-normalize n
  28703. This function takes a Calc object and ``normalizes'' it. At the very
  28704. least this involves re-rounding floating-point values according to the
  28705. current precision and other similar jobs. Also, unless the user has
  28706. selected No-Simplify mode (@pxref{Simplification Modes}), this involves
  28707. actually evaluating a formula object by executing the function calls
  28708. it contains, and possibly also doing algebraic simplification, etc.
  28709. @end defun
  28710. @defun calc-top-list-n n m
  28711. This function is identical to @code{calc-top-list}, except that it calls
  28712. @code{calc-normalize} on the values that it takes from the stack. They
  28713. are also passed through @code{check-complete}, so that incomplete
  28714. objects will be rejected with an error message. All computational
  28715. commands should use this in preference to @code{calc-top-list}; the only
  28716. standard Calc commands that operate on the stack without normalizing
  28717. are stack management commands like @code{calc-enter} and @code{calc-roll-up}.
  28718. This function accepts the same optional selection-mode argument as
  28719. @code{calc-top-list}.
  28720. @end defun
  28721. @defun calc-top-n m
  28722. This function is a convenient form of @code{calc-top-list-n} in which only
  28723. a single element of the stack is taken and returned, rather than a list
  28724. of elements. This also accepts an optional selection-mode argument.
  28725. @end defun
  28726. @defun calc-enter-result n tag vals
  28727. This function is a convenient interface to most of the above functions.
  28728. The @var{vals} argument should be either a single Calc object, or a list
  28729. of Calc objects; the object or objects are normalized, and the top @var{n}
  28730. stack entries are replaced by the normalized objects. If @var{tag} is
  28731. non-@code{nil}, the normalized objects are also recorded in the trail.
  28732. A typical stack-based computational command would take the form,
  28733. @smallexample
  28734. (calc-enter-result @var{n} @var{tag} (cons 'calcFunc-@var{func}
  28735. (calc-top-list-n @var{n})))
  28736. @end smallexample
  28737. If any of the @var{n} stack elements replaced contain sub-formula
  28738. selections, and selections have not been disabled by @kbd{j e},
  28739. this function takes one of two courses of action. If @var{n} is
  28740. equal to the number of elements in @var{vals}, then each element of
  28741. @var{vals} is spliced into the corresponding selection; this is what
  28742. happens when you use the @key{TAB} key, or when you use a unary
  28743. arithmetic operation like @code{sqrt}. If @var{vals} has only one
  28744. element but @var{n} is greater than one, there must be only one
  28745. selection among the top @var{n} stack elements; the element from
  28746. @var{vals} is spliced into that selection. This is what happens when
  28747. you use a binary arithmetic operation like @kbd{+}. Any other
  28748. combination of @var{n} and @var{vals} is an error when selections
  28749. are present.
  28750. @end defun
  28751. @defun calc-unary-op tag func arg
  28752. This function implements a unary operator that allows a numeric prefix
  28753. argument to apply the operator over many stack entries. If the prefix
  28754. argument @var{arg} is @code{nil}, this uses @code{calc-enter-result}
  28755. as outlined above. Otherwise, it maps the function over several stack
  28756. elements; @pxref{Prefix Arguments}. For example,
  28757. @smallexample
  28758. (defun calc-zeta (arg)
  28759. (interactive "P")
  28760. (calc-unary-op "zeta" 'calcFunc-zeta arg))
  28761. @end smallexample
  28762. @end defun
  28763. @defun calc-binary-op tag func arg ident unary
  28764. This function implements a binary operator, analogously to
  28765. @code{calc-unary-op}. The optional @var{ident} and @var{unary}
  28766. arguments specify the behavior when the prefix argument is zero or
  28767. one, respectively. If the prefix is zero, the value @var{ident}
  28768. is pushed onto the stack, if specified, otherwise an error message
  28769. is displayed. If the prefix is one, the unary function @var{unary}
  28770. is applied to the top stack element, or, if @var{unary} is not
  28771. specified, nothing happens. When the argument is two or more,
  28772. the binary function @var{func} is reduced across the top @var{arg}
  28773. stack elements; when the argument is negative, the function is
  28774. mapped between the next-to-top @mathit{-@var{arg}} stack elements and the
  28775. top element.
  28776. @end defun
  28777. @defun calc-stack-size
  28778. Return the number of elements on the stack as an integer. This count
  28779. does not include elements that have been temporarily hidden by stack
  28780. truncation; @pxref{Truncating the Stack}.
  28781. @end defun
  28782. @defun calc-cursor-stack-index n
  28783. Move the point to the @var{n}th stack entry. If @var{n} is zero, this
  28784. will be the @samp{.} line. If @var{n} is from 1 to the current stack size,
  28785. this will be the beginning of the first line of that stack entry's display.
  28786. If line numbers are enabled, this will move to the first character of the
  28787. line number, not the stack entry itself.
  28788. @end defun
  28789. @defun calc-substack-height n
  28790. Return the number of lines between the beginning of the @var{n}th stack
  28791. entry and the bottom of the buffer. If @var{n} is zero, this
  28792. will be one (assuming no stack truncation). If all stack entries are
  28793. one line long (i.e., no matrices are displayed), the return value will
  28794. be equal @var{n}+1 as long as @var{n} is in range. (Note that in Big
  28795. mode, the return value includes the blank lines that separate stack
  28796. entries.)
  28797. @end defun
  28798. @defun calc-refresh
  28799. Erase the @file{*Calculator*} buffer and reformat its contents from memory.
  28800. This must be called after changing any parameter, such as the current
  28801. display radix, which might change the appearance of existing stack
  28802. entries. (During a keyboard macro invoked by the @kbd{X} key, refreshing
  28803. is suppressed, but a flag is set so that the entire stack will be refreshed
  28804. rather than just the top few elements when the macro finishes.)
  28805. @end defun
  28806. @node Predicates, Computational Lisp Functions, Stack Lisp Functions, Internals
  28807. @subsubsection Predicates
  28808. @noindent
  28809. The functions described here are predicates, that is, they return a
  28810. true/false value where @code{nil} means false and anything else means
  28811. true. These predicates are expanded by @code{defmath}, for example,
  28812. from @code{zerop} to @code{math-zerop}. In many cases they correspond
  28813. to native Lisp functions by the same name, but are extended to cover
  28814. the full range of Calc data types.
  28815. @defun zerop x
  28816. Returns true if @var{x} is numerically zero, in any of the Calc data
  28817. types. (Note that for some types, such as error forms and intervals,
  28818. it never makes sense to return true.) In @code{defmath}, the expression
  28819. @samp{(= x 0)} will automatically be converted to @samp{(math-zerop x)},
  28820. and @samp{(/= x 0)} will be converted to @samp{(not (math-zerop x))}.
  28821. @end defun
  28822. @defun negp x
  28823. Returns true if @var{x} is negative. This accepts negative real numbers
  28824. of various types, negative HMS and date forms, and intervals in which
  28825. all included values are negative. In @code{defmath}, the expression
  28826. @samp{(< x 0)} will automatically be converted to @samp{(math-negp x)},
  28827. and @samp{(>= x 0)} will be converted to @samp{(not (math-negp x))}.
  28828. @end defun
  28829. @defun posp x
  28830. Returns true if @var{x} is positive (and non-zero). For complex
  28831. numbers, none of these three predicates will return true.
  28832. @end defun
  28833. @defun looks-negp x
  28834. Returns true if @var{x} is ``negative-looking.'' This returns true if
  28835. @var{x} is a negative number, or a formula with a leading minus sign
  28836. such as @samp{-a/b}. In other words, this is an object which can be
  28837. made simpler by calling @code{(- @var{x})}.
  28838. @end defun
  28839. @defun integerp x
  28840. Returns true if @var{x} is an integer of any size.
  28841. @end defun
  28842. @defun fixnump x
  28843. Returns true if @var{x} is a native Lisp integer.
  28844. @end defun
  28845. @defun natnump x
  28846. Returns true if @var{x} is a nonnegative integer of any size.
  28847. @end defun
  28848. @defun fixnatnump x
  28849. Returns true if @var{x} is a nonnegative Lisp integer.
  28850. @end defun
  28851. @defun num-integerp x
  28852. Returns true if @var{x} is numerically an integer, i.e., either a
  28853. true integer or a float with no significant digits to the right of
  28854. the decimal point.
  28855. @end defun
  28856. @defun messy-integerp x
  28857. Returns true if @var{x} is numerically, but not literally, an integer.
  28858. A value is @code{num-integerp} if it is @code{integerp} or
  28859. @code{messy-integerp} (but it is never both at once).
  28860. @end defun
  28861. @defun num-natnump x
  28862. Returns true if @var{x} is numerically a nonnegative integer.
  28863. @end defun
  28864. @defun evenp x
  28865. Returns true if @var{x} is an even integer.
  28866. @end defun
  28867. @defun looks-evenp x
  28868. Returns true if @var{x} is an even integer, or a formula with a leading
  28869. multiplicative coefficient which is an even integer.
  28870. @end defun
  28871. @defun oddp x
  28872. Returns true if @var{x} is an odd integer.
  28873. @end defun
  28874. @defun ratp x
  28875. Returns true if @var{x} is a rational number, i.e., an integer or a
  28876. fraction.
  28877. @end defun
  28878. @defun realp x
  28879. Returns true if @var{x} is a real number, i.e., an integer, fraction,
  28880. or floating-point number.
  28881. @end defun
  28882. @defun anglep x
  28883. Returns true if @var{x} is a real number or HMS form.
  28884. @end defun
  28885. @defun floatp x
  28886. Returns true if @var{x} is a float, or a complex number, error form,
  28887. interval, date form, or modulo form in which at least one component
  28888. is a float.
  28889. @end defun
  28890. @defun complexp x
  28891. Returns true if @var{x} is a rectangular or polar complex number
  28892. (but not a real number).
  28893. @end defun
  28894. @defun rect-complexp x
  28895. Returns true if @var{x} is a rectangular complex number.
  28896. @end defun
  28897. @defun polar-complexp x
  28898. Returns true if @var{x} is a polar complex number.
  28899. @end defun
  28900. @defun numberp x
  28901. Returns true if @var{x} is a real number or a complex number.
  28902. @end defun
  28903. @defun scalarp x
  28904. Returns true if @var{x} is a real or complex number or an HMS form.
  28905. @end defun
  28906. @defun vectorp x
  28907. Returns true if @var{x} is a vector (this simply checks if its argument
  28908. is a list whose first element is the symbol @code{vec}).
  28909. @end defun
  28910. @defun numvecp x
  28911. Returns true if @var{x} is a number or vector.
  28912. @end defun
  28913. @defun matrixp x
  28914. Returns true if @var{x} is a matrix, i.e., a vector of one or more vectors,
  28915. all of the same size.
  28916. @end defun
  28917. @defun square-matrixp x
  28918. Returns true if @var{x} is a square matrix.
  28919. @end defun
  28920. @defun objectp x
  28921. Returns true if @var{x} is any numeric Calc object, including real and
  28922. complex numbers, HMS forms, date forms, error forms, intervals, and
  28923. modulo forms. (Note that error forms and intervals may include formulas
  28924. as their components; see @code{constp} below.)
  28925. @end defun
  28926. @defun objvecp x
  28927. Returns true if @var{x} is an object or a vector. This also accepts
  28928. incomplete objects, but it rejects variables and formulas (except as
  28929. mentioned above for @code{objectp}).
  28930. @end defun
  28931. @defun primp x
  28932. Returns true if @var{x} is a ``primitive'' or ``atomic'' Calc object,
  28933. i.e., one whose components cannot be regarded as sub-formulas. This
  28934. includes variables, and all @code{objectp} types except error forms
  28935. and intervals.
  28936. @end defun
  28937. @defun constp x
  28938. Returns true if @var{x} is constant, i.e., a real or complex number,
  28939. HMS form, date form, or error form, interval, or vector all of whose
  28940. components are @code{constp}.
  28941. @end defun
  28942. @defun lessp x y
  28943. Returns true if @var{x} is numerically less than @var{y}. Returns false
  28944. if @var{x} is greater than or equal to @var{y}, or if the order is
  28945. undefined or cannot be determined. Generally speaking, this works
  28946. by checking whether @samp{@var{x} - @var{y}} is @code{negp}. In
  28947. @code{defmath}, the expression @samp{(< x y)} will automatically be
  28948. converted to @samp{(lessp x y)}; expressions involving @code{>}, @code{<=},
  28949. and @code{>=} are similarly converted in terms of @code{lessp}.
  28950. @end defun
  28951. @defun beforep x y
  28952. Returns true if @var{x} comes before @var{y} in a canonical ordering
  28953. of Calc objects. If @var{x} and @var{y} are both real numbers, this
  28954. will be the same as @code{lessp}. But whereas @code{lessp} considers
  28955. other types of objects to be unordered, @code{beforep} puts any two
  28956. objects into a definite, consistent order. The @code{beforep}
  28957. function is used by the @kbd{V S} vector-sorting command, and also
  28958. by Calc's algebraic simplifications to put the terms of a product into
  28959. canonical order: This allows @samp{x y + y x} to be simplified easily to
  28960. @samp{2 x y}.
  28961. @end defun
  28962. @defun equal x y
  28963. This is the standard Lisp @code{equal} predicate; it returns true if
  28964. @var{x} and @var{y} are structurally identical. This is the usual way
  28965. to compare numbers for equality, but note that @code{equal} will treat
  28966. 0 and 0.0 as different.
  28967. @end defun
  28968. @defun math-equal x y
  28969. Returns true if @var{x} and @var{y} are numerically equal, either because
  28970. they are @code{equal}, or because their difference is @code{zerop}. In
  28971. @code{defmath}, the expression @samp{(= x y)} will automatically be
  28972. converted to @samp{(math-equal x y)}.
  28973. @end defun
  28974. @defun equal-int x n
  28975. Returns true if @var{x} and @var{n} are numerically equal, where @var{n}
  28976. is a fixnum which is not a multiple of 10. This will automatically be
  28977. used by @code{defmath} in place of the more general @code{math-equal}
  28978. whenever possible.
  28979. @end defun
  28980. @defun nearly-equal x y
  28981. Returns true if @var{x} and @var{y}, as floating-point numbers, are
  28982. equal except possibly in the last decimal place. For example,
  28983. 314.159 and 314.166 are considered nearly equal if the current
  28984. precision is 6 (since they differ by 7 units), but not if the current
  28985. precision is 7 (since they differ by 70 units). Most functions which
  28986. use series expansions use @code{with-extra-prec} to evaluate the
  28987. series with 2 extra digits of precision, then use @code{nearly-equal}
  28988. to decide when the series has converged; this guards against cumulative
  28989. error in the series evaluation without doing extra work which would be
  28990. lost when the result is rounded back down to the current precision.
  28991. In @code{defmath}, this can be written @samp{(~= @var{x} @var{y})}.
  28992. The @var{x} and @var{y} can be numbers of any kind, including complex.
  28993. @end defun
  28994. @defun nearly-zerop x y
  28995. Returns true if @var{x} is nearly zero, compared to @var{y}. This
  28996. checks whether @var{x} plus @var{y} would by be @code{nearly-equal}
  28997. to @var{y} itself, to within the current precision, in other words,
  28998. if adding @var{x} to @var{y} would have a negligible effect on @var{y}
  28999. due to roundoff error. @var{X} may be a real or complex number, but
  29000. @var{y} must be real.
  29001. @end defun
  29002. @defun is-true x
  29003. Return true if the formula @var{x} represents a true value in
  29004. Calc, not Lisp, terms. It tests if @var{x} is a non-zero number
  29005. or a provably non-zero formula.
  29006. @end defun
  29007. @defun reject-arg val pred
  29008. Abort the current function evaluation due to unacceptable argument values.
  29009. This calls @samp{(calc-record-why @var{pred} @var{val})}, then signals a
  29010. Lisp error which @code{normalize} will trap. The net effect is that the
  29011. function call which led here will be left in symbolic form.
  29012. @end defun
  29013. @defun inexact-value
  29014. If Symbolic mode is enabled, this will signal an error that causes
  29015. @code{normalize} to leave the formula in symbolic form, with the message
  29016. ``Inexact result.'' (This function has no effect when not in Symbolic mode.)
  29017. Note that if your function calls @samp{(sin 5)} in Symbolic mode, the
  29018. @code{sin} function will call @code{inexact-value}, which will cause your
  29019. function to be left unsimplified. You may instead wish to call
  29020. @samp{(normalize (list 'calcFunc-sin 5))}, which in Symbolic mode will
  29021. return the formula @samp{sin(5)} to your function.
  29022. @end defun
  29023. @defun overflow
  29024. This signals an error that will be reported as a floating-point overflow.
  29025. @end defun
  29026. @defun underflow
  29027. This signals a floating-point underflow.
  29028. @end defun
  29029. @node Computational Lisp Functions, Vector Lisp Functions, Predicates, Internals
  29030. @subsubsection Computational Functions
  29031. @noindent
  29032. The functions described here do the actual computational work of the
  29033. Calculator. In addition to these, note that any function described in
  29034. the main body of this manual may be called from Lisp; for example, if
  29035. the documentation refers to the @code{calc-sqrt} [@code{sqrt}] command,
  29036. this means @code{calc-sqrt} is an interactive stack-based square-root
  29037. command and @code{sqrt} (which @code{defmath} expands to @code{calcFunc-sqrt})
  29038. is the actual Lisp function for taking square roots.
  29039. The functions @code{math-add}, @code{math-sub}, @code{math-mul},
  29040. @code{math-div}, @code{math-mod}, and @code{math-neg} are not included
  29041. in this list, since @code{defmath} allows you to write native Lisp
  29042. @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, and unary @code{-},
  29043. respectively, instead.
  29044. @defun normalize val
  29045. (Full form: @code{math-normalize}.)
  29046. Reduce the value @var{val} to standard form. For example, if @var{val}
  29047. is a fixnum, it will be converted to a bignum if it is too large, and
  29048. if @var{val} is a bignum it will be normalized by clipping off trailing
  29049. (i.e., most-significant) zero digits and converting to a fixnum if it is
  29050. small. All the various data types are similarly converted to their standard
  29051. forms. Variables are left alone, but function calls are actually evaluated
  29052. in formulas. For example, normalizing @samp{(+ 2 (calcFunc-abs -4))} will
  29053. return 6.
  29054. If a function call fails, because the function is void or has the wrong
  29055. number of parameters, or because it returns @code{nil} or calls
  29056. @code{reject-arg} or @code{inexact-result}, @code{normalize} returns
  29057. the formula still in symbolic form.
  29058. If the current simplification mode is ``none'' or ``numeric arguments
  29059. only,'' @code{normalize} will act appropriately. However, the more
  29060. powerful simplification modes (like Algebraic Simplification) are
  29061. not handled by @code{normalize}. They are handled by @code{calc-normalize},
  29062. which calls @code{normalize} and possibly some other routines, such
  29063. as @code{simplify} or @code{simplify-units}. Programs generally will
  29064. never call @code{calc-normalize} except when popping or pushing values
  29065. on the stack.
  29066. @end defun
  29067. @defun evaluate-expr expr
  29068. Replace all variables in @var{expr} that have values with their values,
  29069. then use @code{normalize} to simplify the result. This is what happens
  29070. when you press the @kbd{=} key interactively.
  29071. @end defun
  29072. @defmac with-extra-prec n body
  29073. Evaluate the Lisp forms in @var{body} with precision increased by @var{n}
  29074. digits. This is a macro which expands to
  29075. @smallexample
  29076. (math-normalize
  29077. (let ((calc-internal-prec (+ calc-internal-prec @var{n})))
  29078. @var{body}))
  29079. @end smallexample
  29080. The surrounding call to @code{math-normalize} causes a floating-point
  29081. result to be rounded down to the original precision afterwards. This
  29082. is important because some arithmetic operations assume a number's
  29083. mantissa contains no more digits than the current precision allows.
  29084. @end defmac
  29085. @defun make-frac n d
  29086. Build a fraction @samp{@var{n}:@var{d}}. This is equivalent to calling
  29087. @samp{(normalize (list 'frac @var{n} @var{d}))}, but more efficient.
  29088. @end defun
  29089. @defun make-float mant exp
  29090. Build a floating-point value out of @var{mant} and @var{exp}, both
  29091. of which are arbitrary integers. This function will return a
  29092. properly normalized float value, or signal an overflow or underflow
  29093. if @var{exp} is out of range.
  29094. @end defun
  29095. @defun make-sdev x sigma
  29096. Build an error form out of @var{x} and the absolute value of @var{sigma}.
  29097. If @var{sigma} is zero, the result is the number @var{x} directly.
  29098. If @var{sigma} is negative or complex, its absolute value is used.
  29099. If @var{x} or @var{sigma} is not a valid type of object for use in
  29100. error forms, this calls @code{reject-arg}.
  29101. @end defun
  29102. @defun make-intv mask lo hi
  29103. Build an interval form out of @var{mask} (which is assumed to be an
  29104. integer from 0 to 3), and the limits @var{lo} and @var{hi}. If
  29105. @var{lo} is greater than @var{hi}, an empty interval form is returned.
  29106. This calls @code{reject-arg} if @var{lo} or @var{hi} is unsuitable.
  29107. @end defun
  29108. @defun sort-intv mask lo hi
  29109. Build an interval form, similar to @code{make-intv}, except that if
  29110. @var{lo} is less than @var{hi} they are simply exchanged, and the
  29111. bits of @var{mask} are swapped accordingly.
  29112. @end defun
  29113. @defun make-mod n m
  29114. Build a modulo form out of @var{n} and the modulus @var{m}. Since modulo
  29115. forms do not allow formulas as their components, if @var{n} or @var{m}
  29116. is not a real number or HMS form the result will be a formula which
  29117. is a call to @code{makemod}, the algebraic version of this function.
  29118. @end defun
  29119. @defun float x
  29120. Convert @var{x} to floating-point form. Integers and fractions are
  29121. converted to numerically equivalent floats; components of complex
  29122. numbers, vectors, HMS forms, date forms, error forms, intervals, and
  29123. modulo forms are recursively floated. If the argument is a variable
  29124. or formula, this calls @code{reject-arg}.
  29125. @end defun
  29126. @defun compare x y
  29127. Compare the numbers @var{x} and @var{y}, and return @mathit{-1} if
  29128. @samp{(lessp @var{x} @var{y})}, 1 if @samp{(lessp @var{y} @var{x})},
  29129. 0 if @samp{(math-equal @var{x} @var{y})}, or 2 if the order is
  29130. undefined or cannot be determined.
  29131. @end defun
  29132. @defun numdigs n
  29133. Return the number of digits of integer @var{n}, effectively
  29134. @samp{ceil(log10(@var{n}))}, but much more efficient. Zero is
  29135. considered to have zero digits.
  29136. @end defun
  29137. @defun scale-int x n
  29138. Shift integer @var{x} left @var{n} decimal digits, or right @mathit{-@var{n}}
  29139. digits with truncation toward zero.
  29140. @end defun
  29141. @defun scale-rounding x n
  29142. Like @code{scale-int}, except that a right shift rounds to the nearest
  29143. integer rather than truncating.
  29144. @end defun
  29145. @defun fixnum n
  29146. Return the integer @var{n} as a fixnum, i.e., a native Lisp integer.
  29147. If @var{n} is outside the permissible range for Lisp integers (usually
  29148. 24 binary bits) the result is undefined.
  29149. @end defun
  29150. @defun sqr x
  29151. Compute the square of @var{x}; short for @samp{(* @var{x} @var{x})}.
  29152. @end defun
  29153. @defun quotient x y
  29154. Divide integer @var{x} by integer @var{y}; return an integer quotient
  29155. and discard the remainder. If @var{x} or @var{y} is negative, the
  29156. direction of rounding is undefined.
  29157. @end defun
  29158. @defun idiv x y
  29159. Perform an integer division; if @var{x} and @var{y} are both nonnegative
  29160. integers, this uses the @code{quotient} function, otherwise it computes
  29161. @samp{floor(@var{x}/@var{y})}. Thus the result is well-defined but
  29162. slower than for @code{quotient}.
  29163. @end defun
  29164. @defun imod x y
  29165. Divide integer @var{x} by integer @var{y}; return the integer remainder
  29166. and discard the quotient. Like @code{quotient}, this works only for
  29167. integer arguments and is not well-defined for negative arguments.
  29168. For a more well-defined result, use @samp{(% @var{x} @var{y})}.
  29169. @end defun
  29170. @defun idivmod x y
  29171. Divide integer @var{x} by integer @var{y}; return a cons cell whose
  29172. @code{car} is @samp{(quotient @var{x} @var{y})} and whose @code{cdr}
  29173. is @samp{(imod @var{x} @var{y})}.
  29174. @end defun
  29175. @defun pow x y
  29176. Compute @var{x} to the power @var{y}. In @code{defmath} code, this can
  29177. also be written @samp{(^ @var{x} @var{y})} or
  29178. @w{@samp{(expt @var{x} @var{y})}}.
  29179. @end defun
  29180. @defun abs-approx x
  29181. Compute a fast approximation to the absolute value of @var{x}. For
  29182. example, for a rectangular complex number the result is the sum of
  29183. the absolute values of the components.
  29184. @end defun
  29185. @findex e
  29186. @findex gamma-const
  29187. @findex ln-2
  29188. @findex ln-10
  29189. @findex phi
  29190. @findex pi-over-2
  29191. @findex pi-over-4
  29192. @findex pi-over-180
  29193. @findex sqrt-two-pi
  29194. @findex sqrt-e
  29195. @findex two-pi
  29196. @defun pi
  29197. The function @samp{(pi)} computes @samp{pi} to the current precision.
  29198. Other related constant-generating functions are @code{two-pi},
  29199. @code{pi-over-2}, @code{pi-over-4}, @code{pi-over-180}, @code{sqrt-two-pi},
  29200. @code{e}, @code{sqrt-e}, @code{ln-2}, @code{ln-10}, @code{phi} and
  29201. @code{gamma-const}. Each function returns a floating-point value in the
  29202. current precision, and each uses caching so that all calls after the
  29203. first are essentially free.
  29204. @end defun
  29205. @defmac math-defcache @var{func} @var{initial} @var{form}
  29206. This macro, usually used as a top-level call like @code{defun} or
  29207. @code{defvar}, defines a new cached constant analogous to @code{pi}, etc.
  29208. It defines a function @code{func} which returns the requested value;
  29209. if @var{initial} is non-@code{nil} it must be a @samp{(float @dots{})}
  29210. form which serves as an initial value for the cache. If @var{func}
  29211. is called when the cache is empty or does not have enough digits to
  29212. satisfy the current precision, the Lisp expression @var{form} is evaluated
  29213. with the current precision increased by four, and the result minus its
  29214. two least significant digits is stored in the cache. For example,
  29215. calling @samp{(pi)} with a precision of 30 computes @samp{pi} to 34
  29216. digits, rounds it down to 32 digits for future use, then rounds it
  29217. again to 30 digits for use in the present request.
  29218. @end defmac
  29219. @findex half-circle
  29220. @findex quarter-circle
  29221. @defun full-circle symb
  29222. If the current angular mode is Degrees or HMS, this function returns the
  29223. integer 360. In Radians mode, this function returns either the
  29224. corresponding value in radians to the current precision, or the formula
  29225. @samp{2*pi}, depending on the Symbolic mode. There are also similar
  29226. function @code{half-circle} and @code{quarter-circle}.
  29227. @end defun
  29228. @defun power-of-2 n
  29229. Compute two to the integer power @var{n}, as a (potentially very large)
  29230. integer. Powers of two are cached, so only the first call for a
  29231. particular @var{n} is expensive.
  29232. @end defun
  29233. @defun integer-log2 n
  29234. Compute the base-2 logarithm of @var{n}, which must be an integer which
  29235. is a power of two. If @var{n} is not a power of two, this function will
  29236. return @code{nil}.
  29237. @end defun
  29238. @defun div-mod a b m
  29239. Divide @var{a} by @var{b}, modulo @var{m}. This returns @code{nil} if
  29240. there is no solution, or if any of the arguments are not integers.
  29241. @end defun
  29242. @defun pow-mod a b m
  29243. Compute @var{a} to the power @var{b}, modulo @var{m}. If @var{a},
  29244. @var{b}, and @var{m} are integers, this uses an especially efficient
  29245. algorithm. Otherwise, it simply computes @samp{(% (^ a b) m)}.
  29246. @end defun
  29247. @defun isqrt n
  29248. Compute the integer square root of @var{n}. This is the square root
  29249. of @var{n} rounded down toward zero, i.e., @samp{floor(sqrt(@var{n}))}.
  29250. If @var{n} is itself an integer, the computation is especially efficient.
  29251. @end defun
  29252. @defun to-hms a ang
  29253. Convert the argument @var{a} into an HMS form. If @var{ang} is specified,
  29254. it is the angular mode in which to interpret @var{a}, either @code{deg}
  29255. or @code{rad}. Otherwise, the current angular mode is used. If @var{a}
  29256. is already an HMS form it is returned as-is.
  29257. @end defun
  29258. @defun from-hms a ang
  29259. Convert the HMS form @var{a} into a real number. If @var{ang} is specified,
  29260. it is the angular mode in which to express the result, otherwise the
  29261. current angular mode is used. If @var{a} is already a real number, it
  29262. is returned as-is.
  29263. @end defun
  29264. @defun to-radians a
  29265. Convert the number or HMS form @var{a} to radians from the current
  29266. angular mode.
  29267. @end defun
  29268. @defun from-radians a
  29269. Convert the number @var{a} from radians to the current angular mode.
  29270. If @var{a} is a formula, this returns the formula @samp{deg(@var{a})}.
  29271. @end defun
  29272. @defun to-radians-2 a
  29273. Like @code{to-radians}, except that in Symbolic mode a degrees to
  29274. radians conversion yields a formula like @samp{@var{a}*pi/180}.
  29275. @end defun
  29276. @defun from-radians-2 a
  29277. Like @code{from-radians}, except that in Symbolic mode a radians to
  29278. degrees conversion yields a formula like @samp{@var{a}*180/pi}.
  29279. @end defun
  29280. @defun random-digit
  29281. Produce a random base-1000 digit in the range 0 to 999.
  29282. @end defun
  29283. @defun random-digits n
  29284. Produce a random @var{n}-digit integer; this will be an integer
  29285. in the interval @samp{[0, 10^@var{n})}.
  29286. @end defun
  29287. @defun random-float
  29288. Produce a random float in the interval @samp{[0, 1)}.
  29289. @end defun
  29290. @defun prime-test n iters
  29291. Determine whether the integer @var{n} is prime. Return a list which has
  29292. one of these forms: @samp{(nil @var{f})} means the number is non-prime
  29293. because it was found to be divisible by @var{f}; @samp{(nil)} means it
  29294. was found to be non-prime by table look-up (so no factors are known);
  29295. @samp{(nil unknown)} means it is definitely non-prime but no factors
  29296. are known because @var{n} was large enough that Fermat's probabilistic
  29297. test had to be used; @samp{(t)} means the number is definitely prime;
  29298. and @samp{(maybe @var{i} @var{p})} means that Fermat's test, after @var{i}
  29299. iterations, is @var{p} percent sure that the number is prime. The
  29300. @var{iters} parameter is the number of Fermat iterations to use, in the
  29301. case that this is necessary. If @code{prime-test} returns ``maybe,''
  29302. you can call it again with the same @var{n} to get a greater certainty;
  29303. @code{prime-test} remembers where it left off.
  29304. @end defun
  29305. @defun to-simple-fraction f
  29306. If @var{f} is a floating-point number which can be represented exactly
  29307. as a small rational number, return that number, else return @var{f}.
  29308. For example, 0.75 would be converted to 3:4. This function is very
  29309. fast.
  29310. @end defun
  29311. @defun to-fraction f tol
  29312. Find a rational approximation to floating-point number @var{f} to within
  29313. a specified tolerance @var{tol}; this corresponds to the algebraic
  29314. function @code{frac}, and can be rather slow.
  29315. @end defun
  29316. @defun quarter-integer n
  29317. If @var{n} is an integer or integer-valued float, this function
  29318. returns zero. If @var{n} is a half-integer (i.e., an integer plus
  29319. @mathit{1:2} or 0.5), it returns 2. If @var{n} is a quarter-integer,
  29320. it returns 1 or 3. If @var{n} is anything else, this function
  29321. returns @code{nil}.
  29322. @end defun
  29323. @node Vector Lisp Functions, Symbolic Lisp Functions, Computational Lisp Functions, Internals
  29324. @subsubsection Vector Functions
  29325. @noindent
  29326. The functions described here perform various operations on vectors and
  29327. matrices.
  29328. @defun math-concat x y
  29329. Do a vector concatenation; this operation is written @samp{@var{x} | @var{y}}
  29330. in a symbolic formula. @xref{Building Vectors}.
  29331. @end defun
  29332. @defun vec-length v
  29333. Return the length of vector @var{v}. If @var{v} is not a vector, the
  29334. result is zero. If @var{v} is a matrix, this returns the number of
  29335. rows in the matrix.
  29336. @end defun
  29337. @defun mat-dimens m
  29338. Determine the dimensions of vector or matrix @var{m}. If @var{m} is not
  29339. a vector, the result is an empty list. If @var{m} is a plain vector
  29340. but not a matrix, the result is a one-element list containing the length
  29341. of the vector. If @var{m} is a matrix with @var{r} rows and @var{c} columns,
  29342. the result is the list @samp{(@var{r} @var{c})}. Higher-order tensors
  29343. produce lists of more than two dimensions. Note that the object
  29344. @samp{[[1, 2, 3], [4, 5]]} is a vector of vectors not all the same size,
  29345. and is treated by this and other Calc routines as a plain vector of two
  29346. elements.
  29347. @end defun
  29348. @defun dimension-error
  29349. Abort the current function with a message of ``Dimension error.''
  29350. The Calculator will leave the function being evaluated in symbolic
  29351. form; this is really just a special case of @code{reject-arg}.
  29352. @end defun
  29353. @defun build-vector args
  29354. Return a Calc vector with @var{args} as elements.
  29355. For example, @samp{(build-vector 1 2 3)} returns the Calc vector
  29356. @samp{[1, 2, 3]}, stored internally as the list @samp{(vec 1 2 3)}.
  29357. @end defun
  29358. @defun make-vec obj dims
  29359. Return a Calc vector or matrix all of whose elements are equal to
  29360. @var{obj}. For example, @samp{(make-vec 27 3 4)} returns a 3x4 matrix
  29361. filled with 27's.
  29362. @end defun
  29363. @defun row-matrix v
  29364. If @var{v} is a plain vector, convert it into a row matrix, i.e.,
  29365. a matrix whose single row is @var{v}. If @var{v} is already a matrix,
  29366. leave it alone.
  29367. @end defun
  29368. @defun col-matrix v
  29369. If @var{v} is a plain vector, convert it into a column matrix, i.e., a
  29370. matrix with each element of @var{v} as a separate row. If @var{v} is
  29371. already a matrix, leave it alone.
  29372. @end defun
  29373. @defun map-vec f v
  29374. Map the Lisp function @var{f} over the Calc vector @var{v}. For example,
  29375. @samp{(map-vec 'math-floor v)} returns a vector of the floored components
  29376. of vector @var{v}.
  29377. @end defun
  29378. @defun map-vec-2 f a b
  29379. Map the Lisp function @var{f} over the two vectors @var{a} and @var{b}.
  29380. If @var{a} and @var{b} are vectors of equal length, the result is a
  29381. vector of the results of calling @samp{(@var{f} @var{ai} @var{bi})}
  29382. for each pair of elements @var{ai} and @var{bi}. If either @var{a} or
  29383. @var{b} is a scalar, it is matched with each value of the other vector.
  29384. For example, @samp{(map-vec-2 'math-add v 1)} returns the vector @var{v}
  29385. with each element increased by one. Note that using @samp{'+} would not
  29386. work here, since @code{defmath} does not expand function names everywhere,
  29387. just where they are in the function position of a Lisp expression.
  29388. @end defun
  29389. @defun reduce-vec f v
  29390. Reduce the function @var{f} over the vector @var{v}. For example, if
  29391. @var{v} is @samp{[10, 20, 30, 40]}, this calls @samp{(f (f (f 10 20) 30) 40)}.
  29392. If @var{v} is a matrix, this reduces over the rows of @var{v}.
  29393. @end defun
  29394. @defun reduce-cols f m
  29395. Reduce the function @var{f} over the columns of matrix @var{m}. For
  29396. example, if @var{m} is @samp{[[1, 2], [3, 4], [5, 6]]}, the result
  29397. is a vector of the two elements @samp{(f (f 1 3) 5)} and @samp{(f (f 2 4) 6)}.
  29398. @end defun
  29399. @defun mat-row m n
  29400. Return the @var{n}th row of matrix @var{m}. This is equivalent to
  29401. @samp{(elt m n)}. For a slower but safer version, use @code{mrow}.
  29402. (@xref{Extracting Elements}.)
  29403. @end defun
  29404. @defun mat-col m n
  29405. Return the @var{n}th column of matrix @var{m}, in the form of a vector.
  29406. The arguments are not checked for correctness.
  29407. @end defun
  29408. @defun mat-less-row m n
  29409. Return a copy of matrix @var{m} with its @var{n}th row deleted. The
  29410. number @var{n} must be in range from 1 to the number of rows in @var{m}.
  29411. @end defun
  29412. @defun mat-less-col m n
  29413. Return a copy of matrix @var{m} with its @var{n}th column deleted.
  29414. @end defun
  29415. @defun transpose m
  29416. Return the transpose of matrix @var{m}.
  29417. @end defun
  29418. @defun flatten-vector v
  29419. Flatten nested vector @var{v} into a vector of scalars. For example,
  29420. if @var{v} is @samp{[[1, 2, 3], [4, 5]]} the result is @samp{[1, 2, 3, 4, 5]}.
  29421. @end defun
  29422. @defun copy-matrix m
  29423. If @var{m} is a matrix, return a copy of @var{m}. This maps
  29424. @code{copy-sequence} over the rows of @var{m}; in Lisp terms, each
  29425. element of the result matrix will be @code{eq} to the corresponding
  29426. element of @var{m}, but none of the @code{cons} cells that make up
  29427. the structure of the matrix will be @code{eq}. If @var{m} is a plain
  29428. vector, this is the same as @code{copy-sequence}.
  29429. @end defun
  29430. @defun swap-rows m r1 r2
  29431. Exchange rows @var{r1} and @var{r2} of matrix @var{m} in-place. In
  29432. other words, unlike most of the other functions described here, this
  29433. function changes @var{m} itself rather than building up a new result
  29434. matrix. The return value is @var{m}, i.e., @samp{(eq (swap-rows m 1 2) m)}
  29435. is true, with the side effect of exchanging the first two rows of
  29436. @var{m}.
  29437. @end defun
  29438. @node Symbolic Lisp Functions, Formatting Lisp Functions, Vector Lisp Functions, Internals
  29439. @subsubsection Symbolic Functions
  29440. @noindent
  29441. The functions described here operate on symbolic formulas in the
  29442. Calculator.
  29443. @defun calc-prepare-selection num
  29444. Prepare a stack entry for selection operations. If @var{num} is
  29445. omitted, the stack entry containing the cursor is used; otherwise,
  29446. it is the number of the stack entry to use. This function stores
  29447. useful information about the current stack entry into a set of
  29448. variables. @code{calc-selection-cache-num} contains the number of
  29449. the stack entry involved (equal to @var{num} if you specified it);
  29450. @code{calc-selection-cache-entry} contains the stack entry as a
  29451. list (such as @code{calc-top-list} would return with @code{entry}
  29452. as the selection mode); and @code{calc-selection-cache-comp} contains
  29453. a special ``tagged'' composition (@pxref{Formatting Lisp Functions})
  29454. which allows Calc to relate cursor positions in the buffer with
  29455. their corresponding sub-formulas.
  29456. A slight complication arises in the selection mechanism because
  29457. formulas may contain small integers. For example, in the vector
  29458. @samp{[1, 2, 1]} the first and last elements are @code{eq} to each
  29459. other; selections are recorded as the actual Lisp object that
  29460. appears somewhere in the tree of the whole formula, but storing
  29461. @code{1} would falsely select both @code{1}'s in the vector. So
  29462. @code{calc-prepare-selection} also checks the stack entry and
  29463. replaces any plain integers with ``complex number'' lists of the form
  29464. @samp{(cplx @var{n} 0)}. This list will be displayed the same as a
  29465. plain @var{n} and the change will be completely invisible to the
  29466. user, but it will guarantee that no two sub-formulas of the stack
  29467. entry will be @code{eq} to each other. Next time the stack entry
  29468. is involved in a computation, @code{calc-normalize} will replace
  29469. these lists with plain numbers again, again invisibly to the user.
  29470. @end defun
  29471. @defun calc-encase-atoms x
  29472. This modifies the formula @var{x} to ensure that each part of the
  29473. formula is a unique atom, using the @samp{(cplx @var{n} 0)} trick
  29474. described above. This function may use @code{setcar} to modify
  29475. the formula in-place.
  29476. @end defun
  29477. @defun calc-find-selected-part
  29478. Find the smallest sub-formula of the current formula that contains
  29479. the cursor. This assumes @code{calc-prepare-selection} has been
  29480. called already. If the cursor is not actually on any part of the
  29481. formula, this returns @code{nil}.
  29482. @end defun
  29483. @defun calc-change-current-selection selection
  29484. Change the currently prepared stack element's selection to
  29485. @var{selection}, which should be @code{eq} to some sub-formula
  29486. of the stack element, or @code{nil} to unselect the formula.
  29487. The stack element's appearance in the Calc buffer is adjusted
  29488. to reflect the new selection.
  29489. @end defun
  29490. @defun calc-find-nth-part expr n
  29491. Return the @var{n}th sub-formula of @var{expr}. This function is used
  29492. by the selection commands, and (unless @kbd{j b} has been used) treats
  29493. sums and products as flat many-element formulas. Thus if @var{expr}
  29494. is @samp{((a + b) - c) + d}, calling @code{calc-find-nth-part} with
  29495. @var{n} equal to four will return @samp{d}.
  29496. @end defun
  29497. @defun calc-find-parent-formula expr part
  29498. Return the sub-formula of @var{expr} which immediately contains
  29499. @var{part}. If @var{expr} is @samp{a*b + (c+1)*d} and @var{part}
  29500. is @code{eq} to the @samp{c+1} term of @var{expr}, then this function
  29501. will return @samp{(c+1)*d}. If @var{part} turns out not to be a
  29502. sub-formula of @var{expr}, the function returns @code{nil}. If
  29503. @var{part} is @code{eq} to @var{expr}, the function returns @code{t}.
  29504. This function does not take associativity into account.
  29505. @end defun
  29506. @defun calc-find-assoc-parent-formula expr part
  29507. This is the same as @code{calc-find-parent-formula}, except that
  29508. (unless @kbd{j b} has been used) it continues widening the selection
  29509. to contain a complete level of the formula. Given @samp{a} from
  29510. @samp{((a + b) - c) + d}, @code{calc-find-parent-formula} will
  29511. return @samp{a + b} but @code{calc-find-assoc-parent-formula} will
  29512. return the whole expression.
  29513. @end defun
  29514. @defun calc-grow-assoc-formula expr part
  29515. This expands sub-formula @var{part} of @var{expr} to encompass a
  29516. complete level of the formula. If @var{part} and its immediate
  29517. parent are not compatible associative operators, or if @kbd{j b}
  29518. has been used, this simply returns @var{part}.
  29519. @end defun
  29520. @defun calc-find-sub-formula expr part
  29521. This finds the immediate sub-formula of @var{expr} which contains
  29522. @var{part}. It returns an index @var{n} such that
  29523. @samp{(calc-find-nth-part @var{expr} @var{n})} would return @var{part}.
  29524. If @var{part} is not a sub-formula of @var{expr}, it returns @code{nil}.
  29525. If @var{part} is @code{eq} to @var{expr}, it returns @code{t}. This
  29526. function does not take associativity into account.
  29527. @end defun
  29528. @defun calc-replace-sub-formula expr old new
  29529. This function returns a copy of formula @var{expr}, with the
  29530. sub-formula that is @code{eq} to @var{old} replaced by @var{new}.
  29531. @end defun
  29532. @defun simplify expr
  29533. Simplify the expression @var{expr} by applying Calc's algebraic
  29534. simplifications. This always returns a copy of the expression; the
  29535. structure @var{expr} points to remains unchanged in memory.
  29536. More precisely, here is what @code{simplify} does: The expression is
  29537. first normalized and evaluated by calling @code{normalize}. If any
  29538. @code{AlgSimpRules} have been defined, they are then applied. Then
  29539. the expression is traversed in a depth-first, bottom-up fashion; at
  29540. each level, any simplifications that can be made are made until no
  29541. further changes are possible. Once the entire formula has been
  29542. traversed in this way, it is compared with the original formula (from
  29543. before the call to @code{normalize}) and, if it has changed,
  29544. the entire procedure is repeated (starting with @code{normalize})
  29545. until no further changes occur. Usually only two iterations are
  29546. needed: one to simplify the formula, and another to verify that no
  29547. further simplifications were possible.
  29548. @end defun
  29549. @defun simplify-extended expr
  29550. Simplify the expression @var{expr}, with additional rules enabled that
  29551. help do a more thorough job, while not being entirely ``safe'' in all
  29552. circumstances. (For example, this mode will simplify @samp{sqrt(x^2)}
  29553. to @samp{x}, which is only valid when @var{x} is positive.) This is
  29554. implemented by temporarily binding the variable @code{math-living-dangerously}
  29555. to @code{t} (using a @code{let} form) and calling @code{simplify}.
  29556. Dangerous simplification rules are written to check this variable
  29557. before taking any action.
  29558. @end defun
  29559. @defun simplify-units expr
  29560. Simplify the expression @var{expr}, treating variable names as units
  29561. whenever possible. This works by binding the variable
  29562. @code{math-simplifying-units} to @code{t} while calling @code{simplify}.
  29563. @end defun
  29564. @defmac math-defsimplify funcs body
  29565. Register a new simplification rule; this is normally called as a top-level
  29566. form, like @code{defun} or @code{defmath}. If @var{funcs} is a symbol
  29567. (like @code{+} or @code{calcFunc-sqrt}), this simplification rule is
  29568. applied to the formulas which are calls to the specified function. Or,
  29569. @var{funcs} can be a list of such symbols; the rule applies to all
  29570. functions on the list. The @var{body} is written like the body of a
  29571. function with a single argument called @code{expr}. The body will be
  29572. executed with @code{expr} bound to a formula which is a call to one of
  29573. the functions @var{funcs}. If the function body returns @code{nil}, or
  29574. if it returns a result @code{equal} to the original @code{expr}, it is
  29575. ignored and Calc goes on to try the next simplification rule that applies.
  29576. If the function body returns something different, that new formula is
  29577. substituted for @var{expr} in the original formula.
  29578. At each point in the formula, rules are tried in the order of the
  29579. original calls to @code{math-defsimplify}; the search stops after the
  29580. first rule that makes a change. Thus later rules for that same
  29581. function will not have a chance to trigger until the next iteration
  29582. of the main @code{simplify} loop.
  29583. Note that, since @code{defmath} is not being used here, @var{body} must
  29584. be written in true Lisp code without the conveniences that @code{defmath}
  29585. provides. If you prefer, you can have @var{body} simply call another
  29586. function (defined with @code{defmath}) which does the real work.
  29587. The arguments of a function call will already have been simplified
  29588. before any rules for the call itself are invoked. Since a new argument
  29589. list is consed up when this happens, this means that the rule's body is
  29590. allowed to rearrange the function's arguments destructively if that is
  29591. convenient. Here is a typical example of a simplification rule:
  29592. @smallexample
  29593. (math-defsimplify calcFunc-arcsinh
  29594. (or (and (math-looks-negp (nth 1 expr))
  29595. (math-neg (list 'calcFunc-arcsinh
  29596. (math-neg (nth 1 expr)))))
  29597. (and (eq (car-safe (nth 1 expr)) 'calcFunc-sinh)
  29598. (or math-living-dangerously
  29599. (math-known-realp (nth 1 (nth 1 expr))))
  29600. (nth 1 (nth 1 expr)))))
  29601. @end smallexample
  29602. This is really a pair of rules written with one @code{math-defsimplify}
  29603. for convenience; the first replaces @samp{arcsinh(-x)} with
  29604. @samp{-arcsinh(x)}, and the second, which is safe only for real @samp{x},
  29605. replaces @samp{arcsinh(sinh(x))} with @samp{x}.
  29606. @end defmac
  29607. @defun common-constant-factor expr
  29608. Check @var{expr} to see if it is a sum of terms all multiplied by the
  29609. same rational value. If so, return this value. If not, return @code{nil}.
  29610. For example, if called on @samp{6x + 9y + 12z}, it would return 3, since
  29611. 3 is a common factor of all the terms.
  29612. @end defun
  29613. @defun cancel-common-factor expr factor
  29614. Assuming @var{expr} is a sum with @var{factor} as a common factor,
  29615. divide each term of the sum by @var{factor}. This is done by
  29616. destructively modifying parts of @var{expr}, on the assumption that
  29617. it is being used by a simplification rule (where such things are
  29618. allowed; see above). For example, consider this built-in rule for
  29619. square roots:
  29620. @smallexample
  29621. (math-defsimplify calcFunc-sqrt
  29622. (let ((fac (math-common-constant-factor (nth 1 expr))))
  29623. (and fac (not (eq fac 1))
  29624. (math-mul (math-normalize (list 'calcFunc-sqrt fac))
  29625. (math-normalize
  29626. (list 'calcFunc-sqrt
  29627. (math-cancel-common-factor
  29628. (nth 1 expr) fac)))))))
  29629. @end smallexample
  29630. @end defun
  29631. @defun frac-gcd a b
  29632. Compute a ``rational GCD'' of @var{a} and @var{b}, which must both be
  29633. rational numbers. This is the fraction composed of the GCD of the
  29634. numerators of @var{a} and @var{b}, over the GCD of the denominators.
  29635. It is used by @code{common-constant-factor}. Note that the standard
  29636. @code{gcd} function uses the LCM to combine the denominators.
  29637. @end defun
  29638. @defun map-tree func expr many
  29639. Try applying Lisp function @var{func} to various sub-expressions of
  29640. @var{expr}. Initially, call @var{func} with @var{expr} itself as an
  29641. argument. If this returns an expression which is not @code{equal} to
  29642. @var{expr}, apply @var{func} again until eventually it does return
  29643. @var{expr} with no changes. Then, if @var{expr} is a function call,
  29644. recursively apply @var{func} to each of the arguments. This keeps going
  29645. until no changes occur anywhere in the expression; this final expression
  29646. is returned by @code{map-tree}. Note that, unlike simplification rules,
  29647. @var{func} functions may @emph{not} make destructive changes to
  29648. @var{expr}. If a third argument @var{many} is provided, it is an
  29649. integer which says how many times @var{func} may be applied; the
  29650. default, as described above, is infinitely many times.
  29651. @end defun
  29652. @defun compile-rewrites rules
  29653. Compile the rewrite rule set specified by @var{rules}, which should
  29654. be a formula that is either a vector or a variable name. If the latter,
  29655. the compiled rules are saved so that later @code{compile-rules} calls
  29656. for that same variable can return immediately. If there are problems
  29657. with the rules, this function calls @code{error} with a suitable
  29658. message.
  29659. @end defun
  29660. @defun apply-rewrites expr crules heads
  29661. Apply the compiled rewrite rule set @var{crules} to the expression
  29662. @var{expr}. This will make only one rewrite and only checks at the
  29663. top level of the expression. The result @code{nil} if no rules
  29664. matched, or if the only rules that matched did not actually change
  29665. the expression. The @var{heads} argument is optional; if is given,
  29666. it should be a list of all function names that (may) appear in
  29667. @var{expr}. The rewrite compiler tags each rule with the
  29668. rarest-looking function name in the rule; if you specify @var{heads},
  29669. @code{apply-rewrites} can use this information to narrow its search
  29670. down to just a few rules in the rule set.
  29671. @end defun
  29672. @defun rewrite-heads expr
  29673. Compute a @var{heads} list for @var{expr} suitable for use with
  29674. @code{apply-rewrites}, as discussed above.
  29675. @end defun
  29676. @defun rewrite expr rules many
  29677. This is an all-in-one rewrite function. It compiles the rule set
  29678. specified by @var{rules}, then uses @code{map-tree} to apply the
  29679. rules throughout @var{expr} up to @var{many} (default infinity)
  29680. times.
  29681. @end defun
  29682. @defun match-patterns pat vec not-flag
  29683. Given a Calc vector @var{vec} and an uncompiled pattern set or
  29684. pattern set variable @var{pat}, this function returns a new vector
  29685. of all elements of @var{vec} which do (or don't, if @var{not-flag} is
  29686. non-@code{nil}) match any of the patterns in @var{pat}.
  29687. @end defun
  29688. @defun deriv expr var value symb
  29689. Compute the derivative of @var{expr} with respect to variable @var{var}
  29690. (which may actually be any sub-expression). If @var{value} is specified,
  29691. the derivative is evaluated at the value of @var{var}; otherwise, the
  29692. derivative is left in terms of @var{var}. If the expression contains
  29693. functions for which no derivative formula is known, new derivative
  29694. functions are invented by adding primes to the names; @pxref{Calculus}.
  29695. However, if @var{symb} is non-@code{nil}, the presence of nondifferentiable
  29696. functions in @var{expr} instead cancels the whole differentiation, and
  29697. @code{deriv} returns @code{nil} instead.
  29698. Derivatives of an @var{n}-argument function can be defined by
  29699. adding a @code{math-derivative-@var{n}} property to the property list
  29700. of the symbol for the function's derivative, which will be the
  29701. function name followed by an apostrophe. The value of the property
  29702. should be a Lisp function; it is called with the same arguments as the
  29703. original function call that is being differentiated. It should return
  29704. a formula for the derivative. For example, the derivative of @code{ln}
  29705. is defined by
  29706. @smallexample
  29707. (put 'calcFunc-ln\' 'math-derivative-1
  29708. (function (lambda (u) (math-div 1 u))))
  29709. @end smallexample
  29710. The two-argument @code{log} function has two derivatives,
  29711. @smallexample
  29712. (put 'calcFunc-log\' 'math-derivative-2 ; d(log(x,b)) / dx
  29713. (function (lambda (x b) ... )))
  29714. (put 'calcFunc-log\'2 'math-derivative-2 ; d(log(x,b)) / db
  29715. (function (lambda (x b) ... )))
  29716. @end smallexample
  29717. @end defun
  29718. @defun tderiv expr var value symb
  29719. Compute the total derivative of @var{expr}. This is the same as
  29720. @code{deriv}, except that variables other than @var{var} are not
  29721. assumed to be constant with respect to @var{var}.
  29722. @end defun
  29723. @defun integ expr var low high
  29724. Compute the integral of @var{expr} with respect to @var{var}.
  29725. @xref{Calculus}, for further details.
  29726. @end defun
  29727. @defmac math-defintegral funcs body
  29728. Define a rule for integrating a function or functions of one argument;
  29729. this macro is very similar in format to @code{math-defsimplify}.
  29730. The main difference is that here @var{body} is the body of a function
  29731. with a single argument @code{u} which is bound to the argument to the
  29732. function being integrated, not the function call itself. Also, the
  29733. variable of integration is available as @code{math-integ-var}. If
  29734. evaluation of the integral requires doing further integrals, the body
  29735. should call @samp{(math-integral @var{x})} to find the integral of
  29736. @var{x} with respect to @code{math-integ-var}; this function returns
  29737. @code{nil} if the integral could not be done. Some examples:
  29738. @smallexample
  29739. (math-defintegral calcFunc-conj
  29740. (let ((int (math-integral u)))
  29741. (and int
  29742. (list 'calcFunc-conj int))))
  29743. (math-defintegral calcFunc-cos
  29744. (and (equal u math-integ-var)
  29745. (math-from-radians-2 (list 'calcFunc-sin u))))
  29746. @end smallexample
  29747. In the @code{cos} example, we define only the integral of @samp{cos(x) dx},
  29748. relying on the general integration-by-substitution facility to handle
  29749. cosines of more complicated arguments. An integration rule should return
  29750. @code{nil} if it can't do the integral; if several rules are defined for
  29751. the same function, they are tried in order until one returns a non-@code{nil}
  29752. result.
  29753. @end defmac
  29754. @defmac math-defintegral-2 funcs body
  29755. Define a rule for integrating a function or functions of two arguments.
  29756. This is exactly analogous to @code{math-defintegral}, except that @var{body}
  29757. is written as the body of a function with two arguments, @var{u} and
  29758. @var{v}.
  29759. @end defmac
  29760. @defun solve-for lhs rhs var full
  29761. Attempt to solve the equation @samp{@var{lhs} = @var{rhs}} by isolating
  29762. the variable @var{var} on the lefthand side; return the resulting righthand
  29763. side, or @code{nil} if the equation cannot be solved. The variable
  29764. @var{var} must appear at least once in @var{lhs} or @var{rhs}. Note that
  29765. the return value is a formula which does not contain @var{var}; this is
  29766. different from the user-level @code{solve} and @code{finv} functions,
  29767. which return a rearranged equation or a functional inverse, respectively.
  29768. If @var{full} is non-@code{nil}, a full solution including dummy signs
  29769. and dummy integers will be produced. User-defined inverses are provided
  29770. as properties in a manner similar to derivatives:
  29771. @smallexample
  29772. (put 'calcFunc-ln 'math-inverse
  29773. (function (lambda (x) (list 'calcFunc-exp x))))
  29774. @end smallexample
  29775. This function can call @samp{(math-solve-get-sign @var{x})} to create
  29776. a new arbitrary sign variable, returning @var{x} times that sign, and
  29777. @samp{(math-solve-get-int @var{x})} to create a new arbitrary integer
  29778. variable multiplied by @var{x}. These functions simply return @var{x}
  29779. if the caller requested a non-``full'' solution.
  29780. @end defun
  29781. @defun solve-eqn expr var full
  29782. This version of @code{solve-for} takes an expression which will
  29783. typically be an equation or inequality. (If it is not, it will be
  29784. interpreted as the equation @samp{@var{expr} = 0}.) It returns an
  29785. equation or inequality, or @code{nil} if no solution could be found.
  29786. @end defun
  29787. @defun solve-system exprs vars full
  29788. This function solves a system of equations. Generally, @var{exprs}
  29789. and @var{vars} will be vectors of equal length.
  29790. @xref{Solving Systems of Equations}, for other options.
  29791. @end defun
  29792. @defun expr-contains expr var
  29793. Returns a non-@code{nil} value if @var{var} occurs as a subexpression
  29794. of @var{expr}.
  29795. This function might seem at first to be identical to
  29796. @code{calc-find-sub-formula}. The key difference is that
  29797. @code{expr-contains} uses @code{equal} to test for matches, whereas
  29798. @code{calc-find-sub-formula} uses @code{eq}. In the formula
  29799. @samp{f(a, a)}, the two @samp{a}s will be @code{equal} but not
  29800. @code{eq} to each other.
  29801. @end defun
  29802. @defun expr-contains-count expr var
  29803. Returns the number of occurrences of @var{var} as a subexpression
  29804. of @var{expr}, or @code{nil} if there are no occurrences.
  29805. @end defun
  29806. @defun expr-depends expr var
  29807. Returns true if @var{expr} refers to any variable the occurs in @var{var}.
  29808. In other words, it checks if @var{expr} and @var{var} have any variables
  29809. in common.
  29810. @end defun
  29811. @defun expr-contains-vars expr
  29812. Return true if @var{expr} contains any variables, or @code{nil} if @var{expr}
  29813. contains only constants and functions with constant arguments.
  29814. @end defun
  29815. @defun expr-subst expr old new
  29816. Returns a copy of @var{expr}, with all occurrences of @var{old} replaced
  29817. by @var{new}. This treats @code{lambda} forms specially with respect
  29818. to the dummy argument variables, so that the effect is always to return
  29819. @var{expr} evaluated at @var{old} = @var{new}.
  29820. @end defun
  29821. @defun multi-subst expr old new
  29822. This is like @code{expr-subst}, except that @var{old} and @var{new}
  29823. are lists of expressions to be substituted simultaneously. If one
  29824. list is shorter than the other, trailing elements of the longer list
  29825. are ignored.
  29826. @end defun
  29827. @defun expr-weight expr
  29828. Returns the ``weight'' of @var{expr}, basically a count of the total
  29829. number of objects and function calls that appear in @var{expr}. For
  29830. ``primitive'' objects, this will be one.
  29831. @end defun
  29832. @defun expr-height expr
  29833. Returns the ``height'' of @var{expr}, which is the deepest level to
  29834. which function calls are nested. (Note that @samp{@var{a} + @var{b}}
  29835. counts as a function call.) For primitive objects, this returns zero.
  29836. @end defun
  29837. @defun polynomial-p expr var
  29838. Check if @var{expr} is a polynomial in variable (or sub-expression)
  29839. @var{var}. If so, return the degree of the polynomial, that is, the
  29840. highest power of @var{var} that appears in @var{expr}. For example,
  29841. for @samp{(x^2 + 3)^3 + 4} this would return 6. This function returns
  29842. @code{nil} unless @var{expr}, when expanded out by @kbd{a x}
  29843. (@code{calc-expand}), would consist of a sum of terms in which @var{var}
  29844. appears only raised to nonnegative integer powers. Note that if
  29845. @var{var} does not occur in @var{expr}, then @var{expr} is considered
  29846. a polynomial of degree 0.
  29847. @end defun
  29848. @defun is-polynomial expr var degree loose
  29849. Check if @var{expr} is a polynomial in variable or sub-expression
  29850. @var{var}, and, if so, return a list representation of the polynomial
  29851. where the elements of the list are coefficients of successive powers of
  29852. @var{var}: @samp{@var{a} + @var{b} x + @var{c} x^3} would produce the
  29853. list @samp{(@var{a} @var{b} 0 @var{c})}, and @samp{(x + 1)^2} would
  29854. produce the list @samp{(1 2 1)}. The highest element of the list will
  29855. be non-zero, with the special exception that if @var{expr} is the
  29856. constant zero, the returned value will be @samp{(0)}. Return @code{nil}
  29857. if @var{expr} is not a polynomial in @var{var}. If @var{degree} is
  29858. specified, this will not consider polynomials of degree higher than that
  29859. value. This is a good precaution because otherwise an input of
  29860. @samp{(x+1)^1000} will cause a huge coefficient list to be built. If
  29861. @var{loose} is non-@code{nil}, then a looser definition of a polynomial
  29862. is used in which coefficients are no longer required not to depend on
  29863. @var{var}, but are only required not to take the form of polynomials
  29864. themselves. For example, @samp{sin(x) x^2 + cos(x)} is a loose
  29865. polynomial with coefficients @samp{((calcFunc-cos x) 0 (calcFunc-sin
  29866. x))}. The result will never be @code{nil} in loose mode, since any
  29867. expression can be interpreted as a ``constant'' loose polynomial.
  29868. @end defun
  29869. @defun polynomial-base expr pred
  29870. Check if @var{expr} is a polynomial in any variable that occurs in it;
  29871. if so, return that variable. (If @var{expr} is a multivariate polynomial,
  29872. this chooses one variable arbitrarily.) If @var{pred} is specified, it should
  29873. be a Lisp function which is called as @samp{(@var{pred} @var{subexpr})},
  29874. and which should return true if @code{mpb-top-expr} (a global name for
  29875. the original @var{expr}) is a suitable polynomial in @var{subexpr}.
  29876. The default predicate uses @samp{(polynomial-p mpb-top-expr @var{subexpr})};
  29877. you can use @var{pred} to specify additional conditions. Or, you could
  29878. have @var{pred} build up a list of every suitable @var{subexpr} that
  29879. is found.
  29880. @end defun
  29881. @defun poly-simplify poly
  29882. Simplify polynomial coefficient list @var{poly} by (destructively)
  29883. clipping off trailing zeros.
  29884. @end defun
  29885. @defun poly-mix a ac b bc
  29886. Mix two polynomial lists @var{a} and @var{b} (in the form returned by
  29887. @code{is-polynomial}) in a linear combination with coefficient expressions
  29888. @var{ac} and @var{bc}. The result is a (not necessarily simplified)
  29889. polynomial list representing @samp{@var{ac} @var{a} + @var{bc} @var{b}}.
  29890. @end defun
  29891. @defun poly-mul a b
  29892. Multiply two polynomial coefficient lists @var{a} and @var{b}. The
  29893. result will be in simplified form if the inputs were simplified.
  29894. @end defun
  29895. @defun build-polynomial-expr poly var
  29896. Construct a Calc formula which represents the polynomial coefficient
  29897. list @var{poly} applied to variable @var{var}. The @kbd{a c}
  29898. (@code{calc-collect}) command uses @code{is-polynomial} to turn an
  29899. expression into a coefficient list, then @code{build-polynomial-expr}
  29900. to turn the list back into an expression in regular form.
  29901. @end defun
  29902. @defun check-unit-name var
  29903. Check if @var{var} is a variable which can be interpreted as a unit
  29904. name. If so, return the units table entry for that unit. This
  29905. will be a list whose first element is the unit name (not counting
  29906. prefix characters) as a symbol and whose second element is the
  29907. Calc expression which defines the unit. (Refer to the Calc sources
  29908. for details on the remaining elements of this list.) If @var{var}
  29909. is not a variable or is not a unit name, return @code{nil}.
  29910. @end defun
  29911. @defun units-in-expr-p expr sub-exprs
  29912. Return true if @var{expr} contains any variables which can be
  29913. interpreted as units. If @var{sub-exprs} is @code{t}, the entire
  29914. expression is searched. If @var{sub-exprs} is @code{nil}, this
  29915. checks whether @var{expr} is directly a units expression.
  29916. @end defun
  29917. @defun single-units-in-expr-p expr
  29918. Check whether @var{expr} contains exactly one units variable. If so,
  29919. return the units table entry for the variable. If @var{expr} does
  29920. not contain any units, return @code{nil}. If @var{expr} contains
  29921. two or more units, return the symbol @code{wrong}.
  29922. @end defun
  29923. @defun to-standard-units expr which
  29924. Convert units expression @var{expr} to base units. If @var{which}
  29925. is @code{nil}, use Calc's native base units. Otherwise, @var{which}
  29926. can specify a units system, which is a list of two-element lists,
  29927. where the first element is a Calc base symbol name and the second
  29928. is an expression to substitute for it.
  29929. @end defun
  29930. @defun remove-units expr
  29931. Return a copy of @var{expr} with all units variables replaced by ones.
  29932. This expression is generally normalized before use.
  29933. @end defun
  29934. @defun extract-units expr
  29935. Return a copy of @var{expr} with everything but units variables replaced
  29936. by ones.
  29937. @end defun
  29938. @node Formatting Lisp Functions, Hooks, Symbolic Lisp Functions, Internals
  29939. @subsubsection I/O and Formatting Functions
  29940. @noindent
  29941. The functions described here are responsible for parsing and formatting
  29942. Calc numbers and formulas.
  29943. @defun calc-eval str sep arg1 arg2 @dots{}
  29944. This is the simplest interface to the Calculator from another Lisp program.
  29945. @xref{Calling Calc from Your Programs}.
  29946. @end defun
  29947. @defun read-number str
  29948. If string @var{str} contains a valid Calc number, either integer,
  29949. fraction, float, or HMS form, this function parses and returns that
  29950. number. Otherwise, it returns @code{nil}.
  29951. @end defun
  29952. @defun read-expr str
  29953. Read an algebraic expression from string @var{str}. If @var{str} does
  29954. not have the form of a valid expression, return a list of the form
  29955. @samp{(error @var{pos} @var{msg})} where @var{pos} is an integer index
  29956. into @var{str} of the general location of the error, and @var{msg} is
  29957. a string describing the problem.
  29958. @end defun
  29959. @defun read-exprs str
  29960. Read a list of expressions separated by commas, and return it as a
  29961. Lisp list. If an error occurs in any expressions, an error list as
  29962. shown above is returned instead.
  29963. @end defun
  29964. @defun calc-do-alg-entry initial prompt no-norm
  29965. Read an algebraic formula or formulas using the minibuffer. All
  29966. conventions of regular algebraic entry are observed. The return value
  29967. is a list of Calc formulas; there will be more than one if the user
  29968. entered a list of values separated by commas. The result is @code{nil}
  29969. if the user presses Return with a blank line. If @var{initial} is
  29970. given, it is a string which the minibuffer will initially contain.
  29971. If @var{prompt} is given, it is the prompt string to use; the default
  29972. is ``Algebraic:''. If @var{no-norm} is @code{t}, the formulas will
  29973. be returned exactly as parsed; otherwise, they will be passed through
  29974. @code{calc-normalize} first.
  29975. To support the use of @kbd{$} characters in the algebraic entry, use
  29976. @code{let} to bind @code{calc-dollar-values} to a list of the values
  29977. to be substituted for @kbd{$}, @kbd{$$}, and so on, and bind
  29978. @code{calc-dollar-used} to 0. Upon return, @code{calc-dollar-used}
  29979. will have been changed to the highest number of consecutive @kbd{$}s
  29980. that actually appeared in the input.
  29981. @end defun
  29982. @defun format-number a
  29983. Convert the real or complex number or HMS form @var{a} to string form.
  29984. @end defun
  29985. @defun format-flat-expr a prec
  29986. Convert the arbitrary Calc number or formula @var{a} to string form,
  29987. in the style used by the trail buffer and the @code{calc-edit} command.
  29988. This is a simple format designed
  29989. mostly to guarantee the string is of a form that can be re-parsed by
  29990. @code{read-expr}. Most formatting modes, such as digit grouping,
  29991. complex number format, and point character, are ignored to ensure the
  29992. result will be re-readable. The @var{prec} parameter is normally 0; if
  29993. you pass a large integer like 1000 instead, the expression will be
  29994. surrounded by parentheses unless it is a plain number or variable name.
  29995. @end defun
  29996. @defun format-nice-expr a width
  29997. This is like @code{format-flat-expr} (with @var{prec} equal to 0),
  29998. except that newlines will be inserted to keep lines down to the
  29999. specified @var{width}, and vectors that look like matrices or rewrite
  30000. rules are written in a pseudo-matrix format. The @code{calc-edit}
  30001. command uses this when only one stack entry is being edited.
  30002. @end defun
  30003. @defun format-value a width
  30004. Convert the Calc number or formula @var{a} to string form, using the
  30005. format seen in the stack buffer. Beware the string returned may
  30006. not be re-readable by @code{read-expr}, for example, because of digit
  30007. grouping. Multi-line objects like matrices produce strings that
  30008. contain newline characters to separate the lines. The @var{w}
  30009. parameter, if given, is the target window size for which to format
  30010. the expressions. If @var{w} is omitted, the width of the Calculator
  30011. window is used.
  30012. @end defun
  30013. @defun compose-expr a prec
  30014. Format the Calc number or formula @var{a} according to the current
  30015. language mode, returning a ``composition.'' To learn about the
  30016. structure of compositions, see the comments in the Calc source code.
  30017. You can specify the format of a given type of function call by putting
  30018. a @code{math-compose-@var{lang}} property on the function's symbol,
  30019. whose value is a Lisp function that takes @var{a} and @var{prec} as
  30020. arguments and returns a composition. Here @var{lang} is a language
  30021. mode name, one of @code{normal}, @code{big}, @code{c}, @code{pascal},
  30022. @code{fortran}, @code{tex}, @code{eqn}, @code{math}, or @code{maple}.
  30023. In Big mode, Calc actually tries @code{math-compose-big} first, then
  30024. tries @code{math-compose-normal}. If this property does not exist,
  30025. or if the function returns @code{nil}, the function is written in the
  30026. normal function-call notation for that language.
  30027. @end defun
  30028. @defun composition-to-string c w
  30029. Convert a composition structure returned by @code{compose-expr} into
  30030. a string. Multi-line compositions convert to strings containing
  30031. newline characters. The target window size is given by @var{w}.
  30032. The @code{format-value} function basically calls @code{compose-expr}
  30033. followed by @code{composition-to-string}.
  30034. @end defun
  30035. @defun comp-width c
  30036. Compute the width in characters of composition @var{c}.
  30037. @end defun
  30038. @defun comp-height c
  30039. Compute the height in lines of composition @var{c}.
  30040. @end defun
  30041. @defun comp-ascent c
  30042. Compute the portion of the height of composition @var{c} which is on or
  30043. above the baseline. For a one-line composition, this will be one.
  30044. @end defun
  30045. @defun comp-descent c
  30046. Compute the portion of the height of composition @var{c} which is below
  30047. the baseline. For a one-line composition, this will be zero.
  30048. @end defun
  30049. @defun comp-first-char c
  30050. If composition @var{c} is a ``flat'' composition, return the first
  30051. (leftmost) character of the composition as an integer. Otherwise,
  30052. return @code{nil}.
  30053. @end defun
  30054. @defun comp-last-char c
  30055. If composition @var{c} is a ``flat'' composition, return the last
  30056. (rightmost) character, otherwise return @code{nil}.
  30057. @end defun
  30058. @comment @node Lisp Variables, Hooks, Formatting Lisp Functions, Internals
  30059. @comment @subsubsection Lisp Variables
  30060. @comment
  30061. @comment @noindent
  30062. @comment (This section is currently unfinished.)
  30063. @node Hooks, , Formatting Lisp Functions, Internals
  30064. @subsubsection Hooks
  30065. @noindent
  30066. Hooks are variables which contain Lisp functions (or lists of functions)
  30067. which are called at various times. Calc defines a number of hooks
  30068. that help you to customize it in various ways. Calc uses the Lisp
  30069. function @code{run-hooks} to invoke the hooks shown below. Several
  30070. other customization-related variables are also described here.
  30071. @defvar calc-load-hook
  30072. This hook is called at the end of @file{calc.el}, after the file has
  30073. been loaded, before any functions in it have been called, but after
  30074. @code{calc-mode-map} and similar variables have been set up.
  30075. @end defvar
  30076. @defvar calc-ext-load-hook
  30077. This hook is called at the end of @file{calc-ext.el}.
  30078. @end defvar
  30079. @defvar calc-start-hook
  30080. This hook is called as the last step in a @kbd{M-x calc} command.
  30081. At this point, the Calc buffer has been created and initialized if
  30082. necessary, the Calc window and trail window have been created,
  30083. and the ``Welcome to Calc'' message has been displayed.
  30084. @end defvar
  30085. @defvar calc-mode-hook
  30086. This hook is called when the Calc buffer is being created. Usually
  30087. this will only happen once per Emacs session. The hook is called
  30088. after Emacs has switched to the new buffer, the mode-settings file
  30089. has been read if necessary, and all other buffer-local variables
  30090. have been set up. After this hook returns, Calc will perform a
  30091. @code{calc-refresh} operation, set up the mode line display, then
  30092. evaluate any deferred @code{calc-define} properties that have not
  30093. been evaluated yet.
  30094. @end defvar
  30095. @defvar calc-trail-mode-hook
  30096. This hook is called when the Calc Trail buffer is being created.
  30097. It is called as the very last step of setting up the Trail buffer.
  30098. Like @code{calc-mode-hook}, this will normally happen only once
  30099. per Emacs session.
  30100. @end defvar
  30101. @defvar calc-end-hook
  30102. This hook is called by @code{calc-quit}, generally because the user
  30103. presses @kbd{q} or @kbd{C-x * c} while in Calc. The Calc buffer will
  30104. be the current buffer. The hook is called as the very first
  30105. step, before the Calc window is destroyed.
  30106. @end defvar
  30107. @defvar calc-window-hook
  30108. If this hook is non-@code{nil}, it is called to create the Calc window.
  30109. Upon return, this new Calc window should be the current window.
  30110. (The Calc buffer will already be the current buffer when the
  30111. hook is called.) If the hook is not defined, Calc will
  30112. generally use @code{split-window}, @code{set-window-buffer},
  30113. and @code{select-window} to create the Calc window.
  30114. @end defvar
  30115. @defvar calc-trail-window-hook
  30116. If this hook is non-@code{nil}, it is called to create the Calc Trail
  30117. window. The variable @code{calc-trail-buffer} will contain the buffer
  30118. which the window should use. Unlike @code{calc-window-hook}, this hook
  30119. must @emph{not} switch into the new window.
  30120. @end defvar
  30121. @defvar calc-embedded-mode-hook
  30122. This hook is called the first time that Embedded mode is entered.
  30123. @end defvar
  30124. @defvar calc-embedded-new-buffer-hook
  30125. This hook is called each time that Embedded mode is entered in a
  30126. new buffer.
  30127. @end defvar
  30128. @defvar calc-embedded-new-formula-hook
  30129. This hook is called each time that Embedded mode is enabled for a
  30130. new formula.
  30131. @end defvar
  30132. @defvar calc-edit-mode-hook
  30133. This hook is called by @code{calc-edit} (and the other ``edit''
  30134. commands) when the temporary editing buffer is being created.
  30135. The buffer will have been selected and set up to be in
  30136. @code{calc-edit-mode}, but will not yet have been filled with
  30137. text. (In fact it may still have leftover text from a previous
  30138. @code{calc-edit} command.)
  30139. @end defvar
  30140. @defvar calc-mode-save-hook
  30141. This hook is called by the @code{calc-save-modes} command,
  30142. after Calc's own mode features have been inserted into the
  30143. Calc init file and just before the ``End of mode settings''
  30144. message is inserted.
  30145. @end defvar
  30146. @defvar calc-reset-hook
  30147. This hook is called after @kbd{C-x * 0} (@code{calc-reset}) has
  30148. reset all modes. The Calc buffer will be the current buffer.
  30149. @end defvar
  30150. @defvar calc-other-modes
  30151. This variable contains a list of strings. The strings are
  30152. concatenated at the end of the modes portion of the Calc
  30153. mode line (after standard modes such as ``Deg'', ``Inv'' and
  30154. ``Hyp''). Each string should be a short, single word followed
  30155. by a space. The variable is @code{nil} by default.
  30156. @end defvar
  30157. @defvar calc-mode-map
  30158. This is the keymap that is used by Calc mode. The best time
  30159. to adjust it is probably in a @code{calc-mode-hook}. If the
  30160. Calc extensions package (@file{calc-ext.el}) has not yet been
  30161. loaded, many of these keys will be bound to @code{calc-missing-key},
  30162. which is a command that loads the extensions package and
  30163. ``retypes'' the key. If your @code{calc-mode-hook} rebinds
  30164. one of these keys, it will probably be overridden when the
  30165. extensions are loaded.
  30166. @end defvar
  30167. @defvar calc-digit-map
  30168. This is the keymap that is used during numeric entry. Numeric
  30169. entry uses the minibuffer, but this map binds every non-numeric
  30170. key to @code{calcDigit-nondigit} which generally calls
  30171. @code{exit-minibuffer} and ``retypes'' the key.
  30172. @end defvar
  30173. @defvar calc-alg-ent-map
  30174. This is the keymap that is used during algebraic entry. This is
  30175. mostly a copy of @code{minibuffer-local-map}.
  30176. @end defvar
  30177. @defvar calc-store-var-map
  30178. This is the keymap that is used during entry of variable names for
  30179. commands like @code{calc-store} and @code{calc-recall}. This is
  30180. mostly a copy of @code{minibuffer-local-completion-map}.
  30181. @end defvar
  30182. @defvar calc-edit-mode-map
  30183. This is the (sparse) keymap used by @code{calc-edit} and other
  30184. temporary editing commands. It binds @key{RET}, @key{LFD},
  30185. and @kbd{C-c C-c} to @code{calc-edit-finish}.
  30186. @end defvar
  30187. @defvar calc-mode-var-list
  30188. This is a list of variables which are saved by @code{calc-save-modes}.
  30189. Each entry is a list of two items, the variable (as a Lisp symbol)
  30190. and its default value. When modes are being saved, each variable
  30191. is compared with its default value (using @code{equal}) and any
  30192. non-default variables are written out.
  30193. @end defvar
  30194. @defvar calc-local-var-list
  30195. This is a list of variables which should be buffer-local to the
  30196. Calc buffer. Each entry is a variable name (as a Lisp symbol).
  30197. These variables also have their default values manipulated by
  30198. the @code{calc} and @code{calc-quit} commands; @pxref{Multiple Calculators}.
  30199. Since @code{calc-mode-hook} is called after this list has been
  30200. used the first time, your hook should add a variable to the
  30201. list and also call @code{make-local-variable} itself.
  30202. @end defvar
  30203. @node Copying, GNU Free Documentation License, Programming, Top
  30204. @appendix GNU GENERAL PUBLIC LICENSE
  30205. @include gpl.texi
  30206. @node GNU Free Documentation License, Customizing Calc, Copying, Top
  30207. @appendix GNU Free Documentation License
  30208. @include doclicense.texi
  30209. @node Customizing Calc, Reporting Bugs, GNU Free Documentation License, Top
  30210. @appendix Customizing Calc
  30211. The usual prefix for Calc is the key sequence @kbd{C-x *}. If you wish
  30212. to use a different prefix, you can put
  30213. @example
  30214. (global-set-key "NEWPREFIX" 'calc-dispatch)
  30215. @end example
  30216. @noindent
  30217. in your .emacs file.
  30218. (@xref{Key Bindings,,Customizing Key Bindings,emacs,
  30219. The GNU Emacs Manual}, for more information on binding keys.)
  30220. A convenient way to start Calc is with @kbd{C-x * *}; to make it equally
  30221. convenient for users who use a different prefix, the prefix can be
  30222. followed by @kbd{=}, @kbd{&}, @kbd{#}, @kbd{\}, @kbd{/}, @kbd{+} or
  30223. @kbd{-} as well as @kbd{*} to start Calc, and so in many cases the last
  30224. character of the prefix can simply be typed twice.
  30225. Calc is controlled by many variables, most of which can be reset
  30226. from within Calc. Some variables are less involved with actual
  30227. calculation and can be set outside of Calc using Emacs's
  30228. customization facilities. These variables are listed below.
  30229. Typing @kbd{M-x customize-variable RET @var{variable-name} RET}
  30230. will bring up a buffer in which the variable's value can be redefined.
  30231. Typing @kbd{M-x customize-group RET calc RET} will bring up a buffer which
  30232. contains all of Calc's customizable variables. (These variables can
  30233. also be reset by putting the appropriate lines in your .emacs file;
  30234. @xref{Init File, ,Init File, emacs, The GNU Emacs Manual}.)
  30235. Some of the customizable variables are regular expressions. A regular
  30236. expression is basically a pattern that Calc can search for.
  30237. See @ref{Regexp Search,, Regular Expression Search, emacs, The GNU Emacs Manual}
  30238. to see how regular expressions work.
  30239. @defvar calc-settings-file
  30240. The variable @code{calc-settings-file} holds the file name in
  30241. which commands like @kbd{m m} and @kbd{Z P} store ``permanent''
  30242. definitions.
  30243. If @code{calc-settings-file} is not your user init file (typically
  30244. @file{~/.emacs}) and if the variable @code{calc-loaded-settings-file} is
  30245. @code{nil}, then Calc will automatically load your settings file (if it
  30246. exists) the first time Calc is invoked.
  30247. The default value for this variable is @code{"~/.emacs.d/calc.el"}
  30248. unless the file @file{~/.calc.el} exists, in which case the default
  30249. value will be @code{"~/.calc.el"}.
  30250. @end defvar
  30251. @defvar calc-gnuplot-name
  30252. See @ref{Graphics}.@*
  30253. The variable @code{calc-gnuplot-name} should be the name of the
  30254. GNUPLOT program (a string). If you have GNUPLOT installed on your
  30255. system but Calc is unable to find it, you may need to set this
  30256. variable. You may also need to set some Lisp variables to show Calc how
  30257. to run GNUPLOT on your system, see @ref{Devices, ,Graphical Devices} .
  30258. The default value of @code{calc-gnuplot-name} is @code{"gnuplot"}.
  30259. @end defvar
  30260. @defvar calc-gnuplot-plot-command
  30261. @defvarx calc-gnuplot-print-command
  30262. See @ref{Devices, ,Graphical Devices}.@*
  30263. The variables @code{calc-gnuplot-plot-command} and
  30264. @code{calc-gnuplot-print-command} represent system commands to
  30265. display and print the output of GNUPLOT, respectively. These may be
  30266. @code{nil} if no command is necessary, or strings which can include
  30267. @samp{%s} to signify the name of the file to be displayed or printed.
  30268. Or, these variables may contain Lisp expressions which are evaluated
  30269. to display or print the output.
  30270. The default value of @code{calc-gnuplot-plot-command} is @code{nil},
  30271. and the default value of @code{calc-gnuplot-print-command} is
  30272. @code{"lp %s"}.
  30273. @end defvar
  30274. @defvar calc-language-alist
  30275. See @ref{Basic Embedded Mode}.@*
  30276. The variable @code{calc-language-alist} controls the languages that
  30277. Calc will associate with major modes. When Calc embedded mode is
  30278. enabled, it will try to use the current major mode to
  30279. determine what language should be used. (This can be overridden using
  30280. Calc's mode changing commands, @xref{Mode Settings in Embedded Mode}.)
  30281. The variable @code{calc-language-alist} consists of a list of pairs of
  30282. the form @code{(@var{MAJOR-MODE} . @var{LANGUAGE})}; for example,
  30283. @code{(latex-mode . latex)} is one such pair. If Calc embedded is
  30284. activated in a buffer whose major mode is @var{MAJOR-MODE}, it will set itself
  30285. to use the language @var{LANGUAGE}.
  30286. The default value of @code{calc-language-alist} is
  30287. @example
  30288. ((latex-mode . latex)
  30289. (tex-mode . tex)
  30290. (plain-tex-mode . tex)
  30291. (context-mode . tex)
  30292. (nroff-mode . eqn)
  30293. (pascal-mode . pascal)
  30294. (c-mode . c)
  30295. (c++-mode . c)
  30296. (fortran-mode . fortran)
  30297. (f90-mode . fortran))
  30298. @end example
  30299. @end defvar
  30300. @defvar calc-embedded-announce-formula
  30301. @defvarx calc-embedded-announce-formula-alist
  30302. See @ref{Customizing Embedded Mode}.@*
  30303. The variable @code{calc-embedded-announce-formula} helps determine
  30304. what formulas @kbd{C-x * a} will activate in a buffer. It is a
  30305. regular expression, and when activating embedded formulas with
  30306. @kbd{C-x * a}, it will tell Calc that what follows is a formula to be
  30307. activated. (Calc also uses other patterns to find formulas, such as
  30308. @samp{=>} and @samp{:=}.)
  30309. The default pattern is @code{"%Embed\n\\(% .*\n\\)*"}, which checks
  30310. for @samp{%Embed} followed by any number of lines beginning with
  30311. @samp{%} and a space.
  30312. The variable @code{calc-embedded-announce-formula-alist} is used to
  30313. set @code{calc-embedded-announce-formula} to different regular
  30314. expressions depending on the major mode of the editing buffer.
  30315. It consists of a list of pairs of the form @code{(@var{MAJOR-MODE} .
  30316. @var{REGEXP})}, and its default value is
  30317. @example
  30318. ((c++-mode . "//Embed\n\\(// .*\n\\)*")
  30319. (c-mode . "/\\*Embed\\*/\n\\(/\\* .*\\*/\n\\)*")
  30320. (f90-mode . "!Embed\n\\(! .*\n\\)*")
  30321. (fortran-mode . "C Embed\n\\(C .*\n\\)*")
  30322. (html-helper-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
  30323. (html-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
  30324. (nroff-mode . "\\\\\"Embed\n\\(\\\\\" .*\n\\)*")
  30325. (pascal-mode . "@{Embed@}\n\\(@{.*@}\n\\)*")
  30326. (sgml-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
  30327. (xml-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
  30328. (texinfo-mode . "@@c Embed\n\\(@@c .*\n\\)*"))
  30329. @end example
  30330. Any major modes added to @code{calc-embedded-announce-formula-alist}
  30331. should also be added to @code{calc-embedded-open-close-plain-alist}
  30332. and @code{calc-embedded-open-close-mode-alist}.
  30333. @end defvar
  30334. @defvar calc-embedded-open-formula
  30335. @defvarx calc-embedded-close-formula
  30336. @defvarx calc-embedded-open-close-formula-alist
  30337. See @ref{Customizing Embedded Mode}.@*
  30338. The variables @code{calc-embedded-open-formula} and
  30339. @code{calc-embedded-close-formula} control the region that Calc will
  30340. activate as a formula when Embedded mode is entered with @kbd{C-x * e}.
  30341. They are regular expressions;
  30342. Calc normally scans backward and forward in the buffer for the
  30343. nearest text matching these regular expressions to be the ``formula
  30344. delimiters''.
  30345. The simplest delimiters are blank lines. Other delimiters that
  30346. Embedded mode understands by default are:
  30347. @enumerate
  30348. @item
  30349. The @TeX{} and @LaTeX{} math delimiters @samp{$ $}, @samp{$$ $$},
  30350. @samp{\[ \]}, and @samp{\( \)};
  30351. @item
  30352. Lines beginning with @samp{\begin} and @samp{\end} (except matrix delimiters);
  30353. @item
  30354. Lines beginning with @samp{@@} (Texinfo delimiters).
  30355. @item
  30356. Lines beginning with @samp{.EQ} and @samp{.EN} (@dfn{eqn} delimiters);
  30357. @item
  30358. Lines containing a single @samp{%} or @samp{.\"} symbol and nothing else.
  30359. @end enumerate
  30360. The variable @code{calc-embedded-open-close-formula-alist} is used to
  30361. set @code{calc-embedded-open-formula} and
  30362. @code{calc-embedded-close-formula} to different regular
  30363. expressions depending on the major mode of the editing buffer.
  30364. It consists of a list of lists of the form
  30365. @code{(@var{MAJOR-MODE} @var{OPEN-FORMULA-REGEXP}
  30366. @var{CLOSE-FORMULA-REGEXP})}, and its default value is
  30367. @code{nil}.
  30368. @end defvar
  30369. @defvar calc-embedded-word-regexp
  30370. @defvarx calc-embedded-word-regexp-alist
  30371. See @ref{Customizing Embedded Mode}.@*
  30372. The variable @code{calc-embedded-word-regexp} determines the expression
  30373. that Calc will activate when Embedded mode is entered with @kbd{C-x *
  30374. w}. It is a regular expressions.
  30375. The default value of @code{calc-embedded-word-regexp} is
  30376. @code{"[-+]?[0-9]+\\(\\.[0-9]+\\)?\\([eE][-+]?[0-9]+\\)?"}.
  30377. The variable @code{calc-embedded-word-regexp-alist} is used to
  30378. set @code{calc-embedded-word-regexp} to a different regular
  30379. expression depending on the major mode of the editing buffer.
  30380. It consists of a list of lists of the form
  30381. @code{(@var{MAJOR-MODE} @var{WORD-REGEXP})}, and its default value is
  30382. @code{nil}.
  30383. @end defvar
  30384. @defvar calc-embedded-open-plain
  30385. @defvarx calc-embedded-close-plain
  30386. @defvarx calc-embedded-open-close-plain-alist
  30387. See @ref{Customizing Embedded Mode}.@*
  30388. The variables @code{calc-embedded-open-plain} and
  30389. @code{calc-embedded-open-plain} are used to delimit ``plain''
  30390. formulas. Note that these are actual strings, not regular
  30391. expressions, because Calc must be able to write these string into a
  30392. buffer as well as to recognize them.
  30393. The default string for @code{calc-embedded-open-plain} is
  30394. @code{"%%% "}, note the trailing space. The default string for
  30395. @code{calc-embedded-close-plain} is @code{" %%%\n"}, without
  30396. the trailing newline here, the first line of a Big mode formula
  30397. that followed might be shifted over with respect to the other lines.
  30398. The variable @code{calc-embedded-open-close-plain-alist} is used to
  30399. set @code{calc-embedded-open-plain} and
  30400. @code{calc-embedded-close-plain} to different strings
  30401. depending on the major mode of the editing buffer.
  30402. It consists of a list of lists of the form
  30403. @code{(@var{MAJOR-MODE} @var{OPEN-PLAIN-STRING}
  30404. @var{CLOSE-PLAIN-STRING})}, and its default value is
  30405. @example
  30406. ((c++-mode "// %% " " %%\n")
  30407. (c-mode "/* %% " " %% */\n")
  30408. (f90-mode "! %% " " %%\n")
  30409. (fortran-mode "C %% " " %%\n")
  30410. (html-helper-mode "<!-- %% " " %% -->\n")
  30411. (html-mode "<!-- %% " " %% -->\n")
  30412. (nroff-mode "\\\" %% " " %%\n")
  30413. (pascal-mode "@{%% " " %%@}\n")
  30414. (sgml-mode "<!-- %% " " %% -->\n")
  30415. (xml-mode "<!-- %% " " %% -->\n")
  30416. (texinfo-mode "@@c %% " " %%\n"))
  30417. @end example
  30418. Any major modes added to @code{calc-embedded-open-close-plain-alist}
  30419. should also be added to @code{calc-embedded-announce-formula-alist}
  30420. and @code{calc-embedded-open-close-mode-alist}.
  30421. @end defvar
  30422. @defvar calc-embedded-open-new-formula
  30423. @defvarx calc-embedded-close-new-formula
  30424. @defvarx calc-embedded-open-close-new-formula-alist
  30425. See @ref{Customizing Embedded Mode}.@*
  30426. The variables @code{calc-embedded-open-new-formula} and
  30427. @code{calc-embedded-close-new-formula} are strings which are
  30428. inserted before and after a new formula when you type @kbd{C-x * f}.
  30429. The default value of @code{calc-embedded-open-new-formula} is
  30430. @code{"\n\n"}. If this string begins with a newline character and the
  30431. @kbd{C-x * f} is typed at the beginning of a line, @kbd{C-x * f} will skip
  30432. this first newline to avoid introducing unnecessary blank lines in the
  30433. file. The default value of @code{calc-embedded-close-new-formula} is
  30434. also @code{"\n\n"}. The final newline is omitted by @w{@kbd{C-x * f}}
  30435. if typed at the end of a line. (It follows that if @kbd{C-x * f} is
  30436. typed on a blank line, both a leading opening newline and a trailing
  30437. closing newline are omitted.)
  30438. The variable @code{calc-embedded-open-close-new-formula-alist} is used to
  30439. set @code{calc-embedded-open-new-formula} and
  30440. @code{calc-embedded-close-new-formula} to different strings
  30441. depending on the major mode of the editing buffer.
  30442. It consists of a list of lists of the form
  30443. @code{(@var{MAJOR-MODE} @var{OPEN-NEW-FORMULA-STRING}
  30444. @var{CLOSE-NEW-FORMULA-STRING})}, and its default value is
  30445. @code{nil}.
  30446. @end defvar
  30447. @defvar calc-embedded-open-mode
  30448. @defvarx calc-embedded-close-mode
  30449. @defvarx calc-embedded-open-close-mode-alist
  30450. See @ref{Customizing Embedded Mode}.@*
  30451. The variables @code{calc-embedded-open-mode} and
  30452. @code{calc-embedded-close-mode} are strings which Calc will place before
  30453. and after any mode annotations that it inserts. Calc never scans for
  30454. these strings; Calc always looks for the annotation itself, so it is not
  30455. necessary to add them to user-written annotations.
  30456. The default value of @code{calc-embedded-open-mode} is @code{"% "}
  30457. and the default value of @code{calc-embedded-close-mode} is
  30458. @code{"\n"}.
  30459. If you change the value of @code{calc-embedded-close-mode}, it is a good
  30460. idea still to end with a newline so that mode annotations will appear on
  30461. lines by themselves.
  30462. The variable @code{calc-embedded-open-close-mode-alist} is used to
  30463. set @code{calc-embedded-open-mode} and
  30464. @code{calc-embedded-close-mode} to different strings
  30465. expressions depending on the major mode of the editing buffer.
  30466. It consists of a list of lists of the form
  30467. @code{(@var{MAJOR-MODE} @var{OPEN-MODE-STRING}
  30468. @var{CLOSE-MODE-STRING})}, and its default value is
  30469. @example
  30470. ((c++-mode "// " "\n")
  30471. (c-mode "/* " " */\n")
  30472. (f90-mode "! " "\n")
  30473. (fortran-mode "C " "\n")
  30474. (html-helper-mode "<!-- " " -->\n")
  30475. (html-mode "<!-- " " -->\n")
  30476. (nroff-mode "\\\" " "\n")
  30477. (pascal-mode "@{ " " @}\n")
  30478. (sgml-mode "<!-- " " -->\n")
  30479. (xml-mode "<!-- " " -->\n")
  30480. (texinfo-mode "@@c " "\n"))
  30481. @end example
  30482. Any major modes added to @code{calc-embedded-open-close-mode-alist}
  30483. should also be added to @code{calc-embedded-announce-formula-alist}
  30484. and @code{calc-embedded-open-close-plain-alist}.
  30485. @end defvar
  30486. @defvar calc-lu-power-reference
  30487. @defvarx calc-lu-field-reference
  30488. See @ref{Logarithmic Units}.@*
  30489. The variables @code{calc-lu-power-reference} and
  30490. @code{calc-lu-field-reference} are unit expressions (written as
  30491. strings) which Calc will use as reference quantities for logarithmic
  30492. units.
  30493. The default value of @code{calc-lu-power-reference} is @code{"mW"}
  30494. and the default value of @code{calc-lu-field-reference} is
  30495. @code{"20 uPa"}.
  30496. @end defvar
  30497. @defvar calc-note-threshold
  30498. See @ref{Musical Notes}.@*
  30499. The variable @code{calc-note-threshold} is a number (written as a
  30500. string) which determines how close (in cents) a frequency needs to be
  30501. to a note to be recognized as that note.
  30502. The default value of @code{calc-note-threshold} is 1.
  30503. @end defvar
  30504. @defvar calc-highlight-selections-with-faces
  30505. @defvarx calc-selected-face
  30506. @defvarx calc-nonselected-face
  30507. See @ref{Displaying Selections}.@*
  30508. The variable @code{calc-highlight-selections-with-faces}
  30509. determines how selected sub-formulas are distinguished.
  30510. If @code{calc-highlight-selections-with-faces} is nil, then
  30511. a selected sub-formula is distinguished either by changing every
  30512. character not part of the sub-formula with a dot or by changing every
  30513. character in the sub-formula with a @samp{#} sign.
  30514. If @code{calc-highlight-selections-with-faces} is t,
  30515. then a selected sub-formula is distinguished either by displaying the
  30516. non-selected portion of the formula with @code{calc-nonselected-face}
  30517. or by displaying the selected sub-formula with
  30518. @code{calc-nonselected-face}.
  30519. @end defvar
  30520. @defvar calc-multiplication-has-precedence
  30521. The variable @code{calc-multiplication-has-precedence} determines
  30522. whether multiplication has precedence over division in algebraic
  30523. formulas in normal language modes. If
  30524. @code{calc-multiplication-has-precedence} is non-@code{nil}, then
  30525. multiplication has precedence (and, for certain obscure reasons, is
  30526. right associative), and so for example @samp{a/b*c} will be interpreted
  30527. as @samp{a/(b*c)}. If @code{calc-multiplication-has-precedence} is
  30528. @code{nil}, then multiplication has the same precedence as division
  30529. (and, like division, is left associative), and so for example
  30530. @samp{a/b*c} will be interpreted as @samp{(a/b)*c}. The default value
  30531. of @code{calc-multiplication-has-precedence} is @code{t}.
  30532. @end defvar
  30533. @defvar calc-context-sensitive-enter
  30534. The commands @code{calc-enter} and @code{calc-pop} will typically
  30535. duplicate the top of the stack. If
  30536. @code{calc-context-sensitive-enter} is non-@code{nil}, then the
  30537. @code{calc-enter} will copy the element at the cursor to the
  30538. top of the stack and @code{calc-pop} will delete the element at the
  30539. cursor. The default value of @code{calc-context-sensitive-enter} is
  30540. @code{nil}.
  30541. @end defvar
  30542. @defvar calc-undo-length
  30543. The variable @code{calc-undo-length} determines the number of undo
  30544. steps that Calc will keep track of when @code{calc-quit} is called.
  30545. If @code{calc-undo-length} is a non-negative integer, then this is the
  30546. number of undo steps that will be preserved; if
  30547. @code{calc-undo-length} has any other value, then all undo steps will
  30548. be preserved. The default value of @code{calc-undo-length} is @expr{100}.
  30549. @end defvar
  30550. @defvar calc-gregorian-switch
  30551. See @ref{Date Forms}.@*
  30552. The variable @code{calc-gregorian-switch} is either a list of integers
  30553. @code{(@var{YEAR} @var{MONTH} @var{DAY})} or @code{nil}.
  30554. If it is @code{nil}, then Calc's date forms always represent Gregorian dates.
  30555. Otherwise, @code{calc-gregorian-switch} represents the date that the
  30556. calendar switches from Julian dates to Gregorian dates;
  30557. @code{(@var{YEAR} @var{MONTH} @var{DAY})} will be the first Gregorian
  30558. date. The customization buffer will offer several standard dates to
  30559. choose from, or the user can enter their own date.
  30560. The default value of @code{calc-gregorian-switch} is @code{nil}.
  30561. @end defvar
  30562. @node Reporting Bugs, Summary, Customizing Calc, Top
  30563. @appendix Reporting Bugs
  30564. @noindent
  30565. If you find a bug in Calc, send e-mail to Jay Belanger,
  30566. @example
  30567. jay.p.belanger@@gmail.com
  30568. @end example
  30569. @noindent
  30570. There is an automatic command @kbd{M-x report-calc-bug} which helps
  30571. you to report bugs. This command prompts you for a brief subject
  30572. line, then leaves you in a mail editing buffer. Type @kbd{C-c C-c} to
  30573. send your mail. Make sure your subject line indicates that you are
  30574. reporting a Calc bug; this command sends mail to the maintainer's
  30575. regular mailbox.
  30576. If you have suggestions for additional features for Calc, please send
  30577. them. Some have dared to suggest that Calc is already top-heavy with
  30578. features; this obviously cannot be the case, so if you have ideas, send
  30579. them right in.
  30580. At the front of the source file, @file{calc.el}, is a list of ideas for
  30581. future work. If any enthusiastic souls wish to take it upon themselves
  30582. to work on these, please send a message (using @kbd{M-x report-calc-bug})
  30583. so any efforts can be coordinated.
  30584. The latest version of Calc is available from Savannah, in the Emacs
  30585. repository. See @uref{http://savannah.gnu.org/projects/emacs}.
  30586. @c [summary]
  30587. @node Summary, Key Index, Reporting Bugs, Top
  30588. @appendix Calc Summary
  30589. @noindent
  30590. This section includes a complete list of Calc keystroke commands.
  30591. Each line lists the stack entries used by the command (top-of-stack
  30592. last), the keystrokes themselves, the prompts asked by the command,
  30593. and the result of the command (also with top-of-stack last).
  30594. The result is expressed using the equivalent algebraic function.
  30595. Commands which put no results on the stack show the full @kbd{M-x}
  30596. command name in that position. Numbers preceding the result or
  30597. command name refer to notes at the end.
  30598. Algebraic functions and @kbd{M-x} commands that don't have corresponding
  30599. keystrokes are not listed in this summary.
  30600. @xref{Command Index}. @xref{Function Index}.
  30601. @iftex
  30602. @begingroup
  30603. @tex
  30604. \vskip-2\baselineskip \null
  30605. \gdef\sumrow#1{\sumrowx#1\relax}%
  30606. \gdef\sumrowx#1\:#2\:#3\:#4\:#5\:#6\relax{%
  30607. \leavevmode%
  30608. {\smallfonts
  30609. \hbox to5em{\sl\hss#1}%
  30610. \hbox to5em{\tt#2\hss}%
  30611. \hbox to4em{\sl#3\hss}%
  30612. \hbox to5em{\rm\hss#4}%
  30613. \thinspace%
  30614. {\tt#5}%
  30615. {\sl#6}%
  30616. }}%
  30617. \gdef\sumlpar{{\rm(}}%
  30618. \gdef\sumrpar{{\rm)}}%
  30619. \gdef\sumcomma{{\rm,\thinspace}}%
  30620. \gdef\sumexcl{{\rm!}}%
  30621. \gdef\sumbreak{\vskip-2.5\baselineskip\goodbreak}%
  30622. \gdef\minus#1{{\tt-}}%
  30623. @end tex
  30624. @let@:=@sumsep
  30625. @let@r=@sumrow
  30626. @catcode`@(=@active @let(=@sumlpar
  30627. @catcode`@)=@active @let)=@sumrpar
  30628. @catcode`@,=@active @let,=@sumcomma
  30629. @catcode`@!=@active @let!=@sumexcl
  30630. @end iftex
  30631. @format
  30632. @iftex
  30633. @advance@baselineskip-2.5pt
  30634. @let@c@sumbreak
  30635. @end iftex
  30636. @r{ @: C-x * a @: @: 33 @:calc-embedded-activate@:}
  30637. @r{ @: C-x * b @: @: @:calc-big-or-small@:}
  30638. @r{ @: C-x * c @: @: @:calc@:}
  30639. @r{ @: C-x * d @: @: @:calc-embedded-duplicate@:}
  30640. @r{ @: C-x * e @: @: 34 @:calc-embedded@:}
  30641. @r{ @: C-x * f @:formula @: @:calc-embedded-new-formula@:}
  30642. @r{ @: C-x * g @: @: 35 @:calc-grab-region@:}
  30643. @r{ @: C-x * i @: @: @:calc-info@:}
  30644. @r{ @: C-x * j @: @: @:calc-embedded-select@:}
  30645. @r{ @: C-x * k @: @: @:calc-keypad@:}
  30646. @r{ @: C-x * l @: @: @:calc-load-everything@:}
  30647. @r{ @: C-x * m @: @: @:read-kbd-macro@:}
  30648. @r{ @: C-x * n @: @: 4 @:calc-embedded-next@:}
  30649. @r{ @: C-x * o @: @: @:calc-other-window@:}
  30650. @r{ @: C-x * p @: @: 4 @:calc-embedded-previous@:}
  30651. @r{ @: C-x * q @:formula @: @:quick-calc@:}
  30652. @r{ @: C-x * r @: @: 36 @:calc-grab-rectangle@:}
  30653. @r{ @: C-x * s @: @: @:calc-info-summary@:}
  30654. @r{ @: C-x * t @: @: @:calc-tutorial@:}
  30655. @r{ @: C-x * u @: @: @:calc-embedded-update-formula@:}
  30656. @r{ @: C-x * w @: @: @:calc-embedded-word@:}
  30657. @r{ @: C-x * x @: @: @:calc-quit@:}
  30658. @r{ @: C-x * y @: @:1,28,49 @:calc-copy-to-buffer@:}
  30659. @r{ @: C-x * z @: @: @:calc-user-invocation@:}
  30660. @r{ @: C-x * : @: @: 36 @:calc-grab-sum-down@:}
  30661. @r{ @: C-x * _ @: @: 36 @:calc-grab-sum-across@:}
  30662. @r{ @: C-x * ` @:editing @: 30 @:calc-embedded-edit@:}
  30663. @r{ @: C-x * 0 @:(zero) @: @:calc-reset@:}
  30664. @c
  30665. @r{ @: 0-9 @:number @: @:@:number}
  30666. @r{ @: . @:number @: @:@:0.number}
  30667. @r{ @: _ @:number @: @:-@:number}
  30668. @r{ @: e @:number @: @:@:1e number}
  30669. @r{ @: # @:number @: @:@:current-radix@tfn{#}number}
  30670. @r{ @: P @:(in number) @: @:+/-@:}
  30671. @r{ @: M @:(in number) @: @:mod@:}
  30672. @r{ @: @@ ' " @: (in number)@: @:@:HMS form}
  30673. @r{ @: h m s @: (in number)@: @:@:HMS form}
  30674. @c
  30675. @r{ @: ' @:formula @: 37,46 @:@:formula}
  30676. @r{ @: $ @:formula @: 37,46 @:$@:formula}
  30677. @r{ @: " @:string @: 37,46 @:@:string}
  30678. @c
  30679. @r{ a b@: + @: @: 2 @:add@:(a,b) a+b}
  30680. @r{ a b@: - @: @: 2 @:sub@:(a,b) a@minus{}b}
  30681. @r{ a b@: * @: @: 2 @:mul@:(a,b) a b, a*b}
  30682. @r{ a b@: / @: @: 2 @:div@:(a,b) a/b}
  30683. @r{ a b@: ^ @: @: 2 @:pow@:(a,b) a^b}
  30684. @r{ a b@: I ^ @: @: 2 @:nroot@:(a,b) a^(1/b)}
  30685. @r{ a b@: % @: @: 2 @:mod@:(a,b) a%b}
  30686. @r{ a b@: \ @: @: 2 @:idiv@:(a,b) a\b}
  30687. @r{ a b@: : @: @: 2 @:fdiv@:(a,b)}
  30688. @r{ a b@: | @: @: 2 @:vconcat@:(a,b) a|b}
  30689. @r{ a b@: I | @: @: @:vconcat@:(b,a) b|a}
  30690. @r{ a b@: H | @: @: 2 @:append@:(a,b)}
  30691. @r{ a b@: I H | @: @: @:append@:(b,a)}
  30692. @r{ a@: & @: @: 1 @:inv@:(a) 1/a}
  30693. @r{ a@: ! @: @: 1 @:fact@:(a) a!}
  30694. @r{ a@: = @: @: 1 @:evalv@:(a)}
  30695. @r{ a@: M-% @: @: @:percent@:(a) a%}
  30696. @c
  30697. @r{ ... a@: @summarykey{RET} @: @: 1 @:@:... a a}
  30698. @r{ ... a@: @summarykey{SPC} @: @: 1 @:@:... a a}
  30699. @r{... a b@: @summarykey{TAB} @: @: 3 @:@:... b a}
  30700. @r{. a b c@: M-@summarykey{TAB} @: @: 3 @:@:... b c a}
  30701. @r{... a b@: @summarykey{LFD} @: @: 1 @:@:... a b a}
  30702. @r{ ... a@: @summarykey{DEL} @: @: 1 @:@:...}
  30703. @r{... a b@: M-@summarykey{DEL} @: @: 1 @:@:... b}
  30704. @r{ @: M-@summarykey{RET} @: @: 4 @:calc-last-args@:}
  30705. @r{ a@: ` @:editing @: 1,30 @:calc-edit@:}
  30706. @c
  30707. @r{ ... a@: C-d @: @: 1 @:@:...}
  30708. @r{ @: C-k @: @: 27 @:calc-kill@:}
  30709. @r{ @: C-w @: @: 27 @:calc-kill-region@:}
  30710. @r{ @: C-y @: @: @:calc-yank@:}
  30711. @r{ @: C-_ @: @: 4 @:calc-undo@:}
  30712. @r{ @: M-k @: @: 27 @:calc-copy-as-kill@:}
  30713. @r{ @: M-w @: @: 27 @:calc-copy-region-as-kill@:}
  30714. @c
  30715. @r{ @: [ @: @: @:@:[...}
  30716. @r{[.. a b@: ] @: @: @:@:[a,b]}
  30717. @r{ @: ( @: @: @:@:(...}
  30718. @r{(.. a b@: ) @: @: @:@:(a,b)}
  30719. @r{ @: , @: @: @:@:vector or rect complex}
  30720. @r{ @: ; @: @: @:@:matrix or polar complex}
  30721. @r{ @: .. @: @: @:@:interval}
  30722. @c
  30723. @r{ @: ~ @: @: @:calc-num-prefix@:}
  30724. @r{ @: < @: @: 4 @:calc-scroll-left@:}
  30725. @r{ @: > @: @: 4 @:calc-scroll-right@:}
  30726. @r{ @: @{ @: @: 4 @:calc-scroll-down@:}
  30727. @r{ @: @} @: @: 4 @:calc-scroll-up@:}
  30728. @r{ @: ? @: @: @:calc-help@:}
  30729. @c
  30730. @r{ a@: n @: @: 1 @:neg@:(a) @minus{}a}
  30731. @r{ @: o @: @: 4 @:calc-realign@:}
  30732. @r{ @: p @:precision @: 31 @:calc-precision@:}
  30733. @r{ @: q @: @: @:calc-quit@:}
  30734. @r{ @: w @: @: @:calc-why@:}
  30735. @r{ @: x @:command @: @:M-x calc-@:command}
  30736. @r{ a@: y @: @:1,28,49 @:calc-copy-to-buffer@:}
  30737. @c
  30738. @r{ a@: A @: @: 1 @:abs@:(a)}
  30739. @r{ a b@: B @: @: 2 @:log@:(a,b)}
  30740. @r{ a b@: I B @: @: 2 @:alog@:(a,b) b^a}
  30741. @r{ a@: C @: @: 1 @:cos@:(a)}
  30742. @r{ a@: I C @: @: 1 @:arccos@:(a)}
  30743. @r{ a@: H C @: @: 1 @:cosh@:(a)}
  30744. @r{ a@: I H C @: @: 1 @:arccosh@:(a)}
  30745. @r{ @: D @: @: 4 @:calc-redo@:}
  30746. @r{ a@: E @: @: 1 @:exp@:(a)}
  30747. @r{ a@: H E @: @: 1 @:exp10@:(a) 10.^a}
  30748. @r{ a@: F @: @: 1,11 @:floor@:(a,d)}
  30749. @r{ a@: I F @: @: 1,11 @:ceil@:(a,d)}
  30750. @r{ a@: H F @: @: 1,11 @:ffloor@:(a,d)}
  30751. @r{ a@: I H F @: @: 1,11 @:fceil@:(a,d)}
  30752. @r{ a@: G @: @: 1 @:arg@:(a)}
  30753. @r{ @: H @:command @: 32 @:@:Hyperbolic}
  30754. @r{ @: I @:command @: 32 @:@:Inverse}
  30755. @r{ a@: J @: @: 1 @:conj@:(a)}
  30756. @r{ @: K @:command @: 32 @:@:Keep-args}
  30757. @r{ a@: L @: @: 1 @:ln@:(a)}
  30758. @r{ a@: H L @: @: 1 @:log10@:(a)}
  30759. @r{ @: M @: @: @:calc-more-recursion-depth@:}
  30760. @r{ @: I M @: @: @:calc-less-recursion-depth@:}
  30761. @r{ a@: N @: @: 5 @:evalvn@:(a)}
  30762. @r{ @: O @:command @: 32 @:@:Option}
  30763. @r{ @: P @: @: @:@:pi}
  30764. @r{ @: I P @: @: @:@:gamma}
  30765. @r{ @: H P @: @: @:@:e}
  30766. @r{ @: I H P @: @: @:@:phi}
  30767. @r{ a@: Q @: @: 1 @:sqrt@:(a)}
  30768. @r{ a@: I Q @: @: 1 @:sqr@:(a) a^2}
  30769. @r{ a@: R @: @: 1,11 @:round@:(a,d)}
  30770. @r{ a@: I R @: @: 1,11 @:trunc@:(a,d)}
  30771. @r{ a@: H R @: @: 1,11 @:fround@:(a,d)}
  30772. @r{ a@: I H R @: @: 1,11 @:ftrunc@:(a,d)}
  30773. @r{ a@: S @: @: 1 @:sin@:(a)}
  30774. @r{ a@: I S @: @: 1 @:arcsin@:(a)}
  30775. @r{ a@: H S @: @: 1 @:sinh@:(a)}
  30776. @r{ a@: I H S @: @: 1 @:arcsinh@:(a)}
  30777. @r{ a@: T @: @: 1 @:tan@:(a)}
  30778. @r{ a@: I T @: @: 1 @:arctan@:(a)}
  30779. @r{ a@: H T @: @: 1 @:tanh@:(a)}
  30780. @r{ a@: I H T @: @: 1 @:arctanh@:(a)}
  30781. @r{ @: U @: @: 4 @:calc-undo@:}
  30782. @r{ @: X @: @: 4 @:calc-call-last-kbd-macro@:}
  30783. @c
  30784. @r{ a b@: a = @: @: 2 @:eq@:(a,b) a=b}
  30785. @r{ a b@: a # @: @: 2 @:neq@:(a,b) a!=b}
  30786. @r{ a b@: a < @: @: 2 @:lt@:(a,b) a<b}
  30787. @r{ a b@: a > @: @: 2 @:gt@:(a,b) a>b}
  30788. @r{ a b@: a [ @: @: 2 @:leq@:(a,b) a<=b}
  30789. @r{ a b@: a ] @: @: 2 @:geq@:(a,b) a>=b}
  30790. @r{ a b@: a @{ @: @: 2 @:in@:(a,b)}
  30791. @r{ a b@: a & @: @: 2,45 @:land@:(a,b) a&&b}
  30792. @r{ a b@: a | @: @: 2,45 @:lor@:(a,b) a||b}
  30793. @r{ a@: a ! @: @: 1,45 @:lnot@:(a) !a}
  30794. @r{ a b c@: a : @: @: 45 @:if@:(a,b,c) a?b:c}
  30795. @r{ a@: a . @: @: 1 @:rmeq@:(a)}
  30796. @r{ a@: a " @: @: 7,8 @:calc-expand-formula@:}
  30797. @c
  30798. @r{ a@: a + @:i, l, h @: 6,38 @:sum@:(a,i,l,h)}
  30799. @r{ a@: a - @:i, l, h @: 6,38 @:asum@:(a,i,l,h)}
  30800. @r{ a@: a * @:i, l, h @: 6,38 @:prod@:(a,i,l,h)}
  30801. @r{ a b@: a _ @: @: 2 @:subscr@:(a,b) a_b}
  30802. @c
  30803. @r{ a b@: a \ @: @: 2 @:pdiv@:(a,b)}
  30804. @r{ a b@: a % @: @: 2 @:prem@:(a,b)}
  30805. @r{ a b@: a / @: @: 2 @:pdivrem@:(a,b) [q,r]}
  30806. @r{ a b@: H a / @: @: 2 @:pdivide@:(a,b) q+r/b}
  30807. @c
  30808. @r{ a@: a a @: @: 1 @:apart@:(a)}
  30809. @r{ a@: a b @:old, new @: 38 @:subst@:(a,old,new)}
  30810. @r{ a@: a c @:v @: 38 @:collect@:(a,v)}
  30811. @r{ a@: a d @:v @: 4,38 @:deriv@:(a,v)}
  30812. @r{ a@: H a d @:v @: 4,38 @:tderiv@:(a,v)}
  30813. @r{ a@: a e @: @: @:esimplify@:(a)}
  30814. @r{ a@: a f @: @: 1 @:factor@:(a)}
  30815. @r{ a@: H a f @: @: 1 @:factors@:(a)}
  30816. @r{ a b@: a g @: @: 2 @:pgcd@:(a,b)}
  30817. @r{ a@: a i @:v @: 38 @:integ@:(a,v)}
  30818. @r{ a@: a m @:pats @: 38 @:match@:(a,pats)}
  30819. @r{ a@: I a m @:pats @: 38 @:matchnot@:(a,pats)}
  30820. @r{ data x@: a p @: @: 28 @:polint@:(data,x)}
  30821. @r{ data x@: H a p @: @: 28 @:ratint@:(data,x)}
  30822. @r{ a@: a n @: @: 1 @:nrat@:(a)}
  30823. @r{ a@: a r @:rules @:4,8,38 @:rewrite@:(a,rules,n)}
  30824. @r{ a@: a s @: @: @:simplify@:(a)}
  30825. @r{ a@: a t @:v, n @: 31,39 @:taylor@:(a,v,n)}
  30826. @r{ a@: a v @: @: 7,8 @:calc-alg-evaluate@:}
  30827. @r{ a@: a x @: @: 4,8 @:expand@:(a)}
  30828. @c
  30829. @r{ data@: a F @:model, vars @: 48 @:fit@:(m,iv,pv,data)}
  30830. @r{ data@: I a F @:model, vars @: 48 @:xfit@:(m,iv,pv,data)}
  30831. @r{ data@: H a F @:model, vars @: 48 @:efit@:(m,iv,pv,data)}
  30832. @r{ a@: a I @:v, l, h @: 38 @:ninteg@:(a,v,l,h)}
  30833. @r{ a b@: a M @:op @: 22 @:mapeq@:(op,a,b)}
  30834. @r{ a b@: I a M @:op @: 22 @:mapeqr@:(op,a,b)}
  30835. @r{ a b@: H a M @:op @: 22 @:mapeqp@:(op,a,b)}
  30836. @r{ a g@: a N @:v @: 38 @:minimize@:(a,v,g)}
  30837. @r{ a g@: H a N @:v @: 38 @:wminimize@:(a,v,g)}
  30838. @r{ a@: a P @:v @: 38 @:roots@:(a,v)}
  30839. @r{ a g@: a R @:v @: 38 @:root@:(a,v,g)}
  30840. @r{ a g@: H a R @:v @: 38 @:wroot@:(a,v,g)}
  30841. @r{ a@: a S @:v @: 38 @:solve@:(a,v)}
  30842. @r{ a@: I a S @:v @: 38 @:finv@:(a,v)}
  30843. @r{ a@: H a S @:v @: 38 @:fsolve@:(a,v)}
  30844. @r{ a@: I H a S @:v @: 38 @:ffinv@:(a,v)}
  30845. @r{ a@: a T @:i, l, h @: 6,38 @:table@:(a,i,l,h)}
  30846. @r{ a g@: a X @:v @: 38 @:maximize@:(a,v,g)}
  30847. @r{ a g@: H a X @:v @: 38 @:wmaximize@:(a,v,g)}
  30848. @c
  30849. @r{ a b@: b a @: @: 9 @:and@:(a,b,w)}
  30850. @r{ a@: b c @: @: 9 @:clip@:(a,w)}
  30851. @r{ a b@: b d @: @: 9 @:diff@:(a,b,w)}
  30852. @r{ a@: b l @: @: 10 @:lsh@:(a,n,w)}
  30853. @r{ a n@: H b l @: @: 9 @:lsh@:(a,n,w)}
  30854. @r{ a@: b n @: @: 9 @:not@:(a,w)}
  30855. @r{ a b@: b o @: @: 9 @:or@:(a,b,w)}
  30856. @r{ v@: b p @: @: 1 @:vpack@:(v)}
  30857. @r{ a@: b r @: @: 10 @:rsh@:(a,n,w)}
  30858. @r{ a n@: H b r @: @: 9 @:rsh@:(a,n,w)}
  30859. @r{ a@: b t @: @: 10 @:rot@:(a,n,w)}
  30860. @r{ a n@: H b t @: @: 9 @:rot@:(a,n,w)}
  30861. @r{ a@: b u @: @: 1 @:vunpack@:(a)}
  30862. @r{ @: b w @:w @: 9,50 @:calc-word-size@:}
  30863. @r{ a b@: b x @: @: 9 @:xor@:(a,b,w)}
  30864. @c
  30865. @r{c s l p@: b D @: @: @:ddb@:(c,s,l,p)}
  30866. @r{ r n p@: b F @: @: @:fv@:(r,n,p)}
  30867. @r{ r n p@: I b F @: @: @:fvb@:(r,n,p)}
  30868. @r{ r n p@: H b F @: @: @:fvl@:(r,n,p)}
  30869. @r{ v@: b I @: @: 19 @:irr@:(v)}
  30870. @r{ v@: I b I @: @: 19 @:irrb@:(v)}
  30871. @r{ a@: b L @: @: 10 @:ash@:(a,n,w)}
  30872. @r{ a n@: H b L @: @: 9 @:ash@:(a,n,w)}
  30873. @r{ r n a@: b M @: @: @:pmt@:(r,n,a)}
  30874. @r{ r n a@: I b M @: @: @:pmtb@:(r,n,a)}
  30875. @r{ r n a@: H b M @: @: @:pmtl@:(r,n,a)}
  30876. @r{ r v@: b N @: @: 19 @:npv@:(r,v)}
  30877. @r{ r v@: I b N @: @: 19 @:npvb@:(r,v)}
  30878. @r{ r n p@: b P @: @: @:pv@:(r,n,p)}
  30879. @r{ r n p@: I b P @: @: @:pvb@:(r,n,p)}
  30880. @r{ r n p@: H b P @: @: @:pvl@:(r,n,p)}
  30881. @r{ a@: b R @: @: 10 @:rash@:(a,n,w)}
  30882. @r{ a n@: H b R @: @: 9 @:rash@:(a,n,w)}
  30883. @r{ c s l@: b S @: @: @:sln@:(c,s,l)}
  30884. @r{ n p a@: b T @: @: @:rate@:(n,p,a)}
  30885. @r{ n p a@: I b T @: @: @:rateb@:(n,p,a)}
  30886. @r{ n p a@: H b T @: @: @:ratel@:(n,p,a)}
  30887. @r{c s l p@: b Y @: @: @:syd@:(c,s,l,p)}
  30888. @r{ r p a@: b # @: @: @:nper@:(r,p,a)}
  30889. @r{ r p a@: I b # @: @: @:nperb@:(r,p,a)}
  30890. @r{ r p a@: H b # @: @: @:nperl@:(r,p,a)}
  30891. @r{ a b@: b % @: @: @:relch@:(a,b)}
  30892. @c
  30893. @r{ a@: c c @: @: 5 @:pclean@:(a,p)}
  30894. @r{ a@: c 0-9 @: @: @:pclean@:(a,p)}
  30895. @r{ a@: H c c @: @: 5 @:clean@:(a,p)}
  30896. @r{ a@: H c 0-9 @: @: @:clean@:(a,p)}
  30897. @r{ a@: c d @: @: 1 @:deg@:(a)}
  30898. @r{ a@: c f @: @: 1 @:pfloat@:(a)}
  30899. @r{ a@: H c f @: @: 1 @:float@:(a)}
  30900. @r{ a@: c h @: @: 1 @:hms@:(a)}
  30901. @r{ a@: c p @: @: @:polar@:(a)}
  30902. @r{ a@: I c p @: @: @:rect@:(a)}
  30903. @r{ a@: c r @: @: 1 @:rad@:(a)}
  30904. @c
  30905. @r{ a@: c F @: @: 5 @:pfrac@:(a,p)}
  30906. @r{ a@: H c F @: @: 5 @:frac@:(a,p)}
  30907. @c
  30908. @r{ a@: c % @: @: @:percent@:(a*100)}
  30909. @c
  30910. @r{ @: d . @:char @: 50 @:calc-point-char@:}
  30911. @r{ @: d , @:char @: 50 @:calc-group-char@:}
  30912. @r{ @: d < @: @: 13,50 @:calc-left-justify@:}
  30913. @r{ @: d = @: @: 13,50 @:calc-center-justify@:}
  30914. @r{ @: d > @: @: 13,50 @:calc-right-justify@:}
  30915. @r{ @: d @{ @:label @: 50 @:calc-left-label@:}
  30916. @r{ @: d @} @:label @: 50 @:calc-right-label@:}
  30917. @r{ @: d [ @: @: 4 @:calc-truncate-up@:}
  30918. @r{ @: d ] @: @: 4 @:calc-truncate-down@:}
  30919. @r{ @: d " @: @: 12,50 @:calc-display-strings@:}
  30920. @r{ @: d @summarykey{SPC} @: @: @:calc-refresh@:}
  30921. @r{ @: d @summarykey{RET} @: @: 1 @:calc-refresh-top@:}
  30922. @c
  30923. @r{ @: d 0 @: @: 50 @:calc-decimal-radix@:}
  30924. @r{ @: d 2 @: @: 50 @:calc-binary-radix@:}
  30925. @r{ @: d 6 @: @: 50 @:calc-hex-radix@:}
  30926. @r{ @: d 8 @: @: 50 @:calc-octal-radix@:}
  30927. @c
  30928. @r{ @: d b @: @:12,13,50 @:calc-line-breaking@:}
  30929. @r{ @: d c @: @: 50 @:calc-complex-notation@:}
  30930. @r{ @: d d @:format @: 50 @:calc-date-notation@:}
  30931. @r{ @: d e @: @: 5,50 @:calc-eng-notation@:}
  30932. @r{ @: d f @:num @: 31,50 @:calc-fix-notation@:}
  30933. @r{ @: d g @: @:12,13,50 @:calc-group-digits@:}
  30934. @r{ @: d h @:format @: 50 @:calc-hms-notation@:}
  30935. @r{ @: d i @: @: 50 @:calc-i-notation@:}
  30936. @r{ @: d j @: @: 50 @:calc-j-notation@:}
  30937. @r{ @: d l @: @: 12,50 @:calc-line-numbering@:}
  30938. @r{ @: d n @: @: 5,50 @:calc-normal-notation@:}
  30939. @r{ @: d o @:format @: 50 @:calc-over-notation@:}
  30940. @r{ @: d p @: @: 12,50 @:calc-show-plain@:}
  30941. @r{ @: d r @:radix @: 31,50 @:calc-radix@:}
  30942. @r{ @: d s @: @: 5,50 @:calc-sci-notation@:}
  30943. @r{ @: d t @: @: 27 @:calc-truncate-stack@:}
  30944. @r{ @: d w @: @: 12,13 @:calc-auto-why@:}
  30945. @r{ @: d z @: @: 12,50 @:calc-leading-zeros@:}
  30946. @c
  30947. @r{ @: d B @: @: 50 @:calc-big-language@:}
  30948. @r{ @: d C @: @: 50 @:calc-c-language@:}
  30949. @r{ @: d E @: @: 50 @:calc-eqn-language@:}
  30950. @r{ @: d F @: @: 50 @:calc-fortran-language@:}
  30951. @r{ @: d M @: @: 50 @:calc-mathematica-language@:}
  30952. @r{ @: d N @: @: 50 @:calc-normal-language@:}
  30953. @r{ @: d O @: @: 50 @:calc-flat-language@:}
  30954. @r{ @: d P @: @: 50 @:calc-pascal-language@:}
  30955. @r{ @: d T @: @: 50 @:calc-tex-language@:}
  30956. @r{ @: d L @: @: 50 @:calc-latex-language@:}
  30957. @r{ @: d U @: @: 50 @:calc-unformatted-language@:}
  30958. @r{ @: d W @: @: 50 @:calc-maple-language@:}
  30959. @c
  30960. @r{ a@: f [ @: @: 4 @:decr@:(a,n)}
  30961. @r{ a@: f ] @: @: 4 @:incr@:(a,n)}
  30962. @c
  30963. @r{ a b@: f b @: @: 2 @:beta@:(a,b)}
  30964. @r{ a@: f e @: @: 1 @:erf@:(a)}
  30965. @r{ a@: I f e @: @: 1 @:erfc@:(a)}
  30966. @r{ a@: f g @: @: 1 @:gamma@:(a)}
  30967. @r{ a b@: f h @: @: 2 @:hypot@:(a,b)}
  30968. @r{ a@: f i @: @: 1 @:im@:(a)}
  30969. @r{ n a@: f j @: @: 2 @:besJ@:(n,a)}
  30970. @r{ a b@: f n @: @: 2 @:min@:(a,b)}
  30971. @r{ a@: f r @: @: 1 @:re@:(a)}
  30972. @r{ a@: f s @: @: 1 @:sign@:(a)}
  30973. @r{ a b@: f x @: @: 2 @:max@:(a,b)}
  30974. @r{ n a@: f y @: @: 2 @:besY@:(n,a)}
  30975. @c
  30976. @r{ a@: f A @: @: 1 @:abssqr@:(a)}
  30977. @r{ x a b@: f B @: @: @:betaI@:(x,a,b)}
  30978. @r{ x a b@: H f B @: @: @:betaB@:(x,a,b)}
  30979. @r{ a@: f E @: @: 1 @:expm1@:(a)}
  30980. @r{ a x@: f G @: @: 2 @:gammaP@:(a,x)}
  30981. @r{ a x@: I f G @: @: 2 @:gammaQ@:(a,x)}
  30982. @r{ a x@: H f G @: @: 2 @:gammag@:(a,x)}
  30983. @r{ a x@: I H f G @: @: 2 @:gammaG@:(a,x)}
  30984. @r{ a b@: f I @: @: 2 @:ilog@:(a,b)}
  30985. @r{ a b@: I f I @: @: 2 @:alog@:(a,b) b^a}
  30986. @r{ a@: f L @: @: 1 @:lnp1@:(a)}
  30987. @r{ a@: f M @: @: 1 @:mant@:(a)}
  30988. @r{ a@: f Q @: @: 1 @:isqrt@:(a)}
  30989. @r{ a@: I f Q @: @: 1 @:sqr@:(a) a^2}
  30990. @r{ a n@: f S @: @: 2 @:scf@:(a,n)}
  30991. @r{ y x@: f T @: @: @:arctan2@:(y,x)}
  30992. @r{ a@: f X @: @: 1 @:xpon@:(a)}
  30993. @c
  30994. @r{ x y@: g a @: @: 28,40 @:calc-graph-add@:}
  30995. @r{ @: g b @: @: 12 @:calc-graph-border@:}
  30996. @r{ @: g c @: @: @:calc-graph-clear@:}
  30997. @r{ @: g d @: @: 41 @:calc-graph-delete@:}
  30998. @r{ x y@: g f @: @: 28,40 @:calc-graph-fast@:}
  30999. @r{ @: g g @: @: 12 @:calc-graph-grid@:}
  31000. @r{ @: g h @:title @: @:calc-graph-header@:}
  31001. @r{ @: g j @: @: 4 @:calc-graph-juggle@:}
  31002. @r{ @: g k @: @: 12 @:calc-graph-key@:}
  31003. @r{ @: g l @: @: 12 @:calc-graph-log-x@:}
  31004. @r{ @: g n @:name @: @:calc-graph-name@:}
  31005. @r{ @: g p @: @: 42 @:calc-graph-plot@:}
  31006. @r{ @: g q @: @: @:calc-graph-quit@:}
  31007. @r{ @: g r @:range @: @:calc-graph-range-x@:}
  31008. @r{ @: g s @: @: 12,13 @:calc-graph-line-style@:}
  31009. @r{ @: g t @:title @: @:calc-graph-title-x@:}
  31010. @r{ @: g v @: @: @:calc-graph-view-commands@:}
  31011. @r{ @: g x @:display @: @:calc-graph-display@:}
  31012. @r{ @: g z @: @: 12 @:calc-graph-zero-x@:}
  31013. @c
  31014. @r{ x y z@: g A @: @: 28,40 @:calc-graph-add-3d@:}
  31015. @r{ @: g C @:command @: @:calc-graph-command@:}
  31016. @r{ @: g D @:device @: 43,44 @:calc-graph-device@:}
  31017. @r{ x y z@: g F @: @: 28,40 @:calc-graph-fast-3d@:}
  31018. @r{ @: g H @: @: 12 @:calc-graph-hide@:}
  31019. @r{ @: g K @: @: @:calc-graph-kill@:}
  31020. @r{ @: g L @: @: 12 @:calc-graph-log-y@:}
  31021. @r{ @: g N @:number @: 43,51 @:calc-graph-num-points@:}
  31022. @r{ @: g O @:filename @: 43,44 @:calc-graph-output@:}
  31023. @r{ @: g P @: @: 42 @:calc-graph-print@:}
  31024. @r{ @: g R @:range @: @:calc-graph-range-y@:}
  31025. @r{ @: g S @: @: 12,13 @:calc-graph-point-style@:}
  31026. @r{ @: g T @:title @: @:calc-graph-title-y@:}
  31027. @r{ @: g V @: @: @:calc-graph-view-trail@:}
  31028. @r{ @: g X @:format @: @:calc-graph-geometry@:}
  31029. @r{ @: g Z @: @: 12 @:calc-graph-zero-y@:}
  31030. @c
  31031. @r{ @: g C-l @: @: 12 @:calc-graph-log-z@:}
  31032. @r{ @: g C-r @:range @: @:calc-graph-range-z@:}
  31033. @r{ @: g C-t @:title @: @:calc-graph-title-z@:}
  31034. @c
  31035. @r{ @: h b @: @: @:calc-describe-bindings@:}
  31036. @r{ @: h c @:key @: @:calc-describe-key-briefly@:}
  31037. @r{ @: h f @:function @: @:calc-describe-function@:}
  31038. @r{ @: h h @: @: @:calc-full-help@:}
  31039. @r{ @: h i @: @: @:calc-info@:}
  31040. @r{ @: h k @:key @: @:calc-describe-key@:}
  31041. @r{ @: h n @: @: @:calc-view-news@:}
  31042. @r{ @: h s @: @: @:calc-info-summary@:}
  31043. @r{ @: h t @: @: @:calc-tutorial@:}
  31044. @r{ @: h v @:var @: @:calc-describe-variable@:}
  31045. @c
  31046. @r{ @: j 1-9 @: @: @:calc-select-part@:}
  31047. @r{ @: j @summarykey{RET} @: @: 27 @:calc-copy-selection@:}
  31048. @r{ @: j @summarykey{DEL} @: @: 27 @:calc-del-selection@:}
  31049. @r{ @: j ' @:formula @: 27 @:calc-enter-selection@:}
  31050. @r{ @: j ` @:editing @: 27,30 @:calc-edit-selection@:}
  31051. @r{ @: j " @: @: 7,27 @:calc-sel-expand-formula@:}
  31052. @c
  31053. @r{ @: j + @:formula @: 27 @:calc-sel-add-both-sides@:}
  31054. @r{ @: j - @:formula @: 27 @:calc-sel-sub-both-sides@:}
  31055. @r{ @: j * @:formula @: 27 @:calc-sel-mul-both-sides@:}
  31056. @r{ @: j / @:formula @: 27 @:calc-sel-div-both-sides@:}
  31057. @r{ @: j & @: @: 27 @:calc-sel-invert@:}
  31058. @c
  31059. @r{ @: j a @: @: 27 @:calc-select-additional@:}
  31060. @r{ @: j b @: @: 12 @:calc-break-selections@:}
  31061. @r{ @: j c @: @: @:calc-clear-selections@:}
  31062. @r{ @: j d @: @: 12,50 @:calc-show-selections@:}
  31063. @r{ @: j e @: @: 12 @:calc-enable-selections@:}
  31064. @r{ @: j l @: @: 4,27 @:calc-select-less@:}
  31065. @r{ @: j m @: @: 4,27 @:calc-select-more@:}
  31066. @r{ @: j n @: @: 4 @:calc-select-next@:}
  31067. @r{ @: j o @: @: 4,27 @:calc-select-once@:}
  31068. @r{ @: j p @: @: 4 @:calc-select-previous@:}
  31069. @r{ @: j r @:rules @:4,8,27 @:calc-rewrite-selection@:}
  31070. @r{ @: j s @: @: 4,27 @:calc-select-here@:}
  31071. @r{ @: j u @: @: 27 @:calc-unselect@:}
  31072. @r{ @: j v @: @: 7,27 @:calc-sel-evaluate@:}
  31073. @c
  31074. @r{ @: j C @: @: 27 @:calc-sel-commute@:}
  31075. @r{ @: j D @: @: 4,27 @:calc-sel-distribute@:}
  31076. @r{ @: j E @: @: 27 @:calc-sel-jump-equals@:}
  31077. @r{ @: j I @: @: 27 @:calc-sel-isolate@:}
  31078. @r{ @: H j I @: @: 27 @:calc-sel-isolate@: (full)}
  31079. @r{ @: j L @: @: 4,27 @:calc-commute-left@:}
  31080. @r{ @: j M @: @: 27 @:calc-sel-merge@:}
  31081. @r{ @: j N @: @: 27 @:calc-sel-negate@:}
  31082. @r{ @: j O @: @: 4,27 @:calc-select-once-maybe@:}
  31083. @r{ @: j R @: @: 4,27 @:calc-commute-right@:}
  31084. @r{ @: j S @: @: 4,27 @:calc-select-here-maybe@:}
  31085. @r{ @: j U @: @: 27 @:calc-sel-unpack@:}
  31086. @c
  31087. @r{ @: k a @: @: @:calc-random-again@:}
  31088. @r{ n@: k b @: @: 1 @:bern@:(n)}
  31089. @r{ n x@: H k b @: @: 2 @:bern@:(n,x)}
  31090. @r{ n m@: k c @: @: 2 @:choose@:(n,m)}
  31091. @r{ n m@: H k c @: @: 2 @:perm@:(n,m)}
  31092. @r{ n@: k d @: @: 1 @:dfact@:(n) n!!}
  31093. @r{ n@: k e @: @: 1 @:euler@:(n)}
  31094. @r{ n x@: H k e @: @: 2 @:euler@:(n,x)}
  31095. @r{ n@: k f @: @: 4 @:prfac@:(n)}
  31096. @r{ n m@: k g @: @: 2 @:gcd@:(n,m)}
  31097. @r{ m n@: k h @: @: 14 @:shuffle@:(n,m)}
  31098. @r{ n m@: k l @: @: 2 @:lcm@:(n,m)}
  31099. @r{ n@: k m @: @: 1 @:moebius@:(n)}
  31100. @r{ n@: k n @: @: 4 @:nextprime@:(n)}
  31101. @r{ n@: I k n @: @: 4 @:prevprime@:(n)}
  31102. @r{ n@: k p @: @: 4,28 @:calc-prime-test@:}
  31103. @r{ m@: k r @: @: 14 @:random@:(m)}
  31104. @r{ n m@: k s @: @: 2 @:stir1@:(n,m)}
  31105. @r{ n m@: H k s @: @: 2 @:stir2@:(n,m)}
  31106. @r{ n@: k t @: @: 1 @:totient@:(n)}
  31107. @c
  31108. @r{ n p x@: k B @: @: @:utpb@:(x,n,p)}
  31109. @r{ n p x@: I k B @: @: @:ltpb@:(x,n,p)}
  31110. @r{ v x@: k C @: @: @:utpc@:(x,v)}
  31111. @r{ v x@: I k C @: @: @:ltpc@:(x,v)}
  31112. @r{ n m@: k E @: @: @:egcd@:(n,m)}
  31113. @r{v1 v2 x@: k F @: @: @:utpf@:(x,v1,v2)}
  31114. @r{v1 v2 x@: I k F @: @: @:ltpf@:(x,v1,v2)}
  31115. @r{ m s x@: k N @: @: @:utpn@:(x,m,s)}
  31116. @r{ m s x@: I k N @: @: @:ltpn@:(x,m,s)}
  31117. @r{ m x@: k P @: @: @:utpp@:(x,m)}
  31118. @r{ m x@: I k P @: @: @:ltpp@:(x,m)}
  31119. @r{ v x@: k T @: @: @:utpt@:(x,v)}
  31120. @r{ v x@: I k T @: @: @:ltpt@:(x,v)}
  31121. @c
  31122. @r{ a b@: l + @: @: @:lupadd@:(a,b)}
  31123. @r{ a b@: H l + @: @: @:lufadd@:(a,b)}
  31124. @r{ a b@: l - @: @: @:lupsub@:(a,b)}
  31125. @r{ a b@: H l - @: @: @:lufsub@:(a,b)}
  31126. @r{ a b@: l * @: @: @:lupmul@:(a,b)}
  31127. @r{ a b@: H l * @: @: @:lufmul@:(a,b)}
  31128. @r{ a b@: l / @: @: @:lupdiv@:(a,b)}
  31129. @r{ a b@: H l / @: @: @:lufdiv@:(a,b)}
  31130. @r{ a@: l d @: @: @:dbpower@:(a)}
  31131. @r{ a b@: O l d @: @: @:dbpower@:(a,b)}
  31132. @r{ a@: H l d @: @: @:dbfield@:(a)}
  31133. @r{ a b@: O H l d @: @: @:dbfield@:(a,b)}
  31134. @r{ a@: l n @: @: @:nppower@:(a)}
  31135. @r{ a b@: O l n @: @: @:nppower@:(a,b)}
  31136. @r{ a@: H l n @: @: @:npfield@:(a)}
  31137. @r{ a b@: O H l n @: @: @:npfield@:(a,b)}
  31138. @r{ a@: l q @: @: @:lupquant@:(a)}
  31139. @r{ a b@: O l q @: @: @:lupquant@:(a,b)}
  31140. @r{ a@: H l q @: @: @:lufquant@:(a)}
  31141. @r{ a b@: O H l q @: @: @:lufquant@:(a,b)}
  31142. @r{ a@: l s @: @: @:spn@:(a)}
  31143. @r{ a@: l m @: @: @:midi@:(a)}
  31144. @r{ a@: l f @: @: @:freq@:(a)}
  31145. @c
  31146. @r{ @: m a @: @: 12,13 @:calc-algebraic-mode@:}
  31147. @r{ @: m d @: @: @:calc-degrees-mode@:}
  31148. @r{ @: m e @: @: @:calc-embedded-preserve-modes@:}
  31149. @r{ @: m f @: @: 12 @:calc-frac-mode@:}
  31150. @r{ @: m g @: @: 52 @:calc-get-modes@:}
  31151. @r{ @: m h @: @: @:calc-hms-mode@:}
  31152. @r{ @: m i @: @: 12,13 @:calc-infinite-mode@:}
  31153. @r{ @: m m @: @: @:calc-save-modes@:}
  31154. @r{ @: m p @: @: 12 @:calc-polar-mode@:}
  31155. @r{ @: m r @: @: @:calc-radians-mode@:}
  31156. @r{ @: m s @: @: 12 @:calc-symbolic-mode@:}
  31157. @r{ @: m t @: @: 12 @:calc-total-algebraic-mode@:}
  31158. @r{ @: m v @: @: 12,13 @:calc-matrix-mode@:}
  31159. @r{ @: m w @: @: 13 @:calc-working@:}
  31160. @r{ @: m x @: @: @:calc-always-load-extensions@:}
  31161. @c
  31162. @r{ @: m A @: @: 12 @:calc-alg-simplify-mode@:}
  31163. @r{ @: m B @: @: 12 @:calc-bin-simplify-mode@:}
  31164. @r{ @: m C @: @: 12 @:calc-auto-recompute@:}
  31165. @r{ @: m D @: @: @:calc-default-simplify-mode@:}
  31166. @r{ @: m E @: @: 12 @:calc-ext-simplify-mode@:}
  31167. @r{ @: m F @:filename @: 13 @:calc-settings-file-name@:}
  31168. @r{ @: m N @: @: 12 @:calc-num-simplify-mode@:}
  31169. @r{ @: m O @: @: 12 @:calc-no-simplify-mode@:}
  31170. @r{ @: m R @: @: 12,13 @:calc-mode-record-mode@:}
  31171. @r{ @: m S @: @: 12 @:calc-shift-prefix@:}
  31172. @r{ @: m U @: @: 12 @:calc-units-simplify-mode@:}
  31173. @c
  31174. @r{ @: r s @:register @: 27 @:calc-copy-to-register@:}
  31175. @r{ @: r i @:register @: @:calc-insert-register@:}
  31176. @c
  31177. @r{ @: s c @:var1, var2 @: 29 @:calc-copy-variable@:}
  31178. @r{ @: s d @:var, decl @: @:calc-declare-variable@:}
  31179. @r{ @: s e @:var, editing @: 29,30 @:calc-edit-variable@:}
  31180. @r{ @: s i @:buffer @: @:calc-insert-variables@:}
  31181. @r{ @: s k @:const, var @: 29 @:calc-copy-special-constant@:}
  31182. @r{ a b@: s l @:var @: 29 @:@:a (letting var=b)}
  31183. @r{ a ...@: s m @:op, var @: 22,29 @:calc-store-map@:}
  31184. @r{ @: s n @:var @: 29,47 @:calc-store-neg@: (v/-1)}
  31185. @r{ @: s p @:var @: 29 @:calc-permanent-variable@:}
  31186. @r{ @: s r @:var @: 29 @:@:v (recalled value)}
  31187. @r{ @: r 0-9 @: @: @:calc-recall-quick@:}
  31188. @r{ a@: s s @:var @: 28,29 @:calc-store@:}
  31189. @r{ a@: s 0-9 @: @: @:calc-store-quick@:}
  31190. @r{ a@: s t @:var @: 29 @:calc-store-into@:}
  31191. @r{ a@: t 0-9 @: @: @:calc-store-into-quick@:}
  31192. @r{ @: s u @:var @: 29 @:calc-unstore@:}
  31193. @r{ a@: s x @:var @: 29 @:calc-store-exchange@:}
  31194. @c
  31195. @r{ @: s A @:editing @: 30 @:calc-edit-AlgSimpRules@:}
  31196. @r{ @: s D @:editing @: 30 @:calc-edit-Decls@:}
  31197. @r{ @: s E @:editing @: 30 @:calc-edit-EvalRules@:}
  31198. @r{ @: s F @:editing @: 30 @:calc-edit-FitRules@:}
  31199. @r{ @: s G @:editing @: 30 @:calc-edit-GenCount@:}
  31200. @r{ @: s H @:editing @: 30 @:calc-edit-Holidays@:}
  31201. @r{ @: s I @:editing @: 30 @:calc-edit-IntegLimit@:}
  31202. @r{ @: s L @:editing @: 30 @:calc-edit-LineStyles@:}
  31203. @r{ @: s P @:editing @: 30 @:calc-edit-PointStyles@:}
  31204. @r{ @: s R @:editing @: 30 @:calc-edit-PlotRejects@:}
  31205. @r{ @: s T @:editing @: 30 @:calc-edit-TimeZone@:}
  31206. @r{ @: s U @:editing @: 30 @:calc-edit-Units@:}
  31207. @r{ @: s X @:editing @: 30 @:calc-edit-ExtSimpRules@:}
  31208. @c
  31209. @r{ a@: s + @:var @: 29,47 @:calc-store-plus@: (v+a)}
  31210. @r{ a@: s - @:var @: 29,47 @:calc-store-minus@: (v-a)}
  31211. @r{ a@: s * @:var @: 29,47 @:calc-store-times@: (v*a)}
  31212. @r{ a@: s / @:var @: 29,47 @:calc-store-div@: (v/a)}
  31213. @r{ a@: s ^ @:var @: 29,47 @:calc-store-power@: (v^a)}
  31214. @r{ a@: s | @:var @: 29,47 @:calc-store-concat@: (v|a)}
  31215. @r{ @: s & @:var @: 29,47 @:calc-store-inv@: (v^-1)}
  31216. @r{ @: s [ @:var @: 29,47 @:calc-store-decr@: (v-1)}
  31217. @r{ @: s ] @:var @: 29,47 @:calc-store-incr@: (v-(-1))}
  31218. @r{ a b@: s : @: @: 2 @:assign@:(a,b) a @tfn{:=} b}
  31219. @r{ a@: s = @: @: 1 @:evalto@:(a,b) a @tfn{=>}}
  31220. @c
  31221. @r{ @: t [ @: @: 4 @:calc-trail-first@:}
  31222. @r{ @: t ] @: @: 4 @:calc-trail-last@:}
  31223. @r{ @: t < @: @: 4 @:calc-trail-scroll-left@:}
  31224. @r{ @: t > @: @: 4 @:calc-trail-scroll-right@:}
  31225. @r{ @: t . @: @: 12 @:calc-full-trail-vectors@:}
  31226. @c
  31227. @r{ @: t b @: @: 4 @:calc-trail-backward@:}
  31228. @r{ @: t d @: @: 12,50 @:calc-trail-display@:}
  31229. @r{ @: t f @: @: 4 @:calc-trail-forward@:}
  31230. @r{ @: t h @: @: @:calc-trail-here@:}
  31231. @r{ @: t i @: @: @:calc-trail-in@:}
  31232. @r{ @: t k @: @: 4 @:calc-trail-kill@:}
  31233. @r{ @: t m @:string @: @:calc-trail-marker@:}
  31234. @r{ @: t n @: @: 4 @:calc-trail-next@:}
  31235. @r{ @: t o @: @: @:calc-trail-out@:}
  31236. @r{ @: t p @: @: 4 @:calc-trail-previous@:}
  31237. @r{ @: t r @:string @: @:calc-trail-isearch-backward@:}
  31238. @r{ @: t s @:string @: @:calc-trail-isearch-forward@:}
  31239. @r{ @: t y @: @: 4 @:calc-trail-yank@:}
  31240. @c
  31241. @r{ d@: t C @:oz, nz @: @:tzconv@:(d,oz,nz)}
  31242. @r{d oz nz@: t C @:$ @: @:tzconv@:(d,oz,nz)}
  31243. @r{ d@: t D @: @: 15 @:date@:(d)}
  31244. @r{ d@: t I @: @: 4 @:incmonth@:(d,n)}
  31245. @r{ d@: t J @: @: 16 @:julian@:(d,z)}
  31246. @r{ d@: t M @: @: 17 @:newmonth@:(d,n)}
  31247. @r{ @: t N @: @: 16 @:now@:(z)}
  31248. @r{ d@: t P @:1 @: 31 @:year@:(d)}
  31249. @r{ d@: t P @:2 @: 31 @:month@:(d)}
  31250. @r{ d@: t P @:3 @: 31 @:day@:(d)}
  31251. @r{ d@: t P @:4 @: 31 @:hour@:(d)}
  31252. @r{ d@: t P @:5 @: 31 @:minute@:(d)}
  31253. @r{ d@: t P @:6 @: 31 @:second@:(d)}
  31254. @r{ d@: t P @:7 @: 31 @:weekday@:(d)}
  31255. @r{ d@: t P @:8 @: 31 @:yearday@:(d)}
  31256. @r{ d@: t P @:9 @: 31 @:time@:(d)}
  31257. @r{ d@: t U @: @: 16 @:unixtime@:(d,z)}
  31258. @r{ d@: t W @: @: 17 @:newweek@:(d,w)}
  31259. @r{ d@: t Y @: @: 17 @:newyear@:(d,n)}
  31260. @c
  31261. @r{ a b@: t + @: @: 2 @:badd@:(a,b)}
  31262. @r{ a b@: t - @: @: 2 @:bsub@:(a,b)}
  31263. @c
  31264. @r{ @: u a @: @: 12 @:calc-autorange-units@:}
  31265. @r{ a@: u b @: @: @:calc-base-units@:}
  31266. @r{ a@: u c @:units @: 18 @:calc-convert-units@:}
  31267. @r{ defn@: u d @:unit, descr @: @:calc-define-unit@:}
  31268. @r{ @: u e @: @: @:calc-explain-units@:}
  31269. @r{ @: u g @:unit @: @:calc-get-unit-definition@:}
  31270. @r{ @: u n @:units @: 18 @:calc-convert-exact-units@:}
  31271. @r{ @: u p @: @: @:calc-permanent-units@:}
  31272. @r{ a@: u r @: @: @:calc-remove-units@:}
  31273. @r{ a@: u s @: @: @:usimplify@:(a)}
  31274. @r{ a@: u t @:units @: 18 @:calc-convert-temperature@:}
  31275. @r{ @: u u @:unit @: @:calc-undefine-unit@:}
  31276. @r{ @: u v @: @: @:calc-enter-units-table@:}
  31277. @r{ a@: u x @: @: @:calc-extract-units@:}
  31278. @r{ a@: u 0-9 @: @: @:calc-quick-units@:}
  31279. @c
  31280. @r{ v1 v2@: u C @: @: 20 @:vcov@:(v1,v2)}
  31281. @r{ v1 v2@: I u C @: @: 20 @:vpcov@:(v1,v2)}
  31282. @r{ v1 v2@: H u C @: @: 20 @:vcorr@:(v1,v2)}
  31283. @r{ v@: u G @: @: 19 @:vgmean@:(v)}
  31284. @r{ a b@: H u G @: @: 2 @:agmean@:(a,b)}
  31285. @r{ v@: u M @: @: 19 @:vmean@:(v)}
  31286. @r{ v@: I u M @: @: 19 @:vmeane@:(v)}
  31287. @r{ v@: H u M @: @: 19 @:vmedian@:(v)}
  31288. @r{ v@: I H u M @: @: 19 @:vhmean@:(v)}
  31289. @r{ v@: u N @: @: 19 @:vmin@:(v)}
  31290. @r{ v@: u R @: @: @:rms@:(v)}
  31291. @r{ v@: u S @: @: 19 @:vsdev@:(v)}
  31292. @r{ v@: I u S @: @: 19 @:vpsdev@:(v)}
  31293. @r{ v@: H u S @: @: 19 @:vvar@:(v)}
  31294. @r{ v@: I H u S @: @: 19 @:vpvar@:(v)}
  31295. @r{ @: u V @: @: @:calc-view-units-table@:}
  31296. @r{ v@: u X @: @: 19 @:vmax@:(v)}
  31297. @c
  31298. @r{ v@: u + @: @: 19 @:vsum@:(v)}
  31299. @r{ v@: u * @: @: 19 @:vprod@:(v)}
  31300. @r{ v@: u # @: @: 19 @:vcount@:(v)}
  31301. @c
  31302. @r{ @: V ( @: @: 50 @:calc-vector-parens@:}
  31303. @r{ @: V @{ @: @: 50 @:calc-vector-braces@:}
  31304. @r{ @: V [ @: @: 50 @:calc-vector-brackets@:}
  31305. @r{ @: V ] @:ROCP @: 50 @:calc-matrix-brackets@:}
  31306. @r{ @: V , @: @: 50 @:calc-vector-commas@:}
  31307. @r{ @: V < @: @: 50 @:calc-matrix-left-justify@:}
  31308. @r{ @: V = @: @: 50 @:calc-matrix-center-justify@:}
  31309. @r{ @: V > @: @: 50 @:calc-matrix-right-justify@:}
  31310. @r{ @: V / @: @: 12,50 @:calc-break-vectors@:}
  31311. @r{ @: V . @: @: 12,50 @:calc-full-vectors@:}
  31312. @c
  31313. @r{ s t@: V ^ @: @: 2 @:vint@:(s,t)}
  31314. @r{ s t@: V - @: @: 2 @:vdiff@:(s,t)}
  31315. @r{ s@: V ~ @: @: 1 @:vcompl@:(s)}
  31316. @r{ s@: V # @: @: 1 @:vcard@:(s)}
  31317. @r{ s@: V : @: @: 1 @:vspan@:(s)}
  31318. @r{ s@: V + @: @: 1 @:rdup@:(s)}
  31319. @c
  31320. @r{ m@: V & @: @: 1 @:inv@:(m) 1/m}
  31321. @c
  31322. @r{ v@: v a @:n @: @:arrange@:(v,n)}
  31323. @r{ a@: v b @:n @: @:cvec@:(a,n)}
  31324. @r{ v@: v c @:n >0 @: 21,31 @:mcol@:(v,n)}
  31325. @r{ v@: v c @:n <0 @: 31 @:mrcol@:(v,-n)}
  31326. @r{ m@: v c @:0 @: 31 @:getdiag@:(m)}
  31327. @r{ v@: v d @: @: 25 @:diag@:(v,n)}
  31328. @r{ v m@: v e @: @: 2 @:vexp@:(v,m)}
  31329. @r{ v m f@: H v e @: @: 2 @:vexp@:(v,m,f)}
  31330. @r{ v a@: v f @: @: 26 @:find@:(v,a,n)}
  31331. @r{ v@: v h @: @: 1 @:head@:(v)}
  31332. @r{ v@: I v h @: @: 1 @:tail@:(v)}
  31333. @r{ v@: H v h @: @: 1 @:rhead@:(v)}
  31334. @r{ v@: I H v h @: @: 1 @:rtail@:(v)}
  31335. @r{ @: v i @:n @: 31 @:idn@:(1,n)}
  31336. @r{ @: v i @:0 @: 31 @:idn@:(1)}
  31337. @r{ h t@: v k @: @: 2 @:cons@:(h,t)}
  31338. @r{ h t@: H v k @: @: 2 @:rcons@:(h,t)}
  31339. @r{ v@: v l @: @: 1 @:vlen@:(v)}
  31340. @r{ v@: H v l @: @: 1 @:mdims@:(v)}
  31341. @r{ v m@: v m @: @: 2 @:vmask@:(v,m)}
  31342. @r{ v@: v n @: @: 1 @:rnorm@:(v)}
  31343. @r{ a b c@: v p @: @: 24 @:calc-pack@:}
  31344. @r{ v@: v r @:n >0 @: 21,31 @:mrow@:(v,n)}
  31345. @r{ v@: v r @:n <0 @: 31 @:mrrow@:(v,-n)}
  31346. @r{ m@: v r @:0 @: 31 @:getdiag@:(m)}
  31347. @r{ v i j@: v s @: @: @:subvec@:(v,i,j)}
  31348. @r{ v i j@: I v s @: @: @:rsubvec@:(v,i,j)}
  31349. @r{ m@: v t @: @: 1 @:trn@:(m)}
  31350. @r{ v@: v u @: @: 24 @:calc-unpack@:}
  31351. @r{ v@: v v @: @: 1 @:rev@:(v)}
  31352. @r{ @: v x @:n @: 31 @:index@:(n)}
  31353. @r{ n s i@: C-u v x @: @: @:index@:(n,s,i)}
  31354. @c
  31355. @r{ v@: V A @:op @: 22 @:apply@:(op,v)}
  31356. @r{ v1 v2@: V C @: @: 2 @:cross@:(v1,v2)}
  31357. @r{ m@: V D @: @: 1 @:det@:(m)}
  31358. @r{ s@: V E @: @: 1 @:venum@:(s)}
  31359. @r{ s@: V F @: @: 1 @:vfloor@:(s)}
  31360. @r{ v@: V G @: @: @:grade@:(v)}
  31361. @r{ v@: I V G @: @: @:rgrade@:(v)}
  31362. @r{ v@: V H @:n @: 31 @:histogram@:(v,n)}
  31363. @r{ v w@: H V H @:n @: 31 @:histogram@:(v,w,n)}
  31364. @r{ v1 v2@: V I @:mop aop @: 22 @:inner@:(mop,aop,v1,v2)}
  31365. @r{ m@: V J @: @: 1 @:ctrn@:(m)}
  31366. @r{ m1 m2@: V K @: @: @:kron@:(m1,m2)}
  31367. @r{ m@: V L @: @: 1 @:lud@:(m)}
  31368. @r{ v@: V M @:op @: 22,23 @:map@:(op,v)}
  31369. @r{ v@: V N @: @: 1 @:cnorm@:(v)}
  31370. @r{ v1 v2@: V O @:op @: 22 @:outer@:(op,v1,v2)}
  31371. @r{ v@: V R @:op @: 22,23 @:reduce@:(op,v)}
  31372. @r{ v@: I V R @:op @: 22,23 @:rreduce@:(op,v)}
  31373. @r{ a n@: H V R @:op @: 22 @:nest@:(op,a,n)}
  31374. @r{ a@: I H V R @:op @: 22 @:fixp@:(op,a)}
  31375. @r{ v@: V S @: @: @:sort@:(v)}
  31376. @r{ v@: I V S @: @: @:rsort@:(v)}
  31377. @r{ m@: V T @: @: 1 @:tr@:(m)}
  31378. @r{ v@: V U @:op @: 22 @:accum@:(op,v)}
  31379. @r{ v@: I V U @:op @: 22 @:raccum@:(op,v)}
  31380. @r{ a n@: H V U @:op @: 22 @:anest@:(op,a,n)}
  31381. @r{ a@: I H V U @:op @: 22 @:afixp@:(op,a)}
  31382. @r{ s t@: V V @: @: 2 @:vunion@:(s,t)}
  31383. @r{ s t@: V X @: @: 2 @:vxor@:(s,t)}
  31384. @c
  31385. @r{ @: Y @: @: @:@:user commands}
  31386. @c
  31387. @r{ @: z @: @: @:@:user commands}
  31388. @c
  31389. @r{ c@: Z [ @: @: 45 @:calc-kbd-if@:}
  31390. @r{ c@: Z | @: @: 45 @:calc-kbd-else-if@:}
  31391. @r{ @: Z : @: @: @:calc-kbd-else@:}
  31392. @r{ @: Z ] @: @: @:calc-kbd-end-if@:}
  31393. @c
  31394. @r{ @: Z @{ @: @: 4 @:calc-kbd-loop@:}
  31395. @r{ c@: Z / @: @: 45 @:calc-kbd-break@:}
  31396. @r{ @: Z @} @: @: @:calc-kbd-end-loop@:}
  31397. @r{ n@: Z < @: @: @:calc-kbd-repeat@:}
  31398. @r{ @: Z > @: @: @:calc-kbd-end-repeat@:}
  31399. @r{ n m@: Z ( @: @: @:calc-kbd-for@:}
  31400. @r{ s@: Z ) @: @: @:calc-kbd-end-for@:}
  31401. @c
  31402. @r{ @: Z C-g @: @: @:@:cancel if/loop command}
  31403. @c
  31404. @r{ @: Z ` @: @: @:calc-kbd-push@:}
  31405. @r{ @: Z ' @: @: @:calc-kbd-pop@:}
  31406. @r{ @: Z # @: @: @:calc-kbd-query@:}
  31407. @c
  31408. @r{ comp@: Z C @:func, args @: 50 @:calc-user-define-composition@:}
  31409. @r{ @: Z D @:key, command @: @:calc-user-define@:}
  31410. @r{ @: Z E @:key, editing @: 30 @:calc-user-define-edit@:}
  31411. @r{ defn@: Z F @:k, c, f, a, n@: 28 @:calc-user-define-formula@:}
  31412. @r{ @: Z G @:key @: @:calc-get-user-defn@:}
  31413. @r{ @: Z I @: @: @:calc-user-define-invocation@:}
  31414. @r{ @: Z K @:key, command @: @:calc-user-define-kbd-macro@:}
  31415. @r{ @: Z P @:key @: @:calc-user-define-permanent@:}
  31416. @r{ @: Z S @: @: 30 @:calc-edit-user-syntax@:}
  31417. @r{ @: Z T @: @: 12 @:calc-timing@:}
  31418. @r{ @: Z U @:key @: @:calc-user-undefine@:}
  31419. @end format
  31420. @c Avoid '@:' from here on, as it now means \sumsep in tex mode.
  31421. @noindent
  31422. NOTES
  31423. @enumerate
  31424. @c 1
  31425. @item
  31426. Positive prefix arguments apply to @expr{n} stack entries.
  31427. Negative prefix arguments apply to the @expr{-n}th stack entry.
  31428. A prefix of zero applies to the entire stack. (For @key{LFD} and
  31429. @kbd{M-@key{DEL}}, the meaning of the sign is reversed.)
  31430. @c 2
  31431. @item
  31432. Positive prefix arguments apply to @expr{n} stack entries.
  31433. Negative prefix arguments apply to the top stack entry
  31434. and the next @expr{-n} stack entries.
  31435. @c 3
  31436. @item
  31437. Positive prefix arguments rotate top @expr{n} stack entries by one.
  31438. Negative prefix arguments rotate the entire stack by @expr{-n}.
  31439. A prefix of zero reverses the entire stack.
  31440. @c 4
  31441. @item
  31442. Prefix argument specifies a repeat count or distance.
  31443. @c 5
  31444. @item
  31445. Positive prefix arguments specify a precision @expr{p}.
  31446. Negative prefix arguments reduce the current precision by @expr{-p}.
  31447. @c 6
  31448. @item
  31449. A prefix argument is interpreted as an additional step-size parameter.
  31450. A plain @kbd{C-u} prefix means to prompt for the step size.
  31451. @c 7
  31452. @item
  31453. A prefix argument specifies simplification level and depth.
  31454. 1=Basic simplifications, 2=Algebraic simplifications, 3=Extended simplifications
  31455. @c 8
  31456. @item
  31457. A negative prefix operates only on the top level of the input formula.
  31458. @c 9
  31459. @item
  31460. Positive prefix arguments specify a word size of @expr{w} bits, unsigned.
  31461. Negative prefix arguments specify a word size of @expr{w} bits, signed.
  31462. @c 10
  31463. @item
  31464. Prefix arguments specify the shift amount @expr{n}. The @expr{w} argument
  31465. cannot be specified in the keyboard version of this command.
  31466. @c 11
  31467. @item
  31468. From the keyboard, @expr{d} is omitted and defaults to zero.
  31469. @c 12
  31470. @item
  31471. Mode is toggled; a positive prefix always sets the mode, and a negative
  31472. prefix always clears the mode.
  31473. @c 13
  31474. @item
  31475. Some prefix argument values provide special variations of the mode.
  31476. @c 14
  31477. @item
  31478. A prefix argument, if any, is used for @expr{m} instead of taking
  31479. @expr{m} from the stack. @expr{M} may take any of these values:
  31480. @iftex
  31481. {@advance@tableindent10pt
  31482. @end iftex
  31483. @table @asis
  31484. @item Integer
  31485. Random integer in the interval @expr{[0 .. m)}.
  31486. @item Float
  31487. Random floating-point number in the interval @expr{[0 .. m)}.
  31488. @item 0.0
  31489. Gaussian with mean 1 and standard deviation 0.
  31490. @item Error form
  31491. Gaussian with specified mean and standard deviation.
  31492. @item Interval
  31493. Random integer or floating-point number in that interval.
  31494. @item Vector
  31495. Random element from the vector.
  31496. @end table
  31497. @iftex
  31498. }
  31499. @end iftex
  31500. @c 15
  31501. @item
  31502. A prefix argument from 1 to 6 specifies number of date components
  31503. to remove from the stack. @xref{Date Conversions}.
  31504. @c 16
  31505. @item
  31506. A prefix argument specifies a time zone; @kbd{C-u} says to take the
  31507. time zone number or name from the top of the stack. @xref{Time Zones}.
  31508. @c 17
  31509. @item
  31510. A prefix argument specifies a day number (0--6, 0--31, or 0--366).
  31511. @c 18
  31512. @item
  31513. If the input has no units, you will be prompted for both the old and
  31514. the new units.
  31515. @c 19
  31516. @item
  31517. With a prefix argument, collect that many stack entries to form the
  31518. input data set. Each entry may be a single value or a vector of values.
  31519. @c 20
  31520. @item
  31521. With a prefix argument of 1, take a single
  31522. @texline @var{n}@math{\times2}
  31523. @infoline @mathit{@var{N}x2}
  31524. matrix from the stack instead of two separate data vectors.
  31525. @c 21
  31526. @item
  31527. The row or column number @expr{n} may be given as a numeric prefix
  31528. argument instead. A plain @kbd{C-u} prefix says to take @expr{n}
  31529. from the top of the stack. If @expr{n} is a vector or interval,
  31530. a subvector/submatrix of the input is created.
  31531. @c 22
  31532. @item
  31533. The @expr{op} prompt can be answered with the key sequence for the
  31534. desired function, or with @kbd{x} or @kbd{z} followed by a function name,
  31535. or with @kbd{$} to take a formula from the top of the stack, or with
  31536. @kbd{'} and a typed formula. In the last two cases, the formula may
  31537. be a nameless function like @samp{<#1+#2>} or @samp{<x, y : x+y>}; or it
  31538. may include @kbd{$}, @kbd{$$}, etc., where @kbd{$} will correspond to the
  31539. last argument of the created function; or otherwise you will be
  31540. prompted for an argument list. The number of vectors popped from the
  31541. stack by @kbd{V M} depends on the number of arguments of the function.
  31542. @c 23
  31543. @item
  31544. One of the mapping direction keys @kbd{_} (horizontal, i.e., map
  31545. by rows or reduce across), @kbd{:} (vertical, i.e., map by columns or
  31546. reduce down), or @kbd{=} (map or reduce by rows) may be used before
  31547. entering @expr{op}; these modify the function name by adding the letter
  31548. @code{r} for ``rows,'' @code{c} for ``columns,'' @code{a} for ``across,''
  31549. or @code{d} for ``down.''
  31550. @c 24
  31551. @item
  31552. The prefix argument specifies a packing mode. A nonnegative mode
  31553. is the number of items (for @kbd{v p}) or the number of levels
  31554. (for @kbd{v u}). A negative mode is as described below. With no
  31555. prefix argument, the mode is taken from the top of the stack and
  31556. may be an integer or a vector of integers.
  31557. @iftex
  31558. {@advance@tableindent-20pt
  31559. @end iftex
  31560. @table @cite
  31561. @item -1
  31562. (@var{2}) Rectangular complex number.
  31563. @item -2
  31564. (@var{2}) Polar complex number.
  31565. @item -3
  31566. (@var{3}) HMS form.
  31567. @item -4
  31568. (@var{2}) Error form.
  31569. @item -5
  31570. (@var{2}) Modulo form.
  31571. @item -6
  31572. (@var{2}) Closed interval.
  31573. @item -7
  31574. (@var{2}) Closed .. open interval.
  31575. @item -8
  31576. (@var{2}) Open .. closed interval.
  31577. @item -9
  31578. (@var{2}) Open interval.
  31579. @item -10
  31580. (@var{2}) Fraction.
  31581. @item -11
  31582. (@var{2}) Float with integer mantissa.
  31583. @item -12
  31584. (@var{2}) Float with mantissa in @expr{[1 .. 10)}.
  31585. @item -13
  31586. (@var{1}) Date form (using date numbers).
  31587. @item -14
  31588. (@var{3}) Date form (using year, month, day).
  31589. @item -15
  31590. (@var{6}) Date form (using year, month, day, hour, minute, second).
  31591. @end table
  31592. @iftex
  31593. }
  31594. @end iftex
  31595. @c 25
  31596. @item
  31597. A prefix argument specifies the size @expr{n} of the matrix. With no
  31598. prefix argument, @expr{n} is omitted and the size is inferred from
  31599. the input vector.
  31600. @c 26
  31601. @item
  31602. The prefix argument specifies the starting position @expr{n} (default 1).
  31603. @c 27
  31604. @item
  31605. Cursor position within stack buffer affects this command.
  31606. @c 28
  31607. @item
  31608. Arguments are not actually removed from the stack by this command.
  31609. @c 29
  31610. @item
  31611. Variable name may be a single digit or a full name.
  31612. @c 30
  31613. @item
  31614. Editing occurs in a separate buffer. Press @kbd{C-c C-c} (or
  31615. @key{LFD}, or in some cases @key{RET}) to finish the edit, or kill the
  31616. buffer with @kbd{C-x k} to cancel the edit. The @key{LFD} key prevents evaluation
  31617. of the result of the edit.
  31618. @c 31
  31619. @item
  31620. The number prompted for can also be provided as a prefix argument.
  31621. @c 32
  31622. @item
  31623. Press this key a second time to cancel the prefix.
  31624. @c 33
  31625. @item
  31626. With a negative prefix, deactivate all formulas. With a positive
  31627. prefix, deactivate and then reactivate from scratch.
  31628. @c 34
  31629. @item
  31630. Default is to scan for nearest formula delimiter symbols. With a
  31631. prefix of zero, formula is delimited by mark and point. With a
  31632. non-zero prefix, formula is delimited by scanning forward or
  31633. backward by that many lines.
  31634. @c 35
  31635. @item
  31636. Parse the region between point and mark as a vector. A nonzero prefix
  31637. parses @var{n} lines before or after point as a vector. A zero prefix
  31638. parses the current line as a vector. A @kbd{C-u} prefix parses the
  31639. region between point and mark as a single formula.
  31640. @c 36
  31641. @item
  31642. Parse the rectangle defined by point and mark as a matrix. A positive
  31643. prefix @var{n} divides the rectangle into columns of width @var{n}.
  31644. A zero or @kbd{C-u} prefix parses each line as one formula. A negative
  31645. prefix suppresses special treatment of bracketed portions of a line.
  31646. @c 37
  31647. @item
  31648. A numeric prefix causes the current language mode to be ignored.
  31649. @c 38
  31650. @item
  31651. Responding to a prompt with a blank line answers that and all
  31652. later prompts by popping additional stack entries.
  31653. @c 39
  31654. @item
  31655. Answer for @expr{v} may also be of the form @expr{v = v_0} or
  31656. @expr{v - v_0}.
  31657. @c 40
  31658. @item
  31659. With a positive prefix argument, stack contains many @expr{y}'s and one
  31660. common @expr{x}. With a zero prefix, stack contains a vector of
  31661. @expr{y}s and a common @expr{x}. With a negative prefix, stack
  31662. contains many @expr{[x,y]} vectors. (For 3D plots, substitute
  31663. @expr{z} for @expr{y} and @expr{x,y} for @expr{x}.)
  31664. @c 41
  31665. @item
  31666. With any prefix argument, all curves in the graph are deleted.
  31667. @c 42
  31668. @item
  31669. With a positive prefix, refines an existing plot with more data points.
  31670. With a negative prefix, forces recomputation of the plot data.
  31671. @c 43
  31672. @item
  31673. With any prefix argument, set the default value instead of the
  31674. value for this graph.
  31675. @c 44
  31676. @item
  31677. With a negative prefix argument, set the value for the printer.
  31678. @c 45
  31679. @item
  31680. Condition is considered ``true'' if it is a nonzero real or complex
  31681. number, or a formula whose value is known to be nonzero; it is ``false''
  31682. otherwise.
  31683. @c 46
  31684. @item
  31685. Several formulas separated by commas are pushed as multiple stack
  31686. entries. Trailing @kbd{)}, @kbd{]}, @kbd{@}}, @kbd{>}, and @kbd{"}
  31687. delimiters may be omitted. The notation @kbd{$$$} refers to the value
  31688. in stack level three, and causes the formula to replace the top three
  31689. stack levels. The notation @kbd{$3} refers to stack level three without
  31690. causing that value to be removed from the stack. Use @key{LFD} in place
  31691. of @key{RET} to prevent evaluation; use @kbd{M-=} in place of @key{RET}
  31692. to evaluate variables.
  31693. @c 47
  31694. @item
  31695. The variable is replaced by the formula shown on the right. The
  31696. Inverse flag reverses the order of the operands, e.g., @kbd{I s - x}
  31697. assigns
  31698. @texline @math{x \coloneq a-x}.
  31699. @infoline @expr{x := a-x}.
  31700. @c 48
  31701. @item
  31702. Press @kbd{?} repeatedly to see how to choose a model. Answer the
  31703. variables prompt with @expr{iv} or @expr{iv;pv} to specify
  31704. independent and parameter variables. A positive prefix argument
  31705. takes @mathit{@var{n}+1} vectors from the stack; a zero prefix takes a matrix
  31706. and a vector from the stack.
  31707. @c 49
  31708. @item
  31709. With a plain @kbd{C-u} prefix, replace the current region of the
  31710. destination buffer with the yanked text instead of inserting.
  31711. @c 50
  31712. @item
  31713. All stack entries are reformatted; the @kbd{H} prefix inhibits this.
  31714. The @kbd{I} prefix sets the mode temporarily, redraws the top stack
  31715. entry, then restores the original setting of the mode.
  31716. @c 51
  31717. @item
  31718. A negative prefix sets the default 3D resolution instead of the
  31719. default 2D resolution.
  31720. @c 52
  31721. @item
  31722. This grabs a vector of the form [@var{prec}, @var{wsize}, @var{ssize},
  31723. @var{radix}, @var{flfmt}, @var{ang}, @var{frac}, @var{symb}, @var{polar},
  31724. @var{matrix}, @var{simp}, @var{inf}]. A prefix argument from 1 to 12
  31725. grabs the @var{n}th mode value only.
  31726. @end enumerate
  31727. @iftex
  31728. (Space is provided below for you to keep your own written notes.)
  31729. @page
  31730. @endgroup
  31731. @end iftex
  31732. @c [end-summary]
  31733. @node Key Index, Command Index, Summary, Top
  31734. @unnumbered Index of Key Sequences
  31735. @printindex ky
  31736. @node Command Index, Function Index, Key Index, Top
  31737. @unnumbered Index of Calculator Commands
  31738. Since all Calculator commands begin with the prefix @samp{calc-}, the
  31739. @kbd{x} key has been provided as a variant of @kbd{M-x} which automatically
  31740. types @samp{calc-} for you. Thus, @kbd{x last-args} is short for
  31741. @kbd{M-x calc-last-args}.
  31742. @printindex pg
  31743. @node Function Index, Concept Index, Command Index, Top
  31744. @unnumbered Index of Algebraic Functions
  31745. This is a list of built-in functions and operators usable in algebraic
  31746. expressions. Their full Lisp names are derived by adding the prefix
  31747. @samp{calcFunc-}, as in @code{calcFunc-sqrt}.
  31748. @iftex
  31749. All functions except those noted with ``*'' have corresponding
  31750. Calc keystrokes and can also be found in the Calc Summary.
  31751. @end iftex
  31752. @printindex tp
  31753. @node Concept Index, Variable Index, Function Index, Top
  31754. @unnumbered Concept Index
  31755. @printindex cp
  31756. @node Variable Index, Lisp Function Index, Concept Index, Top
  31757. @unnumbered Index of Variables
  31758. The variables in this list that do not contain dashes are accessible
  31759. as Calc variables. Add a @samp{var-} prefix to get the name of the
  31760. corresponding Lisp variable.
  31761. The remaining variables are Lisp variables suitable for @code{setq}ing
  31762. in your Calc init file or @file{.emacs} file.
  31763. @printindex vr
  31764. @node Lisp Function Index, , Variable Index, Top
  31765. @unnumbered Index of Lisp Math Functions
  31766. The following functions are meant to be used with @code{defmath}, not
  31767. @code{defun} definitions. For names that do not start with @samp{calc-},
  31768. the corresponding full Lisp name is derived by adding a prefix of
  31769. @samp{math-}.
  31770. @printindex fn
  31771. @bye