calc.texi 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628
  1. \input texinfo @c -*-texinfo-*-
  2. @comment %**start of header (This is for running Texinfo on a region.)
  3. @c smallbook
  4. @setfilename ../info/calc
  5. @c [title]
  6. @settitle GNU Emacs Calc 2.02g Manual
  7. @setchapternewpage odd
  8. @dircategory Emacs
  9. @direntry
  10. * Calc: (calc). Advanced desk calculator and mathematical tool.
  11. @end direntry
  12. @comment %**end of header (This is for running Texinfo on a region.)
  13. @tex
  14. % Some special kludges to make TeX formatting prettier.
  15. % Because makeinfo.c exists, we can't just define new commands.
  16. % So instead, we take over little-used existing commands.
  17. %
  18. % Suggested by Karl Berry <karl@@freefriends.org>
  19. \gdef\!{\mskip-\thinmuskip}
  20. % Redefine @cite{text} to act like $text$ in regular TeX.
  21. % Info will typeset this same as @samp{text}.
  22. \gdef\goodtex{\tex \let\rm\goodrm \let\t\ttfont \turnoffactive}
  23. \gdef\goodrm{\fam0\tenrm}
  24. \gdef\cite{\goodtex$\citexxx}
  25. \gdef\citexxx#1{#1$\Etex}
  26. \global\let\oldxrefX=\xrefX
  27. \gdef\xrefX[#1]{\begingroup\let\cite=\dfn\oldxrefX[#1]\endgroup}
  28. % Redefine @c{tex-stuff} \n @whatever{info-stuff}.
  29. \gdef\c{\futurelet\next\mycxxx}
  30. \gdef\mycxxx{%
  31. \ifx\next\bgroup \goodtex\let\next\mycxxy
  32. \else\ifx\next\mindex \let\next\relax
  33. \else\ifx\next\kindex \let\next\relax
  34. \else\ifx\next\starindex \let\next\relax \else \let\next\comment
  35. \fi\fi\fi\fi \next
  36. }
  37. \gdef\mycxxy#1#2{#1\Etex\mycxxz}
  38. \gdef\mycxxz#1{}
  39. @end tex
  40. @c Fix some other things specifically for this manual.
  41. @iftex
  42. @finalout
  43. @mathcode`@:=`@: @c Make Calc fractions come out right in math mode
  44. @tex
  45. \gdef\coloneq{\mathrel{\mathord:\mathord=}}
  46. \gdef\beforedisplay{\vskip-10pt}
  47. \gdef\afterdisplay{\vskip-5pt}
  48. \gdef\beforedisplayh{\vskip-25pt}
  49. \gdef\afterdisplayh{\vskip-10pt}
  50. @end tex
  51. @newdimen@kyvpos @kyvpos=0pt
  52. @newdimen@kyhpos @kyhpos=0pt
  53. @newcount@calcclubpenalty @calcclubpenalty=1000
  54. @ignore
  55. @newcount@calcpageno
  56. @newtoks@calcoldeverypar @calcoldeverypar=@everypar
  57. @everypar={@calceverypar@the@calcoldeverypar}
  58. @ifx@turnoffactive@undefinedzzz@def@turnoffactive{}@fi
  59. @ifx@ninett@undefinedzzz@font@ninett=cmtt9@fi
  60. @catcode`@\=0 \catcode`\@=11
  61. \r@ggedbottomtrue
  62. \catcode`\@=0 @catcode`@\=@active
  63. @end ignore
  64. @end iftex
  65. @ifnottex
  66. This file documents Calc, the GNU Emacs calculator.
  67. Copyright (C) 1990, 1991, 2001, 2002 Free Software Foundation, Inc.
  68. Permission is granted to copy, distribute and/or modify this document
  69. under the terms of the GNU Free Documentation License, Version 1.1 or
  70. any later version published by the Free Software Foundation; with the
  71. Invariant Sections being just ``GNU GENERAL PUBLIC LICENSE'', with the
  72. Front-Cover texts being ``A GNU Manual,'' and with the Back-Cover
  73. Texts as in (a) below.
  74. (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
  75. this GNU Manual, like GNU software. Copies published by the Free
  76. Software Foundation raise funds for GNU development.''
  77. @end ifnottex
  78. @titlepage
  79. @sp 6
  80. @center @titlefont{Calc Manual}
  81. @sp 4
  82. @center GNU Emacs Calc Version 2.02g
  83. @c [volume]
  84. @sp 1
  85. @center January 2002
  86. @sp 5
  87. @center Dave Gillespie
  88. @center daveg@@synaptics.com
  89. @page
  90. @vskip 0pt plus 1filll
  91. Copyright @copyright{} 1990, 1991, 2001, 2002 Free Software Foundation, Inc.
  92. Permission is granted to copy, distribute and/or modify this document
  93. under the terms of the GNU Free Documentation License, Version 1.1 or
  94. any later version published by the Free Software Foundation; with the
  95. Invariant Sections being just ``GNU GENERAL PUBLIC LICENSE'', with the
  96. Front-Cover texts being ``A GNU Manual,'' and with the Back-Cover
  97. Texts as in (a) below.
  98. (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
  99. this GNU Manual, like GNU software. Copies published by the Free
  100. Software Foundation raise funds for GNU development.''
  101. @end titlepage
  102. @c [begin]
  103. @ifinfo
  104. @node Top, , (dir), (dir)
  105. @chapter The GNU Emacs Calculator
  106. @noindent
  107. @dfn{Calc} is an advanced desk calculator and mathematical tool
  108. that runs as part of the GNU Emacs environment.
  109. This manual is divided into three major parts: ``Getting Started,''
  110. the ``Calc Tutorial,'' and the ``Calc Reference.'' The Tutorial
  111. introduces all the major aspects of Calculator use in an easy,
  112. hands-on way. The remainder of the manual is a complete reference to
  113. the features of the Calculator.
  114. For help in the Emacs Info system (which you are using to read this
  115. file), type @kbd{?}. (You can also type @kbd{h} to run through a
  116. longer Info tutorial.)
  117. @end ifinfo
  118. @menu
  119. * Copying:: How you can copy and share Calc.
  120. * Getting Started:: General description and overview.
  121. * Interactive Tutorial::
  122. * Tutorial:: A step-by-step introduction for beginners.
  123. * Introduction:: Introduction to the Calc reference manual.
  124. * Data Types:: Types of objects manipulated by Calc.
  125. * Stack and Trail:: Manipulating the stack and trail buffers.
  126. * Mode Settings:: Adjusting display format and other modes.
  127. * Arithmetic:: Basic arithmetic functions.
  128. * Scientific Functions:: Transcendentals and other scientific functions.
  129. * Matrix Functions:: Operations on vectors and matrices.
  130. * Algebra:: Manipulating expressions algebraically.
  131. * Units:: Operations on numbers with units.
  132. * Store and Recall:: Storing and recalling variables.
  133. * Graphics:: Commands for making graphs of data.
  134. * Kill and Yank:: Moving data into and out of Calc.
  135. * Embedded Mode:: Working with formulas embedded in a file.
  136. * Programming:: Calc as a programmable calculator.
  137. * Installation:: Installing Calc as a part of GNU Emacs.
  138. * Reporting Bugs:: How to report bugs and make suggestions.
  139. * Summary:: Summary of Calc commands and functions.
  140. * Key Index:: The standard Calc key sequences.
  141. * Command Index:: The interactive Calc commands.
  142. * Function Index:: Functions (in algebraic formulas).
  143. * Concept Index:: General concepts.
  144. * Variable Index:: Variables used by Calc (both user and internal).
  145. * Lisp Function Index:: Internal Lisp math functions.
  146. @end menu
  147. @node Copying, Getting Started, Top, Top
  148. @unnumbered GNU GENERAL PUBLIC LICENSE
  149. @center Version 1, February 1989
  150. @display
  151. Copyright @copyright{} 1989 Free Software Foundation, Inc.
  152. 675 Mass Ave, Cambridge, MA 02139, USA
  153. Everyone is permitted to copy and distribute verbatim copies
  154. of this license document, but changing it is not allowed.
  155. @end display
  156. @unnumberedsec Preamble
  157. The license agreements of most software companies try to keep users
  158. at the mercy of those companies. By contrast, our General Public
  159. License is intended to guarantee your freedom to share and change free
  160. software---to make sure the software is free for all its users. The
  161. General Public License applies to the Free Software Foundation's
  162. software and to any other program whose authors commit to using it.
  163. You can use it for your programs, too.
  164. When we speak of free software, we are referring to freedom, not
  165. price. Specifically, the General Public License is designed to make
  166. sure that you have the freedom to give away or sell copies of free
  167. software, that you receive source code or can get it if you want it,
  168. that you can change the software or use pieces of it in new free
  169. programs; and that you know you can do these things.
  170. To protect your rights, we need to make restrictions that forbid
  171. anyone to deny you these rights or to ask you to surrender the rights.
  172. These restrictions translate to certain responsibilities for you if you
  173. distribute copies of the software, or if you modify it.
  174. For example, if you distribute copies of a such a program, whether
  175. gratis or for a fee, you must give the recipients all the rights that
  176. you have. You must make sure that they, too, receive or can get the
  177. source code. And you must tell them their rights.
  178. We protect your rights with two steps: (1) copyright the software, and
  179. (2) offer you this license which gives you legal permission to copy,
  180. distribute and/or modify the software.
  181. Also, for each author's protection and ours, we want to make certain
  182. that everyone understands that there is no warranty for this free
  183. software. If the software is modified by someone else and passed on, we
  184. want its recipients to know that what they have is not the original, so
  185. that any problems introduced by others will not reflect on the original
  186. authors' reputations.
  187. The precise terms and conditions for copying, distribution and
  188. modification follow.
  189. @iftex
  190. @unnumberedsec TERMS AND CONDITIONS
  191. @end iftex
  192. @ifinfo
  193. @center TERMS AND CONDITIONS
  194. @end ifinfo
  195. @enumerate
  196. @item
  197. This License Agreement applies to any program or other work which
  198. contains a notice placed by the copyright holder saying it may be
  199. distributed under the terms of this General Public License. The
  200. ``Program'', below, refers to any such program or work, and a ``work based
  201. on the Program'' means either the Program or any work containing the
  202. Program or a portion of it, either verbatim or with modifications. Each
  203. licensee is addressed as ``you''.
  204. @item
  205. You may copy and distribute verbatim copies of the Program's source
  206. code as you receive it, in any medium, provided that you conspicuously and
  207. appropriately publish on each copy an appropriate copyright notice and
  208. disclaimer of warranty; keep intact all the notices that refer to this
  209. General Public License and to the absence of any warranty; and give any
  210. other recipients of the Program a copy of this General Public License
  211. along with the Program. You may charge a fee for the physical act of
  212. transferring a copy.
  213. @item
  214. You may modify your copy or copies of the Program or any portion of
  215. it, and copy and distribute such modifications under the terms of Paragraph
  216. 1 above, provided that you also do the following:
  217. @itemize @bullet
  218. @item
  219. cause the modified files to carry prominent notices stating that
  220. you changed the files and the date of any change; and
  221. @item
  222. cause the whole of any work that you distribute or publish, that
  223. in whole or in part contains the Program or any part thereof, either
  224. with or without modifications, to be licensed at no charge to all
  225. third parties under the terms of this General Public License (except
  226. that you may choose to grant warranty protection to some or all
  227. third parties, at your option).
  228. @item
  229. If the modified program normally reads commands interactively when
  230. run, you must cause it, when started running for such interactive use
  231. in the simplest and most usual way, to print or display an
  232. announcement including an appropriate copyright notice and a notice
  233. that there is no warranty (or else, saying that you provide a
  234. warranty) and that users may redistribute the program under these
  235. conditions, and telling the user how to view a copy of this General
  236. Public License.
  237. @item
  238. You may charge a fee for the physical act of transferring a
  239. copy, and you may at your option offer warranty protection in
  240. exchange for a fee.
  241. @end itemize
  242. Mere aggregation of another independent work with the Program (or its
  243. derivative) on a volume of a storage or distribution medium does not bring
  244. the other work under the scope of these terms.
  245. @item
  246. You may copy and distribute the Program (or a portion or derivative of
  247. it, under Paragraph 2) in object code or executable form under the terms of
  248. Paragraphs 1 and 2 above provided that you also do one of the following:
  249. @itemize @bullet
  250. @item
  251. accompany it with the complete corresponding machine-readable
  252. source code, which must be distributed under the terms of
  253. Paragraphs 1 and 2 above; or,
  254. @item
  255. accompany it with a written offer, valid for at least three
  256. years, to give any third party free (except for a nominal charge
  257. for the cost of distribution) a complete machine-readable copy of the
  258. corresponding source code, to be distributed under the terms of
  259. Paragraphs 1 and 2 above; or,
  260. @item
  261. accompany it with the information you received as to where the
  262. corresponding source code may be obtained. (This alternative is
  263. allowed only for noncommercial distribution and only if you
  264. received the program in object code or executable form alone.)
  265. @end itemize
  266. Source code for a work means the preferred form of the work for making
  267. modifications to it. For an executable file, complete source code means
  268. all the source code for all modules it contains; but, as a special
  269. exception, it need not include source code for modules which are standard
  270. libraries that accompany the operating system on which the executable
  271. file runs, or for standard header files or definitions files that
  272. accompany that operating system.
  273. @item
  274. You may not copy, modify, sublicense, distribute or transfer the
  275. Program except as expressly provided under this General Public License.
  276. Any attempt otherwise to copy, modify, sublicense, distribute or transfer
  277. the Program is void, and will automatically terminate your rights to use
  278. the Program under this License. However, parties who have received
  279. copies, or rights to use copies, from you under this General Public
  280. License will not have their licenses terminated so long as such parties
  281. remain in full compliance.
  282. @item
  283. By copying, distributing or modifying the Program (or any work based
  284. on the Program) you indicate your acceptance of this license to do so,
  285. and all its terms and conditions.
  286. @item
  287. Each time you redistribute the Program (or any work based on the
  288. Program), the recipient automatically receives a license from the original
  289. licensor to copy, distribute or modify the Program subject to these
  290. terms and conditions. You may not impose any further restrictions on the
  291. recipients' exercise of the rights granted herein.
  292. @item
  293. The Free Software Foundation may publish revised and/or new versions
  294. of the General Public License from time to time. Such new versions will
  295. be similar in spirit to the present version, but may differ in detail to
  296. address new problems or concerns.
  297. Each version is given a distinguishing version number. If the Program
  298. specifies a version number of the license which applies to it and ``any
  299. later version'', you have the option of following the terms and conditions
  300. either of that version or of any later version published by the Free
  301. Software Foundation. If the Program does not specify a version number of
  302. the license, you may choose any version ever published by the Free Software
  303. Foundation.
  304. @item
  305. If you wish to incorporate parts of the Program into other free
  306. programs whose distribution conditions are different, write to the author
  307. to ask for permission. For software which is copyrighted by the Free
  308. Software Foundation, write to the Free Software Foundation; we sometimes
  309. make exceptions for this. Our decision will be guided by the two goals
  310. of preserving the free status of all derivatives of our free software and
  311. of promoting the sharing and reuse of software generally.
  312. @iftex
  313. @heading NO WARRANTY
  314. @end iftex
  315. @ifinfo
  316. @center NO WARRANTY
  317. @end ifinfo
  318. @item
  319. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  320. FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
  321. OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  322. PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  323. OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  324. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
  325. TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
  326. PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  327. REPAIR OR CORRECTION.
  328. @item
  329. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL
  330. ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  331. REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  332. INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
  333. ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT
  334. LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES
  335. SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
  336. WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  337. ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  338. @end enumerate
  339. @node Getting Started, Tutorial, Copying, Top
  340. @chapter Getting Started
  341. @noindent
  342. This chapter provides a general overview of Calc, the GNU Emacs
  343. Calculator: What it is, how to start it and how to exit from it,
  344. and what are the various ways that it can be used.
  345. @menu
  346. * What is Calc::
  347. * About This Manual::
  348. * Notations Used in This Manual::
  349. * Using Calc::
  350. * Demonstration of Calc::
  351. * History and Acknowledgements::
  352. @end menu
  353. @node What is Calc, About This Manual, Getting Started, Getting Started
  354. @section What is Calc?
  355. @noindent
  356. @dfn{Calc} is an advanced calculator and mathematical tool that runs as
  357. part of the GNU Emacs environment. Very roughly based on the HP-28/48
  358. series of calculators, its many features include:
  359. @itemize @bullet
  360. @item
  361. Choice of algebraic or RPN (stack-based) entry of calculations.
  362. @item
  363. Arbitrary precision integers and floating-point numbers.
  364. @item
  365. Arithmetic on rational numbers, complex numbers (rectangular and polar),
  366. error forms with standard deviations, open and closed intervals, vectors
  367. and matrices, dates and times, infinities, sets, quantities with units,
  368. and algebraic formulas.
  369. @item
  370. Mathematical operations such as logarithms and trigonometric functions.
  371. @item
  372. Programmer's features (bitwise operations, non-decimal numbers).
  373. @item
  374. Financial functions such as future value and internal rate of return.
  375. @item
  376. Number theoretical features such as prime factorization and arithmetic
  377. modulo @var{m} for any @var{m}.
  378. @item
  379. Algebraic manipulation features, including symbolic calculus.
  380. @item
  381. Moving data to and from regular editing buffers.
  382. @item
  383. ``Embedded mode'' for manipulating Calc formulas and data directly
  384. inside any editing buffer.
  385. @item
  386. Graphics using GNUPLOT, a versatile (and free) plotting program.
  387. @item
  388. Easy programming using keyboard macros, algebraic formulas,
  389. algebraic rewrite rules, or extended Emacs Lisp.
  390. @end itemize
  391. Calc tries to include a little something for everyone; as a result it is
  392. large and might be intimidating to the first-time user. If you plan to
  393. use Calc only as a traditional desk calculator, all you really need to
  394. read is the ``Getting Started'' chapter of this manual and possibly the
  395. first few sections of the tutorial. As you become more comfortable with
  396. the program you can learn its additional features. In terms of efficiency,
  397. scope and depth, Calc cannot replace a powerful tool like Mathematica.
  398. But Calc has the advantages of convenience, portability, and availability
  399. of the source code. And, of course, it's free!
  400. @node About This Manual, Notations Used in This Manual, What is Calc, Getting Started
  401. @section About This Manual
  402. @noindent
  403. This document serves as a complete description of the GNU Emacs
  404. Calculator. It works both as an introduction for novices, and as
  405. a reference for experienced users. While it helps to have some
  406. experience with GNU Emacs in order to get the most out of Calc,
  407. this manual ought to be readable even if you don't know or use Emacs
  408. regularly.
  409. @ifinfo
  410. The manual is divided into three major parts:@: the ``Getting
  411. Started'' chapter you are reading now, the Calc tutorial (chapter 2),
  412. and the Calc reference manual (the remaining chapters and appendices).
  413. @end ifinfo
  414. @iftex
  415. The manual is divided into three major parts:@: the ``Getting
  416. Started'' chapter you are reading now, the Calc tutorial (chapter 2),
  417. and the Calc reference manual (the remaining chapters and appendices).
  418. @c [when-split]
  419. @c This manual has been printed in two volumes, the @dfn{Tutorial} and the
  420. @c @dfn{Reference}. Both volumes include a copy of the ``Getting Started''
  421. @c chapter.
  422. @end iftex
  423. If you are in a hurry to use Calc, there is a brief ``demonstration''
  424. below which illustrates the major features of Calc in just a couple of
  425. pages. If you don't have time to go through the full tutorial, this
  426. will show you everything you need to know to begin.
  427. @xref{Demonstration of Calc}.
  428. The tutorial chapter walks you through the various parts of Calc
  429. with lots of hands-on examples and explanations. If you are new
  430. to Calc and you have some time, try going through at least the
  431. beginning of the tutorial. The tutorial includes about 70 exercises
  432. with answers. These exercises give you some guided practice with
  433. Calc, as well as pointing out some interesting and unusual ways
  434. to use its features.
  435. The reference section discusses Calc in complete depth. You can read
  436. the reference from start to finish if you want to learn every aspect
  437. of Calc. Or, you can look in the table of contents or the Concept
  438. Index to find the parts of the manual that discuss the things you
  439. need to know.
  440. @cindex Marginal notes
  441. Every Calc keyboard command is listed in the Calc Summary, and also
  442. in the Key Index. Algebraic functions, @kbd{M-x} commands, and
  443. variables also have their own indices. @c{Each}
  444. @asis{In the printed manual, each}
  445. paragraph that is referenced in the Key or Function Index is marked
  446. in the margin with its index entry.
  447. @c [fix-ref Help Commands]
  448. You can access this manual on-line at any time within Calc by
  449. pressing the @kbd{h i} key sequence. Outside of the Calc window,
  450. you can press @kbd{M-# i} to read the manual on-line. Also, you
  451. can jump directly to the Tutorial by pressing @kbd{h t} or @kbd{M-# t},
  452. or to the Summary by pressing @kbd{h s} or @kbd{M-# s}. Within Calc,
  453. you can also go to the part of the manual describing any Calc key,
  454. function, or variable using @w{@kbd{h k}}, @kbd{h f}, or @kbd{h v},
  455. respectively. @xref{Help Commands}.
  456. Printed copies of this manual are also available from the Free Software
  457. Foundation.
  458. @node Notations Used in This Manual, Demonstration of Calc, About This Manual, Getting Started
  459. @section Notations Used in This Manual
  460. @noindent
  461. This section describes the various notations that are used
  462. throughout the Calc manual.
  463. In keystroke sequences, uppercase letters mean you must hold down
  464. the shift key while typing the letter. Keys pressed with Control
  465. held down are shown as @kbd{C-x}. Keys pressed with Meta held down
  466. are shown as @kbd{M-x}. Other notations are @key{RET} for the
  467. Return key, @key{SPC} for the space bar, @key{TAB} for the Tab key,
  468. @key{DEL} for the Delete key, and @key{LFD} for the Line-Feed key.
  469. (If you don't have the @key{LFD} or @key{TAB} keys on your keyboard,
  470. the @kbd{C-j} and @kbd{C-i} keys are equivalent to them, respectively.
  471. If you don't have a Meta key, look for Alt or Extend Char. You can
  472. also press @key{ESC} or @key{C-[} first to get the same effect, so
  473. that @kbd{M-x}, @kbd{@key{ESC} x}, and @kbd{C-[ x} are all equivalent.)
  474. Sometimes the @key{RET} key is not shown when it is ``obvious''
  475. that you must press @key{RET} to proceed. For example, the @key{RET}
  476. is usually omitted in key sequences like @kbd{M-x calc-keypad @key{RET}}.
  477. Commands are generally shown like this: @kbd{p} (@code{calc-precision})
  478. or @kbd{M-# k} (@code{calc-keypad}). This means that the command is
  479. normally used by pressing the @kbd{p} key or @kbd{M-# k} key sequence,
  480. but it also has the full-name equivalent shown, e.g., @kbd{M-x calc-precision}.
  481. Commands that correspond to functions in algebraic notation
  482. are written: @kbd{C} (@code{calc-cos}) [@code{cos}]. This means
  483. the @kbd{C} key is equivalent to @kbd{M-x calc-cos}, and that
  484. the corresponding function in an algebraic-style formula would
  485. be @samp{cos(@var{x})}.
  486. A few commands don't have key equivalents: @code{calc-sincos}
  487. [@code{sincos}].@refill
  488. @node Demonstration of Calc, Using Calc, Notations Used in This Manual, Getting Started
  489. @section A Demonstration of Calc
  490. @noindent
  491. @cindex Demonstration of Calc
  492. This section will show some typical small problems being solved with
  493. Calc. The focus is more on demonstration than explanation, but
  494. everything you see here will be covered more thoroughly in the
  495. Tutorial.
  496. To begin, start Emacs if necessary (usually the command @code{emacs}
  497. does this), and type @kbd{M-# c} (or @kbd{@key{ESC} # c}) to start the
  498. Calculator. (@xref{Starting Calc}, if this doesn't work for you.)
  499. Be sure to type all the sample input exactly, especially noting the
  500. difference between lower-case and upper-case letters. Remember,
  501. @key{RET}, @key{TAB}, @key{DEL}, and @key{SPC} are the Return, Tab,
  502. Delete, and Space keys.
  503. @strong{RPN calculation.} In RPN, you type the input number(s) first,
  504. then the command to operate on the numbers.
  505. @noindent
  506. Type @kbd{2 @key{RET} 3 + Q} to compute @c{$\sqrt{2+3} = 2.2360679775$}
  507. @asis{the square root of 2+3, which is 2.2360679775}.
  508. @noindent
  509. Type @kbd{P 2 ^} to compute @c{$\pi^2 = 9.86960440109$}
  510. @asis{the value of `pi' squared, 9.86960440109}.
  511. @noindent
  512. Type @key{TAB} to exchange the order of these two results.
  513. @noindent
  514. Type @kbd{- I H S} to subtract these results and compute the Inverse
  515. Hyperbolic sine of the difference, 2.72996136574.
  516. @noindent
  517. Type @key{DEL} to erase this result.
  518. @strong{Algebraic calculation.} You can also enter calculations using
  519. conventional ``algebraic'' notation. To enter an algebraic formula,
  520. use the apostrophe key.
  521. @noindent
  522. Type @kbd{' sqrt(2+3) @key{RET}} to compute @c{$\sqrt{2+3}$}
  523. @asis{the square root of 2+3}.
  524. @noindent
  525. Type @kbd{' pi^2 @key{RET}} to enter @c{$\pi^2$}
  526. @asis{`pi' squared}. To evaluate this symbolic
  527. formula as a number, type @kbd{=}.
  528. @noindent
  529. Type @kbd{' arcsinh($ - $$) @key{RET}} to subtract the second-most-recent
  530. result from the most-recent and compute the Inverse Hyperbolic sine.
  531. @strong{Keypad mode.} If you are using the X window system, press
  532. @w{@kbd{M-# k}} to get Keypad mode. (If you don't use X, skip to
  533. the next section.)
  534. @noindent
  535. Click on the @key{2}, @key{ENTER}, @key{3}, @key{+}, and @key{SQRT}
  536. ``buttons'' using your left mouse button.
  537. @noindent
  538. Click on @key{PI}, @key{2}, and @t{y^x}.
  539. @noindent
  540. Click on @key{INV}, then @key{ENTER} to swap the two results.
  541. @noindent
  542. Click on @key{-}, @key{INV}, @key{HYP}, and @key{SIN}.
  543. @noindent
  544. Click on @key{<-} to erase the result, then click @key{OFF} to turn
  545. the Keypad Calculator off.
  546. @strong{Grabbing data.} Type @kbd{M-# x} if necessary to exit Calc.
  547. Now select the following numbers as an Emacs region: ``Mark'' the
  548. front of the list by typing @kbd{C-@key{SPC}} or @kbd{C-@@} there,
  549. then move to the other end of the list. (Either get this list from
  550. the on-line copy of this manual, accessed by @w{@kbd{M-# i}}, or just
  551. type these numbers into a scratch file.) Now type @kbd{M-# g} to
  552. ``grab'' these numbers into Calc.
  553. @example
  554. @group
  555. 1.23 1.97
  556. 1.6 2
  557. 1.19 1.08
  558. @end group
  559. @end example
  560. @noindent
  561. The result @samp{[1.23, 1.97, 1.6, 2, 1.19, 1.08]} is a Calc ``vector.''
  562. Type @w{@kbd{V R +}} to compute the sum of these numbers.
  563. @noindent
  564. Type @kbd{U} to Undo this command, then type @kbd{V R *} to compute
  565. the product of the numbers.
  566. @noindent
  567. You can also grab data as a rectangular matrix. Place the cursor on
  568. the upper-leftmost @samp{1} and set the mark, then move to just after
  569. the lower-right @samp{8} and press @kbd{M-# r}.
  570. @noindent
  571. Type @kbd{v t} to transpose this @c{$3\times2$}
  572. @asis{3x2} matrix into a @c{$2\times3$}
  573. @asis{2x3} matrix. Type
  574. @w{@kbd{v u}} to unpack the rows into two separate vectors. Now type
  575. @w{@kbd{V R + @key{TAB} V R +}} to compute the sums of the two original columns.
  576. (There is also a special grab-and-sum-columns command, @kbd{M-# :}.)
  577. @strong{Units conversion.} Units are entered algebraically.
  578. Type @w{@kbd{' 43 mi/hr @key{RET}}} to enter the quantity 43 miles-per-hour.
  579. Type @w{@kbd{u c km/hr @key{RET}}}. Type @w{@kbd{u c m/s @key{RET}}}.
  580. @strong{Date arithmetic.} Type @kbd{t N} to get the current date and
  581. time. Type @kbd{90 +} to find the date 90 days from now. Type
  582. @kbd{' <25 dec 87> @key{RET}} to enter a date, then @kbd{- 7 /} to see how
  583. many weeks have passed since then.
  584. @strong{Algebra.} Algebraic entries can also include formulas
  585. or equations involving variables. Type @kbd{@w{' [x + y} = a, x y = 1] @key{RET}}
  586. to enter a pair of equations involving three variables.
  587. (Note the leading apostrophe in this example; also, note that the space
  588. between @samp{x y} is required.) Type @w{@kbd{a S x,y @key{RET}}} to solve
  589. these equations for the variables @cite{x} and @cite{y}.@refill
  590. @noindent
  591. Type @kbd{d B} to view the solutions in more readable notation.
  592. Type @w{@kbd{d C}} to view them in C language notation, and @kbd{d T}
  593. to view them in the notation for the @TeX{} typesetting system.
  594. Type @kbd{d N} to return to normal notation.
  595. @noindent
  596. Type @kbd{7.5}, then @kbd{s l a @key{RET}} to let @cite{a = 7.5} in these formulas.
  597. (That's a letter @kbd{l}, not a numeral @kbd{1}.)
  598. @iftex
  599. @strong{Help functions.} You can read about any command in the on-line
  600. manual. Type @kbd{M-# c} to return to Calc after each of these
  601. commands: @kbd{h k t N} to read about the @kbd{t N} command,
  602. @kbd{h f sqrt @key{RET}} to read about the @code{sqrt} function, and
  603. @kbd{h s} to read the Calc summary.
  604. @end iftex
  605. @ifinfo
  606. @strong{Help functions.} You can read about any command in the on-line
  607. manual. Remember to type the letter @kbd{l}, then @kbd{M-# c}, to
  608. return here after each of these commands: @w{@kbd{h k t N}} to read
  609. about the @w{@kbd{t N}} command, @kbd{h f sqrt @key{RET}} to read about the
  610. @code{sqrt} function, and @kbd{h s} to read the Calc summary.
  611. @end ifinfo
  612. Press @key{DEL} repeatedly to remove any leftover results from the stack.
  613. To exit from Calc, press @kbd{q} or @kbd{M-# c} again.
  614. @node Using Calc, History and Acknowledgements, Demonstration of Calc, Getting Started
  615. @section Using Calc
  616. @noindent
  617. Calc has several user interfaces that are specialized for
  618. different kinds of tasks. As well as Calc's standard interface,
  619. there are Quick Mode, Keypad Mode, and Embedded Mode.
  620. @c [fix-ref Installation]
  621. Calc must be @dfn{installed} before it can be used. @xref{Installation},
  622. for instructions on setting up and installing Calc. We will assume
  623. you or someone on your system has already installed Calc as described
  624. there.
  625. @menu
  626. * Starting Calc::
  627. * The Standard Interface::
  628. * Quick Mode Overview::
  629. * Keypad Mode Overview::
  630. * Standalone Operation::
  631. * Embedded Mode Overview::
  632. * Other M-# Commands::
  633. @end menu
  634. @node Starting Calc, The Standard Interface, Using Calc, Using Calc
  635. @subsection Starting Calc
  636. @noindent
  637. On most systems, you can type @kbd{M-#} to start the Calculator.
  638. The notation @kbd{M-#} is short for Meta-@kbd{#}. On most
  639. keyboards this means holding down the Meta (or Alt) and
  640. Shift keys while typing @kbd{3}.
  641. @cindex META key
  642. Once again, if you don't have a Meta key on your keyboard you can type
  643. @key{ESC} first, then @kbd{#}, to accomplish the same thing. If you
  644. don't even have an @key{ESC} key, you can fake it by holding down
  645. Control or @key{CTRL} while typing a left square bracket
  646. (that's @kbd{C-[} in Emacs notation).@refill
  647. @kbd{M-#} is a @dfn{prefix key}; when you press it, Emacs waits for
  648. you to press a second key to complete the command. In this case,
  649. you will follow @kbd{M-#} with a letter (upper- or lower-case, it
  650. doesn't matter for @kbd{M-#}) that says which Calc interface you
  651. want to use.
  652. To get Calc's standard interface, type @kbd{M-# c}. To get
  653. Keypad Mode, type @kbd{M-# k}. Type @kbd{M-# ?} to get a brief
  654. list of the available options, and type a second @kbd{?} to get
  655. a complete list.
  656. To ease typing, @kbd{M-# M-#} (or @kbd{M-# #} if that's easier)
  657. also works to start Calc. It starts the same interface (either
  658. @kbd{M-# c} or @w{@kbd{M-# k}}) that you last used, selecting the
  659. @kbd{M-# c} interface by default. (If your installation has
  660. a special function key set up to act like @kbd{M-#}, hitting that
  661. function key twice is just like hitting @kbd{M-# M-#}.)
  662. If @kbd{M-#} doesn't work for you, you can always type explicit
  663. commands like @kbd{M-x calc} (for the standard user interface) or
  664. @w{@kbd{M-x calc-keypad}} (for Keypad Mode). First type @kbd{M-x}
  665. (that's Meta with the letter @kbd{x}), then, at the prompt,
  666. type the full command (like @kbd{calc-keypad}) and press Return.
  667. If you type @kbd{M-x calc} and Emacs still doesn't recognize the
  668. command (it will say @samp{[No match]} when you try to press
  669. @key{RET}), then Calc has not been properly installed.
  670. The same commands (like @kbd{M-# c} or @kbd{M-# M-#}) that start
  671. the Calculator also turn it off if it is already on.
  672. @node The Standard Interface, Quick Mode Overview, Starting Calc, Using Calc
  673. @subsection The Standard Calc Interface
  674. @noindent
  675. @cindex Standard user interface
  676. Calc's standard interface acts like a traditional RPN calculator,
  677. operated by the normal Emacs keyboard. When you type @kbd{M-# c}
  678. to start the Calculator, the Emacs screen splits into two windows
  679. with the file you were editing on top and Calc on the bottom.
  680. @smallexample
  681. @group
  682. ...
  683. --**-Emacs: myfile (Fundamental)----All----------------------
  684. --- Emacs Calculator Mode --- |Emacs Calc Mode v2.00...
  685. 2: 17.3 | 17.3
  686. 1: -5 | 3
  687. . | 2
  688. | 4
  689. | * 8
  690. | ->-5
  691. |
  692. --%%-Calc: 12 Deg (Calculator)----All----- --%%-Emacs: *Calc Trail*
  693. @end group
  694. @end smallexample
  695. In this figure, the mode-line for @file{myfile} has moved up and the
  696. ``Calculator'' window has appeared below it. As you can see, Calc
  697. actually makes two windows side-by-side. The lefthand one is
  698. called the @dfn{stack window} and the righthand one is called the
  699. @dfn{trail window.} The stack holds the numbers involved in the
  700. calculation you are currently performing. The trail holds a complete
  701. record of all calculations you have done. In a desk calculator with
  702. a printer, the trail corresponds to the paper tape that records what
  703. you do.
  704. In this case, the trail shows that four numbers (17.3, 3, 2, and 4)
  705. were first entered into the Calculator, then the 2 and 4 were
  706. multiplied to get 8, then the 3 and 8 were subtracted to get @i{-5}.
  707. (The @samp{>} symbol shows that this was the most recent calculation.)
  708. The net result is the two numbers 17.3 and @i{-5} sitting on the stack.
  709. Most Calculator commands deal explicitly with the stack only, but
  710. there is a set of commands that allow you to search back through
  711. the trail and retrieve any previous result.
  712. Calc commands use the digits, letters, and punctuation keys.
  713. Shifted (i.e., upper-case) letters are different from lowercase
  714. letters. Some letters are @dfn{prefix} keys that begin two-letter
  715. commands. For example, @kbd{e} means ``enter exponent'' and shifted
  716. @kbd{E} means @cite{e^x}. With the @kbd{d} (``display modes'') prefix
  717. the letter ``e'' takes on very different meanings: @kbd{d e} means
  718. ``engineering notation'' and @kbd{d E} means ``@dfn{eqn} language mode.''
  719. There is nothing stopping you from switching out of the Calc
  720. window and back into your editing window, say by using the Emacs
  721. @w{@kbd{C-x o}} (@code{other-window}) command. When the cursor is
  722. inside a regular window, Emacs acts just like normal. When the
  723. cursor is in the Calc stack or trail windows, keys are interpreted
  724. as Calc commands.
  725. When you quit by pressing @kbd{M-# c} a second time, the Calculator
  726. windows go away but the actual Stack and Trail are not gone, just
  727. hidden. When you press @kbd{M-# c} once again you will get the
  728. same stack and trail contents you had when you last used the
  729. Calculator.
  730. The Calculator does not remember its state between Emacs sessions.
  731. Thus if you quit Emacs and start it again, @kbd{M-# c} will give you
  732. a fresh stack and trail. There is a command (@kbd{m m}) that lets
  733. you save your favorite mode settings between sessions, though.
  734. One of the things it saves is which user interface (standard or
  735. Keypad) you last used; otherwise, a freshly started Emacs will
  736. always treat @kbd{M-# M-#} the same as @kbd{M-# c}.
  737. The @kbd{q} key is another equivalent way to turn the Calculator off.
  738. If you type @kbd{M-# b} first and then @kbd{M-# c}, you get a
  739. full-screen version of Calc (@code{full-calc}) in which the stack and
  740. trail windows are still side-by-side but are now as tall as the whole
  741. Emacs screen. When you press @kbd{q} or @kbd{M-# c} again to quit,
  742. the file you were editing before reappears. The @kbd{M-# b} key
  743. switches back and forth between ``big'' full-screen mode and the
  744. normal partial-screen mode.
  745. Finally, @kbd{M-# o} (@code{calc-other-window}) is like @kbd{M-# c}
  746. except that the Calc window is not selected. The buffer you were
  747. editing before remains selected instead. @kbd{M-# o} is a handy
  748. way to switch out of Calc momentarily to edit your file; type
  749. @kbd{M-# c} to switch back into Calc when you are done.
  750. @node Quick Mode Overview, Keypad Mode Overview, The Standard Interface, Using Calc
  751. @subsection Quick Mode (Overview)
  752. @noindent
  753. @dfn{Quick Mode} is a quick way to use Calc when you don't need the
  754. full complexity of the stack and trail. To use it, type @kbd{M-# q}
  755. (@code{quick-calc}) in any regular editing buffer.
  756. Quick Mode is very simple: It prompts you to type any formula in
  757. standard algebraic notation (like @samp{4 - 2/3}) and then displays
  758. the result at the bottom of the Emacs screen (@i{3.33333333333}
  759. in this case). You are then back in the same editing buffer you
  760. were in before, ready to continue editing or to type @kbd{M-# q}
  761. again to do another quick calculation. The result of the calculation
  762. will also be in the Emacs ``kill ring'' so that a @kbd{C-y} command
  763. at this point will yank the result into your editing buffer.
  764. Calc mode settings affect Quick Mode, too, though you will have to
  765. go into regular Calc (with @kbd{M-# c}) to change the mode settings.
  766. @c [fix-ref Quick Calculator mode]
  767. @xref{Quick Calculator}, for further information.
  768. @node Keypad Mode Overview, Standalone Operation, Quick Mode Overview, Using Calc
  769. @subsection Keypad Mode (Overview)
  770. @noindent
  771. @dfn{Keypad Mode} is a mouse-based interface to the Calculator.
  772. It is designed for use with the X window system. If you don't
  773. have X, you will have to operate keypad mode with your arrow
  774. keys (which is probably more trouble than it's worth). Keypad
  775. mode is currently not supported under Emacs 19.
  776. Type @kbd{M-# k} to turn Keypad Mode on or off. Once again you
  777. get two new windows, this time on the righthand side of the screen
  778. instead of at the bottom. The upper window is the familiar Calc
  779. Stack; the lower window is a picture of a typical calculator keypad.
  780. @tex
  781. \dimen0=\pagetotal%
  782. \advance \dimen0 by 24\baselineskip%
  783. \ifdim \dimen0>\pagegoal \vfill\eject \fi%
  784. \medskip
  785. @end tex
  786. @smallexample
  787. |--- Emacs Calculator Mode ---
  788. |2: 17.3
  789. |1: -5
  790. | .
  791. |--%%-Calc: 12 Deg (Calcul
  792. |----+-----Calc 2.00-----+----1
  793. |FLR |CEIL|RND |TRNC|CLN2|FLT |
  794. |----+----+----+----+----+----|
  795. | LN |EXP | |ABS |IDIV|MOD |
  796. |----+----+----+----+----+----|
  797. |SIN |COS |TAN |SQRT|y^x |1/x |
  798. |----+----+----+----+----+----|
  799. | ENTER |+/- |EEX |UNDO| <- |
  800. |-----+---+-+--+--+-+---++----|
  801. | INV | 7 | 8 | 9 | / |
  802. |-----+-----+-----+-----+-----|
  803. | HYP | 4 | 5 | 6 | * |
  804. |-----+-----+-----+-----+-----|
  805. |EXEC | 1 | 2 | 3 | - |
  806. |-----+-----+-----+-----+-----|
  807. | OFF | 0 | . | PI | + |
  808. |-----+-----+-----+-----+-----+
  809. @end smallexample
  810. Keypad Mode is much easier for beginners to learn, because there
  811. is no need to memorize lots of obscure key sequences. But not all
  812. commands in regular Calc are available on the Keypad. You can
  813. always switch the cursor into the Calc stack window to use
  814. standard Calc commands if you need. Serious Calc users, though,
  815. often find they prefer the standard interface over Keypad Mode.
  816. To operate the Calculator, just click on the ``buttons'' of the
  817. keypad using your left mouse button. To enter the two numbers
  818. shown here you would click @w{@kbd{1 7 .@: 3 ENTER 5 +/- ENTER}}; to
  819. add them together you would then click @kbd{+} (to get 12.3 on
  820. the stack).
  821. If you click the right mouse button, the top three rows of the
  822. keypad change to show other sets of commands, such as advanced
  823. math functions, vector operations, and operations on binary
  824. numbers.
  825. Because Keypad Mode doesn't use the regular keyboard, Calc leaves
  826. the cursor in your original editing buffer. You can type in
  827. this buffer in the usual way while also clicking on the Calculator
  828. keypad. One advantage of Keypad Mode is that you don't need an
  829. explicit command to switch between editing and calculating.
  830. If you press @kbd{M-# b} first, you get a full-screen Keypad Mode
  831. (@code{full-calc-keypad}) with three windows: The keypad in the lower
  832. left, the stack in the lower right, and the trail on top.
  833. @c [fix-ref Keypad Mode]
  834. @xref{Keypad Mode}, for further information.
  835. @node Standalone Operation, Embedded Mode Overview, Keypad Mode Overview, Using Calc
  836. @subsection Standalone Operation
  837. @noindent
  838. @cindex Standalone Operation
  839. If you are not in Emacs at the moment but you wish to use Calc,
  840. you must start Emacs first. If all you want is to run Calc, you
  841. can give the commands:
  842. @example
  843. emacs -f full-calc
  844. @end example
  845. @noindent
  846. or
  847. @example
  848. emacs -f full-calc-keypad
  849. @end example
  850. @noindent
  851. which run a full-screen Calculator (as if by @kbd{M-# b M-# c}) or
  852. a full-screen X-based Calculator (as if by @kbd{M-# b M-# k}).
  853. In standalone operation, quitting the Calculator (by pressing
  854. @kbd{q} or clicking on the keypad @key{EXIT} button) quits Emacs
  855. itself.
  856. @node Embedded Mode Overview, Other M-# Commands, Standalone Operation, Using Calc
  857. @subsection Embedded Mode (Overview)
  858. @noindent
  859. @dfn{Embedded Mode} is a way to use Calc directly from inside an
  860. editing buffer. Suppose you have a formula written as part of a
  861. document like this:
  862. @smallexample
  863. @group
  864. The derivative of
  865. ln(ln(x))
  866. is
  867. @end group
  868. @end smallexample
  869. @noindent
  870. and you wish to have Calc compute and format the derivative for
  871. you and store this derivative in the buffer automatically. To
  872. do this with Embedded Mode, first copy the formula down to where
  873. you want the result to be:
  874. @smallexample
  875. @group
  876. The derivative of
  877. ln(ln(x))
  878. is
  879. ln(ln(x))
  880. @end group
  881. @end smallexample
  882. Now, move the cursor onto this new formula and press @kbd{M-# e}.
  883. Calc will read the formula (using the surrounding blank lines to
  884. tell how much text to read), then push this formula (invisibly)
  885. onto the Calc stack. The cursor will stay on the formula in the
  886. editing buffer, but the buffer's mode line will change to look
  887. like the Calc mode line (with mode indicators like @samp{12 Deg}
  888. and so on). Even though you are still in your editing buffer,
  889. the keyboard now acts like the Calc keyboard, and any new result
  890. you get is copied from the stack back into the buffer. To take
  891. the derivative, you would type @kbd{a d x @key{RET}}.
  892. @smallexample
  893. @group
  894. The derivative of
  895. ln(ln(x))
  896. is
  897. 1 / ln(x) x
  898. @end group
  899. @end smallexample
  900. To make this look nicer, you might want to press @kbd{d =} to center
  901. the formula, and even @kbd{d B} to use ``big'' display mode.
  902. @smallexample
  903. @group
  904. The derivative of
  905. ln(ln(x))
  906. is
  907. % [calc-mode: justify: center]
  908. % [calc-mode: language: big]
  909. 1
  910. -------
  911. ln(x) x
  912. @end group
  913. @end smallexample
  914. Calc has added annotations to the file to help it remember the modes
  915. that were used for this formula. They are formatted like comments
  916. in the @TeX{} typesetting language, just in case you are using @TeX{}.
  917. (In this example @TeX{} is not being used, so you might want to move
  918. these comments up to the top of the file or otherwise put them out
  919. of the way.)
  920. As an extra flourish, we can add an equation number using a
  921. righthand label: Type @kbd{d @} (1) @key{RET}}.
  922. @smallexample
  923. @group
  924. % [calc-mode: justify: center]
  925. % [calc-mode: language: big]
  926. % [calc-mode: right-label: " (1)"]
  927. 1
  928. ------- (1)
  929. ln(x) x
  930. @end group
  931. @end smallexample
  932. To leave Embedded Mode, type @kbd{M-# e} again. The mode line
  933. and keyboard will revert to the way they were before. (If you have
  934. actually been trying this as you read along, you'll want to press
  935. @kbd{M-# 0} [with the digit zero] now to reset the modes you changed.)
  936. The related command @kbd{M-# w} operates on a single word, which
  937. generally means a single number, inside text. It uses any
  938. non-numeric characters rather than blank lines to delimit the
  939. formula it reads. Here's an example of its use:
  940. @smallexample
  941. A slope of one-third corresponds to an angle of 1 degrees.
  942. @end smallexample
  943. Place the cursor on the @samp{1}, then type @kbd{M-# w} to enable
  944. Embedded Mode on that number. Now type @kbd{3 /} (to get one-third),
  945. and @kbd{I T} (the Inverse Tangent converts a slope into an angle),
  946. then @w{@kbd{M-# w}} again to exit Embedded mode.
  947. @smallexample
  948. A slope of one-third corresponds to an angle of 18.4349488229 degrees.
  949. @end smallexample
  950. @c [fix-ref Embedded Mode]
  951. @xref{Embedded Mode}, for full details.
  952. @node Other M-# Commands, , Embedded Mode Overview, Using Calc
  953. @subsection Other @kbd{M-#} Commands
  954. @noindent
  955. Two more Calc-related commands are @kbd{M-# g} and @kbd{M-# r},
  956. which ``grab'' data from a selected region of a buffer into the
  957. Calculator. The region is defined in the usual Emacs way, by
  958. a ``mark'' placed at one end of the region, and the Emacs
  959. cursor or ``point'' placed at the other.
  960. The @kbd{M-# g} command reads the region in the usual left-to-right,
  961. top-to-bottom order. The result is packaged into a Calc vector
  962. of numbers and placed on the stack. Calc (in its standard
  963. user interface) is then started. Type @kbd{v u} if you want
  964. to unpack this vector into separate numbers on the stack. Also,
  965. @kbd{C-u M-# g} interprets the region as a single number or
  966. formula.
  967. The @kbd{M-# r} command reads a rectangle, with the point and
  968. mark defining opposite corners of the rectangle. The result
  969. is a matrix of numbers on the Calculator stack.
  970. Complementary to these is @kbd{M-# y}, which ``yanks'' the
  971. value at the top of the Calc stack back into an editing buffer.
  972. If you type @w{@kbd{M-# y}} while in such a buffer, the value is
  973. yanked at the current position. If you type @kbd{M-# y} while
  974. in the Calc buffer, Calc makes an educated guess as to which
  975. editing buffer you want to use. The Calc window does not have
  976. to be visible in order to use this command, as long as there
  977. is something on the Calc stack.
  978. Here, for reference, is the complete list of @kbd{M-#} commands.
  979. The shift, control, and meta keys are ignored for the keystroke
  980. following @kbd{M-#}.
  981. @noindent
  982. Commands for turning Calc on and off:
  983. @table @kbd
  984. @item #
  985. Turn Calc on or off, employing the same user interface as last time.
  986. @item C
  987. Turn Calc on or off using its standard bottom-of-the-screen
  988. interface. If Calc is already turned on but the cursor is not
  989. in the Calc window, move the cursor into the window.
  990. @item O
  991. Same as @kbd{C}, but don't select the new Calc window. If
  992. Calc is already turned on and the cursor is in the Calc window,
  993. move it out of that window.
  994. @item B
  995. Control whether @kbd{M-# c} and @kbd{M-# k} use the full screen.
  996. @item Q
  997. Use Quick Mode for a single short calculation.
  998. @item K
  999. Turn Calc Keypad mode on or off.
  1000. @item E
  1001. Turn Calc Embedded mode on or off at the current formula.
  1002. @item J
  1003. Turn Calc Embedded mode on or off, select the interesting part.
  1004. @item W
  1005. Turn Calc Embedded mode on or off at the current word (number).
  1006. @item Z
  1007. Turn Calc on in a user-defined way, as defined by a @kbd{Z I} command.
  1008. @item X
  1009. Quit Calc; turn off standard, Keypad, or Embedded mode if on.
  1010. (This is like @kbd{q} or @key{OFF} inside of Calc.)
  1011. @end table
  1012. @iftex
  1013. @sp 2
  1014. @end iftex
  1015. @noindent
  1016. Commands for moving data into and out of the Calculator:
  1017. @table @kbd
  1018. @item G
  1019. Grab the region into the Calculator as a vector.
  1020. @item R
  1021. Grab the rectangular region into the Calculator as a matrix.
  1022. @item :
  1023. Grab the rectangular region and compute the sums of its columns.
  1024. @item _
  1025. Grab the rectangular region and compute the sums of its rows.
  1026. @item Y
  1027. Yank a value from the Calculator into the current editing buffer.
  1028. @end table
  1029. @iftex
  1030. @sp 2
  1031. @end iftex
  1032. @noindent
  1033. Commands for use with Embedded Mode:
  1034. @table @kbd
  1035. @item A
  1036. ``Activate'' the current buffer. Locate all formulas that
  1037. contain @samp{:=} or @samp{=>} symbols and record their locations
  1038. so that they can be updated automatically as variables are changed.
  1039. @item D
  1040. Duplicate the current formula immediately below and select
  1041. the duplicate.
  1042. @item F
  1043. Insert a new formula at the current point.
  1044. @item N
  1045. Move the cursor to the next active formula in the buffer.
  1046. @item P
  1047. Move the cursor to the previous active formula in the buffer.
  1048. @item U
  1049. Update (i.e., as if by the @kbd{=} key) the formula at the current point.
  1050. @item `
  1051. Edit (as if by @code{calc-edit}) the formula at the current point.
  1052. @end table
  1053. @iftex
  1054. @sp 2
  1055. @end iftex
  1056. @noindent
  1057. Miscellaneous commands:
  1058. @table @kbd
  1059. @item I
  1060. Run the Emacs Info system to read the Calc manual.
  1061. (This is the same as @kbd{h i} inside of Calc.)
  1062. @item T
  1063. Run the Emacs Info system to read the Calc Tutorial.
  1064. @item S
  1065. Run the Emacs Info system to read the Calc Summary.
  1066. @item L
  1067. Load Calc entirely into memory. (Normally the various parts
  1068. are loaded only as they are needed.)
  1069. @item M
  1070. Read a region of written keystroke names (like @kbd{C-n a b c @key{RET}})
  1071. and record them as the current keyboard macro.
  1072. @item 0
  1073. (This is the ``zero'' digit key.) Reset the Calculator to
  1074. its default state: Empty stack, and default mode settings.
  1075. With any prefix argument, reset everything but the stack.
  1076. @end table
  1077. @node History and Acknowledgements, , Using Calc, Getting Started
  1078. @section History and Acknowledgements
  1079. @noindent
  1080. Calc was originally started as a two-week project to occupy a lull
  1081. in the author's schedule. Basically, a friend asked if I remembered
  1082. the value of @c{$2^{32}$}
  1083. @cite{2^32}. I didn't offhand, but I said, ``that's
  1084. easy, just call up an @code{xcalc}.'' @code{Xcalc} duly reported
  1085. that the answer to our question was @samp{4.294967e+09}---with no way to
  1086. see the full ten digits even though we knew they were there in the
  1087. program's memory! I was so annoyed, I vowed to write a calculator
  1088. of my own, once and for all.
  1089. I chose Emacs Lisp, a) because I had always been curious about it
  1090. and b) because, being only a text editor extension language after
  1091. all, Emacs Lisp would surely reach its limits long before the project
  1092. got too far out of hand.
  1093. To make a long story short, Emacs Lisp turned out to be a distressingly
  1094. solid implementation of Lisp, and the humble task of calculating
  1095. turned out to be more open-ended than one might have expected.
  1096. Emacs Lisp doesn't have built-in floating point math, so it had to be
  1097. simulated in software. In fact, Emacs integers will only comfortably
  1098. fit six decimal digits or so---not enough for a decent calculator. So
  1099. I had to write my own high-precision integer code as well, and once I had
  1100. this I figured that arbitrary-size integers were just as easy as large
  1101. integers. Arbitrary floating-point precision was the logical next step.
  1102. Also, since the large integer arithmetic was there anyway it seemed only
  1103. fair to give the user direct access to it, which in turn made it practical
  1104. to support fractions as well as floats. All these features inspired me
  1105. to look around for other data types that might be worth having.
  1106. Around this time, my friend Rick Koshi showed me his nifty new HP-28
  1107. calculator. It allowed the user to manipulate formulas as well as
  1108. numerical quantities, and it could also operate on matrices. I decided
  1109. that these would be good for Calc to have, too. And once things had
  1110. gone this far, I figured I might as well take a look at serious algebra
  1111. systems like Mathematica, Macsyma, and Maple for further ideas. Since
  1112. these systems did far more than I could ever hope to implement, I decided
  1113. to focus on rewrite rules and other programming features so that users
  1114. could implement what they needed for themselves.
  1115. Rick complained that matrices were hard to read, so I put in code to
  1116. format them in a 2D style. Once these routines were in place, Big mode
  1117. was obligatory. Gee, what other language modes would be useful?
  1118. Scott Hemphill and Allen Knutson, two friends with a strong mathematical
  1119. bent, contributed ideas and algorithms for a number of Calc features
  1120. including modulo forms, primality testing, and float-to-fraction conversion.
  1121. Units were added at the eager insistence of Mass Sivilotti. Later,
  1122. Ulrich Mueller at CERN and Przemek Klosowski at NIST provided invaluable
  1123. expert assistance with the units table. As far as I can remember, the
  1124. idea of using algebraic formulas and variables to represent units dates
  1125. back to an ancient article in Byte magazine about muMath, an early
  1126. algebra system for microcomputers.
  1127. Many people have contributed to Calc by reporting bugs and suggesting
  1128. features, large and small. A few deserve special mention: Tim Peters,
  1129. who helped develop the ideas that led to the selection commands, rewrite
  1130. rules, and many other algebra features; @c{Fran\c cois}
  1131. @asis{Francois} Pinard, who contributed
  1132. an early prototype of the Calc Summary appendix as well as providing
  1133. valuable suggestions in many other areas of Calc; Carl Witty, whose eagle
  1134. eyes discovered many typographical and factual errors in the Calc manual;
  1135. Tim Kay, who drove the development of Embedded mode; Ove Ewerlid, who
  1136. made many suggestions relating to the algebra commands and contributed
  1137. some code for polynomial operations; Randal Schwartz, who suggested the
  1138. @code{calc-eval} function; Robert J. Chassell, who suggested the Calc
  1139. Tutorial and exercises; and Juha Sarlin, who first worked out how to split
  1140. Calc into quickly-loading parts. Bob Weiner helped immensely with the
  1141. Lucid Emacs port.
  1142. @cindex Bibliography
  1143. @cindex Knuth, Art of Computer Programming
  1144. @cindex Numerical Recipes
  1145. @c Should these be expanded into more complete references?
  1146. Among the books used in the development of Calc were Knuth's @emph{Art
  1147. of Computer Programming} (especially volume II, @emph{Seminumerical
  1148. Algorithms}); @emph{Numerical Recipes} by Press, Flannery, Teukolsky,
  1149. and Vetterling; Bevington's @emph{Data Reduction and Error Analysis for
  1150. the Physical Sciences}; @emph{Concrete Mathematics} by Graham, Knuth,
  1151. and Patashnik; Steele's @emph{Common Lisp, the Language}; the @emph{CRC
  1152. Standard Math Tables} (William H. Beyer, ed.); and Abramowitz and
  1153. Stegun's venerable @emph{Handbook of Mathematical Functions}. I
  1154. consulted the user's manuals for the HP-28 and HP-48 calculators, as
  1155. well as for the programs Mathematica, SMP, Macsyma, Maple, MathCAD,
  1156. Gnuplot, and others. Also, of course, Calc could not have been written
  1157. without the excellent @emph{GNU Emacs Lisp Reference Manual}, by Bil
  1158. Lewis and Dan LaLiberte.
  1159. Final thanks go to Richard Stallman, without whose fine implementations
  1160. of the Emacs editor, language, and environment, Calc would have been
  1161. finished in two weeks.
  1162. @c [tutorial]
  1163. @ifinfo
  1164. @c This node is accessed by the `M-# t' command.
  1165. @node Interactive Tutorial, , , Top
  1166. @chapter Tutorial
  1167. @noindent
  1168. Some brief instructions on using the Emacs Info system for this tutorial:
  1169. Press the space bar and Delete keys to go forward and backward in a
  1170. section by screenfuls (or use the regular Emacs scrolling commands
  1171. for this).
  1172. Press @kbd{n} or @kbd{p} to go to the Next or Previous section.
  1173. If the section has a @dfn{menu}, press a digit key like @kbd{1}
  1174. or @kbd{2} to go to a sub-section from the menu. Press @kbd{u} to
  1175. go back up from a sub-section to the menu it is part of.
  1176. Exercises in the tutorial all have cross-references to the
  1177. appropriate page of the ``answers'' section. Press @kbd{f}, then
  1178. the exercise number, to see the answer to an exercise. After
  1179. you have followed a cross-reference, you can press the letter
  1180. @kbd{l} to return to where you were before.
  1181. You can press @kbd{?} at any time for a brief summary of Info commands.
  1182. Press @kbd{1} now to enter the first section of the Tutorial.
  1183. @menu
  1184. * Tutorial::
  1185. @end menu
  1186. @end ifinfo
  1187. @node Tutorial, Introduction, Getting Started, Top
  1188. @chapter Tutorial
  1189. @noindent
  1190. This chapter explains how to use Calc and its many features, in
  1191. a step-by-step, tutorial way. You are encouraged to run Calc and
  1192. work along with the examples as you read (@pxref{Starting Calc}).
  1193. If you are already familiar with advanced calculators, you may wish
  1194. @c [not-split]
  1195. to skip on to the rest of this manual.
  1196. @c [when-split]
  1197. @c to skip on to volume II of this manual, the @dfn{Calc Reference}.
  1198. @c [fix-ref Embedded Mode]
  1199. This tutorial describes the standard user interface of Calc only.
  1200. The ``Quick Mode'' and ``Keypad Mode'' interfaces are fairly
  1201. self-explanatory. @xref{Embedded Mode}, for a description of
  1202. the ``Embedded Mode'' interface.
  1203. @ifinfo
  1204. The easiest way to read this tutorial on-line is to have two windows on
  1205. your Emacs screen, one with Calc and one with the Info system. (If you
  1206. have a printed copy of the manual you can use that instead.) Press
  1207. @kbd{M-# c} to turn Calc on or to switch into the Calc window, and
  1208. press @kbd{M-# i} to start the Info system or to switch into its window.
  1209. Or, you may prefer to use the tutorial in printed form.
  1210. @end ifinfo
  1211. @iftex
  1212. The easiest way to read this tutorial on-line is to have two windows on
  1213. your Emacs screen, one with Calc and one with the Info system. (If you
  1214. have a printed copy of the manual you can use that instead.) Press
  1215. @kbd{M-# c} to turn Calc on or to switch into the Calc window, and
  1216. press @kbd{M-# i} to start the Info system or to switch into its window.
  1217. @end iftex
  1218. This tutorial is designed to be done in sequence. But the rest of this
  1219. manual does not assume you have gone through the tutorial. The tutorial
  1220. does not cover everything in the Calculator, but it touches on most
  1221. general areas.
  1222. @ifinfo
  1223. You may wish to print out a copy of the Calc Summary and keep notes on
  1224. it as you learn Calc. @xref{Installation}, to see how to make a printed
  1225. summary. @xref{Summary}.
  1226. @end ifinfo
  1227. @iftex
  1228. The Calc Summary at the end of the reference manual includes some blank
  1229. space for your own use. You may wish to keep notes there as you learn
  1230. Calc.
  1231. @end iftex
  1232. @menu
  1233. * Basic Tutorial::
  1234. * Arithmetic Tutorial::
  1235. * Vector/Matrix Tutorial::
  1236. * Types Tutorial::
  1237. * Algebra Tutorial::
  1238. * Programming Tutorial::
  1239. * Answers to Exercises::
  1240. @end menu
  1241. @node Basic Tutorial, Arithmetic Tutorial, Tutorial, Tutorial
  1242. @section Basic Tutorial
  1243. @noindent
  1244. In this section, we learn how RPN and algebraic-style calculations
  1245. work, how to undo and redo an operation done by mistake, and how
  1246. to control various modes of the Calculator.
  1247. @menu
  1248. * RPN Tutorial:: Basic operations with the stack.
  1249. * Algebraic Tutorial:: Algebraic entry; variables.
  1250. * Undo Tutorial:: If you make a mistake: Undo and the trail.
  1251. * Modes Tutorial:: Common mode-setting commands.
  1252. @end menu
  1253. @node RPN Tutorial, Algebraic Tutorial, Basic Tutorial, Basic Tutorial
  1254. @subsection RPN Calculations and the Stack
  1255. @cindex RPN notation
  1256. @ifinfo
  1257. @noindent
  1258. Calc normally uses RPN notation. You may be familiar with the RPN
  1259. system from Hewlett-Packard calculators, FORTH, or PostScript.
  1260. (Reverse Polish Notation, RPN, is named after the Polish mathematician
  1261. Jan Lukasiewicz.)
  1262. @end ifinfo
  1263. @tex
  1264. \noindent
  1265. Calc normally uses RPN notation. You may be familiar with the RPN
  1266. system from Hewlett-Packard calculators, FORTH, or PostScript.
  1267. (Reverse Polish Notation, RPN, is named after the Polish mathematician
  1268. Jan \L ukasiewicz.)
  1269. @end tex
  1270. The central component of an RPN calculator is the @dfn{stack}. A
  1271. calculator stack is like a stack of dishes. New dishes (numbers) are
  1272. added at the top of the stack, and numbers are normally only removed
  1273. from the top of the stack.
  1274. @cindex Operators
  1275. @cindex Operands
  1276. In an operation like @cite{2+3}, the 2 and 3 are called the @dfn{operands}
  1277. and the @cite{+} is the @dfn{operator}. In an RPN calculator you always
  1278. enter the operands first, then the operator. Each time you type a
  1279. number, Calc adds or @dfn{pushes} it onto the top of the Stack.
  1280. When you press an operator key like @kbd{+}, Calc @dfn{pops} the appropriate
  1281. number of operands from the stack and pushes back the result.
  1282. Thus we could add the numbers 2 and 3 in an RPN calculator by typing:
  1283. @kbd{2 @key{RET} 3 @key{RET} +}. (The @key{RET} key, Return, corresponds to
  1284. the @key{ENTER} key on traditional RPN calculators.) Try this now if
  1285. you wish; type @kbd{M-# c} to switch into the Calc window (you can type
  1286. @kbd{M-# c} again or @kbd{M-# o} to switch back to the Tutorial window).
  1287. The first four keystrokes ``push'' the numbers 2 and 3 onto the stack.
  1288. The @kbd{+} key ``pops'' the top two numbers from the stack, adds them,
  1289. and pushes the result (5) back onto the stack. Here's how the stack
  1290. will look at various points throughout the calculation:@refill
  1291. @smallexample
  1292. @group
  1293. . 1: 2 2: 2 1: 5 .
  1294. . 1: 3 .
  1295. .
  1296. M-# c 2 @key{RET} 3 @key{RET} + @key{DEL}
  1297. @end group
  1298. @end smallexample
  1299. The @samp{.} symbol is a marker that represents the top of the stack.
  1300. Note that the ``top'' of the stack is really shown at the bottom of
  1301. the Stack window. This may seem backwards, but it turns out to be
  1302. less distracting in regular use.
  1303. @cindex Stack levels
  1304. @cindex Levels of stack
  1305. The numbers @samp{1:} and @samp{2:} on the left are @dfn{stack level
  1306. numbers}. Old RPN calculators always had four stack levels called
  1307. @cite{x}, @cite{y}, @cite{z}, and @cite{t}. Calc's stack can grow
  1308. as large as you like, so it uses numbers instead of letters. Some
  1309. stack-manipulation commands accept a numeric argument that says
  1310. which stack level to work on. Normal commands like @kbd{+} always
  1311. work on the top few levels of the stack.@refill
  1312. @c [fix-ref Truncating the Stack]
  1313. The Stack buffer is just an Emacs buffer, and you can move around in
  1314. it using the regular Emacs motion commands. But no matter where the
  1315. cursor is, even if you have scrolled the @samp{.} marker out of
  1316. view, most Calc commands always move the cursor back down to level 1
  1317. before doing anything. It is possible to move the @samp{.} marker
  1318. upwards through the stack, temporarily ``hiding'' some numbers from
  1319. commands like @kbd{+}. This is called @dfn{stack truncation} and
  1320. we will not cover it in this tutorial; @pxref{Truncating the Stack},
  1321. if you are interested.
  1322. You don't really need the second @key{RET} in @kbd{2 @key{RET} 3
  1323. @key{RET} +}. That's because if you type any operator name or
  1324. other non-numeric key when you are entering a number, the Calculator
  1325. automatically enters that number and then does the requested command.
  1326. Thus @kbd{2 @key{RET} 3 +} will work just as well.@refill
  1327. Examples in this tutorial will often omit @key{RET} even when the
  1328. stack displays shown would only happen if you did press @key{RET}:
  1329. @smallexample
  1330. @group
  1331. 1: 2 2: 2 1: 5
  1332. . 1: 3 .
  1333. .
  1334. 2 @key{RET} 3 +
  1335. @end group
  1336. @end smallexample
  1337. @noindent
  1338. Here, after pressing @kbd{3} the stack would really show @samp{1: 2}
  1339. with @samp{Calc:@: 3} in the minibuffer. In these situations, you can
  1340. press the optional @key{RET} to see the stack as the figure shows.
  1341. (@bullet{}) @strong{Exercise 1.} (This tutorial will include exercises
  1342. at various points. Try them if you wish. Answers to all the exercises
  1343. are located at the end of the Tutorial chapter. Each exercise will
  1344. include a cross-reference to its particular answer. If you are
  1345. reading with the Emacs Info system, press @kbd{f} and the
  1346. exercise number to go to the answer, then the letter @kbd{l} to
  1347. return to where you were.)
  1348. @noindent
  1349. Here's the first exercise: What will the keystrokes @kbd{1 @key{RET} 2
  1350. @key{RET} 3 @key{RET} 4 + * -} compute? (@samp{*} is the symbol for
  1351. multiplication.) Figure it out by hand, then try it with Calc to see
  1352. if you're right. @xref{RPN Answer 1, 1}. (@bullet{})
  1353. (@bullet{}) @strong{Exercise 2.} Compute @c{$(2\times4) + (7\times9.4) + {5\over4}$}
  1354. @cite{2*4 + 7*9.5 + 5/4} using the
  1355. stack. @xref{RPN Answer 2, 2}. (@bullet{})
  1356. The @key{DEL} key is called Backspace on some keyboards. It is
  1357. whatever key you would use to correct a simple typing error when
  1358. regularly using Emacs. The @key{DEL} key pops and throws away the
  1359. top value on the stack. (You can still get that value back from
  1360. the Trail if you should need it later on.) There are many places
  1361. in this tutorial where we assume you have used @key{DEL} to erase the
  1362. results of the previous example at the beginning of a new example.
  1363. In the few places where it is really important to use @key{DEL} to
  1364. clear away old results, the text will remind you to do so.
  1365. (It won't hurt to let things accumulate on the stack, except that
  1366. whenever you give a display-mode-changing command Calc will have to
  1367. spend a long time reformatting such a large stack.)
  1368. Since the @kbd{-} key is also an operator (it subtracts the top two
  1369. stack elements), how does one enter a negative number? Calc uses
  1370. the @kbd{_} (underscore) key to act like the minus sign in a number.
  1371. So, typing @kbd{-5 @key{RET}} won't work because the @kbd{-} key
  1372. will try to do a subtraction, but @kbd{_5 @key{RET}} works just fine.
  1373. You can also press @kbd{n}, which means ``change sign.'' It changes
  1374. the number at the top of the stack (or the number being entered)
  1375. from positive to negative or vice-versa: @kbd{5 n @key{RET}}.
  1376. @cindex Duplicating a stack entry
  1377. If you press @key{RET} when you're not entering a number, the effect
  1378. is to duplicate the top number on the stack. Consider this calculation:
  1379. @smallexample
  1380. @group
  1381. 1: 3 2: 3 1: 9 2: 9 1: 81
  1382. . 1: 3 . 1: 9 .
  1383. . .
  1384. 3 @key{RET} @key{RET} * @key{RET} *
  1385. @end group
  1386. @end smallexample
  1387. @noindent
  1388. (Of course, an easier way to do this would be @kbd{3 @key{RET} 4 ^},
  1389. to raise 3 to the fourth power.)
  1390. The space-bar key (denoted @key{SPC} here) performs the same function
  1391. as @key{RET}; you could replace all three occurrences of @key{RET} in
  1392. the above example with @key{SPC} and the effect would be the same.
  1393. @cindex Exchanging stack entries
  1394. Another stack manipulation key is @key{TAB}. This exchanges the top
  1395. two stack entries. Suppose you have computed @kbd{2 @key{RET} 3 +}
  1396. to get 5, and then you realize what you really wanted to compute
  1397. was @cite{20 / (2+3)}.
  1398. @smallexample
  1399. @group
  1400. 1: 5 2: 5 2: 20 1: 4
  1401. . 1: 20 1: 5 .
  1402. . .
  1403. 2 @key{RET} 3 + 20 @key{TAB} /
  1404. @end group
  1405. @end smallexample
  1406. @noindent
  1407. Planning ahead, the calculation would have gone like this:
  1408. @smallexample
  1409. @group
  1410. 1: 20 2: 20 3: 20 2: 20 1: 4
  1411. . 1: 2 2: 2 1: 5 .
  1412. . 1: 3 .
  1413. .
  1414. 20 @key{RET} 2 @key{RET} 3 + /
  1415. @end group
  1416. @end smallexample
  1417. A related stack command is @kbd{M-@key{TAB}} (hold @key{META} and type
  1418. @key{TAB}). It rotates the top three elements of the stack upward,
  1419. bringing the object in level 3 to the top.
  1420. @smallexample
  1421. @group
  1422. 1: 10 2: 10 3: 10 3: 20 3: 30
  1423. . 1: 20 2: 20 2: 30 2: 10
  1424. . 1: 30 1: 10 1: 20
  1425. . . .
  1426. 10 @key{RET} 20 @key{RET} 30 @key{RET} M-@key{TAB} M-@key{TAB}
  1427. @end group
  1428. @end smallexample
  1429. (@bullet{}) @strong{Exercise 3.} Suppose the numbers 10, 20, and 30 are
  1430. on the stack. Figure out how to add one to the number in level 2
  1431. without affecting the rest of the stack. Also figure out how to add
  1432. one to the number in level 3. @xref{RPN Answer 3, 3}. (@bullet{})
  1433. Operations like @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, and @kbd{^} pop two
  1434. arguments from the stack and push a result. Operations like @kbd{n} and
  1435. @kbd{Q} (square root) pop a single number and push the result. You can
  1436. think of them as simply operating on the top element of the stack.
  1437. @smallexample
  1438. @group
  1439. 1: 3 1: 9 2: 9 1: 25 1: 5
  1440. . . 1: 16 . .
  1441. .
  1442. 3 @key{RET} @key{RET} * 4 @key{RET} @key{RET} * + Q
  1443. @end group
  1444. @end smallexample
  1445. @noindent
  1446. (Note that capital @kbd{Q} means to hold down the Shift key while
  1447. typing @kbd{q}. Remember, plain unshifted @kbd{q} is the Quit command.)
  1448. @cindex Pythagorean Theorem
  1449. Here we've used the Pythagorean Theorem to determine the hypotenuse of a
  1450. right triangle. Calc actually has a built-in command for that called
  1451. @kbd{f h}, but let's suppose we can't remember the necessary keystrokes.
  1452. We can still enter it by its full name using @kbd{M-x} notation:
  1453. @smallexample
  1454. @group
  1455. 1: 3 2: 3 1: 5
  1456. . 1: 4 .
  1457. .
  1458. 3 @key{RET} 4 @key{RET} M-x calc-hypot
  1459. @end group
  1460. @end smallexample
  1461. All Calculator commands begin with the word @samp{calc-}. Since it
  1462. gets tiring to type this, Calc provides an @kbd{x} key which is just
  1463. like the regular Emacs @kbd{M-x} key except that it types the @samp{calc-}
  1464. prefix for you:
  1465. @smallexample
  1466. @group
  1467. 1: 3 2: 3 1: 5
  1468. . 1: 4 .
  1469. .
  1470. 3 @key{RET} 4 @key{RET} x hypot
  1471. @end group
  1472. @end smallexample
  1473. What happens if you take the square root of a negative number?
  1474. @smallexample
  1475. @group
  1476. 1: 4 1: -4 1: (0, 2)
  1477. . . .
  1478. 4 @key{RET} n Q
  1479. @end group
  1480. @end smallexample
  1481. @noindent
  1482. The notation @cite{(a, b)} represents a complex number.
  1483. Complex numbers are more traditionally written @c{$a + b i$}
  1484. @cite{a + b i};
  1485. Calc can display in this format, too, but for now we'll stick to the
  1486. @cite{(a, b)} notation.
  1487. If you don't know how complex numbers work, you can safely ignore this
  1488. feature. Complex numbers only arise from operations that would be
  1489. errors in a calculator that didn't have complex numbers. (For example,
  1490. taking the square root or logarithm of a negative number produces a
  1491. complex result.)
  1492. Complex numbers are entered in the notation shown. The @kbd{(} and
  1493. @kbd{,} and @kbd{)} keys manipulate ``incomplete complex numbers.''
  1494. @smallexample
  1495. @group
  1496. 1: ( ... 2: ( ... 1: (2, ... 1: (2, ... 1: (2, 3)
  1497. . 1: 2 . 3 .
  1498. . .
  1499. ( 2 , 3 )
  1500. @end group
  1501. @end smallexample
  1502. You can perform calculations while entering parts of incomplete objects.
  1503. However, an incomplete object cannot actually participate in a calculation:
  1504. @smallexample
  1505. @group
  1506. 1: ( ... 2: ( ... 3: ( ... 1: ( ... 1: ( ...
  1507. . 1: 2 2: 2 5 5
  1508. . 1: 3 . .
  1509. .
  1510. (error)
  1511. ( 2 @key{RET} 3 + +
  1512. @end group
  1513. @end smallexample
  1514. @noindent
  1515. Adding 5 to an incomplete object makes no sense, so the last command
  1516. produces an error message and leaves the stack the same.
  1517. Incomplete objects can't participate in arithmetic, but they can be
  1518. moved around by the regular stack commands.
  1519. @smallexample
  1520. @group
  1521. 2: 2 3: 2 3: 3 1: ( ... 1: (2, 3)
  1522. 1: 3 2: 3 2: ( ... 2 .
  1523. . 1: ( ... 1: 2 3
  1524. . . .
  1525. 2 @key{RET} 3 @key{RET} ( M-@key{TAB} M-@key{TAB} )
  1526. @end group
  1527. @end smallexample
  1528. @noindent
  1529. Note that the @kbd{,} (comma) key did not have to be used here.
  1530. When you press @kbd{)} all the stack entries between the incomplete
  1531. entry and the top are collected, so there's never really a reason
  1532. to use the comma. It's up to you.
  1533. (@bullet{}) @strong{Exercise 4.} To enter the complex number @cite{(2, 3)},
  1534. your friend Joe typed @kbd{( 2 , @key{SPC} 3 )}. What happened?
  1535. (Joe thought of a clever way to correct his mistake in only two
  1536. keystrokes, but it didn't quite work. Try it to find out why.)
  1537. @xref{RPN Answer 4, 4}. (@bullet{})
  1538. Vectors are entered the same way as complex numbers, but with square
  1539. brackets in place of parentheses. We'll meet vectors again later in
  1540. the tutorial.
  1541. Any Emacs command can be given a @dfn{numeric prefix argument} by
  1542. typing a series of @key{META}-digits beforehand. If @key{META} is
  1543. awkward for you, you can instead type @kbd{C-u} followed by the
  1544. necessary digits. Numeric prefix arguments can be negative, as in
  1545. @kbd{M-- M-3 M-5} or @w{@kbd{C-u - 3 5}}. Calc commands use numeric
  1546. prefix arguments in a variety of ways. For example, a numeric prefix
  1547. on the @kbd{+} operator adds any number of stack entries at once:
  1548. @smallexample
  1549. @group
  1550. 1: 10 2: 10 3: 10 3: 10 1: 60
  1551. . 1: 20 2: 20 2: 20 .
  1552. . 1: 30 1: 30
  1553. . .
  1554. 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u 3 +
  1555. @end group
  1556. @end smallexample
  1557. For stack manipulation commands like @key{RET}, a positive numeric
  1558. prefix argument operates on the top @var{n} stack entries at once. A
  1559. negative argument operates on the entry in level @var{n} only. An
  1560. argument of zero operates on the entire stack. In this example, we copy
  1561. the second-to-top element of the stack:
  1562. @smallexample
  1563. @group
  1564. 1: 10 2: 10 3: 10 3: 10 4: 10
  1565. . 1: 20 2: 20 2: 20 3: 20
  1566. . 1: 30 1: 30 2: 30
  1567. . . 1: 20
  1568. .
  1569. 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u -2 @key{RET}
  1570. @end group
  1571. @end smallexample
  1572. @cindex Clearing the stack
  1573. @cindex Emptying the stack
  1574. Another common idiom is @kbd{M-0 @key{DEL}}, which clears the stack.
  1575. (The @kbd{M-0} numeric prefix tells @key{DEL} to operate on the
  1576. entire stack.)
  1577. @node Algebraic Tutorial, Undo Tutorial, RPN Tutorial, Basic Tutorial
  1578. @subsection Algebraic-Style Calculations
  1579. @noindent
  1580. If you are not used to RPN notation, you may prefer to operate the
  1581. Calculator in ``algebraic mode,'' which is closer to the way
  1582. non-RPN calculators work. In algebraic mode, you enter formulas
  1583. in traditional @cite{2+3} notation.
  1584. You don't really need any special ``mode'' to enter algebraic formulas.
  1585. You can enter a formula at any time by pressing the apostrophe (@kbd{'})
  1586. key. Answer the prompt with the desired formula, then press @key{RET}.
  1587. The formula is evaluated and the result is pushed onto the RPN stack.
  1588. If you don't want to think in RPN at all, you can enter your whole
  1589. computation as a formula, read the result from the stack, then press
  1590. @key{DEL} to delete it from the stack.
  1591. Try pressing the apostrophe key, then @kbd{2+3+4}, then @key{RET}.
  1592. The result should be the number 9.
  1593. Algebraic formulas use the operators @samp{+}, @samp{-}, @samp{*},
  1594. @samp{/}, and @samp{^}. You can use parentheses to make the order
  1595. of evaluation clear. In the absence of parentheses, @samp{^} is
  1596. evaluated first, then @samp{*}, then @samp{/}, then finally
  1597. @samp{+} and @samp{-}. For example, the expression
  1598. @example
  1599. 2 + 3*4*5 / 6*7^8 - 9
  1600. @end example
  1601. @noindent
  1602. is equivalent to
  1603. @example
  1604. 2 + ((3*4*5) / (6*(7^8)) - 9
  1605. @end example
  1606. @noindent
  1607. or, in large mathematical notation,
  1608. @ifinfo
  1609. @example
  1610. @group
  1611. 3 * 4 * 5
  1612. 2 + --------- - 9
  1613. 8
  1614. 6 * 7
  1615. @end group
  1616. @end example
  1617. @end ifinfo
  1618. @tex
  1619. \turnoffactive
  1620. \beforedisplay
  1621. $$ 2 + { 3 \times 4 \times 5 \over 6 \times 7^8 } - 9 $$
  1622. \afterdisplay
  1623. @end tex
  1624. @noindent
  1625. The result of this expression will be the number @i{-6.99999826533}.
  1626. Calc's order of evaluation is the same as for most computer languages,
  1627. except that @samp{*} binds more strongly than @samp{/}, as the above
  1628. example shows. As in normal mathematical notation, the @samp{*} symbol
  1629. can often be omitted: @samp{2 a} is the same as @samp{2*a}.
  1630. Operators at the same level are evaluated from left to right, except
  1631. that @samp{^} is evaluated from right to left. Thus, @samp{2-3-4} is
  1632. equivalent to @samp{(2-3)-4} or @i{-5}, whereas @samp{2^3^4} is equivalent
  1633. to @samp{2^(3^4)} (a very large integer; try it!).
  1634. If you tire of typing the apostrophe all the time, there is an
  1635. ``algebraic mode'' you can select in which Calc automatically senses
  1636. when you are about to type an algebraic expression. To enter this
  1637. mode, press the two letters @w{@kbd{m a}}. (An @samp{Alg} indicator
  1638. should appear in the Calc window's mode line.)
  1639. Press @kbd{m a}, then @kbd{2+3+4} with no apostrophe, then @key{RET}.
  1640. In algebraic mode, when you press any key that would normally begin
  1641. entering a number (such as a digit, a decimal point, or the @kbd{_}
  1642. key), or if you press @kbd{(} or @kbd{[}, Calc automatically begins
  1643. an algebraic entry.
  1644. Functions which do not have operator symbols like @samp{+} and @samp{*}
  1645. must be entered in formulas using function-call notation. For example,
  1646. the function name corresponding to the square-root key @kbd{Q} is
  1647. @code{sqrt}. To compute a square root in a formula, you would use
  1648. the notation @samp{sqrt(@var{x})}.
  1649. Press the apostrophe, then type @kbd{sqrt(5*2) - 3}. The result should
  1650. be @cite{0.16227766017}.
  1651. Note that if the formula begins with a function name, you need to use
  1652. the apostrophe even if you are in algebraic mode. If you type @kbd{arcsin}
  1653. out of the blue, the @kbd{a r} will be taken as an Algebraic Rewrite
  1654. command, and the @kbd{csin} will be taken as the name of the rewrite
  1655. rule to use!
  1656. Some people prefer to enter complex numbers and vectors in algebraic
  1657. form because they find RPN entry with incomplete objects to be too
  1658. distracting, even though they otherwise use Calc as an RPN calculator.
  1659. Still in algebraic mode, type:
  1660. @smallexample
  1661. @group
  1662. 1: (2, 3) 2: (2, 3) 1: (8, -1) 2: (8, -1) 1: (9, -1)
  1663. . 1: (1, -2) . 1: 1 .
  1664. . .
  1665. (2,3) @key{RET} (1,-2) @key{RET} * 1 @key{RET} +
  1666. @end group
  1667. @end smallexample
  1668. Algebraic mode allows us to enter complex numbers without pressing
  1669. an apostrophe first, but it also means we need to press @key{RET}
  1670. after every entry, even for a simple number like @cite{1}.
  1671. (You can type @kbd{C-u m a} to enable a special ``incomplete algebraic
  1672. mode'' in which the @kbd{(} and @kbd{[} keys use algebraic entry even
  1673. though regular numeric keys still use RPN numeric entry. There is also
  1674. a ``total algebraic mode,'' started by typing @kbd{m t}, in which all
  1675. normal keys begin algebraic entry. You must then use the @key{META} key
  1676. to type Calc commands: @kbd{M-m t} to get back out of total algebraic
  1677. mode, @kbd{M-q} to quit, etc. Total algebraic mode is not supported
  1678. under Emacs 19.)
  1679. If you're still in algebraic mode, press @kbd{m a} again to turn it off.
  1680. Actual non-RPN calculators use a mixture of algebraic and RPN styles.
  1681. In general, operators of two numbers (like @kbd{+} and @kbd{*})
  1682. use algebraic form, but operators of one number (like @kbd{n} and @kbd{Q})
  1683. use RPN form. Also, a non-RPN calculator allows you to see the
  1684. intermediate results of a calculation as you go along. You can
  1685. accomplish this in Calc by performing your calculation as a series
  1686. of algebraic entries, using the @kbd{$} sign to tie them together.
  1687. In an algebraic formula, @kbd{$} represents the number on the top
  1688. of the stack. Here, we perform the calculation @c{$\sqrt{2\times4+1}$}
  1689. @cite{sqrt(2*4+1)},
  1690. which on a traditional calculator would be done by pressing
  1691. @kbd{2 * 4 + 1 =} and then the square-root key.
  1692. @smallexample
  1693. @group
  1694. 1: 8 1: 9 1: 3
  1695. . . .
  1696. ' 2*4 @key{RET} $+1 @key{RET} Q
  1697. @end group
  1698. @end smallexample
  1699. @noindent
  1700. Notice that we didn't need to press an apostrophe for the @kbd{$+1},
  1701. because the dollar sign always begins an algebraic entry.
  1702. (@bullet{}) @strong{Exercise 1.} How could you get the same effect as
  1703. pressing @kbd{Q} but using an algebraic entry instead? How about
  1704. if the @kbd{Q} key on your keyboard were broken?
  1705. @xref{Algebraic Answer 1, 1}. (@bullet{})
  1706. The notations @kbd{$$}, @kbd{$$$}, and so on stand for higher stack
  1707. entries. For example, @kbd{' $$+$ @key{RET}} is just like typing @kbd{+}.
  1708. Algebraic formulas can include @dfn{variables}. To store in a
  1709. variable, press @kbd{s s}, then type the variable name, then press
  1710. @key{RET}. (There are actually two flavors of store command:
  1711. @kbd{s s} stores a number in a variable but also leaves the number
  1712. on the stack, while @w{@kbd{s t}} removes a number from the stack and
  1713. stores it in the variable.) A variable name should consist of one
  1714. or more letters or digits, beginning with a letter.
  1715. @smallexample
  1716. @group
  1717. 1: 17 . 1: a + a^2 1: 306
  1718. . . .
  1719. 17 s t a @key{RET} ' a+a^2 @key{RET} =
  1720. @end group
  1721. @end smallexample
  1722. @noindent
  1723. The @kbd{=} key @dfn{evaluates} a formula by replacing all its
  1724. variables by the values that were stored in them.
  1725. For RPN calculations, you can recall a variable's value on the
  1726. stack either by entering its name as a formula and pressing @kbd{=},
  1727. or by using the @kbd{s r} command.
  1728. @smallexample
  1729. @group
  1730. 1: 17 2: 17 3: 17 2: 17 1: 306
  1731. . 1: 17 2: 17 1: 289 .
  1732. . 1: 2 .
  1733. .
  1734. s r a @key{RET} ' a @key{RET} = 2 ^ +
  1735. @end group
  1736. @end smallexample
  1737. If you press a single digit for a variable name (as in @kbd{s t 3}, you
  1738. get one of ten @dfn{quick variables} @code{q0} through @code{q9}.
  1739. They are ``quick'' simply because you don't have to type the letter
  1740. @code{q} or the @key{RET} after their names. In fact, you can type
  1741. simply @kbd{s 3} as a shorthand for @kbd{s s 3}, and likewise for
  1742. @kbd{t 3} and @w{@kbd{r 3}}.
  1743. Any variables in an algebraic formula for which you have not stored
  1744. values are left alone, even when you evaluate the formula.
  1745. @smallexample
  1746. @group
  1747. 1: 2 a + 2 b 1: 34 + 2 b
  1748. . .
  1749. ' 2a+2b @key{RET} =
  1750. @end group
  1751. @end smallexample
  1752. Calls to function names which are undefined in Calc are also left
  1753. alone, as are calls for which the value is undefined.
  1754. @smallexample
  1755. @group
  1756. 1: 2 + log10(0) + log10(x) + log10(5, 6) + foo(3)
  1757. .
  1758. ' log10(100) + log10(0) + log10(x) + log10(5,6) + foo(3) @key{RET}
  1759. @end group
  1760. @end smallexample
  1761. @noindent
  1762. In this example, the first call to @code{log10} works, but the other
  1763. calls are not evaluated. In the second call, the logarithm is
  1764. undefined for that value of the argument; in the third, the argument
  1765. is symbolic, and in the fourth, there are too many arguments. In the
  1766. fifth case, there is no function called @code{foo}. You will see a
  1767. ``Wrong number of arguments'' message referring to @samp{log10(5,6)}.
  1768. Press the @kbd{w} (``why'') key to see any other messages that may
  1769. have arisen from the last calculation. In this case you will get
  1770. ``logarithm of zero,'' then ``number expected: @code{x}''. Calc
  1771. automatically displays the first message only if the message is
  1772. sufficiently important; for example, Calc considers ``wrong number
  1773. of arguments'' and ``logarithm of zero'' to be important enough to
  1774. report automatically, while a message like ``number expected: @code{x}''
  1775. will only show up if you explicitly press the @kbd{w} key.
  1776. (@bullet{}) @strong{Exercise 2.} Joe entered the formula @samp{2 x y},
  1777. stored 5 in @code{x}, pressed @kbd{=}, and got the expected result,
  1778. @samp{10 y}. He then tried the same for the formula @samp{2 x (1+y)},
  1779. expecting @samp{10 (1+y)}, but it didn't work. Why not?
  1780. @xref{Algebraic Answer 2, 2}. (@bullet{})
  1781. (@bullet{}) @strong{Exercise 3.} What result would you expect
  1782. @kbd{1 @key{RET} 0 /} to give? What if you then type @kbd{0 *}?
  1783. @xref{Algebraic Answer 3, 3}. (@bullet{})
  1784. One interesting way to work with variables is to use the
  1785. @dfn{evaluates-to} (@samp{=>}) operator. It works like this:
  1786. Enter a formula algebraically in the usual way, but follow
  1787. the formula with an @samp{=>} symbol. (There is also an @kbd{s =}
  1788. command which builds an @samp{=>} formula using the stack.) On
  1789. the stack, you will see two copies of the formula with an @samp{=>}
  1790. between them. The lefthand formula is exactly like you typed it;
  1791. the righthand formula has been evaluated as if by typing @kbd{=}.
  1792. @smallexample
  1793. @group
  1794. 2: 2 + 3 => 5 2: 2 + 3 => 5
  1795. 1: 2 a + 2 b => 34 + 2 b 1: 2 a + 2 b => 20 + 2 b
  1796. . .
  1797. ' 2+3 => @key{RET} ' 2a+2b @key{RET} s = 10 s t a @key{RET}
  1798. @end group
  1799. @end smallexample
  1800. @noindent
  1801. Notice that the instant we stored a new value in @code{a}, all
  1802. @samp{=>} operators already on the stack that referred to @cite{a}
  1803. were updated to use the new value. With @samp{=>}, you can push a
  1804. set of formulas on the stack, then change the variables experimentally
  1805. to see the effects on the formulas' values.
  1806. You can also ``unstore'' a variable when you are through with it:
  1807. @smallexample
  1808. @group
  1809. 2: 2 + 5 => 5
  1810. 1: 2 a + 2 b => 2 a + 2 b
  1811. .
  1812. s u a @key{RET}
  1813. @end group
  1814. @end smallexample
  1815. We will encounter formulas involving variables and functions again
  1816. when we discuss the algebra and calculus features of the Calculator.
  1817. @node Undo Tutorial, Modes Tutorial, Algebraic Tutorial, Basic Tutorial
  1818. @subsection Undo and Redo
  1819. @noindent
  1820. If you make a mistake, you can usually correct it by pressing shift-@kbd{U},
  1821. the ``undo'' command. First, clear the stack (@kbd{M-0 @key{DEL}}) and exit
  1822. and restart Calc (@kbd{M-# M-# M-# M-#}) to make sure things start off
  1823. with a clean slate. Now:
  1824. @smallexample
  1825. @group
  1826. 1: 2 2: 2 1: 8 2: 2 1: 6
  1827. . 1: 3 . 1: 3 .
  1828. . .
  1829. 2 @key{RET} 3 ^ U *
  1830. @end group
  1831. @end smallexample
  1832. You can undo any number of times. Calc keeps a complete record of
  1833. all you have done since you last opened the Calc window. After the
  1834. above example, you could type:
  1835. @smallexample
  1836. @group
  1837. 1: 6 2: 2 1: 2 . .
  1838. . 1: 3 .
  1839. .
  1840. (error)
  1841. U U U U
  1842. @end group
  1843. @end smallexample
  1844. You can also type @kbd{D} to ``redo'' a command that you have undone
  1845. mistakenly.
  1846. @smallexample
  1847. @group
  1848. . 1: 2 2: 2 1: 6 1: 6
  1849. . 1: 3 . .
  1850. .
  1851. (error)
  1852. D D D D
  1853. @end group
  1854. @end smallexample
  1855. @noindent
  1856. It was not possible to redo past the @cite{6}, since that was placed there
  1857. by something other than an undo command.
  1858. @cindex Time travel
  1859. You can think of undo and redo as a sort of ``time machine.'' Press
  1860. @kbd{U} to go backward in time, @kbd{D} to go forward. If you go
  1861. backward and do something (like @kbd{*}) then, as any science fiction
  1862. reader knows, you have changed your future and you cannot go forward
  1863. again. Thus, the inability to redo past the @cite{6} even though there
  1864. was an earlier undo command.
  1865. You can always recall an earlier result using the Trail. We've ignored
  1866. the trail so far, but it has been faithfully recording everything we
  1867. did since we loaded the Calculator. If the Trail is not displayed,
  1868. press @kbd{t d} now to turn it on.
  1869. Let's try grabbing an earlier result. The @cite{8} we computed was
  1870. undone by a @kbd{U} command, and was lost even to Redo when we pressed
  1871. @kbd{*}, but it's still there in the trail. There should be a little
  1872. @samp{>} arrow (the @dfn{trail pointer}) resting on the last trail
  1873. entry. If there isn't, press @kbd{t ]} to reset the trail pointer.
  1874. Now, press @w{@kbd{t p}} to move the arrow onto the line containing
  1875. @cite{8}, and press @w{@kbd{t y}} to ``yank'' that number back onto the
  1876. stack.
  1877. If you press @kbd{t ]} again, you will see that even our Yank command
  1878. went into the trail.
  1879. Let's go further back in time. Earlier in the tutorial we computed
  1880. a huge integer using the formula @samp{2^3^4}. We don't remember
  1881. what it was, but the first digits were ``241''. Press @kbd{t r}
  1882. (which stands for trail-search-reverse), then type @kbd{241}.
  1883. The trail cursor will jump back to the next previous occurrence of
  1884. the string ``241'' in the trail. This is just a regular Emacs
  1885. incremental search; you can now press @kbd{C-s} or @kbd{C-r} to
  1886. continue the search forwards or backwards as you like.
  1887. To finish the search, press @key{RET}. This halts the incremental
  1888. search and leaves the trail pointer at the thing we found. Now we
  1889. can type @kbd{t y} to yank that number onto the stack. If we hadn't
  1890. remembered the ``241'', we could simply have searched for @kbd{2^3^4},
  1891. then pressed @kbd{@key{RET} t n} to halt and then move to the next item.
  1892. You may have noticed that all the trail-related commands begin with
  1893. the letter @kbd{t}. (The store-and-recall commands, on the other hand,
  1894. all began with @kbd{s}.) Calc has so many commands that there aren't
  1895. enough keys for all of them, so various commands are grouped into
  1896. two-letter sequences where the first letter is called the @dfn{prefix}
  1897. key. If you type a prefix key by accident, you can press @kbd{C-g}
  1898. to cancel it. (In fact, you can press @kbd{C-g} to cancel almost
  1899. anything in Emacs.) To get help on a prefix key, press that key
  1900. followed by @kbd{?}. Some prefixes have several lines of help,
  1901. so you need to press @kbd{?} repeatedly to see them all. This may
  1902. not work under Lucid Emacs, but you can also type @kbd{h h} to
  1903. see all the help at once.
  1904. Try pressing @kbd{t ?} now. You will see a line of the form,
  1905. @smallexample
  1906. trail/time: Display; Fwd, Back; Next, Prev, Here, [, ]; Yank: [MORE] t-
  1907. @end smallexample
  1908. @noindent
  1909. The word ``trail'' indicates that the @kbd{t} prefix key contains
  1910. trail-related commands. Each entry on the line shows one command,
  1911. with a single capital letter showing which letter you press to get
  1912. that command. We have used @kbd{t n}, @kbd{t p}, @kbd{t ]}, and
  1913. @kbd{t y} so far. The @samp{[MORE]} means you can press @kbd{?}
  1914. again to see more @kbd{t}-prefix comands. Notice that the commands
  1915. are roughly divided (by semicolons) into related groups.
  1916. When you are in the help display for a prefix key, the prefix is
  1917. still active. If you press another key, like @kbd{y} for example,
  1918. it will be interpreted as a @kbd{t y} command. If all you wanted
  1919. was to look at the help messages, press @kbd{C-g} afterwards to cancel
  1920. the prefix.
  1921. One more way to correct an error is by editing the stack entries.
  1922. The actual Stack buffer is marked read-only and must not be edited
  1923. directly, but you can press @kbd{`} (the backquote or accent grave)
  1924. to edit a stack entry.
  1925. Try entering @samp{3.141439} now. If this is supposed to represent
  1926. @c{$\pi$}
  1927. @cite{pi}, it's got several errors. Press @kbd{`} to edit this number.
  1928. Now use the normal Emacs cursor motion and editing keys to change
  1929. the second 4 to a 5, and to transpose the 3 and the 9. When you
  1930. press @key{RET}, the number on the stack will be replaced by your
  1931. new number. This works for formulas, vectors, and all other types
  1932. of values you can put on the stack. The @kbd{`} key also works
  1933. during entry of a number or algebraic formula.
  1934. @node Modes Tutorial, , Undo Tutorial, Basic Tutorial
  1935. @subsection Mode-Setting Commands
  1936. @noindent
  1937. Calc has many types of @dfn{modes} that affect the way it interprets
  1938. your commands or the way it displays data. We have already seen one
  1939. mode, namely algebraic mode. There are many others, too; we'll
  1940. try some of the most common ones here.
  1941. Perhaps the most fundamental mode in Calc is the current @dfn{precision}.
  1942. Notice the @samp{12} on the Calc window's mode line:
  1943. @smallexample
  1944. --%%-Calc: 12 Deg (Calculator)----All------
  1945. @end smallexample
  1946. @noindent
  1947. Most of the symbols there are Emacs things you don't need to worry
  1948. about, but the @samp{12} and the @samp{Deg} are mode indicators.
  1949. The @samp{12} means that calculations should always be carried to
  1950. 12 significant figures. That is why, when we type @kbd{1 @key{RET} 7 /},
  1951. we get @cite{0.142857142857} with exactly 12 digits, not counting
  1952. leading and trailing zeros.
  1953. You can set the precision to anything you like by pressing @kbd{p},
  1954. then entering a suitable number. Try pressing @kbd{p 30 @key{RET}},
  1955. then doing @kbd{1 @key{RET} 7 /} again:
  1956. @smallexample
  1957. @group
  1958. 1: 0.142857142857
  1959. 2: 0.142857142857142857142857142857
  1960. .
  1961. @end group
  1962. @end smallexample
  1963. Although the precision can be set arbitrarily high, Calc always
  1964. has to have @emph{some} value for the current precision. After
  1965. all, the true value @cite{1/7} is an infinitely repeating decimal;
  1966. Calc has to stop somewhere.
  1967. Of course, calculations are slower the more digits you request.
  1968. Press @w{@kbd{p 12}} now to set the precision back down to the default.
  1969. Calculations always use the current precision. For example, even
  1970. though we have a 30-digit value for @cite{1/7} on the stack, if
  1971. we use it in a calculation in 12-digit mode it will be rounded
  1972. down to 12 digits before it is used. Try it; press @key{RET} to
  1973. duplicate the number, then @w{@kbd{1 +}}. Notice that the @key{RET}
  1974. key didn't round the number, because it doesn't do any calculation.
  1975. But the instant we pressed @kbd{+}, the number was rounded down.
  1976. @smallexample
  1977. @group
  1978. 1: 0.142857142857
  1979. 2: 0.142857142857142857142857142857
  1980. 3: 1.14285714286
  1981. .
  1982. @end group
  1983. @end smallexample
  1984. @noindent
  1985. In fact, since we added a digit on the left, we had to lose one
  1986. digit on the right from even the 12-digit value of @cite{1/7}.
  1987. How did we get more than 12 digits when we computed @samp{2^3^4}? The
  1988. answer is that Calc makes a distinction between @dfn{integers} and
  1989. @dfn{floating-point} numbers, or @dfn{floats}. An integer is a number
  1990. that does not contain a decimal point. There is no such thing as an
  1991. ``infinitely repeating fraction integer,'' so Calc doesn't have to limit
  1992. itself. If you asked for @samp{2^10000} (don't try this!), you would
  1993. have to wait a long time but you would eventually get an exact answer.
  1994. If you ask for @samp{2.^10000}, you will quickly get an answer which is
  1995. correct only to 12 places. The decimal point tells Calc that it should
  1996. use floating-point arithmetic to get the answer, not exact integer
  1997. arithmetic.
  1998. You can use the @kbd{F} (@code{calc-floor}) command to convert a
  1999. floating-point value to an integer, and @kbd{c f} (@code{calc-float})
  2000. to convert an integer to floating-point form.
  2001. Let's try entering that last calculation:
  2002. @smallexample
  2003. @group
  2004. 1: 2. 2: 2. 1: 1.99506311689e3010
  2005. . 1: 10000 .
  2006. .
  2007. 2.0 @key{RET} 10000 @key{RET} ^
  2008. @end group
  2009. @end smallexample
  2010. @noindent
  2011. @cindex Scientific notation, entry of
  2012. Notice the letter @samp{e} in there. It represents ``times ten to the
  2013. power of,'' and is used by Calc automatically whenever writing the
  2014. number out fully would introduce more extra zeros than you probably
  2015. want to see. You can enter numbers in this notation, too.
  2016. @smallexample
  2017. @group
  2018. 1: 2. 2: 2. 1: 1.99506311678e3010
  2019. . 1: 10000. .
  2020. .
  2021. 2.0 @key{RET} 1e4 @key{RET} ^
  2022. @end group
  2023. @end smallexample
  2024. @cindex Round-off errors
  2025. @noindent
  2026. Hey, the answer is different! Look closely at the middle columns
  2027. of the two examples. In the first, the stack contained the
  2028. exact integer @cite{10000}, but in the second it contained
  2029. a floating-point value with a decimal point. When you raise a
  2030. number to an integer power, Calc uses repeated squaring and
  2031. multiplication to get the answer. When you use a floating-point
  2032. power, Calc uses logarithms and exponentials. As you can see,
  2033. a slight error crept in during one of these methods. Which
  2034. one should we trust? Let's raise the precision a bit and find
  2035. out:
  2036. @smallexample
  2037. @group
  2038. . 1: 2. 2: 2. 1: 1.995063116880828e3010
  2039. . 1: 10000. .
  2040. .
  2041. p 16 @key{RET} 2. @key{RET} 1e4 ^ p 12 @key{RET}
  2042. @end group
  2043. @end smallexample
  2044. @noindent
  2045. @cindex Guard digits
  2046. Presumably, it doesn't matter whether we do this higher-precision
  2047. calculation using an integer or floating-point power, since we
  2048. have added enough ``guard digits'' to trust the first 12 digits
  2049. no matter what. And the verdict is@dots{} Integer powers were more
  2050. accurate; in fact, the result was only off by one unit in the
  2051. last place.
  2052. @cindex Guard digits
  2053. Calc does many of its internal calculations to a slightly higher
  2054. precision, but it doesn't always bump the precision up enough.
  2055. In each case, Calc added about two digits of precision during
  2056. its calculation and then rounded back down to 12 digits
  2057. afterward. In one case, it was enough; in the other, it
  2058. wasn't. If you really need @var{x} digits of precision, it
  2059. never hurts to do the calculation with a few extra guard digits.
  2060. What if we want guard digits but don't want to look at them?
  2061. We can set the @dfn{float format}. Calc supports four major
  2062. formats for floating-point numbers, called @dfn{normal},
  2063. @dfn{fixed-point}, @dfn{scientific notation}, and @dfn{engineering
  2064. notation}. You get them by pressing @w{@kbd{d n}}, @kbd{d f},
  2065. @kbd{d s}, and @kbd{d e}, respectively. In each case, you can
  2066. supply a numeric prefix argument which says how many digits
  2067. should be displayed. As an example, let's put a few numbers
  2068. onto the stack and try some different display modes. First,
  2069. use @kbd{M-0 @key{DEL}} to clear the stack, then enter the four
  2070. numbers shown here:
  2071. @smallexample
  2072. @group
  2073. 4: 12345 4: 12345 4: 12345 4: 12345 4: 12345
  2074. 3: 12345. 3: 12300. 3: 1.2345e4 3: 1.23e4 3: 12345.000
  2075. 2: 123.45 2: 123. 2: 1.2345e2 2: 1.23e2 2: 123.450
  2076. 1: 12.345 1: 12.3 1: 1.2345e1 1: 1.23e1 1: 12.345
  2077. . . . . .
  2078. d n M-3 d n d s M-3 d s M-3 d f
  2079. @end group
  2080. @end smallexample
  2081. @noindent
  2082. Notice that when we typed @kbd{M-3 d n}, the numbers were rounded down
  2083. to three significant digits, but then when we typed @kbd{d s} all
  2084. five significant figures reappeared. The float format does not
  2085. affect how numbers are stored, it only affects how they are
  2086. displayed. Only the current precision governs the actual rounding
  2087. of numbers in the Calculator's memory.
  2088. Engineering notation, not shown here, is like scientific notation
  2089. except the exponent (the power-of-ten part) is always adjusted to be
  2090. a multiple of three (as in ``kilo,'' ``micro,'' etc.). As a result
  2091. there will be one, two, or three digits before the decimal point.
  2092. Whenever you change a display-related mode, Calc redraws everything
  2093. in the stack. This may be slow if there are many things on the stack,
  2094. so Calc allows you to type shift-@kbd{H} before any mode command to
  2095. prevent it from updating the stack. Anything Calc displays after the
  2096. mode-changing command will appear in the new format.
  2097. @smallexample
  2098. @group
  2099. 4: 12345 4: 12345 4: 12345 4: 12345 4: 12345
  2100. 3: 12345.000 3: 12345.000 3: 12345.000 3: 1.2345e4 3: 12345.
  2101. 2: 123.450 2: 123.450 2: 1.2345e1 2: 1.2345e1 2: 123.45
  2102. 1: 12.345 1: 1.2345e1 1: 1.2345e2 1: 1.2345e2 1: 12.345
  2103. . . . . .
  2104. H d s @key{DEL} U @key{TAB} d @key{SPC} d n
  2105. @end group
  2106. @end smallexample
  2107. @noindent
  2108. Here the @kbd{H d s} command changes to scientific notation but without
  2109. updating the screen. Deleting the top stack entry and undoing it back
  2110. causes it to show up in the new format; swapping the top two stack
  2111. entries reformats both entries. The @kbd{d @key{SPC}} command refreshes the
  2112. whole stack. The @kbd{d n} command changes back to the normal float
  2113. format; since it doesn't have an @kbd{H} prefix, it also updates all
  2114. the stack entries to be in @kbd{d n} format.
  2115. Notice that the integer @cite{12345} was not affected by any
  2116. of the float formats. Integers are integers, and are always
  2117. displayed exactly.
  2118. @cindex Large numbers, readability
  2119. Large integers have their own problems. Let's look back at
  2120. the result of @kbd{2^3^4}.
  2121. @example
  2122. 2417851639229258349412352
  2123. @end example
  2124. @noindent
  2125. Quick---how many digits does this have? Try typing @kbd{d g}:
  2126. @example
  2127. 2,417,851,639,229,258,349,412,352
  2128. @end example
  2129. @noindent
  2130. Now how many digits does this have? It's much easier to tell!
  2131. We can actually group digits into clumps of any size. Some
  2132. people prefer @kbd{M-5 d g}:
  2133. @example
  2134. 24178,51639,22925,83494,12352
  2135. @end example
  2136. Let's see what happens to floating-point numbers when they are grouped.
  2137. First, type @kbd{p 25 @key{RET}} to make sure we have enough precision
  2138. to get ourselves into trouble. Now, type @kbd{1e13 /}:
  2139. @example
  2140. 24,17851,63922.9258349412352
  2141. @end example
  2142. @noindent
  2143. The integer part is grouped but the fractional part isn't. Now try
  2144. @kbd{M-- M-5 d g} (that's meta-minus-sign, meta-five):
  2145. @example
  2146. 24,17851,63922.92583,49412,352
  2147. @end example
  2148. If you find it hard to tell the decimal point from the commas, try
  2149. changing the grouping character to a space with @kbd{d , @key{SPC}}:
  2150. @example
  2151. 24 17851 63922.92583 49412 352
  2152. @end example
  2153. Type @kbd{d , ,} to restore the normal grouping character, then
  2154. @kbd{d g} again to turn grouping off. Also, press @kbd{p 12} to
  2155. restore the default precision.
  2156. Press @kbd{U} enough times to get the original big integer back.
  2157. (Notice that @kbd{U} does not undo each mode-setting command; if
  2158. you want to undo a mode-setting command, you have to do it yourself.)
  2159. Now, type @kbd{d r 16 @key{RET}}:
  2160. @example
  2161. 16#200000000000000000000
  2162. @end example
  2163. @noindent
  2164. The number is now displayed in @dfn{hexadecimal}, or ``base-16'' form.
  2165. Suddenly it looks pretty simple; this should be no surprise, since we
  2166. got this number by computing a power of two, and 16 is a power of 2.
  2167. In fact, we can use @w{@kbd{d r 2 @key{RET}}} to see it in actual binary
  2168. form:
  2169. @example
  2170. 2#1000000000000000000000000000000000000000000000000000000 @dots{}
  2171. @end example
  2172. @noindent
  2173. We don't have enough space here to show all the zeros! They won't
  2174. fit on a typical screen, either, so you will have to use horizontal
  2175. scrolling to see them all. Press @kbd{<} and @kbd{>} to scroll the
  2176. stack window left and right by half its width. Another way to view
  2177. something large is to press @kbd{`} (back-quote) to edit the top of
  2178. stack in a separate window. (Press @kbd{M-# M-#} when you are done.)
  2179. You can enter non-decimal numbers using the @kbd{#} symbol, too.
  2180. Let's see what the hexadecimal number @samp{5FE} looks like in
  2181. binary. Type @kbd{16#5FE} (the letters can be typed in upper or
  2182. lower case; they will always appear in upper case). It will also
  2183. help to turn grouping on with @kbd{d g}:
  2184. @example
  2185. 2#101,1111,1110
  2186. @end example
  2187. Notice that @kbd{d g} groups by fours by default if the display radix
  2188. is binary or hexadecimal, but by threes if it is decimal, octal, or any
  2189. other radix.
  2190. Now let's see that number in decimal; type @kbd{d r 10}:
  2191. @example
  2192. 1,534
  2193. @end example
  2194. Numbers are not @emph{stored} with any particular radix attached. They're
  2195. just numbers; they can be entered in any radix, and are always displayed
  2196. in whatever radix you've chosen with @kbd{d r}. The current radix applies
  2197. to integers, fractions, and floats.
  2198. @cindex Roundoff errors, in non-decimal numbers
  2199. (@bullet{}) @strong{Exercise 1.} Your friend Joe tried to enter one-third
  2200. as @samp{3#0.1} in @kbd{d r 3} mode with a precision of 12. He got
  2201. @samp{3#0.0222222...} (with 25 2's) in the display. When he multiplied
  2202. that by three, he got @samp{3#0.222222...} instead of the expected
  2203. @samp{3#1}. Next, Joe entered @samp{3#0.2} and, to his great relief,
  2204. saw @samp{3#0.2} on the screen. But when he typed @kbd{2 /}, he got
  2205. @samp{3#0.10000001} (some zeros omitted). What's going on here?
  2206. @xref{Modes Answer 1, 1}. (@bullet{})
  2207. @cindex Scientific notation, in non-decimal numbers
  2208. (@bullet{}) @strong{Exercise 2.} Scientific notation works in non-decimal
  2209. modes in the natural way (the exponent is a power of the radix instead of
  2210. a power of ten, although the exponent itself is always written in decimal).
  2211. Thus @samp{8#1.23e3 = 8#1230.0}. Suppose we have the hexadecimal number
  2212. @samp{f.e8f} times 16 to the 15th power: We write @samp{16#f.e8fe15}.
  2213. What is wrong with this picture? What could we write instead that would
  2214. work better? @xref{Modes Answer 2, 2}. (@bullet{})
  2215. The @kbd{m} prefix key has another set of modes, relating to the way
  2216. Calc interprets your inputs and does computations. Whereas @kbd{d}-prefix
  2217. modes generally affect the way things look, @kbd{m}-prefix modes affect
  2218. the way they are actually computed.
  2219. The most popular @kbd{m}-prefix mode is the @dfn{angular mode}. Notice
  2220. the @samp{Deg} indicator in the mode line. This means that if you use
  2221. a command that interprets a number as an angle, it will assume the
  2222. angle is measured in degrees. For example,
  2223. @smallexample
  2224. @group
  2225. 1: 45 1: 0.707106781187 1: 0.500000000001 1: 0.5
  2226. . . . .
  2227. 45 S 2 ^ c 1
  2228. @end group
  2229. @end smallexample
  2230. @noindent
  2231. The shift-@kbd{S} command computes the sine of an angle. The sine
  2232. of 45 degrees is @c{$\sqrt{2}/2$}
  2233. @cite{sqrt(2)/2}; squaring this yields @cite{2/4 = 0.5}.
  2234. However, there has been a slight roundoff error because the
  2235. representation of @c{$\sqrt{2}/2$}
  2236. @cite{sqrt(2)/2} wasn't exact. The @kbd{c 1}
  2237. command is a handy way to clean up numbers in this case; it
  2238. temporarily reduces the precision by one digit while it
  2239. re-rounds the number on the top of the stack.
  2240. @cindex Roundoff errors, examples
  2241. (@bullet{}) @strong{Exercise 3.} Your friend Joe computed the sine
  2242. of 45 degrees as shown above, then, hoping to avoid an inexact
  2243. result, he increased the precision to 16 digits before squaring.
  2244. What happened? @xref{Modes Answer 3, 3}. (@bullet{})
  2245. To do this calculation in radians, we would type @kbd{m r} first.
  2246. (The indicator changes to @samp{Rad}.) 45 degrees corresponds to
  2247. @c{$\pi\over4$}
  2248. @cite{pi/4} radians. To get @c{$\pi$}
  2249. @cite{pi}, press the @kbd{P} key. (Once
  2250. again, this is a shifted capital @kbd{P}. Remember, unshifted
  2251. @kbd{p} sets the precision.)
  2252. @smallexample
  2253. @group
  2254. 1: 3.14159265359 1: 0.785398163398 1: 0.707106781187
  2255. . . .
  2256. P 4 / m r S
  2257. @end group
  2258. @end smallexample
  2259. Likewise, inverse trigonometric functions generate results in
  2260. either radians or degrees, depending on the current angular mode.
  2261. @smallexample
  2262. @group
  2263. 1: 0.707106781187 1: 0.785398163398 1: 45.
  2264. . . .
  2265. .5 Q m r I S m d U I S
  2266. @end group
  2267. @end smallexample
  2268. @noindent
  2269. Here we compute the Inverse Sine of @c{$\sqrt{0.5}$}
  2270. @cite{sqrt(0.5)}, first in
  2271. radians, then in degrees.
  2272. Use @kbd{c d} and @kbd{c r} to convert a number from radians to degrees
  2273. and vice-versa.
  2274. @smallexample
  2275. @group
  2276. 1: 45 1: 0.785398163397 1: 45.
  2277. . . .
  2278. 45 c r c d
  2279. @end group
  2280. @end smallexample
  2281. Another interesting mode is @dfn{fraction mode}. Normally,
  2282. dividing two integers produces a floating-point result if the
  2283. quotient can't be expressed as an exact integer. Fraction mode
  2284. causes integer division to produce a fraction, i.e., a rational
  2285. number, instead.
  2286. @smallexample
  2287. @group
  2288. 2: 12 1: 1.33333333333 1: 4:3
  2289. 1: 9 . .
  2290. .
  2291. 12 @key{RET} 9 / m f U / m f
  2292. @end group
  2293. @end smallexample
  2294. @noindent
  2295. In the first case, we get an approximate floating-point result.
  2296. In the second case, we get an exact fractional result (four-thirds).
  2297. You can enter a fraction at any time using @kbd{:} notation.
  2298. (Calc uses @kbd{:} instead of @kbd{/} as the fraction separator
  2299. because @kbd{/} is already used to divide the top two stack
  2300. elements.) Calculations involving fractions will always
  2301. produce exact fractional results; fraction mode only says
  2302. what to do when dividing two integers.
  2303. @cindex Fractions vs. floats
  2304. @cindex Floats vs. fractions
  2305. (@bullet{}) @strong{Exercise 4.} If fractional arithmetic is exact,
  2306. why would you ever use floating-point numbers instead?
  2307. @xref{Modes Answer 4, 4}. (@bullet{})
  2308. Typing @kbd{m f} doesn't change any existing values in the stack.
  2309. In the above example, we had to Undo the division and do it over
  2310. again when we changed to fraction mode. But if you use the
  2311. evaluates-to operator you can get commands like @kbd{m f} to
  2312. recompute for you.
  2313. @smallexample
  2314. @group
  2315. 1: 12 / 9 => 1.33333333333 1: 12 / 9 => 1.333 1: 12 / 9 => 4:3
  2316. . . .
  2317. ' 12/9 => @key{RET} p 4 @key{RET} m f
  2318. @end group
  2319. @end smallexample
  2320. @noindent
  2321. In this example, the righthand side of the @samp{=>} operator
  2322. on the stack is recomputed when we change the precision, then
  2323. again when we change to fraction mode. All @samp{=>} expressions
  2324. on the stack are recomputed every time you change any mode that
  2325. might affect their values.
  2326. @node Arithmetic Tutorial, Vector/Matrix Tutorial, Basic Tutorial, Tutorial
  2327. @section Arithmetic Tutorial
  2328. @noindent
  2329. In this section, we explore the arithmetic and scientific functions
  2330. available in the Calculator.
  2331. The standard arithmetic commands are @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/},
  2332. and @kbd{^}. Each normally takes two numbers from the top of the stack
  2333. and pushes back a result. The @kbd{n} and @kbd{&} keys perform
  2334. change-sign and reciprocal operations, respectively.
  2335. @smallexample
  2336. @group
  2337. 1: 5 1: 0.2 1: 5. 1: -5. 1: 5.
  2338. . . . . .
  2339. 5 & & n n
  2340. @end group
  2341. @end smallexample
  2342. @cindex Binary operators
  2343. You can apply a ``binary operator'' like @kbd{+} across any number of
  2344. stack entries by giving it a numeric prefix. You can also apply it
  2345. pairwise to several stack elements along with the top one if you use
  2346. a negative prefix.
  2347. @smallexample
  2348. @group
  2349. 3: 2 1: 9 3: 2 4: 2 3: 12
  2350. 2: 3 . 2: 3 3: 3 2: 13
  2351. 1: 4 1: 4 2: 4 1: 14
  2352. . . 1: 10 .
  2353. .
  2354. 2 @key{RET} 3 @key{RET} 4 M-3 + U 10 M-- M-3 +
  2355. @end group
  2356. @end smallexample
  2357. @cindex Unary operators
  2358. You can apply a ``unary operator'' like @kbd{&} to the top @var{n}
  2359. stack entries with a numeric prefix, too.
  2360. @smallexample
  2361. @group
  2362. 3: 2 3: 0.5 3: 0.5
  2363. 2: 3 2: 0.333333333333 2: 3.
  2364. 1: 4 1: 0.25 1: 4.
  2365. . . .
  2366. 2 @key{RET} 3 @key{RET} 4 M-3 & M-2 &
  2367. @end group
  2368. @end smallexample
  2369. Notice that the results here are left in floating-point form.
  2370. We can convert them back to integers by pressing @kbd{F}, the
  2371. ``floor'' function. This function rounds down to the next lower
  2372. integer. There is also @kbd{R}, which rounds to the nearest
  2373. integer.
  2374. @smallexample
  2375. @group
  2376. 7: 2. 7: 2 7: 2
  2377. 6: 2.4 6: 2 6: 2
  2378. 5: 2.5 5: 2 5: 3
  2379. 4: 2.6 4: 2 4: 3
  2380. 3: -2. 3: -2 3: -2
  2381. 2: -2.4 2: -3 2: -2
  2382. 1: -2.6 1: -3 1: -3
  2383. . . .
  2384. M-7 F U M-7 R
  2385. @end group
  2386. @end smallexample
  2387. Since dividing-and-flooring (i.e., ``integer quotient'') is such a
  2388. common operation, Calc provides a special command for that purpose, the
  2389. backslash @kbd{\}. Another common arithmetic operator is @kbd{%}, which
  2390. computes the remainder that would arise from a @kbd{\} operation, i.e.,
  2391. the ``modulo'' of two numbers. For example,
  2392. @smallexample
  2393. @group
  2394. 2: 1234 1: 12 2: 1234 1: 34
  2395. 1: 100 . 1: 100 .
  2396. . .
  2397. 1234 @key{RET} 100 \ U %
  2398. @end group
  2399. @end smallexample
  2400. These commands actually work for any real numbers, not just integers.
  2401. @smallexample
  2402. @group
  2403. 2: 3.1415 1: 3 2: 3.1415 1: 0.1415
  2404. 1: 1 . 1: 1 .
  2405. . .
  2406. 3.1415 @key{RET} 1 \ U %
  2407. @end group
  2408. @end smallexample
  2409. (@bullet{}) @strong{Exercise 1.} The @kbd{\} command would appear to be a
  2410. frill, since you could always do the same thing with @kbd{/ F}. Think
  2411. of a situation where this is not true---@kbd{/ F} would be inadequate.
  2412. Now think of a way you could get around the problem if Calc didn't
  2413. provide a @kbd{\} command. @xref{Arithmetic Answer 1, 1}. (@bullet{})
  2414. We've already seen the @kbd{Q} (square root) and @kbd{S} (sine)
  2415. commands. Other commands along those lines are @kbd{C} (cosine),
  2416. @kbd{T} (tangent), @kbd{E} (@cite{e^x}) and @kbd{L} (natural
  2417. logarithm). These can be modified by the @kbd{I} (inverse) and
  2418. @kbd{H} (hyperbolic) prefix keys.
  2419. Let's compute the sine and cosine of an angle, and verify the
  2420. identity @c{$\sin^2x + \cos^2x = 1$}
  2421. @cite{sin(x)^2 + cos(x)^2 = 1}. We'll
  2422. arbitrarily pick @i{-64} degrees as a good value for @cite{x}. With
  2423. the angular mode set to degrees (type @w{@kbd{m d}}), do:
  2424. @smallexample
  2425. @group
  2426. 2: -64 2: -64 2: -0.89879 2: -0.89879 1: 1.
  2427. 1: -64 1: -0.89879 1: -64 1: 0.43837 .
  2428. . . . .
  2429. 64 n @key{RET} @key{RET} S @key{TAB} C f h
  2430. @end group
  2431. @end smallexample
  2432. @noindent
  2433. (For brevity, we're showing only five digits of the results here.
  2434. You can of course do these calculations to any precision you like.)
  2435. Remember, @kbd{f h} is the @code{calc-hypot}, or square-root of sum
  2436. of squares, command.
  2437. Another identity is @c{$\displaystyle\tan x = {\sin x \over \cos x}$}
  2438. @cite{tan(x) = sin(x) / cos(x)}.
  2439. @smallexample
  2440. @group
  2441. 2: -0.89879 1: -2.0503 1: -64.
  2442. 1: 0.43837 . .
  2443. .
  2444. U / I T
  2445. @end group
  2446. @end smallexample
  2447. A physical interpretation of this calculation is that if you move
  2448. @cite{0.89879} units downward and @cite{0.43837} units to the right,
  2449. your direction of motion is @i{-64} degrees from horizontal. Suppose
  2450. we move in the opposite direction, up and to the left:
  2451. @smallexample
  2452. @group
  2453. 2: -0.89879 2: 0.89879 1: -2.0503 1: -64.
  2454. 1: 0.43837 1: -0.43837 . .
  2455. . .
  2456. U U M-2 n / I T
  2457. @end group
  2458. @end smallexample
  2459. @noindent
  2460. How can the angle be the same? The answer is that the @kbd{/} operation
  2461. loses information about the signs of its inputs. Because the quotient
  2462. is negative, we know exactly one of the inputs was negative, but we
  2463. can't tell which one. There is an @kbd{f T} [@code{arctan2}] function which
  2464. computes the inverse tangent of the quotient of a pair of numbers.
  2465. Since you feed it the two original numbers, it has enough information
  2466. to give you a full 360-degree answer.
  2467. @smallexample
  2468. @group
  2469. 2: 0.89879 1: 116. 3: 116. 2: 116. 1: 180.
  2470. 1: -0.43837 . 2: -0.89879 1: -64. .
  2471. . 1: 0.43837 .
  2472. .
  2473. U U f T M-@key{RET} M-2 n f T -
  2474. @end group
  2475. @end smallexample
  2476. @noindent
  2477. The resulting angles differ by 180 degrees; in other words, they
  2478. point in opposite directions, just as we would expect.
  2479. The @key{META}-@key{RET} we used in the third step is the
  2480. ``last-arguments'' command. It is sort of like Undo, except that it
  2481. restores the arguments of the last command to the stack without removing
  2482. the command's result. It is useful in situations like this one,
  2483. where we need to do several operations on the same inputs. We could
  2484. have accomplished the same thing by using @kbd{M-2 @key{RET}} to duplicate
  2485. the top two stack elements right after the @kbd{U U}, then a pair of
  2486. @kbd{M-@key{TAB}} commands to cycle the 116 up around the duplicates.
  2487. A similar identity is supposed to hold for hyperbolic sines and cosines,
  2488. except that it is the @emph{difference}
  2489. @c{$\cosh^2x - \sinh^2x$}
  2490. @cite{cosh(x)^2 - sinh(x)^2} that always equals one.
  2491. Let's try to verify this identity.@refill
  2492. @smallexample
  2493. @group
  2494. 2: -64 2: -64 2: -64 2: 9.7192e54 2: 9.7192e54
  2495. 1: -64 1: -3.1175e27 1: 9.7192e54 1: -64 1: 9.7192e54
  2496. . . . . .
  2497. 64 n @key{RET} @key{RET} H C 2 ^ @key{TAB} H S 2 ^
  2498. @end group
  2499. @end smallexample
  2500. @noindent
  2501. @cindex Roundoff errors, examples
  2502. Something's obviously wrong, because when we subtract these numbers
  2503. the answer will clearly be zero! But if you think about it, if these
  2504. numbers @emph{did} differ by one, it would be in the 55th decimal
  2505. place. The difference we seek has been lost entirely to roundoff
  2506. error.
  2507. We could verify this hypothesis by doing the actual calculation with,
  2508. say, 60 decimal places of precision. This will be slow, but not
  2509. enormously so. Try it if you wish; sure enough, the answer is
  2510. 0.99999, reasonably close to 1.
  2511. Of course, a more reasonable way to verify the identity is to use
  2512. a more reasonable value for @cite{x}!
  2513. @cindex Common logarithm
  2514. Some Calculator commands use the Hyperbolic prefix for other purposes.
  2515. The logarithm and exponential functions, for example, work to the base
  2516. @cite{e} normally but use base-10 instead if you use the Hyperbolic
  2517. prefix.
  2518. @smallexample
  2519. @group
  2520. 1: 1000 1: 6.9077 1: 1000 1: 3
  2521. . . . .
  2522. 1000 L U H L
  2523. @end group
  2524. @end smallexample
  2525. @noindent
  2526. First, we mistakenly compute a natural logarithm. Then we undo
  2527. and compute a common logarithm instead.
  2528. The @kbd{B} key computes a general base-@var{b} logarithm for any
  2529. value of @var{b}.
  2530. @smallexample
  2531. @group
  2532. 2: 1000 1: 3 1: 1000. 2: 1000. 1: 6.9077
  2533. 1: 10 . . 1: 2.71828 .
  2534. . .
  2535. 1000 @key{RET} 10 B H E H P B
  2536. @end group
  2537. @end smallexample
  2538. @noindent
  2539. Here we first use @kbd{B} to compute the base-10 logarithm, then use
  2540. the ``hyperbolic'' exponential as a cheap hack to recover the number
  2541. 1000, then use @kbd{B} again to compute the natural logarithm. Note
  2542. that @kbd{P} with the hyperbolic prefix pushes the constant @cite{e}
  2543. onto the stack.
  2544. You may have noticed that both times we took the base-10 logarithm
  2545. of 1000, we got an exact integer result. Calc always tries to give
  2546. an exact rational result for calculations involving rational numbers
  2547. where possible. But when we used @kbd{H E}, the result was a
  2548. floating-point number for no apparent reason. In fact, if we had
  2549. computed @kbd{10 @key{RET} 3 ^} we @emph{would} have gotten an
  2550. exact integer 1000. But the @kbd{H E} command is rigged to generate
  2551. a floating-point result all of the time so that @kbd{1000 H E} will
  2552. not waste time computing a thousand-digit integer when all you
  2553. probably wanted was @samp{1e1000}.
  2554. (@bullet{}) @strong{Exercise 2.} Find a pair of integer inputs to
  2555. the @kbd{B} command for which Calc could find an exact rational
  2556. result but doesn't. @xref{Arithmetic Answer 2, 2}. (@bullet{})
  2557. The Calculator also has a set of functions relating to combinatorics
  2558. and statistics. You may be familiar with the @dfn{factorial} function,
  2559. which computes the product of all the integers up to a given number.
  2560. @smallexample
  2561. @group
  2562. 1: 100 1: 93326215443... 1: 100. 1: 9.3326e157
  2563. . . . .
  2564. 100 ! U c f !
  2565. @end group
  2566. @end smallexample
  2567. @noindent
  2568. Recall, the @kbd{c f} command converts the integer or fraction at the
  2569. top of the stack to floating-point format. If you take the factorial
  2570. of a floating-point number, you get a floating-point result
  2571. accurate to the current precision. But if you give @kbd{!} an
  2572. exact integer, you get an exact integer result (158 digits long
  2573. in this case).
  2574. If you take the factorial of a non-integer, Calc uses a generalized
  2575. factorial function defined in terms of Euler's Gamma function
  2576. @c{$\Gamma(n)$}
  2577. @cite{gamma(n)}
  2578. (which is itself available as the @kbd{f g} command).
  2579. @smallexample
  2580. @group
  2581. 3: 4. 3: 24. 1: 5.5 1: 52.342777847
  2582. 2: 4.5 2: 52.3427777847 . .
  2583. 1: 5. 1: 120.
  2584. . .
  2585. M-3 ! M-0 @key{DEL} 5.5 f g
  2586. @end group
  2587. @end smallexample
  2588. @noindent
  2589. Here we verify the identity @c{$n! = \Gamma(n+1)$}
  2590. @cite{@var{n}!@: = gamma(@var{n}+1)}.
  2591. The binomial coefficient @var{n}-choose-@var{m}@c{ or $\displaystyle {n \choose m}$}
  2592. @asis{} is defined by
  2593. @c{$\displaystyle {n! \over m! \, (n-m)!}$}
  2594. @cite{n!@: / m!@: (n-m)!} for all reals @cite{n} and
  2595. @cite{m}. The intermediate results in this formula can become quite
  2596. large even if the final result is small; the @kbd{k c} command computes
  2597. a binomial coefficient in a way that avoids large intermediate
  2598. values.
  2599. The @kbd{k} prefix key defines several common functions out of
  2600. combinatorics and number theory. Here we compute the binomial
  2601. coefficient 30-choose-20, then determine its prime factorization.
  2602. @smallexample
  2603. @group
  2604. 2: 30 1: 30045015 1: [3, 3, 5, 7, 11, 13, 23, 29]
  2605. 1: 20 . .
  2606. .
  2607. 30 @key{RET} 20 k c k f
  2608. @end group
  2609. @end smallexample
  2610. @noindent
  2611. You can verify these prime factors by using @kbd{v u} to ``unpack''
  2612. this vector into 8 separate stack entries, then @kbd{M-8 *} to
  2613. multiply them back together. The result is the original number,
  2614. 30045015.
  2615. @cindex Hash tables
  2616. Suppose a program you are writing needs a hash table with at least
  2617. 10000 entries. It's best to use a prime number as the actual size
  2618. of a hash table. Calc can compute the next prime number after 10000:
  2619. @smallexample
  2620. @group
  2621. 1: 10000 1: 10007 1: 9973
  2622. . . .
  2623. 10000 k n I k n
  2624. @end group
  2625. @end smallexample
  2626. @noindent
  2627. Just for kicks we've also computed the next prime @emph{less} than
  2628. 10000.
  2629. @c [fix-ref Financial Functions]
  2630. @xref{Financial Functions}, for a description of the Calculator
  2631. commands that deal with business and financial calculations (functions
  2632. like @code{pv}, @code{rate}, and @code{sln}).
  2633. @c [fix-ref Binary Number Functions]
  2634. @xref{Binary Functions}, to read about the commands for operating
  2635. on binary numbers (like @code{and}, @code{xor}, and @code{lsh}).
  2636. @node Vector/Matrix Tutorial, Types Tutorial, Arithmetic Tutorial, Tutorial
  2637. @section Vector/Matrix Tutorial
  2638. @noindent
  2639. A @dfn{vector} is a list of numbers or other Calc data objects.
  2640. Calc provides a large set of commands that operate on vectors. Some
  2641. are familiar operations from vector analysis. Others simply treat
  2642. a vector as a list of objects.
  2643. @menu
  2644. * Vector Analysis Tutorial::
  2645. * Matrix Tutorial::
  2646. * List Tutorial::
  2647. @end menu
  2648. @node Vector Analysis Tutorial, Matrix Tutorial, Vector/Matrix Tutorial, Vector/Matrix Tutorial
  2649. @subsection Vector Analysis
  2650. @noindent
  2651. If you add two vectors, the result is a vector of the sums of the
  2652. elements, taken pairwise.
  2653. @smallexample
  2654. @group
  2655. 1: [1, 2, 3] 2: [1, 2, 3] 1: [8, 8, 3]
  2656. . 1: [7, 6, 0] .
  2657. .
  2658. [1,2,3] s 1 [7 6 0] s 2 +
  2659. @end group
  2660. @end smallexample
  2661. @noindent
  2662. Note that we can separate the vector elements with either commas or
  2663. spaces. This is true whether we are using incomplete vectors or
  2664. algebraic entry. The @kbd{s 1} and @kbd{s 2} commands save these
  2665. vectors so we can easily reuse them later.
  2666. If you multiply two vectors, the result is the sum of the products
  2667. of the elements taken pairwise. This is called the @dfn{dot product}
  2668. of the vectors.
  2669. @smallexample
  2670. @group
  2671. 2: [1, 2, 3] 1: 19
  2672. 1: [7, 6, 0] .
  2673. .
  2674. r 1 r 2 *
  2675. @end group
  2676. @end smallexample
  2677. @cindex Dot product
  2678. The dot product of two vectors is equal to the product of their
  2679. lengths times the cosine of the angle between them. (Here the vector
  2680. is interpreted as a line from the origin @cite{(0,0,0)} to the
  2681. specified point in three-dimensional space.) The @kbd{A}
  2682. (absolute value) command can be used to compute the length of a
  2683. vector.
  2684. @smallexample
  2685. @group
  2686. 3: 19 3: 19 1: 0.550782 1: 56.579
  2687. 2: [1, 2, 3] 2: 3.741657 . .
  2688. 1: [7, 6, 0] 1: 9.219544
  2689. . .
  2690. M-@key{RET} M-2 A * / I C
  2691. @end group
  2692. @end smallexample
  2693. @noindent
  2694. First we recall the arguments to the dot product command, then
  2695. we compute the absolute values of the top two stack entries to
  2696. obtain the lengths of the vectors, then we divide the dot product
  2697. by the product of the lengths to get the cosine of the angle.
  2698. The inverse cosine finds that the angle between the vectors
  2699. is about 56 degrees.
  2700. @cindex Cross product
  2701. @cindex Perpendicular vectors
  2702. The @dfn{cross product} of two vectors is a vector whose length
  2703. is the product of the lengths of the inputs times the sine of the
  2704. angle between them, and whose direction is perpendicular to both
  2705. input vectors. Unlike the dot product, the cross product is
  2706. defined only for three-dimensional vectors. Let's double-check
  2707. our computation of the angle using the cross product.
  2708. @smallexample
  2709. @group
  2710. 2: [1, 2, 3] 3: [-18, 21, -8] 1: [-0.52, 0.61, -0.23] 1: 56.579
  2711. 1: [7, 6, 0] 2: [1, 2, 3] . .
  2712. . 1: [7, 6, 0]
  2713. .
  2714. r 1 r 2 V C s 3 M-@key{RET} M-2 A * / A I S
  2715. @end group
  2716. @end smallexample
  2717. @noindent
  2718. First we recall the original vectors and compute their cross product,
  2719. which we also store for later reference. Now we divide the vector
  2720. by the product of the lengths of the original vectors. The length of
  2721. this vector should be the sine of the angle; sure enough, it is!
  2722. @c [fix-ref General Mode Commands]
  2723. Vector-related commands generally begin with the @kbd{v} prefix key.
  2724. Some are uppercase letters and some are lowercase. To make it easier
  2725. to type these commands, the shift-@kbd{V} prefix key acts the same as
  2726. the @kbd{v} key. (@xref{General Mode Commands}, for a way to make all
  2727. prefix keys have this property.)
  2728. If we take the dot product of two perpendicular vectors we expect
  2729. to get zero, since the cosine of 90 degrees is zero. Let's check
  2730. that the cross product is indeed perpendicular to both inputs:
  2731. @smallexample
  2732. @group
  2733. 2: [1, 2, 3] 1: 0 2: [7, 6, 0] 1: 0
  2734. 1: [-18, 21, -8] . 1: [-18, 21, -8] .
  2735. . .
  2736. r 1 r 3 * @key{DEL} r 2 r 3 *
  2737. @end group
  2738. @end smallexample
  2739. @cindex Normalizing a vector
  2740. @cindex Unit vectors
  2741. (@bullet{}) @strong{Exercise 1.} Given a vector on the top of the
  2742. stack, what keystrokes would you use to @dfn{normalize} the
  2743. vector, i.e., to reduce its length to one without changing its
  2744. direction? @xref{Vector Answer 1, 1}. (@bullet{})
  2745. (@bullet{}) @strong{Exercise 2.} Suppose a certain particle can be
  2746. at any of several positions along a ruler. You have a list of
  2747. those positions in the form of a vector, and another list of the
  2748. probabilities for the particle to be at the corresponding positions.
  2749. Find the average position of the particle.
  2750. @xref{Vector Answer 2, 2}. (@bullet{})
  2751. @node Matrix Tutorial, List Tutorial, Vector Analysis Tutorial, Vector/Matrix Tutorial
  2752. @subsection Matrices
  2753. @noindent
  2754. A @dfn{matrix} is just a vector of vectors, all the same length.
  2755. This means you can enter a matrix using nested brackets. You can
  2756. also use the semicolon character to enter a matrix. We'll show
  2757. both methods here:
  2758. @smallexample
  2759. @group
  2760. 1: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
  2761. [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
  2762. . .
  2763. [[1 2 3] [4 5 6]] ' [1 2 3; 4 5 6] @key{RET}
  2764. @end group
  2765. @end smallexample
  2766. @noindent
  2767. We'll be using this matrix again, so type @kbd{s 4} to save it now.
  2768. Note that semicolons work with incomplete vectors, but they work
  2769. better in algebraic entry. That's why we use the apostrophe in
  2770. the second example.
  2771. When two matrices are multiplied, the lefthand matrix must have
  2772. the same number of columns as the righthand matrix has rows.
  2773. Row @cite{i}, column @cite{j} of the result is effectively the
  2774. dot product of row @cite{i} of the left matrix by column @cite{j}
  2775. of the right matrix.
  2776. If we try to duplicate this matrix and multiply it by itself,
  2777. the dimensions are wrong and the multiplication cannot take place:
  2778. @smallexample
  2779. @group
  2780. 1: [ [ 1, 2, 3 ] * [ [ 1, 2, 3 ]
  2781. [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
  2782. .
  2783. @key{RET} *
  2784. @end group
  2785. @end smallexample
  2786. @noindent
  2787. Though rather hard to read, this is a formula which shows the product
  2788. of two matrices. The @samp{*} function, having invalid arguments, has
  2789. been left in symbolic form.
  2790. We can multiply the matrices if we @dfn{transpose} one of them first.
  2791. @smallexample
  2792. @group
  2793. 2: [ [ 1, 2, 3 ] 1: [ [ 14, 32 ] 1: [ [ 17, 22, 27 ]
  2794. [ 4, 5, 6 ] ] [ 32, 77 ] ] [ 22, 29, 36 ]
  2795. 1: [ [ 1, 4 ] . [ 27, 36, 45 ] ]
  2796. [ 2, 5 ] .
  2797. [ 3, 6 ] ]
  2798. .
  2799. U v t * U @key{TAB} *
  2800. @end group
  2801. @end smallexample
  2802. Matrix multiplication is not commutative; indeed, switching the
  2803. order of the operands can even change the dimensions of the result
  2804. matrix, as happened here!
  2805. If you multiply a plain vector by a matrix, it is treated as a
  2806. single row or column depending on which side of the matrix it is
  2807. on. The result is a plain vector which should also be interpreted
  2808. as a row or column as appropriate.
  2809. @smallexample
  2810. @group
  2811. 2: [ [ 1, 2, 3 ] 1: [14, 32]
  2812. [ 4, 5, 6 ] ] .
  2813. 1: [1, 2, 3]
  2814. .
  2815. r 4 r 1 *
  2816. @end group
  2817. @end smallexample
  2818. Multiplying in the other order wouldn't work because the number of
  2819. rows in the matrix is different from the number of elements in the
  2820. vector.
  2821. (@bullet{}) @strong{Exercise 1.} Use @samp{*} to sum along the rows
  2822. of the above @c{$2\times3$}
  2823. @asis{2x3} matrix to get @cite{[6, 15]}. Now use @samp{*} to
  2824. sum along the columns to get @cite{[5, 7, 9]}.
  2825. @xref{Matrix Answer 1, 1}. (@bullet{})
  2826. @cindex Identity matrix
  2827. An @dfn{identity matrix} is a square matrix with ones along the
  2828. diagonal and zeros elsewhere. It has the property that multiplication
  2829. by an identity matrix, on the left or on the right, always produces
  2830. the original matrix.
  2831. @smallexample
  2832. @group
  2833. 1: [ [ 1, 2, 3 ] 2: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
  2834. [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
  2835. . 1: [ [ 1, 0, 0 ] .
  2836. [ 0, 1, 0 ]
  2837. [ 0, 0, 1 ] ]
  2838. .
  2839. r 4 v i 3 @key{RET} *
  2840. @end group
  2841. @end smallexample
  2842. If a matrix is square, it is often possible to find its @dfn{inverse},
  2843. that is, a matrix which, when multiplied by the original matrix, yields
  2844. an identity matrix. The @kbd{&} (reciprocal) key also computes the
  2845. inverse of a matrix.
  2846. @smallexample
  2847. @group
  2848. 1: [ [ 1, 2, 3 ] 1: [ [ -2.4, 1.2, -0.2 ]
  2849. [ 4, 5, 6 ] [ 2.8, -1.4, 0.4 ]
  2850. [ 7, 6, 0 ] ] [ -0.73333, 0.53333, -0.2 ] ]
  2851. . .
  2852. r 4 r 2 | s 5 &
  2853. @end group
  2854. @end smallexample
  2855. @noindent
  2856. The vertical bar @kbd{|} @dfn{concatenates} numbers, vectors, and
  2857. matrices together. Here we have used it to add a new row onto
  2858. our matrix to make it square.
  2859. We can multiply these two matrices in either order to get an identity.
  2860. @smallexample
  2861. @group
  2862. 1: [ [ 1., 0., 0. ] 1: [ [ 1., 0., 0. ]
  2863. [ 0., 1., 0. ] [ 0., 1., 0. ]
  2864. [ 0., 0., 1. ] ] [ 0., 0., 1. ] ]
  2865. . .
  2866. M-@key{RET} * U @key{TAB} *
  2867. @end group
  2868. @end smallexample
  2869. @cindex Systems of linear equations
  2870. @cindex Linear equations, systems of
  2871. Matrix inverses are related to systems of linear equations in algebra.
  2872. Suppose we had the following set of equations:
  2873. @ifinfo
  2874. @group
  2875. @example
  2876. a + 2b + 3c = 6
  2877. 4a + 5b + 6c = 2
  2878. 7a + 6b = 3
  2879. @end example
  2880. @end group
  2881. @end ifinfo
  2882. @tex
  2883. \turnoffactive
  2884. \beforedisplayh
  2885. $$ \openup1\jot \tabskip=0pt plus1fil
  2886. \halign to\displaywidth{\tabskip=0pt
  2887. $\hfil#$&$\hfil{}#{}$&
  2888. $\hfil#$&$\hfil{}#{}$&
  2889. $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
  2890. a&+&2b&+&3c&=6 \cr
  2891. 4a&+&5b&+&6c&=2 \cr
  2892. 7a&+&6b& & &=3 \cr}
  2893. $$
  2894. \afterdisplayh
  2895. @end tex
  2896. @noindent
  2897. This can be cast into the matrix equation,
  2898. @ifinfo
  2899. @group
  2900. @example
  2901. [ [ 1, 2, 3 ] [ [ a ] [ [ 6 ]
  2902. [ 4, 5, 6 ] * [ b ] = [ 2 ]
  2903. [ 7, 6, 0 ] ] [ c ] ] [ 3 ] ]
  2904. @end example
  2905. @end group
  2906. @end ifinfo
  2907. @tex
  2908. \turnoffactive
  2909. \beforedisplay
  2910. $$ \pmatrix{ 1 & 2 & 3 \cr 4 & 5 & 6 \cr 7 & 6 & 0 }
  2911. \times
  2912. \pmatrix{ a \cr b \cr c } = \pmatrix{ 6 \cr 2 \cr 3 }
  2913. $$
  2914. \afterdisplay
  2915. @end tex
  2916. We can solve this system of equations by multiplying both sides by the
  2917. inverse of the matrix. Calc can do this all in one step:
  2918. @smallexample
  2919. @group
  2920. 2: [6, 2, 3] 1: [-12.6, 15.2, -3.93333]
  2921. 1: [ [ 1, 2, 3 ] .
  2922. [ 4, 5, 6 ]
  2923. [ 7, 6, 0 ] ]
  2924. .
  2925. [6,2,3] r 5 /
  2926. @end group
  2927. @end smallexample
  2928. @noindent
  2929. The result is the @cite{[a, b, c]} vector that solves the equations.
  2930. (Dividing by a square matrix is equivalent to multiplying by its
  2931. inverse.)
  2932. Let's verify this solution:
  2933. @smallexample
  2934. @group
  2935. 2: [ [ 1, 2, 3 ] 1: [6., 2., 3.]
  2936. [ 4, 5, 6 ] .
  2937. [ 7, 6, 0 ] ]
  2938. 1: [-12.6, 15.2, -3.93333]
  2939. .
  2940. r 5 @key{TAB} *
  2941. @end group
  2942. @end smallexample
  2943. @noindent
  2944. Note that we had to be careful about the order in which we multiplied
  2945. the matrix and vector. If we multiplied in the other order, Calc would
  2946. assume the vector was a row vector in order to make the dimensions
  2947. come out right, and the answer would be incorrect. If you
  2948. don't feel safe letting Calc take either interpretation of your
  2949. vectors, use explicit @c{$N\times1$}
  2950. @asis{Nx1} or @c{$1\times N$}
  2951. @asis{1xN} matrices instead.
  2952. In this case, you would enter the original column vector as
  2953. @samp{[[6], [2], [3]]} or @samp{[6; 2; 3]}.
  2954. (@bullet{}) @strong{Exercise 2.} Algebraic entry allows you to make
  2955. vectors and matrices that include variables. Solve the following
  2956. system of equations to get expressions for @cite{x} and @cite{y}
  2957. in terms of @cite{a} and @cite{b}.
  2958. @ifinfo
  2959. @group
  2960. @example
  2961. x + a y = 6
  2962. x + b y = 10
  2963. @end example
  2964. @end group
  2965. @end ifinfo
  2966. @tex
  2967. \turnoffactive
  2968. \beforedisplay
  2969. $$ \eqalign{ x &+ a y = 6 \cr
  2970. x &+ b y = 10}
  2971. $$
  2972. \afterdisplay
  2973. @end tex
  2974. @noindent
  2975. @xref{Matrix Answer 2, 2}. (@bullet{})
  2976. @cindex Least-squares for over-determined systems
  2977. @cindex Over-determined systems of equations
  2978. (@bullet{}) @strong{Exercise 3.} A system of equations is ``over-determined''
  2979. if it has more equations than variables. It is often the case that
  2980. there are no values for the variables that will satisfy all the
  2981. equations at once, but it is still useful to find a set of values
  2982. which ``nearly'' satisfy all the equations. In terms of matrix equations,
  2983. you can't solve @cite{A X = B} directly because the matrix @cite{A}
  2984. is not square for an over-determined system. Matrix inversion works
  2985. only for square matrices. One common trick is to multiply both sides
  2986. on the left by the transpose of @cite{A}:
  2987. @ifinfo
  2988. @samp{trn(A)*A*X = trn(A)*B}.
  2989. @end ifinfo
  2990. @tex
  2991. \turnoffactive
  2992. $A^T A \, X = A^T B$, where $A^T$ is the transpose \samp{trn(A)}.
  2993. @end tex
  2994. Now @c{$A^T A$}
  2995. @cite{trn(A)*A} is a square matrix so a solution is possible. It
  2996. turns out that the @cite{X} vector you compute in this way will be a
  2997. ``least-squares'' solution, which can be regarded as the ``closest''
  2998. solution to the set of equations. Use Calc to solve the following
  2999. over-determined system:@refill
  3000. @ifinfo
  3001. @group
  3002. @example
  3003. a + 2b + 3c = 6
  3004. 4a + 5b + 6c = 2
  3005. 7a + 6b = 3
  3006. 2a + 4b + 6c = 11
  3007. @end example
  3008. @end group
  3009. @end ifinfo
  3010. @tex
  3011. \turnoffactive
  3012. \beforedisplayh
  3013. $$ \openup1\jot \tabskip=0pt plus1fil
  3014. \halign to\displaywidth{\tabskip=0pt
  3015. $\hfil#$&$\hfil{}#{}$&
  3016. $\hfil#$&$\hfil{}#{}$&
  3017. $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
  3018. a&+&2b&+&3c&=6 \cr
  3019. 4a&+&5b&+&6c&=2 \cr
  3020. 7a&+&6b& & &=3 \cr
  3021. 2a&+&4b&+&6c&=11 \cr}
  3022. $$
  3023. \afterdisplayh
  3024. @end tex
  3025. @noindent
  3026. @xref{Matrix Answer 3, 3}. (@bullet{})
  3027. @node List Tutorial, , Matrix Tutorial, Vector/Matrix Tutorial
  3028. @subsection Vectors as Lists
  3029. @noindent
  3030. @cindex Lists
  3031. Although Calc has a number of features for manipulating vectors and
  3032. matrices as mathematical objects, you can also treat vectors as
  3033. simple lists of values. For example, we saw that the @kbd{k f}
  3034. command returns a vector which is a list of the prime factors of a
  3035. number.
  3036. You can pack and unpack stack entries into vectors:
  3037. @smallexample
  3038. @group
  3039. 3: 10 1: [10, 20, 30] 3: 10
  3040. 2: 20 . 2: 20
  3041. 1: 30 1: 30
  3042. . .
  3043. M-3 v p v u
  3044. @end group
  3045. @end smallexample
  3046. You can also build vectors out of consecutive integers, or out
  3047. of many copies of a given value:
  3048. @smallexample
  3049. @group
  3050. 1: [1, 2, 3, 4] 2: [1, 2, 3, 4] 2: [1, 2, 3, 4]
  3051. . 1: 17 1: [17, 17, 17, 17]
  3052. . .
  3053. v x 4 @key{RET} 17 v b 4 @key{RET}
  3054. @end group
  3055. @end smallexample
  3056. You can apply an operator to every element of a vector using the
  3057. @dfn{map} command.
  3058. @smallexample
  3059. @group
  3060. 1: [17, 34, 51, 68] 1: [289, 1156, 2601, 4624] 1: [17, 34, 51, 68]
  3061. . . .
  3062. V M * 2 V M ^ V M Q
  3063. @end group
  3064. @end smallexample
  3065. @noindent
  3066. In the first step, we multiply the vector of integers by the vector
  3067. of 17's elementwise. In the second step, we raise each element to
  3068. the power two. (The general rule is that both operands must be
  3069. vectors of the same length, or else one must be a vector and the
  3070. other a plain number.) In the final step, we take the square root
  3071. of each element.
  3072. (@bullet{}) @strong{Exercise 1.} Compute a vector of powers of two
  3073. from @c{$2^{-4}$}
  3074. @cite{2^-4} to @cite{2^4}. @xref{List Answer 1, 1}. (@bullet{})
  3075. You can also @dfn{reduce} a binary operator across a vector.
  3076. For example, reducing @samp{*} computes the product of all the
  3077. elements in the vector:
  3078. @smallexample
  3079. @group
  3080. 1: 123123 1: [3, 7, 11, 13, 41] 1: 123123
  3081. . . .
  3082. 123123 k f V R *
  3083. @end group
  3084. @end smallexample
  3085. @noindent
  3086. In this example, we decompose 123123 into its prime factors, then
  3087. multiply those factors together again to yield the original number.
  3088. We could compute a dot product ``by hand'' using mapping and
  3089. reduction:
  3090. @smallexample
  3091. @group
  3092. 2: [1, 2, 3] 1: [7, 12, 0] 1: 19
  3093. 1: [7, 6, 0] . .
  3094. .
  3095. r 1 r 2 V M * V R +
  3096. @end group
  3097. @end smallexample
  3098. @noindent
  3099. Recalling two vectors from the previous section, we compute the
  3100. sum of pairwise products of the elements to get the same answer
  3101. for the dot product as before.
  3102. A slight variant of vector reduction is the @dfn{accumulate} operation,
  3103. @kbd{V U}. This produces a vector of the intermediate results from
  3104. a corresponding reduction. Here we compute a table of factorials:
  3105. @smallexample
  3106. @group
  3107. 1: [1, 2, 3, 4, 5, 6] 1: [1, 2, 6, 24, 120, 720]
  3108. . .
  3109. v x 6 @key{RET} V U *
  3110. @end group
  3111. @end smallexample
  3112. Calc allows vectors to grow as large as you like, although it gets
  3113. rather slow if vectors have more than about a hundred elements.
  3114. Actually, most of the time is spent formatting these large vectors
  3115. for display, not calculating on them. Try the following experiment
  3116. (if your computer is very fast you may need to substitute a larger
  3117. vector size).
  3118. @smallexample
  3119. @group
  3120. 1: [1, 2, 3, 4, ... 1: [2, 3, 4, 5, ...
  3121. . .
  3122. v x 500 @key{RET} 1 V M +
  3123. @end group
  3124. @end smallexample
  3125. Now press @kbd{v .} (the letter @kbd{v}, then a period) and try the
  3126. experiment again. In @kbd{v .} mode, long vectors are displayed
  3127. ``abbreviated'' like this:
  3128. @smallexample
  3129. @group
  3130. 1: [1, 2, 3, ..., 500] 1: [2, 3, 4, ..., 501]
  3131. . .
  3132. v x 500 @key{RET} 1 V M +
  3133. @end group
  3134. @end smallexample
  3135. @noindent
  3136. (where now the @samp{...} is actually part of the Calc display).
  3137. You will find both operations are now much faster. But notice that
  3138. even in @w{@kbd{v .}} mode, the full vectors are still shown in the Trail.
  3139. Type @w{@kbd{t .}} to cause the trail to abbreviate as well, and try the
  3140. experiment one more time. Operations on long vectors are now quite
  3141. fast! (But of course if you use @kbd{t .} you will lose the ability
  3142. to get old vectors back using the @kbd{t y} command.)
  3143. An easy way to view a full vector when @kbd{v .} mode is active is
  3144. to press @kbd{`} (back-quote) to edit the vector; editing always works
  3145. with the full, unabbreviated value.
  3146. @cindex Least-squares for fitting a straight line
  3147. @cindex Fitting data to a line
  3148. @cindex Line, fitting data to
  3149. @cindex Data, extracting from buffers
  3150. @cindex Columns of data, extracting
  3151. As a larger example, let's try to fit a straight line to some data,
  3152. using the method of least squares. (Calc has a built-in command for
  3153. least-squares curve fitting, but we'll do it by hand here just to
  3154. practice working with vectors.) Suppose we have the following list
  3155. of values in a file we have loaded into Emacs:
  3156. @smallexample
  3157. x y
  3158. --- ---
  3159. 1.34 0.234
  3160. 1.41 0.298
  3161. 1.49 0.402
  3162. 1.56 0.412
  3163. 1.64 0.466
  3164. 1.73 0.473
  3165. 1.82 0.601
  3166. 1.91 0.519
  3167. 2.01 0.603
  3168. 2.11 0.637
  3169. 2.22 0.645
  3170. 2.33 0.705
  3171. 2.45 0.917
  3172. 2.58 1.009
  3173. 2.71 0.971
  3174. 2.85 1.062
  3175. 3.00 1.148
  3176. 3.15 1.157
  3177. 3.32 1.354
  3178. @end smallexample
  3179. @noindent
  3180. If you are reading this tutorial in printed form, you will find it
  3181. easiest to press @kbd{M-# i} to enter the on-line Info version of
  3182. the manual and find this table there. (Press @kbd{g}, then type
  3183. @kbd{List Tutorial}, to jump straight to this section.)
  3184. Position the cursor at the upper-left corner of this table, just
  3185. to the left of the @cite{1.34}. Press @kbd{C-@@} to set the mark.
  3186. (On your system this may be @kbd{C-2}, @kbd{C-@key{SPC}}, or @kbd{NUL}.)
  3187. Now position the cursor to the lower-right, just after the @cite{1.354}.
  3188. You have now defined this region as an Emacs ``rectangle.'' Still
  3189. in the Info buffer, type @kbd{M-# r}. This command
  3190. (@code{calc-grab-rectangle}) will pop you back into the Calculator, with
  3191. the contents of the rectangle you specified in the form of a matrix.@refill
  3192. @smallexample
  3193. @group
  3194. 1: [ [ 1.34, 0.234 ]
  3195. [ 1.41, 0.298 ]
  3196. @dots{}
  3197. @end group
  3198. @end smallexample
  3199. @noindent
  3200. (You may wish to use @kbd{v .} mode to abbreviate the display of this
  3201. large matrix.)
  3202. We want to treat this as a pair of lists. The first step is to
  3203. transpose this matrix into a pair of rows. Remember, a matrix is
  3204. just a vector of vectors. So we can unpack the matrix into a pair
  3205. of row vectors on the stack.
  3206. @smallexample
  3207. @group
  3208. 1: [ [ 1.34, 1.41, 1.49, ... ] 2: [1.34, 1.41, 1.49, ... ]
  3209. [ 0.234, 0.298, 0.402, ... ] ] 1: [0.234, 0.298, 0.402, ... ]
  3210. . .
  3211. v t v u
  3212. @end group
  3213. @end smallexample
  3214. @noindent
  3215. Let's store these in quick variables 1 and 2, respectively.
  3216. @smallexample
  3217. @group
  3218. 1: [1.34, 1.41, 1.49, ... ] .
  3219. .
  3220. t 2 t 1
  3221. @end group
  3222. @end smallexample
  3223. @noindent
  3224. (Recall that @kbd{t 2} is a variant of @kbd{s 2} that removes the
  3225. stored value from the stack.)
  3226. In a least squares fit, the slope @cite{m} is given by the formula
  3227. @ifinfo
  3228. @example
  3229. m = (N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)
  3230. @end example
  3231. @end ifinfo
  3232. @tex
  3233. \turnoffactive
  3234. \beforedisplay
  3235. $$ m = {N \sum x y - \sum x \sum y \over
  3236. N \sum x^2 - \left( \sum x \right)^2} $$
  3237. \afterdisplay
  3238. @end tex
  3239. @noindent
  3240. where @c{$\sum x$}
  3241. @cite{sum(x)} represents the sum of all the values of @cite{x}.
  3242. While there is an actual @code{sum} function in Calc, it's easier to
  3243. sum a vector using a simple reduction. First, let's compute the four
  3244. different sums that this formula uses.
  3245. @smallexample
  3246. @group
  3247. 1: 41.63 1: 98.0003
  3248. . .
  3249. r 1 V R + t 3 r 1 2 V M ^ V R + t 4
  3250. @end group
  3251. @end smallexample
  3252. @noindent
  3253. @smallexample
  3254. @group
  3255. 1: 13.613 1: 33.36554
  3256. . .
  3257. r 2 V R + t 5 r 1 r 2 V M * V R + t 6
  3258. @end group
  3259. @end smallexample
  3260. @ifinfo
  3261. @noindent
  3262. These are @samp{sum(x)}, @samp{sum(x^2)}, @samp{sum(y)}, and @samp{sum(x y)},
  3263. respectively. (We could have used @kbd{*} to compute @samp{sum(x^2)} and
  3264. @samp{sum(x y)}.)
  3265. @end ifinfo
  3266. @tex
  3267. \turnoffactive
  3268. These are $\sum x$, $\sum x^2$, $\sum y$, and $\sum x y$,
  3269. respectively. (We could have used \kbd{*} to compute $\sum x^2$ and
  3270. $\sum x y$.)
  3271. @end tex
  3272. Finally, we also need @cite{N}, the number of data points. This is just
  3273. the length of either of our lists.
  3274. @smallexample
  3275. @group
  3276. 1: 19
  3277. .
  3278. r 1 v l t 7
  3279. @end group
  3280. @end smallexample
  3281. @noindent
  3282. (That's @kbd{v} followed by a lower-case @kbd{l}.)
  3283. Now we grind through the formula:
  3284. @smallexample
  3285. @group
  3286. 1: 633.94526 2: 633.94526 1: 67.23607
  3287. . 1: 566.70919 .
  3288. .
  3289. r 7 r 6 * r 3 r 5 * -
  3290. @end group
  3291. @end smallexample
  3292. @noindent
  3293. @smallexample
  3294. @group
  3295. 2: 67.23607 3: 67.23607 2: 67.23607 1: 0.52141679
  3296. 1: 1862.0057 2: 1862.0057 1: 128.9488 .
  3297. . 1: 1733.0569 .
  3298. .
  3299. r 7 r 4 * r 3 2 ^ - / t 8
  3300. @end group
  3301. @end smallexample
  3302. That gives us the slope @cite{m}. The y-intercept @cite{b} can now
  3303. be found with the simple formula,
  3304. @ifinfo
  3305. @example
  3306. b = (sum(y) - m sum(x)) / N
  3307. @end example
  3308. @end ifinfo
  3309. @tex
  3310. \turnoffactive
  3311. \beforedisplay
  3312. $$ b = {\sum y - m \sum x \over N} $$
  3313. \afterdisplay
  3314. \vskip10pt
  3315. @end tex
  3316. @smallexample
  3317. @group
  3318. 1: 13.613 2: 13.613 1: -8.09358 1: -0.425978
  3319. . 1: 21.70658 . .
  3320. .
  3321. r 5 r 8 r 3 * - r 7 / t 9
  3322. @end group
  3323. @end smallexample
  3324. Let's ``plot'' this straight line approximation, @c{$y \approx m x + b$}
  3325. @cite{m x + b}, and compare it with the original data.@refill
  3326. @smallexample
  3327. @group
  3328. 1: [0.699, 0.735, ... ] 1: [0.273, 0.309, ... ]
  3329. . .
  3330. r 1 r 8 * r 9 + s 0
  3331. @end group
  3332. @end smallexample
  3333. @noindent
  3334. Notice that multiplying a vector by a constant, and adding a constant
  3335. to a vector, can be done without mapping commands since these are
  3336. common operations from vector algebra. As far as Calc is concerned,
  3337. we've just been doing geometry in 19-dimensional space!
  3338. We can subtract this vector from our original @cite{y} vector to get
  3339. a feel for the error of our fit. Let's find the maximum error:
  3340. @smallexample
  3341. @group
  3342. 1: [0.0387, 0.0112, ... ] 1: [0.0387, 0.0112, ... ] 1: 0.0897
  3343. . . .
  3344. r 2 - V M A V R X
  3345. @end group
  3346. @end smallexample
  3347. @noindent
  3348. First we compute a vector of differences, then we take the absolute
  3349. values of these differences, then we reduce the @code{max} function
  3350. across the vector. (The @code{max} function is on the two-key sequence
  3351. @kbd{f x}; because it is so common to use @code{max} in a vector
  3352. operation, the letters @kbd{X} and @kbd{N} are also accepted for
  3353. @code{max} and @code{min} in this context. In general, you answer
  3354. the @kbd{V M} or @kbd{V R} prompt with the actual key sequence that
  3355. invokes the function you want. You could have typed @kbd{V R f x} or
  3356. even @kbd{V R x max @key{RET}} if you had preferred.)
  3357. If your system has the GNUPLOT program, you can see graphs of your
  3358. data and your straight line to see how well they match. (If you have
  3359. GNUPLOT 3.0, the following instructions will work regardless of the
  3360. kind of display you have. Some GNUPLOT 2.0, non-X-windows systems
  3361. may require additional steps to view the graphs.)
  3362. Let's start by plotting the original data. Recall the ``@var{x}'' and ``@var{y}''
  3363. vectors onto the stack and press @kbd{g f}. This ``fast'' graphing
  3364. command does everything you need to do for simple, straightforward
  3365. plotting of data.
  3366. @smallexample
  3367. @group
  3368. 2: [1.34, 1.41, 1.49, ... ]
  3369. 1: [0.234, 0.298, 0.402, ... ]
  3370. .
  3371. r 1 r 2 g f
  3372. @end group
  3373. @end smallexample
  3374. If all goes well, you will shortly get a new window containing a graph
  3375. of the data. (If not, contact your GNUPLOT or Calc installer to find
  3376. out what went wrong.) In the X window system, this will be a separate
  3377. graphics window. For other kinds of displays, the default is to
  3378. display the graph in Emacs itself using rough character graphics.
  3379. Press @kbd{q} when you are done viewing the character graphics.
  3380. Next, let's add the line we got from our least-squares fit:
  3381. @smallexample
  3382. @group
  3383. 2: [1.34, 1.41, 1.49, ... ]
  3384. 1: [0.273, 0.309, 0.351, ... ]
  3385. .
  3386. @key{DEL} r 0 g a g p
  3387. @end group
  3388. @end smallexample
  3389. It's not very useful to get symbols to mark the data points on this
  3390. second curve; you can type @kbd{g S g p} to remove them. Type @kbd{g q}
  3391. when you are done to remove the X graphics window and terminate GNUPLOT.
  3392. (@bullet{}) @strong{Exercise 2.} An earlier exercise showed how to do
  3393. least squares fitting to a general system of equations. Our 19 data
  3394. points are really 19 equations of the form @cite{y_i = m x_i + b} for
  3395. different pairs of @cite{(x_i,y_i)}. Use the matrix-transpose method
  3396. to solve for @cite{m} and @cite{b}, duplicating the above result.
  3397. @xref{List Answer 2, 2}. (@bullet{})
  3398. @cindex Geometric mean
  3399. (@bullet{}) @strong{Exercise 3.} If the input data do not form a
  3400. rectangle, you can use @w{@kbd{M-# g}} (@code{calc-grab-region})
  3401. to grab the data the way Emacs normally works with regions---it reads
  3402. left-to-right, top-to-bottom, treating line breaks the same as spaces.
  3403. Use this command to find the geometric mean of the following numbers.
  3404. (The geometric mean is the @var{n}th root of the product of @var{n} numbers.)
  3405. @example
  3406. 2.3 6 22 15.1 7
  3407. 15 14 7.5
  3408. 2.5
  3409. @end example
  3410. @noindent
  3411. The @kbd{M-# g} command accepts numbers separated by spaces or commas,
  3412. with or without surrounding vector brackets.
  3413. @xref{List Answer 3, 3}. (@bullet{})
  3414. @ifinfo
  3415. As another example, a theorem about binomial coefficients tells
  3416. us that the alternating sum of binomial coefficients
  3417. @var{n}-choose-0 minus @var{n}-choose-1 plus @var{n}-choose-2, and so
  3418. on up to @var{n}-choose-@var{n},
  3419. always comes out to zero. Let's verify this
  3420. for @cite{n=6}.@refill
  3421. @end ifinfo
  3422. @tex
  3423. As another example, a theorem about binomial coefficients tells
  3424. us that the alternating sum of binomial coefficients
  3425. ${n \choose 0} - {n \choose 1} + {n \choose 2} - \cdots \pm {n \choose n}$
  3426. always comes out to zero. Let's verify this
  3427. for \cite{n=6}.
  3428. @end tex
  3429. @smallexample
  3430. @group
  3431. 1: [1, 2, 3, 4, 5, 6, 7] 1: [0, 1, 2, 3, 4, 5, 6]
  3432. . .
  3433. v x 7 @key{RET} 1 -
  3434. @end group
  3435. @end smallexample
  3436. @noindent
  3437. @smallexample
  3438. @group
  3439. 1: [1, -6, 15, -20, 15, -6, 1] 1: 0
  3440. . .
  3441. V M ' (-1)^$ choose(6,$) @key{RET} V R +
  3442. @end group
  3443. @end smallexample
  3444. The @kbd{V M '} command prompts you to enter any algebraic expression
  3445. to define the function to map over the vector. The symbol @samp{$}
  3446. inside this expression represents the argument to the function.
  3447. The Calculator applies this formula to each element of the vector,
  3448. substituting each element's value for the @samp{$} sign(s) in turn.
  3449. To define a two-argument function, use @samp{$$} for the first
  3450. argument and @samp{$} for the second: @kbd{V M ' $$-$ @key{RET}} is
  3451. equivalent to @kbd{V M -}. This is analogous to regular algebraic
  3452. entry, where @samp{$$} would refer to the next-to-top stack entry
  3453. and @samp{$} would refer to the top stack entry, and @kbd{' $$-$ @key{RET}}
  3454. would act exactly like @kbd{-}.
  3455. Notice that the @kbd{V M '} command has recorded two things in the
  3456. trail: The result, as usual, and also a funny-looking thing marked
  3457. @samp{oper} that represents the operator function you typed in.
  3458. The function is enclosed in @samp{< >} brackets, and the argument is
  3459. denoted by a @samp{#} sign. If there were several arguments, they
  3460. would be shown as @samp{#1}, @samp{#2}, and so on. (For example,
  3461. @kbd{V M ' $$-$} will put the function @samp{<#1 - #2>} on the
  3462. trail.) This object is a ``nameless function''; you can use nameless
  3463. @w{@samp{< >}} notation to answer the @kbd{V M '} prompt if you like.
  3464. Nameless function notation has the interesting, occasionally useful
  3465. property that a nameless function is not actually evaluated until
  3466. it is used. For example, @kbd{V M ' $+random(2.0)} evaluates
  3467. @samp{random(2.0)} once and adds that random number to all elements
  3468. of the vector, but @kbd{V M ' <#+random(2.0)>} evaluates the
  3469. @samp{random(2.0)} separately for each vector element.
  3470. Another group of operators that are often useful with @kbd{V M} are
  3471. the relational operators: @kbd{a =}, for example, compares two numbers
  3472. and gives the result 1 if they are equal, or 0 if not. Similarly,
  3473. @w{@kbd{a <}} checks for one number being less than another.
  3474. Other useful vector operations include @kbd{v v}, to reverse a
  3475. vector end-for-end; @kbd{V S}, to sort the elements of a vector
  3476. into increasing order; and @kbd{v r} and @w{@kbd{v c}}, to extract
  3477. one row or column of a matrix, or (in both cases) to extract one
  3478. element of a plain vector. With a negative argument, @kbd{v r}
  3479. and @kbd{v c} instead delete one row, column, or vector element.
  3480. @cindex Divisor functions
  3481. (@bullet{}) @strong{Exercise 4.} The @cite{k}th @dfn{divisor function}
  3482. @tex
  3483. $\sigma_k(n)$
  3484. @end tex
  3485. is the sum of the @cite{k}th powers of all the divisors of an
  3486. integer @cite{n}. Figure out a method for computing the divisor
  3487. function for reasonably small values of @cite{n}. As a test,
  3488. the 0th and 1st divisor functions of 30 are 8 and 72, respectively.
  3489. @xref{List Answer 4, 4}. (@bullet{})
  3490. @cindex Square-free numbers
  3491. @cindex Duplicate values in a list
  3492. (@bullet{}) @strong{Exercise 5.} The @kbd{k f} command produces a
  3493. list of prime factors for a number. Sometimes it is important to
  3494. know that a number is @dfn{square-free}, i.e., that no prime occurs
  3495. more than once in its list of prime factors. Find a sequence of
  3496. keystrokes to tell if a number is square-free; your method should
  3497. leave 1 on the stack if it is, or 0 if it isn't.
  3498. @xref{List Answer 5, 5}. (@bullet{})
  3499. @cindex Triangular lists
  3500. (@bullet{}) @strong{Exercise 6.} Build a list of lists that looks
  3501. like the following diagram. (You may wish to use the @kbd{v /}
  3502. command to enable multi-line display of vectors.)
  3503. @smallexample
  3504. @group
  3505. 1: [ [1],
  3506. [1, 2],
  3507. [1, 2, 3],
  3508. [1, 2, 3, 4],
  3509. [1, 2, 3, 4, 5],
  3510. [1, 2, 3, 4, 5, 6] ]
  3511. @end group
  3512. @end smallexample
  3513. @noindent
  3514. @xref{List Answer 6, 6}. (@bullet{})
  3515. (@bullet{}) @strong{Exercise 7.} Build the following list of lists.
  3516. @smallexample
  3517. @group
  3518. 1: [ [0],
  3519. [1, 2],
  3520. [3, 4, 5],
  3521. [6, 7, 8, 9],
  3522. [10, 11, 12, 13, 14],
  3523. [15, 16, 17, 18, 19, 20] ]
  3524. @end group
  3525. @end smallexample
  3526. @noindent
  3527. @xref{List Answer 7, 7}. (@bullet{})
  3528. @cindex Maximizing a function over a list of values
  3529. @c [fix-ref Numerical Solutions]
  3530. (@bullet{}) @strong{Exercise 8.} Compute a list of values of Bessel's
  3531. @c{$J_1(x)$}
  3532. @cite{J1} function @samp{besJ(1,x)} for @cite{x} from 0 to 5
  3533. in steps of 0.25.
  3534. Find the value of @cite{x} (from among the above set of values) for
  3535. which @samp{besJ(1,x)} is a maximum. Use an ``automatic'' method,
  3536. i.e., just reading along the list by hand to find the largest value
  3537. is not allowed! (There is an @kbd{a X} command which does this kind
  3538. of thing automatically; @pxref{Numerical Solutions}.)
  3539. @xref{List Answer 8, 8}. (@bullet{})@refill
  3540. @cindex Digits, vectors of
  3541. (@bullet{}) @strong{Exercise 9.} You are given an integer in the range
  3542. @c{$0 \le N < 10^m$}
  3543. @cite{0 <= N < 10^m} for @cite{m=12} (i.e., an integer of less than
  3544. twelve digits). Convert this integer into a vector of @cite{m}
  3545. digits, each in the range from 0 to 9. In vector-of-digits notation,
  3546. add one to this integer to produce a vector of @cite{m+1} digits
  3547. (since there could be a carry out of the most significant digit).
  3548. Convert this vector back into a regular integer. A good integer
  3549. to try is 25129925999. @xref{List Answer 9, 9}. (@bullet{})
  3550. (@bullet{}) @strong{Exercise 10.} Your friend Joe tried to use
  3551. @kbd{V R a =} to test if all numbers in a list were equal. What
  3552. happened? How would you do this test? @xref{List Answer 10, 10}. (@bullet{})
  3553. (@bullet{}) @strong{Exercise 11.} The area of a circle of radius one
  3554. is @c{$\pi$}
  3555. @cite{pi}. The area of the @c{$2\times2$}
  3556. @asis{2x2} square that encloses that
  3557. circle is 4. So if we throw @var{n} darts at random points in the square,
  3558. about @c{$\pi/4$}
  3559. @cite{pi/4} of them will land inside the circle. This gives us
  3560. an entertaining way to estimate the value of @c{$\pi$}
  3561. @cite{pi}. The @w{@kbd{k r}}
  3562. command picks a random number between zero and the value on the stack.
  3563. We could get a random floating-point number between @i{-1} and 1 by typing
  3564. @w{@kbd{2.0 k r 1 -}}. Build a vector of 100 random @cite{(x,y)} points in
  3565. this square, then use vector mapping and reduction to count how many
  3566. points lie inside the unit circle. Hint: Use the @kbd{v b} command.
  3567. @xref{List Answer 11, 11}. (@bullet{})
  3568. @cindex Matchstick problem
  3569. (@bullet{}) @strong{Exercise 12.} The @dfn{matchstick problem} provides
  3570. another way to calculate @c{$\pi$}
  3571. @cite{pi}. Say you have an infinite field
  3572. of vertical lines with a spacing of one inch. Toss a one-inch matchstick
  3573. onto the field. The probability that the matchstick will land crossing
  3574. a line turns out to be @c{$2/\pi$}
  3575. @cite{2/pi}. Toss 100 matchsticks to estimate
  3576. @c{$\pi$}
  3577. @cite{pi}. (If you want still more fun, the probability that the GCD
  3578. (@w{@kbd{k g}}) of two large integers is one turns out to be @c{$6/\pi^2$}
  3579. @cite{6/pi^2}.
  3580. That provides yet another way to estimate @c{$\pi$}
  3581. @cite{pi}.)
  3582. @xref{List Answer 12, 12}. (@bullet{})
  3583. (@bullet{}) @strong{Exercise 13.} An algebraic entry of a string in
  3584. double-quote marks, @samp{"hello"}, creates a vector of the numerical
  3585. (ASCII) codes of the characters (here, @cite{[104, 101, 108, 108, 111]}).
  3586. Sometimes it is convenient to compute a @dfn{hash code} of a string,
  3587. which is just an integer that represents the value of that string.
  3588. Two equal strings have the same hash code; two different strings
  3589. @dfn{probably} have different hash codes. (For example, Calc has
  3590. over 400 function names, but Emacs can quickly find the definition for
  3591. any given name because it has sorted the functions into ``buckets'' by
  3592. their hash codes. Sometimes a few names will hash into the same bucket,
  3593. but it is easier to search among a few names than among all the names.)
  3594. One popular hash function is computed as follows: First set @cite{h = 0}.
  3595. Then, for each character from the string in turn, set @cite{h = 3h + c_i}
  3596. where @cite{c_i} is the character's ASCII code. If we have 511 buckets,
  3597. we then take the hash code modulo 511 to get the bucket number. Develop a
  3598. simple command or commands for converting string vectors into hash codes.
  3599. The hash code for @samp{"Testing, 1, 2, 3"} is 1960915098, which modulo
  3600. 511 is 121. @xref{List Answer 13, 13}. (@bullet{})
  3601. (@bullet{}) @strong{Exercise 14.} The @kbd{H V R} and @kbd{H V U}
  3602. commands do nested function evaluations. @kbd{H V U} takes a starting
  3603. value and a number of steps @var{n} from the stack; it then applies the
  3604. function you give to the starting value 0, 1, 2, up to @var{n} times
  3605. and returns a vector of the results. Use this command to create a
  3606. ``random walk'' of 50 steps. Start with the two-dimensional point
  3607. @cite{(0,0)}; then take one step a random distance between @i{-1} and 1
  3608. in both @cite{x} and @cite{y}; then take another step, and so on. Use the
  3609. @kbd{g f} command to display this random walk. Now modify your random
  3610. walk to walk a unit distance, but in a random direction, at each step.
  3611. (Hint: The @code{sincos} function returns a vector of the cosine and
  3612. sine of an angle.) @xref{List Answer 14, 14}. (@bullet{})
  3613. @node Types Tutorial, Algebra Tutorial, Vector/Matrix Tutorial, Tutorial
  3614. @section Types Tutorial
  3615. @noindent
  3616. Calc understands a variety of data types as well as simple numbers.
  3617. In this section, we'll experiment with each of these types in turn.
  3618. The numbers we've been using so far have mainly been either @dfn{integers}
  3619. or @dfn{floats}. We saw that floats are usually a good approximation to
  3620. the mathematical concept of real numbers, but they are only approximations
  3621. and are susceptible to roundoff error. Calc also supports @dfn{fractions},
  3622. which can exactly represent any rational number.
  3623. @smallexample
  3624. @group
  3625. 1: 3628800 2: 3628800 1: 518400:7 1: 518414:7 1: 7:518414
  3626. . 1: 49 . . .
  3627. .
  3628. 10 ! 49 @key{RET} : 2 + &
  3629. @end group
  3630. @end smallexample
  3631. @noindent
  3632. The @kbd{:} command divides two integers to get a fraction; @kbd{/}
  3633. would normally divide integers to get a floating-point result.
  3634. Notice we had to type @key{RET} between the @kbd{49} and the @kbd{:}
  3635. since the @kbd{:} would otherwise be interpreted as part of a
  3636. fraction beginning with 49.
  3637. You can convert between floating-point and fractional format using
  3638. @kbd{c f} and @kbd{c F}:
  3639. @smallexample
  3640. @group
  3641. 1: 1.35027217629e-5 1: 7:518414
  3642. . .
  3643. c f c F
  3644. @end group
  3645. @end smallexample
  3646. The @kbd{c F} command replaces a floating-point number with the
  3647. ``simplest'' fraction whose floating-point representation is the
  3648. same, to within the current precision.
  3649. @smallexample
  3650. @group
  3651. 1: 3.14159265359 1: 1146408:364913 1: 3.1416 1: 355:113
  3652. . . . .
  3653. P c F @key{DEL} p 5 @key{RET} P c F
  3654. @end group
  3655. @end smallexample
  3656. (@bullet{}) @strong{Exercise 1.} A calculation has produced the
  3657. result 1.26508260337. You suspect it is the square root of the
  3658. product of @c{$\pi$}
  3659. @cite{pi} and some rational number. Is it? (Be sure
  3660. to allow for roundoff error!) @xref{Types Answer 1, 1}. (@bullet{})
  3661. @dfn{Complex numbers} can be stored in both rectangular and polar form.
  3662. @smallexample
  3663. @group
  3664. 1: -9 1: (0, 3) 1: (3; 90.) 1: (6; 90.) 1: (2.4495; 45.)
  3665. . . . . .
  3666. 9 n Q c p 2 * Q
  3667. @end group
  3668. @end smallexample
  3669. @noindent
  3670. The square root of @i{-9} is by default rendered in rectangular form
  3671. (@w{@cite{0 + 3i}}), but we can convert it to polar form (3 with a
  3672. phase angle of 90 degrees). All the usual arithmetic and scientific
  3673. operations are defined on both types of complex numbers.
  3674. Another generalized kind of number is @dfn{infinity}. Infinity
  3675. isn't really a number, but it can sometimes be treated like one.
  3676. Calc uses the symbol @code{inf} to represent positive infinity,
  3677. i.e., a value greater than any real number. Naturally, you can
  3678. also write @samp{-inf} for minus infinity, a value less than any
  3679. real number. The word @code{inf} can only be input using
  3680. algebraic entry.
  3681. @smallexample
  3682. @group
  3683. 2: inf 2: -inf 2: -inf 2: -inf 1: nan
  3684. 1: -17 1: -inf 1: -inf 1: inf .
  3685. . . . .
  3686. ' inf @key{RET} 17 n * @key{RET} 72 + A +
  3687. @end group
  3688. @end smallexample
  3689. @noindent
  3690. Since infinity is infinitely large, multiplying it by any finite
  3691. number (like @i{-17}) has no effect, except that since @i{-17}
  3692. is negative, it changes a plus infinity to a minus infinity.
  3693. (``A huge positive number, multiplied by @i{-17}, yields a huge
  3694. negative number.'') Adding any finite number to infinity also
  3695. leaves it unchanged. Taking an absolute value gives us plus
  3696. infinity again. Finally, we add this plus infinity to the minus
  3697. infinity we had earlier. If you work it out, you might expect
  3698. the answer to be @i{-72} for this. But the 72 has been completely
  3699. lost next to the infinities; by the time we compute @w{@samp{inf - inf}}
  3700. the finite difference between them, if any, is indetectable.
  3701. So we say the result is @dfn{indeterminate}, which Calc writes
  3702. with the symbol @code{nan} (for Not A Number).
  3703. Dividing by zero is normally treated as an error, but you can get
  3704. Calc to write an answer in terms of infinity by pressing @kbd{m i}
  3705. to turn on ``infinite mode.''
  3706. @smallexample
  3707. @group
  3708. 3: nan 2: nan 2: nan 2: nan 1: nan
  3709. 2: 1 1: 1 / 0 1: uinf 1: uinf .
  3710. 1: 0 . . .
  3711. .
  3712. 1 @key{RET} 0 / m i U / 17 n * +
  3713. @end group
  3714. @end smallexample
  3715. @noindent
  3716. Dividing by zero normally is left unevaluated, but after @kbd{m i}
  3717. it instead gives an infinite result. The answer is actually
  3718. @code{uinf}, ``undirected infinity.'' If you look at a graph of
  3719. @cite{1 / x} around @w{@cite{x = 0}}, you'll see that it goes toward
  3720. plus infinity as you approach zero from above, but toward minus
  3721. infinity as you approach from below. Since we said only @cite{1 / 0},
  3722. Calc knows that the answer is infinite but not in which direction.
  3723. That's what @code{uinf} means. Notice that multiplying @code{uinf}
  3724. by a negative number still leaves plain @code{uinf}; there's no
  3725. point in saying @samp{-uinf} because the sign of @code{uinf} is
  3726. unknown anyway. Finally, we add @code{uinf} to our @code{nan},
  3727. yielding @code{nan} again. It's easy to see that, because
  3728. @code{nan} means ``totally unknown'' while @code{uinf} means
  3729. ``unknown sign but known to be infinite,'' the more mysterious
  3730. @code{nan} wins out when it is combined with @code{uinf}, or, for
  3731. that matter, with anything else.
  3732. (@bullet{}) @strong{Exercise 2.} Predict what Calc will answer
  3733. for each of these formulas: @samp{inf / inf}, @samp{exp(inf)},
  3734. @samp{exp(-inf)}, @samp{sqrt(-inf)}, @samp{sqrt(uinf)},
  3735. @samp{abs(uinf)}, @samp{ln(0)}.
  3736. @xref{Types Answer 2, 2}. (@bullet{})
  3737. (@bullet{}) @strong{Exercise 3.} We saw that @samp{inf - inf = nan},
  3738. which stands for an unknown value. Can @code{nan} stand for
  3739. a complex number? Can it stand for infinity?
  3740. @xref{Types Answer 3, 3}. (@bullet{})
  3741. @dfn{HMS forms} represent a value in terms of hours, minutes, and
  3742. seconds.
  3743. @smallexample
  3744. @group
  3745. 1: 2@@ 30' 0" 1: 3@@ 30' 0" 2: 3@@ 30' 0" 1: 2.
  3746. . . 1: 1@@ 45' 0." .
  3747. .
  3748. 2@@ 30' @key{RET} 1 + @key{RET} 2 / /
  3749. @end group
  3750. @end smallexample
  3751. HMS forms can also be used to hold angles in degrees, minutes, and
  3752. seconds.
  3753. @smallexample
  3754. @group
  3755. 1: 0.5 1: 26.56505 1: 26@@ 33' 54.18" 1: 0.44721
  3756. . . . .
  3757. 0.5 I T c h S
  3758. @end group
  3759. @end smallexample
  3760. @noindent
  3761. First we convert the inverse tangent of 0.5 to degrees-minutes-seconds
  3762. form, then we take the sine of that angle. Note that the trigonometric
  3763. functions will accept HMS forms directly as input.
  3764. @cindex Beatles
  3765. (@bullet{}) @strong{Exercise 4.} The Beatles' @emph{Abbey Road} is
  3766. 47 minutes and 26 seconds long, and contains 17 songs. What is the
  3767. average length of a song on @emph{Abbey Road}? If the Extended Disco
  3768. Version of @emph{Abbey Road} added 20 seconds to the length of each
  3769. song, how long would the album be? @xref{Types Answer 4, 4}. (@bullet{})
  3770. A @dfn{date form} represents a date, or a date and time. Dates must
  3771. be entered using algebraic entry. Date forms are surrounded by
  3772. @samp{< >} symbols; most standard formats for dates are recognized.
  3773. @smallexample
  3774. @group
  3775. 2: <Sun Jan 13, 1991> 1: 2.25
  3776. 1: <6:00pm Thu Jan 10, 1991> .
  3777. .
  3778. ' <13 Jan 1991>, <1/10/91, 6pm> @key{RET} -
  3779. @end group
  3780. @end smallexample
  3781. @noindent
  3782. In this example, we enter two dates, then subtract to find the
  3783. number of days between them. It is also possible to add an
  3784. HMS form or a number (of days) to a date form to get another
  3785. date form.
  3786. @smallexample
  3787. @group
  3788. 1: <4:45:59pm Mon Jan 14, 1991> 1: <2:50:59am Thu Jan 17, 1991>
  3789. . .
  3790. t N 2 + 10@@ 5' +
  3791. @end group
  3792. @end smallexample
  3793. @c [fix-ref Date Arithmetic]
  3794. @noindent
  3795. The @kbd{t N} (``now'') command pushes the current date and time on the
  3796. stack; then we add two days, ten hours and five minutes to the date and
  3797. time. Other date-and-time related commands include @kbd{t J}, which
  3798. does Julian day conversions, @kbd{t W}, which finds the beginning of
  3799. the week in which a date form lies, and @kbd{t I}, which increments a
  3800. date by one or several months. @xref{Date Arithmetic}, for more.
  3801. (@bullet{}) @strong{Exercise 5.} How many days until the next
  3802. Friday the 13th? @xref{Types Answer 5, 5}. (@bullet{})
  3803. (@bullet{}) @strong{Exercise 6.} How many leap years will there be
  3804. between now and the year 10001 A.D.? @xref{Types Answer 6, 6}. (@bullet{})
  3805. @cindex Slope and angle of a line
  3806. @cindex Angle and slope of a line
  3807. An @dfn{error form} represents a mean value with an attached standard
  3808. deviation, or error estimate. Suppose our measurements indicate that
  3809. a certain telephone pole is about 30 meters away, with an estimated
  3810. error of 1 meter, and 8 meters tall, with an estimated error of 0.2
  3811. meters. What is the slope of a line from here to the top of the
  3812. pole, and what is the equivalent angle in degrees?
  3813. @smallexample
  3814. @group
  3815. 1: 8 +/- 0.2 2: 8 +/- 0.2 1: 0.266 +/- 0.011 1: 14.93 +/- 0.594
  3816. . 1: 30 +/- 1 . .
  3817. .
  3818. 8 p .2 @key{RET} 30 p 1 / I T
  3819. @end group
  3820. @end smallexample
  3821. @noindent
  3822. This means that the angle is about 15 degrees, and, assuming our
  3823. original error estimates were valid standard deviations, there is about
  3824. a 60% chance that the result is correct within 0.59 degrees.
  3825. @cindex Torus, volume of
  3826. (@bullet{}) @strong{Exercise 7.} The volume of a torus (a donut shape) is
  3827. @c{$2 \pi^2 R r^2$}
  3828. @w{@cite{2 pi^2 R r^2}} where @cite{R} is the radius of the circle that
  3829. defines the center of the tube and @cite{r} is the radius of the tube
  3830. itself. Suppose @cite{R} is 20 cm and @cite{r} is 4 cm, each known to
  3831. within 5 percent. What is the volume and the relative uncertainty of
  3832. the volume? @xref{Types Answer 7, 7}. (@bullet{})
  3833. An @dfn{interval form} represents a range of values. While an
  3834. error form is best for making statistical estimates, intervals give
  3835. you exact bounds on an answer. Suppose we additionally know that
  3836. our telephone pole is definitely between 28 and 31 meters away,
  3837. and that it is between 7.7 and 8.1 meters tall.
  3838. @smallexample
  3839. @group
  3840. 1: [7.7 .. 8.1] 2: [7.7 .. 8.1] 1: [0.24 .. 0.28] 1: [13.9 .. 16.1]
  3841. . 1: [28 .. 31] . .
  3842. .
  3843. [ 7.7 .. 8.1 ] [ 28 .. 31 ] / I T
  3844. @end group
  3845. @end smallexample
  3846. @noindent
  3847. If our bounds were correct, then the angle to the top of the pole
  3848. is sure to lie in the range shown.
  3849. The square brackets around these intervals indicate that the endpoints
  3850. themselves are allowable values. In other words, the distance to the
  3851. telephone pole is between 28 and 31, @emph{inclusive}. You can also
  3852. make an interval that is exclusive of its endpoints by writing
  3853. parentheses instead of square brackets. You can even make an interval
  3854. which is inclusive (``closed'') on one end and exclusive (``open'') on
  3855. the other.
  3856. @smallexample
  3857. @group
  3858. 1: [1 .. 10) 1: (0.1 .. 1] 2: (0.1 .. 1] 1: (0.2 .. 3)
  3859. . . 1: [2 .. 3) .
  3860. .
  3861. [ 1 .. 10 ) & [ 2 .. 3 ) *
  3862. @end group
  3863. @end smallexample
  3864. @noindent
  3865. The Calculator automatically keeps track of which end values should
  3866. be open and which should be closed. You can also make infinite or
  3867. semi-infinite intervals by using @samp{-inf} or @samp{inf} for one
  3868. or both endpoints.
  3869. (@bullet{}) @strong{Exercise 8.} What answer would you expect from
  3870. @samp{@w{1 /} @w{(0 .. 10)}}? What about @samp{@w{1 /} @w{(-10 .. 0)}}? What
  3871. about @samp{@w{1 /} @w{[0 .. 10]}} (where the interval actually includes
  3872. zero)? What about @samp{@w{1 /} @w{(-10 .. 10)}}?
  3873. @xref{Types Answer 8, 8}. (@bullet{})
  3874. (@bullet{}) @strong{Exercise 9.} Two easy ways of squaring a number
  3875. are @kbd{@key{RET} *} and @w{@kbd{2 ^}}. Normally these produce the same
  3876. answer. Would you expect this still to hold true for interval forms?
  3877. If not, which of these will result in a larger interval?
  3878. @xref{Types Answer 9, 9}. (@bullet{})
  3879. A @dfn{modulo form} is used for performing arithmetic modulo @var{m}.
  3880. For example, arithmetic involving time is generally done modulo 12
  3881. or 24 hours.
  3882. @smallexample
  3883. @group
  3884. 1: 17 mod 24 1: 3 mod 24 1: 21 mod 24 1: 9 mod 24
  3885. . . . .
  3886. 17 M 24 @key{RET} 10 + n 5 /
  3887. @end group
  3888. @end smallexample
  3889. @noindent
  3890. In this last step, Calc has found a new number which, when multiplied
  3891. by 5 modulo 24, produces the original number, 21. If @var{m} is prime
  3892. it is always possible to find such a number. For non-prime @var{m}
  3893. like 24, it is only sometimes possible.
  3894. @smallexample
  3895. @group
  3896. 1: 10 mod 24 1: 16 mod 24 1: 1000000... 1: 16
  3897. . . . .
  3898. 10 M 24 @key{RET} 100 ^ 10 @key{RET} 100 ^ 24 %
  3899. @end group
  3900. @end smallexample
  3901. @noindent
  3902. These two calculations get the same answer, but the first one is
  3903. much more efficient because it avoids the huge intermediate value
  3904. that arises in the second one.
  3905. @cindex Fermat, primality test of
  3906. (@bullet{}) @strong{Exercise 10.} A theorem of Pierre de Fermat
  3907. says that @c{\w{$x^{n-1} \bmod n = 1$}}
  3908. @cite{x^(n-1) mod n = 1} if @cite{n} is a prime number
  3909. and @cite{x} is an integer less than @cite{n}. If @cite{n} is
  3910. @emph{not} a prime number, this will @emph{not} be true for most
  3911. values of @cite{x}. Thus we can test informally if a number is
  3912. prime by trying this formula for several values of @cite{x}.
  3913. Use this test to tell whether the following numbers are prime:
  3914. 811749613, 15485863. @xref{Types Answer 10, 10}. (@bullet{})
  3915. It is possible to use HMS forms as parts of error forms, intervals,
  3916. modulo forms, or as the phase part of a polar complex number.
  3917. For example, the @code{calc-time} command pushes the current time
  3918. of day on the stack as an HMS/modulo form.
  3919. @smallexample
  3920. @group
  3921. 1: 17@@ 34' 45" mod 24@@ 0' 0" 1: 6@@ 22' 15" mod 24@@ 0' 0"
  3922. . .
  3923. x time @key{RET} n
  3924. @end group
  3925. @end smallexample
  3926. @noindent
  3927. This calculation tells me it is six hours and 22 minutes until midnight.
  3928. (@bullet{}) @strong{Exercise 11.} A rule of thumb is that one year
  3929. is about @c{$\pi \times 10^7$}
  3930. @w{@cite{pi * 10^7}} seconds. What time will it be that
  3931. many seconds from right now? @xref{Types Answer 11, 11}. (@bullet{})
  3932. (@bullet{}) @strong{Exercise 12.} You are preparing to order packaging
  3933. for the CD release of the Extended Disco Version of @emph{Abbey Road}.
  3934. You are told that the songs will actually be anywhere from 20 to 60
  3935. seconds longer than the originals. One CD can hold about 75 minutes
  3936. of music. Should you order single or double packages?
  3937. @xref{Types Answer 12, 12}. (@bullet{})
  3938. Another kind of data the Calculator can manipulate is numbers with
  3939. @dfn{units}. This isn't strictly a new data type; it's simply an
  3940. application of algebraic expressions, where we use variables with
  3941. suggestive names like @samp{cm} and @samp{in} to represent units
  3942. like centimeters and inches.
  3943. @smallexample
  3944. @group
  3945. 1: 2 in 1: 5.08 cm 1: 0.027778 fath 1: 0.0508 m
  3946. . . . .
  3947. ' 2in @key{RET} u c cm @key{RET} u c fath @key{RET} u b
  3948. @end group
  3949. @end smallexample
  3950. @noindent
  3951. We enter the quantity ``2 inches'' (actually an algebraic expression
  3952. which means two times the variable @samp{in}), then we convert it
  3953. first to centimeters, then to fathoms, then finally to ``base'' units,
  3954. which in this case means meters.
  3955. @smallexample
  3956. @group
  3957. 1: 9 acre 1: 3 sqrt(acre) 1: 190.84 m 1: 190.84 m + 30 cm
  3958. . . . .
  3959. ' 9 acre @key{RET} Q u s ' $+30 cm @key{RET}
  3960. @end group
  3961. @end smallexample
  3962. @noindent
  3963. @smallexample
  3964. @group
  3965. 1: 191.14 m 1: 36536.3046 m^2 1: 365363046 cm^2
  3966. . . .
  3967. u s 2 ^ u c cgs
  3968. @end group
  3969. @end smallexample
  3970. @noindent
  3971. Since units expressions are really just formulas, taking the square
  3972. root of @samp{acre} is undefined. After all, @code{acre} might be an
  3973. algebraic variable that you will someday assign a value. We use the
  3974. ``units-simplify'' command to simplify the expression with variables
  3975. being interpreted as unit names.
  3976. In the final step, we have converted not to a particular unit, but to a
  3977. units system. The ``cgs'' system uses centimeters instead of meters
  3978. as its standard unit of length.
  3979. There is a wide variety of units defined in the Calculator.
  3980. @smallexample
  3981. @group
  3982. 1: 55 mph 1: 88.5139 kph 1: 88.5139 km / hr 1: 8.201407e-8 c
  3983. . . . .
  3984. ' 55 mph @key{RET} u c kph @key{RET} u c km/hr @key{RET} u c c @key{RET}
  3985. @end group
  3986. @end smallexample
  3987. @noindent
  3988. We express a speed first in miles per hour, then in kilometers per
  3989. hour, then again using a slightly more explicit notation, then
  3990. finally in terms of fractions of the speed of light.
  3991. Temperature conversions are a bit more tricky. There are two ways to
  3992. interpret ``20 degrees Fahrenheit''---it could mean an actual
  3993. temperature, or it could mean a change in temperature. For normal
  3994. units there is no difference, but temperature units have an offset
  3995. as well as a scale factor and so there must be two explicit commands
  3996. for them.
  3997. @smallexample
  3998. @group
  3999. 1: 20 degF 1: 11.1111 degC 1: -20:3 degC 1: -6.666 degC
  4000. . . . .
  4001. ' 20 degF @key{RET} u c degC @key{RET} U u t degC @key{RET} c f
  4002. @end group
  4003. @end smallexample
  4004. @noindent
  4005. First we convert a change of 20 degrees Fahrenheit into an equivalent
  4006. change in degrees Celsius (or Centigrade). Then, we convert the
  4007. absolute temperature 20 degrees Fahrenheit into Celsius. Since
  4008. this comes out as an exact fraction, we then convert to floating-point
  4009. for easier comparison with the other result.
  4010. For simple unit conversions, you can put a plain number on the stack.
  4011. Then @kbd{u c} and @kbd{u t} will prompt for both old and new units.
  4012. When you use this method, you're responsible for remembering which
  4013. numbers are in which units:
  4014. @smallexample
  4015. @group
  4016. 1: 55 1: 88.5139 1: 8.201407e-8
  4017. . . .
  4018. 55 u c mph @key{RET} kph @key{RET} u c km/hr @key{RET} c @key{RET}
  4019. @end group
  4020. @end smallexample
  4021. To see a complete list of built-in units, type @kbd{u v}. Press
  4022. @w{@kbd{M-# c}} again to re-enter the Calculator when you're done looking
  4023. at the units table.
  4024. (@bullet{}) @strong{Exercise 13.} How many seconds are there really
  4025. in a year? @xref{Types Answer 13, 13}. (@bullet{})
  4026. @cindex Speed of light
  4027. (@bullet{}) @strong{Exercise 14.} Supercomputer designs are limited by
  4028. the speed of light (and of electricity, which is nearly as fast).
  4029. Suppose a computer has a 4.1 ns (nanosecond) clock cycle, and its
  4030. cabinet is one meter across. Is speed of light going to be a
  4031. significant factor in its design? @xref{Types Answer 14, 14}. (@bullet{})
  4032. (@bullet{}) @strong{Exercise 15.} Sam the Slug normally travels about
  4033. five yards in an hour. He has obtained a supply of Power Pills; each
  4034. Power Pill he eats doubles his speed. How many Power Pills can he
  4035. swallow and still travel legally on most US highways?
  4036. @xref{Types Answer 15, 15}. (@bullet{})
  4037. @node Algebra Tutorial, Programming Tutorial, Types Tutorial, Tutorial
  4038. @section Algebra and Calculus Tutorial
  4039. @noindent
  4040. This section shows how to use Calc's algebra facilities to solve
  4041. equations, do simple calculus problems, and manipulate algebraic
  4042. formulas.
  4043. @menu
  4044. * Basic Algebra Tutorial::
  4045. * Rewrites Tutorial::
  4046. @end menu
  4047. @node Basic Algebra Tutorial, Rewrites Tutorial, Algebra Tutorial, Algebra Tutorial
  4048. @subsection Basic Algebra
  4049. @noindent
  4050. If you enter a formula in algebraic mode that refers to variables,
  4051. the formula itself is pushed onto the stack. You can manipulate
  4052. formulas as regular data objects.
  4053. @smallexample
  4054. @group
  4055. 1: 2 x^2 - 6 1: 6 - 2 x^2 1: (6 - 2 x^2) (3 x^2 + y)
  4056. . . .
  4057. ' 2x^2-6 @key{RET} n ' 3x^2+y @key{RET} *
  4058. @end group
  4059. @end smallexample
  4060. (@bullet{}) @strong{Exercise 1.} Do @kbd{' x @key{RET} Q 2 ^} and
  4061. @kbd{' x @key{RET} 2 ^ Q} both wind up with the same result (@samp{x})?
  4062. Why or why not? @xref{Algebra Answer 1, 1}. (@bullet{})
  4063. There are also commands for doing common algebraic operations on
  4064. formulas. Continuing with the formula from the last example,
  4065. @smallexample
  4066. @group
  4067. 1: 18 x^2 + 6 y - 6 x^4 - 2 x^2 y 1: (18 - 2 y) x^2 - 6 x^4 + 6 y
  4068. . .
  4069. a x a c x @key{RET}
  4070. @end group
  4071. @end smallexample
  4072. @noindent
  4073. First we ``expand'' using the distributive law, then we ``collect''
  4074. terms involving like powers of @cite{x}.
  4075. Let's find the value of this expression when @cite{x} is 2 and @cite{y}
  4076. is one-half.
  4077. @smallexample
  4078. @group
  4079. 1: 17 x^2 - 6 x^4 + 3 1: -25
  4080. . .
  4081. 1:2 s l y @key{RET} 2 s l x @key{RET}
  4082. @end group
  4083. @end smallexample
  4084. @noindent
  4085. The @kbd{s l} command means ``let''; it takes a number from the top of
  4086. the stack and temporarily assigns it as the value of the variable
  4087. you specify. It then evaluates (as if by the @kbd{=} key) the
  4088. next expression on the stack. After this command, the variable goes
  4089. back to its original value, if any.
  4090. (An earlier exercise in this tutorial involved storing a value in the
  4091. variable @code{x}; if this value is still there, you will have to
  4092. unstore it with @kbd{s u x @key{RET}} before the above example will work
  4093. properly.)
  4094. @cindex Maximum of a function using Calculus
  4095. Let's find the maximum value of our original expression when @cite{y}
  4096. is one-half and @cite{x} ranges over all possible values. We can
  4097. do this by taking the derivative with respect to @cite{x} and examining
  4098. values of @cite{x} for which the derivative is zero. If the second
  4099. derivative of the function at that value of @cite{x} is negative,
  4100. the function has a local maximum there.
  4101. @smallexample
  4102. @group
  4103. 1: 17 x^2 - 6 x^4 + 3 1: 34 x - 24 x^3
  4104. . .
  4105. U @key{DEL} s 1 a d x @key{RET} s 2
  4106. @end group
  4107. @end smallexample
  4108. @noindent
  4109. Well, the derivative is clearly zero when @cite{x} is zero. To find
  4110. the other root(s), let's divide through by @cite{x} and then solve:
  4111. @smallexample
  4112. @group
  4113. 1: (34 x - 24 x^3) / x 1: 34 x / x - 24 x^3 / x 1: 34 - 24 x^2
  4114. . . .
  4115. ' x @key{RET} / a x a s
  4116. @end group
  4117. @end smallexample
  4118. @noindent
  4119. @smallexample
  4120. @group
  4121. 1: 34 - 24 x^2 = 0 1: x = 1.19023
  4122. . .
  4123. 0 a = s 3 a S x @key{RET}
  4124. @end group
  4125. @end smallexample
  4126. @noindent
  4127. Notice the use of @kbd{a s} to ``simplify'' the formula. When the
  4128. default algebraic simplifications don't do enough, you can use
  4129. @kbd{a s} to tell Calc to spend more time on the job.
  4130. Now we compute the second derivative and plug in our values of @cite{x}:
  4131. @smallexample
  4132. @group
  4133. 1: 1.19023 2: 1.19023 2: 1.19023
  4134. . 1: 34 x - 24 x^3 1: 34 - 72 x^2
  4135. . .
  4136. a . r 2 a d x @key{RET} s 4
  4137. @end group
  4138. @end smallexample
  4139. @noindent
  4140. (The @kbd{a .} command extracts just the righthand side of an equation.
  4141. Another method would have been to use @kbd{v u} to unpack the equation
  4142. @w{@samp{x = 1.19}} to @samp{x} and @samp{1.19}, then use @kbd{M-- M-2 @key{DEL}}
  4143. to delete the @samp{x}.)
  4144. @smallexample
  4145. @group
  4146. 2: 34 - 72 x^2 1: -68. 2: 34 - 72 x^2 1: 34
  4147. 1: 1.19023 . 1: 0 .
  4148. . .
  4149. @key{TAB} s l x @key{RET} U @key{DEL} 0 s l x @key{RET}
  4150. @end group
  4151. @end smallexample
  4152. @noindent
  4153. The first of these second derivatives is negative, so we know the function
  4154. has a maximum value at @cite{x = 1.19023}. (The function also has a
  4155. local @emph{minimum} at @cite{x = 0}.)
  4156. When we solved for @cite{x}, we got only one value even though
  4157. @cite{34 - 24 x^2 = 0} is a quadratic equation that ought to have
  4158. two solutions. The reason is that @w{@kbd{a S}} normally returns a
  4159. single ``principal'' solution. If it needs to come up with an
  4160. arbitrary sign (as occurs in the quadratic formula) it picks @cite{+}.
  4161. If it needs an arbitrary integer, it picks zero. We can get a full
  4162. solution by pressing @kbd{H} (the Hyperbolic flag) before @kbd{a S}.
  4163. @smallexample
  4164. @group
  4165. 1: 34 - 24 x^2 = 0 1: x = 1.19023 s1 1: x = -1.19023
  4166. . . .
  4167. r 3 H a S x @key{RET} s 5 1 n s l s1 @key{RET}
  4168. @end group
  4169. @end smallexample
  4170. @noindent
  4171. Calc has invented the variable @samp{s1} to represent an unknown sign;
  4172. it is supposed to be either @i{+1} or @i{-1}. Here we have used
  4173. the ``let'' command to evaluate the expression when the sign is negative.
  4174. If we plugged this into our second derivative we would get the same,
  4175. negative, answer, so @cite{x = -1.19023} is also a maximum.
  4176. To find the actual maximum value, we must plug our two values of @cite{x}
  4177. into the original formula.
  4178. @smallexample
  4179. @group
  4180. 2: 17 x^2 - 6 x^4 + 3 1: 24.08333 s1^2 - 12.04166 s1^4 + 3
  4181. 1: x = 1.19023 s1 .
  4182. .
  4183. r 1 r 5 s l @key{RET}
  4184. @end group
  4185. @end smallexample
  4186. @noindent
  4187. (Here we see another way to use @kbd{s l}; if its input is an equation
  4188. with a variable on the lefthand side, then @kbd{s l} treats the equation
  4189. like an assignment to that variable if you don't give a variable name.)
  4190. It's clear that this will have the same value for either sign of
  4191. @code{s1}, but let's work it out anyway, just for the exercise:
  4192. @smallexample
  4193. @group
  4194. 2: [-1, 1] 1: [15.04166, 15.04166]
  4195. 1: 24.08333 s1^2 ... .
  4196. .
  4197. [ 1 n , 1 ] @key{TAB} V M $ @key{RET}
  4198. @end group
  4199. @end smallexample
  4200. @noindent
  4201. Here we have used a vector mapping operation to evaluate the function
  4202. at several values of @samp{s1} at once. @kbd{V M $} is like @kbd{V M '}
  4203. except that it takes the formula from the top of the stack. The
  4204. formula is interpreted as a function to apply across the vector at the
  4205. next-to-top stack level. Since a formula on the stack can't contain
  4206. @samp{$} signs, Calc assumes the variables in the formula stand for
  4207. different arguments. It prompts you for an @dfn{argument list}, giving
  4208. the list of all variables in the formula in alphabetical order as the
  4209. default list. In this case the default is @samp{(s1)}, which is just
  4210. what we want so we simply press @key{RET} at the prompt.
  4211. If there had been several different values, we could have used
  4212. @w{@kbd{V R X}} to find the global maximum.
  4213. Calc has a built-in @kbd{a P} command that solves an equation using
  4214. @w{@kbd{H a S}} and returns a vector of all the solutions. It simply
  4215. automates the job we just did by hand. Applied to our original
  4216. cubic polynomial, it would produce the vector of solutions
  4217. @cite{[1.19023, -1.19023, 0]}. (There is also an @kbd{a X} command
  4218. which finds a local maximum of a function. It uses a numerical search
  4219. method rather than examining the derivatives, and thus requires you
  4220. to provide some kind of initial guess to show it where to look.)
  4221. (@bullet{}) @strong{Exercise 2.} Given a vector of the roots of a
  4222. polynomial (such as the output of an @kbd{a P} command), what
  4223. sequence of commands would you use to reconstruct the original
  4224. polynomial? (The answer will be unique to within a constant
  4225. multiple; choose the solution where the leading coefficient is one.)
  4226. @xref{Algebra Answer 2, 2}. (@bullet{})
  4227. The @kbd{m s} command enables ``symbolic mode,'' in which formulas
  4228. like @samp{sqrt(5)} that can't be evaluated exactly are left in
  4229. symbolic form rather than giving a floating-point approximate answer.
  4230. Fraction mode (@kbd{m f}) is also useful when doing algebra.
  4231. @smallexample
  4232. @group
  4233. 2: 34 x - 24 x^3 2: 34 x - 24 x^3
  4234. 1: 34 x - 24 x^3 1: [sqrt(51) / 6, sqrt(51) / -6, 0]
  4235. . .
  4236. r 2 @key{RET} m s m f a P x @key{RET}
  4237. @end group
  4238. @end smallexample
  4239. One more mode that makes reading formulas easier is ``Big mode.''
  4240. @smallexample
  4241. @group
  4242. 3
  4243. 2: 34 x - 24 x
  4244. ____ ____
  4245. V 51 V 51
  4246. 1: [-----, -----, 0]
  4247. 6 -6
  4248. .
  4249. d B
  4250. @end group
  4251. @end smallexample
  4252. Here things like powers, square roots, and quotients and fractions
  4253. are displayed in a two-dimensional pictorial form. Calc has other
  4254. language modes as well, such as C mode, FORTRAN mode, and @TeX{} mode.
  4255. @smallexample
  4256. @group
  4257. 2: 34*x - 24*pow(x, 3) 2: 34*x - 24*x**3
  4258. 1: @{sqrt(51) / 6, sqrt(51) / -6, 0@} 1: /sqrt(51) / 6, sqrt(51) / -6, 0/
  4259. . .
  4260. d C d F
  4261. @end group
  4262. @end smallexample
  4263. @noindent
  4264. @smallexample
  4265. @group
  4266. 3: 34 x - 24 x^3
  4267. 2: [@{\sqrt@{51@} \over 6@}, @{\sqrt@{51@} \over -6@}, 0]
  4268. 1: @{2 \over 3@} \sqrt@{5@}
  4269. .
  4270. d T ' 2 \sqrt@{5@} \over 3 @key{RET}
  4271. @end group
  4272. @end smallexample
  4273. @noindent
  4274. As you can see, language modes affect both entry and display of
  4275. formulas. They affect such things as the names used for built-in
  4276. functions, the set of arithmetic operators and their precedences,
  4277. and notations for vectors and matrices.
  4278. Notice that @samp{sqrt(51)} may cause problems with older
  4279. implementations of C and FORTRAN, which would require something more
  4280. like @samp{sqrt(51.0)}. It is always wise to check over the formulas
  4281. produced by the various language modes to make sure they are fully
  4282. correct.
  4283. Type @kbd{m s}, @kbd{m f}, and @kbd{d N} to reset these modes. (You
  4284. may prefer to remain in Big mode, but all the examples in the tutorial
  4285. are shown in normal mode.)
  4286. @cindex Area under a curve
  4287. What is the area under the portion of this curve from @cite{x = 1} to @cite{2}?
  4288. This is simply the integral of the function:
  4289. @smallexample
  4290. @group
  4291. 1: 17 x^2 - 6 x^4 + 3 1: 5.6666 x^3 - 1.2 x^5 + 3 x
  4292. . .
  4293. r 1 a i x
  4294. @end group
  4295. @end smallexample
  4296. @noindent
  4297. We want to evaluate this at our two values for @cite{x} and subtract.
  4298. One way to do it is again with vector mapping and reduction:
  4299. @smallexample
  4300. @group
  4301. 2: [2, 1] 1: [12.93333, 7.46666] 1: 5.46666
  4302. 1: 5.6666 x^3 ... . .
  4303. [ 2 , 1 ] @key{TAB} V M $ @key{RET} V R -
  4304. @end group
  4305. @end smallexample
  4306. (@bullet{}) @strong{Exercise 3.} Find the integral from 1 to @cite{y}
  4307. of @c{$x \sin \pi x$}
  4308. @w{@cite{x sin(pi x)}} (where the sine is calculated in radians).
  4309. Find the values of the integral for integers @cite{y} from 1 to 5.
  4310. @xref{Algebra Answer 3, 3}. (@bullet{})
  4311. Calc's integrator can do many simple integrals symbolically, but many
  4312. others are beyond its capabilities. Suppose we wish to find the area
  4313. under the curve @c{$\sin x \ln x$}
  4314. @cite{sin(x) ln(x)} over the same range of @cite{x}. If
  4315. you entered this formula and typed @kbd{a i x @key{RET}} (don't bother to try
  4316. this), Calc would work for a long time but would be unable to find a
  4317. solution. In fact, there is no closed-form solution to this integral.
  4318. Now what do we do?
  4319. @cindex Integration, numerical
  4320. @cindex Numerical integration
  4321. One approach would be to do the integral numerically. It is not hard
  4322. to do this by hand using vector mapping and reduction. It is rather
  4323. slow, though, since the sine and logarithm functions take a long time.
  4324. We can save some time by reducing the working precision.
  4325. @smallexample
  4326. @group
  4327. 3: 10 1: [1, 1.1, 1.2, ... , 1.8, 1.9]
  4328. 2: 1 .
  4329. 1: 0.1
  4330. .
  4331. 10 @key{RET} 1 @key{RET} .1 @key{RET} C-u v x
  4332. @end group
  4333. @end smallexample
  4334. @noindent
  4335. (Note that we have used the extended version of @kbd{v x}; we could
  4336. also have used plain @kbd{v x} as follows: @kbd{v x 10 @key{RET} 9 + .1 *}.)
  4337. @smallexample
  4338. @group
  4339. 2: [1, 1.1, ... ] 1: [0., 0.084941, 0.16993, ... ]
  4340. 1: sin(x) ln(x) .
  4341. .
  4342. ' sin(x) ln(x) @key{RET} s 1 m r p 5 @key{RET} V M $ @key{RET}
  4343. @end group
  4344. @end smallexample
  4345. @noindent
  4346. @smallexample
  4347. @group
  4348. 1: 3.4195 0.34195
  4349. . .
  4350. V R + 0.1 *
  4351. @end group
  4352. @end smallexample
  4353. @noindent
  4354. (If you got wildly different results, did you remember to switch
  4355. to radians mode?)
  4356. Here we have divided the curve into ten segments of equal width;
  4357. approximating these segments as rectangular boxes (i.e., assuming
  4358. the curve is nearly flat at that resolution), we compute the areas
  4359. of the boxes (height times width), then sum the areas. (It is
  4360. faster to sum first, then multiply by the width, since the width
  4361. is the same for every box.)
  4362. The true value of this integral turns out to be about 0.374, so
  4363. we're not doing too well. Let's try another approach.
  4364. @smallexample
  4365. @group
  4366. 1: sin(x) ln(x) 1: 0.84147 x - 0.84147 + 0.11957 (x - 1)^2 - ...
  4367. . .
  4368. r 1 a t x=1 @key{RET} 4 @key{RET}
  4369. @end group
  4370. @end smallexample
  4371. @noindent
  4372. Here we have computed the Taylor series expansion of the function
  4373. about the point @cite{x=1}. We can now integrate this polynomial
  4374. approximation, since polynomials are easy to integrate.
  4375. @smallexample
  4376. @group
  4377. 1: 0.42074 x^2 + ... 1: [-0.0446, -0.42073] 1: 0.3761
  4378. . . .
  4379. a i x @key{RET} [ 2 , 1 ] @key{TAB} V M $ @key{RET} V R -
  4380. @end group
  4381. @end smallexample
  4382. @noindent
  4383. Better! By increasing the precision and/or asking for more terms
  4384. in the Taylor series, we can get a result as accurate as we like.
  4385. (Taylor series converge better away from singularities in the
  4386. function such as the one at @code{ln(0)}, so it would also help to
  4387. expand the series about the points @cite{x=2} or @cite{x=1.5} instead
  4388. of @cite{x=1}.)
  4389. @cindex Simpson's rule
  4390. @cindex Integration by Simpson's rule
  4391. (@bullet{}) @strong{Exercise 4.} Our first method approximated the
  4392. curve by stairsteps of width 0.1; the total area was then the sum
  4393. of the areas of the rectangles under these stairsteps. Our second
  4394. method approximated the function by a polynomial, which turned out
  4395. to be a better approximation than stairsteps. A third method is
  4396. @dfn{Simpson's rule}, which is like the stairstep method except
  4397. that the steps are not required to be flat. Simpson's rule boils
  4398. down to the formula,
  4399. @ifinfo
  4400. @example
  4401. (h/3) * (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + ...
  4402. + 2 f(a+(n-2)*h) + 4 f(a+(n-1)*h) + f(a+n*h))
  4403. @end example
  4404. @end ifinfo
  4405. @tex
  4406. \turnoffactive
  4407. \beforedisplay
  4408. $$ \displaylines{
  4409. \qquad {h \over 3} (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + \cdots
  4410. \hfill \cr \hfill {} + 2 f(a+(n-2)h) + 4 f(a+(n-1)h) + f(a+n h)) \qquad
  4411. } $$
  4412. \afterdisplay
  4413. @end tex
  4414. @noindent
  4415. where @cite{n} (which must be even) is the number of slices and @cite{h}
  4416. is the width of each slice. These are 10 and 0.1 in our example.
  4417. For reference, here is the corresponding formula for the stairstep
  4418. method:
  4419. @ifinfo
  4420. @example
  4421. h * (f(a) + f(a+h) + f(a+2h) + f(a+3h) + ...
  4422. + f(a+(n-2)*h) + f(a+(n-1)*h))
  4423. @end example
  4424. @end ifinfo
  4425. @tex
  4426. \turnoffactive
  4427. \beforedisplay
  4428. $$ h (f(a) + f(a+h) + f(a+2h) + f(a+3h) + \cdots
  4429. + f(a+(n-2)h) + f(a+(n-1)h)) $$
  4430. \afterdisplay
  4431. @end tex
  4432. Compute the integral from 1 to 2 of @c{$\sin x \ln x$}
  4433. @cite{sin(x) ln(x)} using
  4434. Simpson's rule with 10 slices. @xref{Algebra Answer 4, 4}. (@bullet{})
  4435. Calc has a built-in @kbd{a I} command for doing numerical integration.
  4436. It uses @dfn{Romberg's method}, which is a more sophisticated cousin
  4437. of Simpson's rule. In particular, it knows how to keep refining the
  4438. result until the current precision is satisfied.
  4439. @c [fix-ref Selecting Sub-Formulas]
  4440. Aside from the commands we've seen so far, Calc also provides a
  4441. large set of commands for operating on parts of formulas. You
  4442. indicate the desired sub-formula by placing the cursor on any part
  4443. of the formula before giving a @dfn{selection} command. Selections won't
  4444. be covered in the tutorial; @pxref{Selecting Subformulas}, for
  4445. details and examples.
  4446. @c hard exercise: simplify (2^(n r) - 2^(r*(n - 1))) / (2^r - 1) 2^(n - 1)
  4447. @c to 2^((n-1)*(r-1)).
  4448. @node Rewrites Tutorial, , Basic Algebra Tutorial, Algebra Tutorial
  4449. @subsection Rewrite Rules
  4450. @noindent
  4451. No matter how many built-in commands Calc provided for doing algebra,
  4452. there would always be something you wanted to do that Calc didn't have
  4453. in its repertoire. So Calc also provides a @dfn{rewrite rule} system
  4454. that you can use to define your own algebraic manipulations.
  4455. Suppose we want to simplify this trigonometric formula:
  4456. @smallexample
  4457. @group
  4458. 1: 1 / cos(x) - sin(x) tan(x)
  4459. .
  4460. ' 1/cos(x) - sin(x) tan(x) @key{RET} s 1
  4461. @end group
  4462. @end smallexample
  4463. @noindent
  4464. If we were simplifying this by hand, we'd probably replace the
  4465. @samp{tan} with a @samp{sin/cos} first, then combine over a common
  4466. denominator. There is no Calc command to do the former; the @kbd{a n}
  4467. algebra command will do the latter but we'll do both with rewrite
  4468. rules just for practice.
  4469. Rewrite rules are written with the @samp{:=} symbol.
  4470. @smallexample
  4471. @group
  4472. 1: 1 / cos(x) - sin(x)^2 / cos(x)
  4473. .
  4474. a r tan(a) := sin(a)/cos(a) @key{RET}
  4475. @end group
  4476. @end smallexample
  4477. @noindent
  4478. (The ``assignment operator'' @samp{:=} has several uses in Calc. All
  4479. by itself the formula @samp{tan(a) := sin(a)/cos(a)} doesn't do anything,
  4480. but when it is given to the @kbd{a r} command, that command interprets
  4481. it as a rewrite rule.)
  4482. The lefthand side, @samp{tan(a)}, is called the @dfn{pattern} of the
  4483. rewrite rule. Calc searches the formula on the stack for parts that
  4484. match the pattern. Variables in a rewrite pattern are called
  4485. @dfn{meta-variables}, and when matching the pattern each meta-variable
  4486. can match any sub-formula. Here, the meta-variable @samp{a} matched
  4487. the actual variable @samp{x}.
  4488. When the pattern part of a rewrite rule matches a part of the formula,
  4489. that part is replaced by the righthand side with all the meta-variables
  4490. substituted with the things they matched. So the result is
  4491. @samp{sin(x) / cos(x)}. Calc's normal algebraic simplifications then
  4492. mix this in with the rest of the original formula.
  4493. To merge over a common denominator, we can use another simple rule:
  4494. @smallexample
  4495. @group
  4496. 1: (1 - sin(x)^2) / cos(x)
  4497. .
  4498. a r a/x + b/x := (a+b)/x @key{RET}
  4499. @end group
  4500. @end smallexample
  4501. This rule points out several interesting features of rewrite patterns.
  4502. First, if a meta-variable appears several times in a pattern, it must
  4503. match the same thing everywhere. This rule detects common denominators
  4504. because the same meta-variable @samp{x} is used in both of the
  4505. denominators.
  4506. Second, meta-variable names are independent from variables in the
  4507. target formula. Notice that the meta-variable @samp{x} here matches
  4508. the subformula @samp{cos(x)}; Calc never confuses the two meanings of
  4509. @samp{x}.
  4510. And third, rewrite patterns know a little bit about the algebraic
  4511. properties of formulas. The pattern called for a sum of two quotients;
  4512. Calc was able to match a difference of two quotients by matching
  4513. @samp{a = 1}, @samp{b = -sin(x)^2}, and @samp{x = cos(x)}.
  4514. @c [fix-ref Algebraic Properties of Rewrite Rules]
  4515. We could just as easily have written @samp{a/x - b/x := (a-b)/x} for
  4516. the rule. It would have worked just the same in all cases. (If we
  4517. really wanted the rule to apply only to @samp{+} or only to @samp{-},
  4518. we could have used the @code{plain} symbol. @xref{Algebraic Properties
  4519. of Rewrite Rules}, for some examples of this.)
  4520. One more rewrite will complete the job. We want to use the identity
  4521. @samp{sin(x)^2 + cos(x)^2 = 1}, but of course we must first rearrange
  4522. the identity in a way that matches our formula. The obvious rule
  4523. would be @samp{@w{1 - sin(x)^2} := cos(x)^2}, but a little thought shows
  4524. that the rule @samp{sin(x)^2 := 1 - cos(x)^2} will also work. The
  4525. latter rule has a more general pattern so it will work in many other
  4526. situations, too.
  4527. @smallexample
  4528. @group
  4529. 1: (1 + cos(x)^2 - 1) / cos(x) 1: cos(x)
  4530. . .
  4531. a r sin(x)^2 := 1 - cos(x)^2 @key{RET} a s
  4532. @end group
  4533. @end smallexample
  4534. You may ask, what's the point of using the most general rule if you
  4535. have to type it in every time anyway? The answer is that Calc allows
  4536. you to store a rewrite rule in a variable, then give the variable
  4537. name in the @kbd{a r} command. In fact, this is the preferred way to
  4538. use rewrites. For one, if you need a rule once you'll most likely
  4539. need it again later. Also, if the rule doesn't work quite right you
  4540. can simply Undo, edit the variable, and run the rule again without
  4541. having to retype it.
  4542. @smallexample
  4543. @group
  4544. ' tan(x) := sin(x)/cos(x) @key{RET} s t tsc @key{RET}
  4545. ' a/x + b/x := (a+b)/x @key{RET} s t merge @key{RET}
  4546. ' sin(x)^2 := 1 - cos(x)^2 @key{RET} s t sinsqr @key{RET}
  4547. 1: 1 / cos(x) - sin(x) tan(x) 1: cos(x)
  4548. . .
  4549. r 1 a r tsc @key{RET} a r merge @key{RET} a r sinsqr @key{RET} a s
  4550. @end group
  4551. @end smallexample
  4552. To edit a variable, type @kbd{s e} and the variable name, use regular
  4553. Emacs editing commands as necessary, then type @kbd{M-# M-#} or
  4554. @kbd{C-c C-c} to store the edited value back into the variable.
  4555. You can also use @w{@kbd{s e}} to create a new variable if you wish.
  4556. Notice that the first time you use each rule, Calc puts up a ``compiling''
  4557. message briefly. The pattern matcher converts rules into a special
  4558. optimized pattern-matching language rather than using them directly.
  4559. This allows @kbd{a r} to apply even rather complicated rules very
  4560. efficiently. If the rule is stored in a variable, Calc compiles it
  4561. only once and stores the compiled form along with the variable. That's
  4562. another good reason to store your rules in variables rather than
  4563. entering them on the fly.
  4564. (@bullet{}) @strong{Exercise 1.} Type @kbd{m s} to get symbolic
  4565. mode, then enter the formula @samp{@w{(2 + sqrt(2))} / @w{(1 + sqrt(2))}}.
  4566. Using a rewrite rule, simplify this formula by multiplying both
  4567. sides by the conjugate @w{@samp{1 - sqrt(2)}}. The result will have
  4568. to be expanded by the distributive law; do this with another
  4569. rewrite. @xref{Rewrites Answer 1, 1}. (@bullet{})
  4570. The @kbd{a r} command can also accept a vector of rewrite rules, or
  4571. a variable containing a vector of rules.
  4572. @smallexample
  4573. @group
  4574. 1: [tsc, merge, sinsqr] 1: [tan(x) := sin(x) / cos(x), ... ]
  4575. . .
  4576. ' [tsc,merge,sinsqr] @key{RET} =
  4577. @end group
  4578. @end smallexample
  4579. @noindent
  4580. @smallexample
  4581. @group
  4582. 1: 1 / cos(x) - sin(x) tan(x) 1: cos(x)
  4583. . .
  4584. s t trig @key{RET} r 1 a r trig @key{RET} a s
  4585. @end group
  4586. @end smallexample
  4587. @c [fix-ref Nested Formulas with Rewrite Rules]
  4588. Calc tries all the rules you give against all parts of the formula,
  4589. repeating until no further change is possible. (The exact order in
  4590. which things are tried is rather complex, but for simple rules like
  4591. the ones we've used here the order doesn't really matter.
  4592. @xref{Nested Formulas with Rewrite Rules}.)
  4593. Calc actually repeats only up to 100 times, just in case your rule set
  4594. has gotten into an infinite loop. You can give a numeric prefix argument
  4595. to @kbd{a r} to specify any limit. In particular, @kbd{M-1 a r} does
  4596. only one rewrite at a time.
  4597. @smallexample
  4598. @group
  4599. 1: 1 / cos(x) - sin(x)^2 / cos(x) 1: (1 - sin(x)^2) / cos(x)
  4600. . .
  4601. r 1 M-1 a r trig @key{RET} M-1 a r trig @key{RET}
  4602. @end group
  4603. @end smallexample
  4604. You can type @kbd{M-0 a r} if you want no limit at all on the number
  4605. of rewrites that occur.
  4606. Rewrite rules can also be @dfn{conditional}. Simply follow the rule
  4607. with a @samp{::} symbol and the desired condition. For example,
  4608. @smallexample
  4609. @group
  4610. 1: exp(2 pi i) + exp(3 pi i) + exp(4 pi i)
  4611. .
  4612. ' exp(2 pi i) + exp(3 pi i) + exp(4 pi i) @key{RET}
  4613. @end group
  4614. @end smallexample
  4615. @noindent
  4616. @smallexample
  4617. @group
  4618. 1: 1 + exp(3 pi i) + 1
  4619. .
  4620. a r exp(k pi i) := 1 :: k % 2 = 0 @key{RET}
  4621. @end group
  4622. @end smallexample
  4623. @noindent
  4624. (Recall, @samp{k % 2} is the remainder from dividing @samp{k} by 2,
  4625. which will be zero only when @samp{k} is an even integer.)
  4626. An interesting point is that the variables @samp{pi} and @samp{i}
  4627. were matched literally rather than acting as meta-variables.
  4628. This is because they are special-constant variables. The special
  4629. constants @samp{e}, @samp{phi}, and so on also match literally.
  4630. A common error with rewrite
  4631. rules is to write, say, @samp{f(a,b,c,d,e) := g(a+b+c+d+e)}, expecting
  4632. to match any @samp{f} with five arguments but in fact matching
  4633. only when the fifth argument is literally @samp{e}!@refill
  4634. @cindex Fibonacci numbers
  4635. @ignore
  4636. @starindex
  4637. @end ignore
  4638. @tindex fib
  4639. Rewrite rules provide an interesting way to define your own functions.
  4640. Suppose we want to define @samp{fib(n)} to produce the @var{n}th
  4641. Fibonacci number. The first two Fibonacci numbers are each 1;
  4642. later numbers are formed by summing the two preceding numbers in
  4643. the sequence. This is easy to express in a set of three rules:
  4644. @smallexample
  4645. @group
  4646. ' [fib(1) := 1, fib(2) := 1, fib(n) := fib(n-1) + fib(n-2)] @key{RET} s t fib
  4647. 1: fib(7) 1: 13
  4648. . .
  4649. ' fib(7) @key{RET} a r fib @key{RET}
  4650. @end group
  4651. @end smallexample
  4652. One thing that is guaranteed about the order that rewrites are tried
  4653. is that, for any given subformula, earlier rules in the rule set will
  4654. be tried for that subformula before later ones. So even though the
  4655. first and third rules both match @samp{fib(1)}, we know the first will
  4656. be used preferentially.
  4657. This rule set has one dangerous bug: Suppose we apply it to the
  4658. formula @samp{fib(x)}? (Don't actually try this.) The third rule
  4659. will match @samp{fib(x)} and replace it with @w{@samp{fib(x-1) + fib(x-2)}}.
  4660. Each of these will then be replaced to get @samp{fib(x-2) + 2 fib(x-3) +
  4661. fib(x-4)}, and so on, expanding forever. What we really want is to apply
  4662. the third rule only when @samp{n} is an integer greater than two. Type
  4663. @w{@kbd{s e fib @key{RET}}}, then edit the third rule to:
  4664. @smallexample
  4665. fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2
  4666. @end smallexample
  4667. @noindent
  4668. Now:
  4669. @smallexample
  4670. @group
  4671. 1: fib(6) + fib(x) + fib(0) 1: 8 + fib(x) + fib(0)
  4672. . .
  4673. ' fib(6)+fib(x)+fib(0) @key{RET} a r fib @key{RET}
  4674. @end group
  4675. @end smallexample
  4676. @noindent
  4677. We've created a new function, @code{fib}, and a new command,
  4678. @w{@kbd{a r fib @key{RET}}}, which means ``evaluate all @code{fib} calls in
  4679. this formula.'' To make things easier still, we can tell Calc to
  4680. apply these rules automatically by storing them in the special
  4681. variable @code{EvalRules}.
  4682. @smallexample
  4683. @group
  4684. 1: [fib(1) := ...] . 1: [8, 13]
  4685. . .
  4686. s r fib @key{RET} s t EvalRules @key{RET} ' [fib(6), fib(7)] @key{RET}
  4687. @end group
  4688. @end smallexample
  4689. It turns out that this rule set has the problem that it does far
  4690. more work than it needs to when @samp{n} is large. Consider the
  4691. first few steps of the computation of @samp{fib(6)}:
  4692. @smallexample
  4693. @group
  4694. fib(6) =
  4695. fib(5) + fib(4) =
  4696. fib(4) + fib(3) + fib(3) + fib(2) =
  4697. fib(3) + fib(2) + fib(2) + fib(1) + fib(2) + fib(1) + 1 = ...
  4698. @end group
  4699. @end smallexample
  4700. @noindent
  4701. Note that @samp{fib(3)} appears three times here. Unless Calc's
  4702. algebraic simplifier notices the multiple @samp{fib(3)}s and combines
  4703. them (and, as it happens, it doesn't), this rule set does lots of
  4704. needless recomputation. To cure the problem, type @code{s e EvalRules}
  4705. to edit the rules (or just @kbd{s E}, a shorthand command for editing
  4706. @code{EvalRules}) and add another condition:
  4707. @smallexample
  4708. fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2 :: remember
  4709. @end smallexample
  4710. @noindent
  4711. If a @samp{:: remember} condition appears anywhere in a rule, then if
  4712. that rule succeeds Calc will add another rule that describes that match
  4713. to the front of the rule set. (Remembering works in any rule set, but
  4714. for technical reasons it is most effective in @code{EvalRules}.) For
  4715. example, if the rule rewrites @samp{fib(7)} to something that evaluates
  4716. to 13, then the rule @samp{fib(7) := 13} will be added to the rule set.
  4717. Type @kbd{' fib(8) @key{RET}} to compute the eighth Fibonacci number, then
  4718. type @kbd{s E} again to see what has happened to the rule set.
  4719. With the @code{remember} feature, our rule set can now compute
  4720. @samp{fib(@var{n})} in just @var{n} steps. In the process it builds
  4721. up a table of all Fibonacci numbers up to @var{n}. After we have
  4722. computed the result for a particular @var{n}, we can get it back
  4723. (and the results for all smaller @var{n}) later in just one step.
  4724. All Calc operations will run somewhat slower whenever @code{EvalRules}
  4725. contains any rules. You should type @kbd{s u EvalRules @key{RET}} now to
  4726. un-store the variable.
  4727. (@bullet{}) @strong{Exercise 2.} Sometimes it is possible to reformulate
  4728. a problem to reduce the amount of recursion necessary to solve it.
  4729. Create a rule that, in about @var{n} simple steps and without recourse
  4730. to the @code{remember} option, replaces @samp{fib(@var{n}, 1, 1)} with
  4731. @samp{fib(1, @var{x}, @var{y})} where @var{x} and @var{y} are the
  4732. @var{n}th and @var{n+1}st Fibonacci numbers, respectively. This rule is
  4733. rather clunky to use, so add a couple more rules to make the ``user
  4734. interface'' the same as for our first version: enter @samp{fib(@var{n})},
  4735. get back a plain number. @xref{Rewrites Answer 2, 2}. (@bullet{})
  4736. There are many more things that rewrites can do. For example, there
  4737. are @samp{&&&} and @samp{|||} pattern operators that create ``and''
  4738. and ``or'' combinations of rules. As one really simple example, we
  4739. could combine our first two Fibonacci rules thusly:
  4740. @example
  4741. [fib(1 ||| 2) := 1, fib(n) := ... ]
  4742. @end example
  4743. @noindent
  4744. That means ``@code{fib} of something matching either 1 or 2 rewrites
  4745. to 1.''
  4746. You can also make meta-variables optional by enclosing them in @code{opt}.
  4747. For example, the pattern @samp{a + b x} matches @samp{2 + 3 x} but not
  4748. @samp{2 + x} or @samp{3 x} or @samp{x}. The pattern @samp{opt(a) + opt(b) x}
  4749. matches all of these forms, filling in a default of zero for @samp{a}
  4750. and one for @samp{b}.
  4751. (@bullet{}) @strong{Exercise 3.} Your friend Joe had @samp{2 + 3 x}
  4752. on the stack and tried to use the rule
  4753. @samp{opt(a) + opt(b) x := f(a, b, x)}. What happened?
  4754. @xref{Rewrites Answer 3, 3}. (@bullet{})
  4755. (@bullet{}) @strong{Exercise 4.} Starting with a positive integer @cite{a},
  4756. divide @cite{a} by two if it is even, otherwise compute @cite{3 a + 1}.
  4757. Now repeat this step over and over. A famous unproved conjecture
  4758. is that for any starting @cite{a}, the sequence always eventually
  4759. reaches 1. Given the formula @samp{seq(@var{a}, 0)}, write a set of
  4760. rules that convert this into @samp{seq(1, @var{n})} where @var{n}
  4761. is the number of steps it took the sequence to reach the value 1.
  4762. Now enhance the rules to accept @samp{seq(@var{a})} as a starting
  4763. configuration, and to stop with just the number @var{n} by itself.
  4764. Now make the result be a vector of values in the sequence, from @var{a}
  4765. to 1. (The formula @samp{@var{x}|@var{y}} appends the vectors @var{x}
  4766. and @var{y}.) For example, rewriting @samp{seq(6)} should yield the
  4767. vector @cite{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
  4768. @xref{Rewrites Answer 4, 4}. (@bullet{})
  4769. (@bullet{}) @strong{Exercise 5.} Define, using rewrite rules, a function
  4770. @samp{nterms(@var{x})} that returns the number of terms in the sum
  4771. @var{x}, or 1 if @var{x} is not a sum. (A @dfn{sum} for our purposes
  4772. is one or more non-sum terms separated by @samp{+} or @samp{-} signs,
  4773. so that @cite{2 - 3 (x + y) + x y} is a sum of three terms.)
  4774. @xref{Rewrites Answer 5, 5}. (@bullet{})
  4775. (@bullet{}) @strong{Exercise 6.} Calc considers the form @cite{0^0}
  4776. to be ``indeterminate,'' and leaves it unevaluated (assuming infinite
  4777. mode is not enabled). Some people prefer to define @cite{0^0 = 1},
  4778. so that the identity @cite{x^0 = 1} can safely be used for all @cite{x}.
  4779. Find a way to make Calc follow this convention. What happens if you
  4780. now type @kbd{m i} to turn on infinite mode?
  4781. @xref{Rewrites Answer 6, 6}. (@bullet{})
  4782. (@bullet{}) @strong{Exercise 7.} A Taylor series for a function is an
  4783. infinite series that exactly equals the value of that function at
  4784. values of @cite{x} near zero.
  4785. @ifinfo
  4786. @example
  4787. cos(x) = 1 - x^2 / 2! + x^4 / 4! - x^6 / 6! + ...
  4788. @end example
  4789. @end ifinfo
  4790. @tex
  4791. \turnoffactive \let\rm\goodrm
  4792. \beforedisplay
  4793. $$ \cos x = 1 - {x^2 \over 2!} + {x^4 \over 4!} - {x^6 \over 6!} + \cdots $$
  4794. \afterdisplay
  4795. @end tex
  4796. The @kbd{a t} command produces a @dfn{truncated Taylor series} which
  4797. is obtained by dropping all the terms higher than, say, @cite{x^2}.
  4798. Calc represents the truncated Taylor series as a polynomial in @cite{x}.
  4799. Mathematicians often write a truncated series using a ``big-O'' notation
  4800. that records what was the lowest term that was truncated.
  4801. @ifinfo
  4802. @example
  4803. cos(x) = 1 - x^2 / 2! + O(x^3)
  4804. @end example
  4805. @end ifinfo
  4806. @tex
  4807. \turnoffactive \let\rm\goodrm
  4808. \beforedisplay
  4809. $$ \cos x = 1 - {x^2 \over 2!} + O(x^3) $$
  4810. \afterdisplay
  4811. @end tex
  4812. @noindent
  4813. The meaning of @cite{O(x^3)} is ``a quantity which is negligibly small
  4814. if @cite{x^3} is considered negligibly small as @cite{x} goes to zero.''
  4815. The exercise is to create rewrite rules that simplify sums and products of
  4816. power series represented as @samp{@var{polynomial} + O(@var{var}^@var{n})}.
  4817. For example, given @samp{1 - x^2 / 2 + O(x^3)} and @samp{x - x^3 / 6 + O(x^4)}
  4818. on the stack, we want to be able to type @kbd{*} and get the result
  4819. @samp{x - 2:3 x^3 + O(x^4)}. Don't worry if the terms of the sum are
  4820. rearranged or if @kbd{a s} needs to be typed after rewriting. (This one
  4821. is rather tricky; the solution at the end of this chapter uses 6 rewrite
  4822. rules. Hint: The @samp{constant(x)} condition tests whether @samp{x} is
  4823. a number.) @xref{Rewrites Answer 7, 7}. (@bullet{})
  4824. @c [fix-ref Rewrite Rules]
  4825. @xref{Rewrite Rules}, for the whole story on rewrite rules.
  4826. @node Programming Tutorial, Answers to Exercises, Algebra Tutorial, Tutorial
  4827. @section Programming Tutorial
  4828. @noindent
  4829. The Calculator is written entirely in Emacs Lisp, a highly extensible
  4830. language. If you know Lisp, you can program the Calculator to do
  4831. anything you like. Rewrite rules also work as a powerful programming
  4832. system. But Lisp and rewrite rules take a while to master, and often
  4833. all you want to do is define a new function or repeat a command a few
  4834. times. Calc has features that allow you to do these things easily.
  4835. (Note that the programming commands relating to user-defined keys
  4836. are not yet supported under Lucid Emacs 19.)
  4837. One very limited form of programming is defining your own functions.
  4838. Calc's @kbd{Z F} command allows you to define a function name and
  4839. key sequence to correspond to any formula. Programming commands use
  4840. the shift-@kbd{Z} prefix; the user commands they create use the lower
  4841. case @kbd{z} prefix.
  4842. @smallexample
  4843. @group
  4844. 1: 1 + x + x^2 / 2 + x^3 / 6 1: 1 + x + x^2 / 2 + x^3 / 6
  4845. . .
  4846. ' 1 + x + x^2/2! + x^3/3! @key{RET} Z F e myexp @key{RET} @key{RET} @key{RET} y
  4847. @end group
  4848. @end smallexample
  4849. This polynomial is a Taylor series approximation to @samp{exp(x)}.
  4850. The @kbd{Z F} command asks a number of questions. The above answers
  4851. say that the key sequence for our function should be @kbd{z e}; the
  4852. @kbd{M-x} equivalent should be @code{calc-myexp}; the name of the
  4853. function in algebraic formulas should also be @code{myexp}; the
  4854. default argument list @samp{(x)} is acceptable; and finally @kbd{y}
  4855. answers the question ``leave it in symbolic form for non-constant
  4856. arguments?''
  4857. @smallexample
  4858. @group
  4859. 1: 1.3495 2: 1.3495 3: 1.3495
  4860. . 1: 1.34986 2: 1.34986
  4861. . 1: myexp(a + 1)
  4862. .
  4863. .3 z e .3 E ' a+1 @key{RET} z e
  4864. @end group
  4865. @end smallexample
  4866. @noindent
  4867. First we call our new @code{exp} approximation with 0.3 as an
  4868. argument, and compare it with the true @code{exp} function. Then
  4869. we note that, as requested, if we try to give @kbd{z e} an
  4870. argument that isn't a plain number, it leaves the @code{myexp}
  4871. function call in symbolic form. If we had answered @kbd{n} to the
  4872. final question, @samp{myexp(a + 1)} would have evaluated by plugging
  4873. in @samp{a + 1} for @samp{x} in the defining formula.
  4874. @cindex Sine integral Si(x)
  4875. @ignore
  4876. @starindex
  4877. @end ignore
  4878. @tindex Si
  4879. (@bullet{}) @strong{Exercise 1.} The ``sine integral'' function
  4880. @c{${\rm Si}(x)$}
  4881. @cite{Si(x)} is defined as the integral of @samp{sin(t)/t} for
  4882. @cite{t = 0} to @cite{x} in radians. (It was invented because this
  4883. integral has no solution in terms of basic functions; if you give it
  4884. to Calc's @kbd{a i} command, it will ponder it for a long time and then
  4885. give up.) We can use the numerical integration command, however,
  4886. which in algebraic notation is written like @samp{ninteg(f(t), t, 0, x)}
  4887. with any integrand @samp{f(t)}. Define a @kbd{z s} command and
  4888. @code{Si} function that implement this. You will need to edit the
  4889. default argument list a bit. As a test, @samp{Si(1)} should return
  4890. 0.946083. (Hint: @code{ninteg} will run a lot faster if you reduce
  4891. the precision to, say, six digits beforehand.)
  4892. @xref{Programming Answer 1, 1}. (@bullet{})
  4893. The simplest way to do real ``programming'' of Emacs is to define a
  4894. @dfn{keyboard macro}. A keyboard macro is simply a sequence of
  4895. keystrokes which Emacs has stored away and can play back on demand.
  4896. For example, if you find yourself typing @kbd{H a S x @key{RET}} often,
  4897. you may wish to program a keyboard macro to type this for you.
  4898. @smallexample
  4899. @group
  4900. 1: y = sqrt(x) 1: x = y^2
  4901. . .
  4902. ' y=sqrt(x) @key{RET} C-x ( H a S x @key{RET} C-x )
  4903. 1: y = cos(x) 1: x = s1 arccos(y) + 2 pi n1
  4904. . .
  4905. ' y=cos(x) @key{RET} X
  4906. @end group
  4907. @end smallexample
  4908. @noindent
  4909. When you type @kbd{C-x (}, Emacs begins recording. But it is also
  4910. still ready to execute your keystrokes, so you're really ``training''
  4911. Emacs by walking it through the procedure once. When you type
  4912. @w{@kbd{C-x )}}, the macro is recorded. You can now type @kbd{X} to
  4913. re-execute the same keystrokes.
  4914. You can give a name to your macro by typing @kbd{Z K}.
  4915. @smallexample
  4916. @group
  4917. 1: . 1: y = x^4 1: x = s2 sqrt(s1 sqrt(y))
  4918. . .
  4919. Z K x @key{RET} ' y=x^4 @key{RET} z x
  4920. @end group
  4921. @end smallexample
  4922. @noindent
  4923. Notice that we use shift-@kbd{Z} to define the command, and lower-case
  4924. @kbd{z} to call it up.
  4925. Keyboard macros can call other macros.
  4926. @smallexample
  4927. @group
  4928. 1: abs(x) 1: x = s1 y 1: 2 / x 1: x = 2 / y
  4929. . . . .
  4930. ' abs(x) @key{RET} C-x ( ' y @key{RET} a = z x C-x ) ' 2/x @key{RET} X
  4931. @end group
  4932. @end smallexample
  4933. (@bullet{}) @strong{Exercise 2.} Define a keyboard macro to negate
  4934. the item in level 3 of the stack, without disturbing the rest of
  4935. the stack. @xref{Programming Answer 2, 2}. (@bullet{})
  4936. (@bullet{}) @strong{Exercise 3.} Define keyboard macros to compute
  4937. the following functions:
  4938. @enumerate
  4939. @item
  4940. Compute @c{$\displaystyle{\sin x \over x}$}
  4941. @cite{sin(x) / x}, where @cite{x} is the number on the
  4942. top of the stack.
  4943. @item
  4944. Compute the base-@cite{b} logarithm, just like the @kbd{B} key except
  4945. the arguments are taken in the opposite order.
  4946. @item
  4947. Produce a vector of integers from 1 to the integer on the top of
  4948. the stack.
  4949. @end enumerate
  4950. @noindent
  4951. @xref{Programming Answer 3, 3}. (@bullet{})
  4952. (@bullet{}) @strong{Exercise 4.} Define a keyboard macro to compute
  4953. the average (mean) value of a list of numbers.
  4954. @xref{Programming Answer 4, 4}. (@bullet{})
  4955. In many programs, some of the steps must execute several times.
  4956. Calc has @dfn{looping} commands that allow this. Loops are useful
  4957. inside keyboard macros, but actually work at any time.
  4958. @smallexample
  4959. @group
  4960. 1: x^6 2: x^6 1: 360 x^2
  4961. . 1: 4 .
  4962. .
  4963. ' x^6 @key{RET} 4 Z < a d x @key{RET} Z >
  4964. @end group
  4965. @end smallexample
  4966. @noindent
  4967. Here we have computed the fourth derivative of @cite{x^6} by
  4968. enclosing a derivative command in a ``repeat loop'' structure.
  4969. This structure pops a repeat count from the stack, then
  4970. executes the body of the loop that many times.
  4971. If you make a mistake while entering the body of the loop,
  4972. type @w{@kbd{Z C-g}} to cancel the loop command.
  4973. @cindex Fibonacci numbers
  4974. Here's another example:
  4975. @smallexample
  4976. @group
  4977. 3: 1 2: 10946
  4978. 2: 1 1: 17711
  4979. 1: 20 .
  4980. .
  4981. 1 @key{RET} @key{RET} 20 Z < @key{TAB} C-j + Z >
  4982. @end group
  4983. @end smallexample
  4984. @noindent
  4985. The numbers in levels 2 and 1 should be the 21st and 22nd Fibonacci
  4986. numbers, respectively. (To see what's going on, try a few repetitions
  4987. of the loop body by hand; @kbd{C-j}, also on the Line-Feed or @key{LFD}
  4988. key if you have one, makes a copy of the number in level 2.)
  4989. @cindex Golden ratio
  4990. @cindex Phi, golden ratio
  4991. A fascinating property of the Fibonacci numbers is that the @cite{n}th
  4992. Fibonacci number can be found directly by computing @c{$\phi^n / \sqrt{5}$}
  4993. @cite{phi^n / sqrt(5)}
  4994. and then rounding to the nearest integer, where @c{$\phi$ (``phi'')}
  4995. @cite{phi}, the
  4996. ``golden ratio,'' is @c{$(1 + \sqrt{5}) / 2$}
  4997. @cite{(1 + sqrt(5)) / 2}. (For convenience, this constant is available
  4998. from the @code{phi} variable, or the @kbd{I H P} command.)
  4999. @smallexample
  5000. @group
  5001. 1: 1.61803 1: 24476.0000409 1: 10945.9999817 1: 10946
  5002. . . . .
  5003. I H P 21 ^ 5 Q / R
  5004. @end group
  5005. @end smallexample
  5006. @cindex Continued fractions
  5007. (@bullet{}) @strong{Exercise 5.} The @dfn{continued fraction}
  5008. representation of @c{$\phi$}
  5009. @cite{phi} is @c{$1 + 1/(1 + 1/(1 + 1/( \ldots )))$}
  5010. @cite{1 + 1/(1 + 1/(1 + 1/( ...@: )))}.
  5011. We can compute an approximate value by carrying this however far
  5012. and then replacing the innermost @c{$1/( \ldots )$}
  5013. @cite{1/( ...@: )} by 1. Approximate
  5014. @c{$\phi$}
  5015. @cite{phi} using a twenty-term continued fraction.
  5016. @xref{Programming Answer 5, 5}. (@bullet{})
  5017. (@bullet{}) @strong{Exercise 6.} Linear recurrences like the one for
  5018. Fibonacci numbers can be expressed in terms of matrices. Given a
  5019. vector @w{@cite{[a, b]}} determine a matrix which, when multiplied by this
  5020. vector, produces the vector @cite{[b, c]}, where @cite{a}, @cite{b} and
  5021. @cite{c} are three successive Fibonacci numbers. Now write a program
  5022. that, given an integer @cite{n}, computes the @cite{n}th Fibonacci number
  5023. using matrix arithmetic. @xref{Programming Answer 6, 6}. (@bullet{})
  5024. @cindex Harmonic numbers
  5025. A more sophisticated kind of loop is the @dfn{for} loop. Suppose
  5026. we wish to compute the 20th ``harmonic'' number, which is equal to
  5027. the sum of the reciprocals of the integers from 1 to 20.
  5028. @smallexample
  5029. @group
  5030. 3: 0 1: 3.597739
  5031. 2: 1 .
  5032. 1: 20
  5033. .
  5034. 0 @key{RET} 1 @key{RET} 20 Z ( & + 1 Z )
  5035. @end group
  5036. @end smallexample
  5037. @noindent
  5038. The ``for'' loop pops two numbers, the lower and upper limits, then
  5039. repeats the body of the loop as an internal counter increases from
  5040. the lower limit to the upper one. Just before executing the loop
  5041. body, it pushes the current loop counter. When the loop body
  5042. finishes, it pops the ``step,'' i.e., the amount by which to
  5043. increment the loop counter. As you can see, our loop always
  5044. uses a step of one.
  5045. This harmonic number function uses the stack to hold the running
  5046. total as well as for the various loop housekeeping functions. If
  5047. you find this disorienting, you can sum in a variable instead:
  5048. @smallexample
  5049. @group
  5050. 1: 0 2: 1 . 1: 3.597739
  5051. . 1: 20 .
  5052. .
  5053. 0 t 7 1 @key{RET} 20 Z ( & s + 7 1 Z ) r 7
  5054. @end group
  5055. @end smallexample
  5056. @noindent
  5057. The @kbd{s +} command adds the top-of-stack into the value in a
  5058. variable (and removes that value from the stack).
  5059. It's worth noting that many jobs that call for a ``for'' loop can
  5060. also be done more easily by Calc's high-level operations. Two
  5061. other ways to compute harmonic numbers are to use vector mapping
  5062. and reduction (@kbd{v x 20}, then @w{@kbd{V M &}}, then @kbd{V R +}),
  5063. or to use the summation command @kbd{a +}. Both of these are
  5064. probably easier than using loops. However, there are some
  5065. situations where loops really are the way to go:
  5066. (@bullet{}) @strong{Exercise 7.} Use a ``for'' loop to find the first
  5067. harmonic number which is greater than 4.0.
  5068. @xref{Programming Answer 7, 7}. (@bullet{})
  5069. Of course, if we're going to be using variables in our programs,
  5070. we have to worry about the programs clobbering values that the
  5071. caller was keeping in those same variables. This is easy to
  5072. fix, though:
  5073. @smallexample
  5074. @group
  5075. . 1: 0.6667 1: 0.6667 3: 0.6667
  5076. . . 2: 3.597739
  5077. 1: 0.6667
  5078. .
  5079. Z ` p 4 @key{RET} 2 @key{RET} 3 / s 7 s s a @key{RET} Z ' r 7 s r a @key{RET}
  5080. @end group
  5081. @end smallexample
  5082. @noindent
  5083. When we type @kbd{Z `} (that's a back-quote character), Calc saves
  5084. its mode settings and the contents of the ten ``quick variables''
  5085. for later reference. When we type @kbd{Z '} (that's an apostrophe
  5086. now), Calc restores those saved values. Thus the @kbd{p 4} and
  5087. @kbd{s 7} commands have no effect outside this sequence. Wrapping
  5088. this around the body of a keyboard macro ensures that it doesn't
  5089. interfere with what the user of the macro was doing. Notice that
  5090. the contents of the stack, and the values of named variables,
  5091. survive past the @kbd{Z '} command.
  5092. @cindex Bernoulli numbers, approximate
  5093. The @dfn{Bernoulli numbers} are a sequence with the interesting
  5094. property that all of the odd Bernoulli numbers are zero, and the
  5095. even ones, while difficult to compute, can be roughly approximated
  5096. by the formula @c{$\displaystyle{2 n! \over (2 \pi)^n}$}
  5097. @cite{2 n!@: / (2 pi)^n}. Let's write a keyboard
  5098. macro to compute (approximate) Bernoulli numbers. (Calc has a
  5099. command, @kbd{k b}, to compute exact Bernoulli numbers, but
  5100. this command is very slow for large @cite{n} since the higher
  5101. Bernoulli numbers are very large fractions.)
  5102. @smallexample
  5103. @group
  5104. 1: 10 1: 0.0756823
  5105. . .
  5106. 10 C-x ( @key{RET} 2 % Z [ @key{DEL} 0 Z : ' 2 $! / (2 pi)^$ @key{RET} = Z ] C-x )
  5107. @end group
  5108. @end smallexample
  5109. @noindent
  5110. You can read @kbd{Z [} as ``then,'' @kbd{Z :} as ``else,'' and
  5111. @kbd{Z ]} as ``end-if.'' There is no need for an explicit ``if''
  5112. command. For the purposes of @w{@kbd{Z [}}, the condition is ``true''
  5113. if the value it pops from the stack is a nonzero number, or ``false''
  5114. if it pops zero or something that is not a number (like a formula).
  5115. Here we take our integer argument modulo 2; this will be nonzero
  5116. if we're asking for an odd Bernoulli number.
  5117. The actual tenth Bernoulli number is @cite{5/66}.
  5118. @smallexample
  5119. @group
  5120. 3: 0.0756823 1: 0 1: 0.25305 1: 0 1: 1.16659
  5121. 2: 5:66 . . . .
  5122. 1: 0.0757575
  5123. .
  5124. 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
  5125. @end group
  5126. @end smallexample
  5127. Just to exercise loops a bit more, let's compute a table of even
  5128. Bernoulli numbers.
  5129. @smallexample
  5130. @group
  5131. 3: [] 1: [0.10132, 0.03079, 0.02340, 0.033197, ...]
  5132. 2: 2 .
  5133. 1: 30
  5134. .
  5135. [ ] 2 @key{RET} 30 Z ( X | 2 Z )
  5136. @end group
  5137. @end smallexample
  5138. @noindent
  5139. The vertical-bar @kbd{|} is the vector-concatenation command. When
  5140. we execute it, the list we are building will be in stack level 2
  5141. (initially this is an empty list), and the next Bernoulli number
  5142. will be in level 1. The effect is to append the Bernoulli number
  5143. onto the end of the list. (To create a table of exact fractional
  5144. Bernoulli numbers, just replace @kbd{X} with @kbd{k b} in the above
  5145. sequence of keystrokes.)
  5146. With loops and conditionals, you can program essentially anything
  5147. in Calc. One other command that makes looping easier is @kbd{Z /},
  5148. which takes a condition from the stack and breaks out of the enclosing
  5149. loop if the condition is true (non-zero). You can use this to make
  5150. ``while'' and ``until'' style loops.
  5151. If you make a mistake when entering a keyboard macro, you can edit
  5152. it using @kbd{Z E}. First, you must attach it to a key with @kbd{Z K}.
  5153. One technique is to enter a throwaway dummy definition for the macro,
  5154. then enter the real one in the edit command.
  5155. @smallexample
  5156. @group
  5157. 1: 3 1: 3 Keyboard Macro Editor.
  5158. . . Original keys: 1 @key{RET} 2 +
  5159. type "1\r"
  5160. type "2"
  5161. calc-plus
  5162. C-x ( 1 @key{RET} 2 + C-x ) Z K h @key{RET} Z E h
  5163. @end group
  5164. @end smallexample
  5165. @noindent
  5166. This shows the screen display assuming you have the @file{macedit}
  5167. keyboard macro editing package installed, which is usually the case
  5168. since a copy of @file{macedit} comes bundled with Calc.
  5169. A keyboard macro is stored as a pure keystroke sequence. The
  5170. @file{macedit} package (invoked by @kbd{Z E}) scans along the
  5171. macro and tries to decode it back into human-readable steps.
  5172. If a key or keys are simply shorthand for some command with a
  5173. @kbd{M-x} name, that name is shown. Anything that doesn't correspond
  5174. to a @kbd{M-x} command is written as a @samp{type} command.
  5175. Let's edit in a new definition, for computing harmonic numbers.
  5176. First, erase the three lines of the old definition. Then, type
  5177. in the new definition (or use Emacs @kbd{M-w} and @kbd{C-y} commands
  5178. to copy it from this page of the Info file; you can skip typing
  5179. the comments that begin with @samp{#}).
  5180. @smallexample
  5181. calc-kbd-push # Save local values (Z `)
  5182. type "0" # Push a zero
  5183. calc-store-into # Store it in variable 1
  5184. type "1"
  5185. type "1" # Initial value for loop
  5186. calc-roll-down # This is the @key{TAB} key; swap initial & final
  5187. calc-kbd-for # Begin "for" loop...
  5188. calc-inv # Take reciprocal
  5189. calc-store-plus # Add to accumulator
  5190. type "1"
  5191. type "1" # Loop step is 1
  5192. calc-kbd-end-for # End "for" loop
  5193. calc-recall # Now recall final accumulated value
  5194. type "1"
  5195. calc-kbd-pop # Restore values (Z ')
  5196. @end smallexample
  5197. @noindent
  5198. Press @kbd{M-# M-#} to finish editing and return to the Calculator.
  5199. @smallexample
  5200. @group
  5201. 1: 20 1: 3.597739
  5202. . .
  5203. 20 z h
  5204. @end group
  5205. @end smallexample
  5206. If you don't know how to write a particular command in @file{macedit}
  5207. format, you can always write it as keystrokes in a @code{type} command.
  5208. There is also a @code{keys} command which interprets the rest of the
  5209. line as standard Emacs keystroke names. In fact, @file{macedit} defines
  5210. a handy @code{read-kbd-macro} command which reads the current region
  5211. of the current buffer as a sequence of keystroke names, and defines that
  5212. sequence on the @kbd{X} (and @kbd{C-x e}) key. Because this is so
  5213. useful, Calc puts this command on the @kbd{M-# m} key. Try reading in
  5214. this macro in the following form: Press @kbd{C-@@} (or @kbd{C-@key{SPC}}) at
  5215. one end of the text below, then type @kbd{M-# m} at the other.
  5216. @example
  5217. @group
  5218. Z ` 0 t 1
  5219. 1 @key{TAB}
  5220. Z ( & s + 1 1 Z )
  5221. r 1
  5222. Z '
  5223. @end group
  5224. @end example
  5225. (@bullet{}) @strong{Exercise 8.} A general algorithm for solving
  5226. equations numerically is @dfn{Newton's Method}. Given the equation
  5227. @cite{f(x) = 0} for any function @cite{f}, and an initial guess
  5228. @cite{x_0} which is reasonably close to the desired solution, apply
  5229. this formula over and over:
  5230. @ifinfo
  5231. @example
  5232. new_x = x - f(x)/f'(x)
  5233. @end example
  5234. @end ifinfo
  5235. @tex
  5236. \beforedisplay
  5237. $$ x_{\goodrm new} = x - {f(x) \over f'(x)} $$
  5238. \afterdisplay
  5239. @end tex
  5240. @noindent
  5241. where @cite{f'(x)} is the derivative of @cite{f}. The @cite{x}
  5242. values will quickly converge to a solution, i.e., eventually
  5243. @c{$x_{\rm new}$}
  5244. @cite{new_x} and @cite{x} will be equal to within the limits
  5245. of the current precision. Write a program which takes a formula
  5246. involving the variable @cite{x}, and an initial guess @cite{x_0},
  5247. on the stack, and produces a value of @cite{x} for which the formula
  5248. is zero. Use it to find a solution of @c{$\sin(\cos x) = 0.5$}
  5249. @cite{sin(cos(x)) = 0.5}
  5250. near @cite{x = 4.5}. (Use angles measured in radians.) Note that
  5251. the built-in @w{@kbd{a R}} (@code{calc-find-root}) command uses Newton's
  5252. method when it is able. @xref{Programming Answer 8, 8}. (@bullet{})
  5253. @cindex Digamma function
  5254. @cindex Gamma constant, Euler's
  5255. @cindex Euler's gamma constant
  5256. (@bullet{}) @strong{Exercise 9.} The @dfn{digamma} function @c{$\psi(z)$ (``psi'')}
  5257. @cite{psi(z)}
  5258. is defined as the derivative of @c{$\ln \Gamma(z)$}
  5259. @cite{ln(gamma(z))}. For large
  5260. values of @cite{z}, it can be approximated by the infinite sum
  5261. @ifinfo
  5262. @example
  5263. psi(z) ~= ln(z) - 1/2z - sum(bern(2 n) / 2 n z^(2 n), n, 1, inf)
  5264. @end example
  5265. @end ifinfo
  5266. @tex
  5267. \let\rm\goodrm
  5268. \beforedisplay
  5269. $$ \psi(z) \approx \ln z - {1\over2z} -
  5270. \sum_{n=1}^\infty {\code{bern}(2 n) \over 2 n z^{2n}}
  5271. $$
  5272. \afterdisplay
  5273. @end tex
  5274. @noindent
  5275. where @c{$\sum$}
  5276. @cite{sum} represents the sum over @cite{n} from 1 to infinity
  5277. (or to some limit high enough to give the desired accuracy), and
  5278. the @code{bern} function produces (exact) Bernoulli numbers.
  5279. While this sum is not guaranteed to converge, in practice it is safe.
  5280. An interesting mathematical constant is Euler's gamma, which is equal
  5281. to about 0.5772. One way to compute it is by the formula,
  5282. @c{$\gamma = -\psi(1)$}
  5283. @cite{gamma = -psi(1)}. Unfortunately, 1 isn't a large enough argument
  5284. for the above formula to work (5 is a much safer value for @cite{z}).
  5285. Fortunately, we can compute @c{$\psi(1)$}
  5286. @cite{psi(1)} from @c{$\psi(5)$}
  5287. @cite{psi(5)} using
  5288. the recurrence @c{$\psi(z+1) = \psi(z) + {1 \over z}$}
  5289. @cite{psi(z+1) = psi(z) + 1/z}. Your task: Develop
  5290. a program to compute @c{$\psi(z)$}
  5291. @cite{psi(z)}; it should ``pump up'' @cite{z}
  5292. if necessary to be greater than 5, then use the above summation
  5293. formula. Use looping commands to compute the sum. Use your function
  5294. to compute @c{$\gamma$}
  5295. @cite{gamma} to twelve decimal places. (Calc has a built-in command
  5296. for Euler's constant, @kbd{I P}, which you can use to check your answer.)
  5297. @xref{Programming Answer 9, 9}. (@bullet{})
  5298. @cindex Polynomial, list of coefficients
  5299. (@bullet{}) @strong{Exercise 10.} Given a polynomial in @cite{x} and
  5300. a number @cite{m} on the stack, where the polynomial is of degree
  5301. @cite{m} or less (i.e., does not have any terms higher than @cite{x^m}),
  5302. write a program to convert the polynomial into a list-of-coefficients
  5303. notation. For example, @cite{5 x^4 + (x + 1)^2} with @cite{m = 6}
  5304. should produce the list @cite{[1, 2, 1, 0, 5, 0, 0]}. Also develop
  5305. a way to convert from this form back to the standard algebraic form.
  5306. @xref{Programming Answer 10, 10}. (@bullet{})
  5307. @cindex Recursion
  5308. (@bullet{}) @strong{Exercise 11.} The @dfn{Stirling numbers of the
  5309. first kind} are defined by the recurrences,
  5310. @ifinfo
  5311. @example
  5312. s(n,n) = 1 for n >= 0,
  5313. s(n,0) = 0 for n > 0,
  5314. s(n+1,m) = s(n,m-1) - n s(n,m) for n >= m >= 1.
  5315. @end example
  5316. @end ifinfo
  5317. @tex
  5318. \turnoffactive
  5319. \beforedisplay
  5320. $$ \eqalign{ s(n,n) &= 1 \qquad \hbox{for } n \ge 0, \cr
  5321. s(n,0) &= 0 \qquad \hbox{for } n > 0, \cr
  5322. s(n+1,m) &= s(n,m-1) - n \, s(n,m) \qquad
  5323. \hbox{for } n \ge m \ge 1.}
  5324. $$
  5325. \afterdisplay
  5326. \vskip5pt
  5327. (These numbers are also sometimes written $\displaystyle{n \brack m}$.)
  5328. @end tex
  5329. This can be implemented using a @dfn{recursive} program in Calc; the
  5330. program must invoke itself in order to calculate the two righthand
  5331. terms in the general formula. Since it always invokes itself with
  5332. ``simpler'' arguments, it's easy to see that it must eventually finish
  5333. the computation. Recursion is a little difficult with Emacs keyboard
  5334. macros since the macro is executed before its definition is complete.
  5335. So here's the recommended strategy: Create a ``dummy macro'' and assign
  5336. it to a key with, e.g., @kbd{Z K s}. Now enter the true definition,
  5337. using the @kbd{z s} command to call itself recursively, then assign it
  5338. to the same key with @kbd{Z K s}. Now the @kbd{z s} command will run
  5339. the complete recursive program. (Another way is to use @w{@kbd{Z E}}
  5340. or @kbd{M-# m} (@code{read-kbd-macro}) to read the whole macro at once,
  5341. thus avoiding the ``training'' phase.) The task: Write a program
  5342. that computes Stirling numbers of the first kind, given @cite{n} and
  5343. @cite{m} on the stack. Test it with @emph{small} inputs like
  5344. @cite{s(4,2)}. (There is a built-in command for Stirling numbers,
  5345. @kbd{k s}, which you can use to check your answers.)
  5346. @xref{Programming Answer 11, 11}. (@bullet{})
  5347. The programming commands we've seen in this part of the tutorial
  5348. are low-level, general-purpose operations. Often you will find
  5349. that a higher-level function, such as vector mapping or rewrite
  5350. rules, will do the job much more easily than a detailed, step-by-step
  5351. program can:
  5352. (@bullet{}) @strong{Exercise 12.} Write another program for
  5353. computing Stirling numbers of the first kind, this time using
  5354. rewrite rules. Once again, @cite{n} and @cite{m} should be taken
  5355. from the stack. @xref{Programming Answer 12, 12}. (@bullet{})
  5356. @example
  5357. @end example
  5358. This ends the tutorial section of the Calc manual. Now you know enough
  5359. about Calc to use it effectively for many kinds of calculations. But
  5360. Calc has many features that were not even touched upon in this tutorial.
  5361. @c [not-split]
  5362. The rest of this manual tells the whole story.
  5363. @c [when-split]
  5364. @c Volume II of this manual, the @dfn{Calc Reference}, tells the whole story.
  5365. @page
  5366. @node Answers to Exercises, , Programming Tutorial, Tutorial
  5367. @section Answers to Exercises
  5368. @noindent
  5369. This section includes answers to all the exercises in the Calc tutorial.
  5370. @menu
  5371. * RPN Answer 1:: 1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -
  5372. * RPN Answer 2:: 2*4 + 7*9.5 + 5/4
  5373. * RPN Answer 3:: Operating on levels 2 and 3
  5374. * RPN Answer 4:: Joe's complex problems
  5375. * Algebraic Answer 1:: Simulating Q command
  5376. * Algebraic Answer 2:: Joe's algebraic woes
  5377. * Algebraic Answer 3:: 1 / 0
  5378. * Modes Answer 1:: 3#0.1 = 3#0.0222222?
  5379. * Modes Answer 2:: 16#f.e8fe15
  5380. * Modes Answer 3:: Joe's rounding bug
  5381. * Modes Answer 4:: Why floating point?
  5382. * Arithmetic Answer 1:: Why the \ command?
  5383. * Arithmetic Answer 2:: Tripping up the B command
  5384. * Vector Answer 1:: Normalizing a vector
  5385. * Vector Answer 2:: Average position
  5386. * Matrix Answer 1:: Row and column sums
  5387. * Matrix Answer 2:: Symbolic system of equations
  5388. * Matrix Answer 3:: Over-determined system
  5389. * List Answer 1:: Powers of two
  5390. * List Answer 2:: Least-squares fit with matrices
  5391. * List Answer 3:: Geometric mean
  5392. * List Answer 4:: Divisor function
  5393. * List Answer 5:: Duplicate factors
  5394. * List Answer 6:: Triangular list
  5395. * List Answer 7:: Another triangular list
  5396. * List Answer 8:: Maximum of Bessel function
  5397. * List Answer 9:: Integers the hard way
  5398. * List Answer 10:: All elements equal
  5399. * List Answer 11:: Estimating pi with darts
  5400. * List Answer 12:: Estimating pi with matchsticks
  5401. * List Answer 13:: Hash codes
  5402. * List Answer 14:: Random walk
  5403. * Types Answer 1:: Square root of pi times rational
  5404. * Types Answer 2:: Infinities
  5405. * Types Answer 3:: What can "nan" be?
  5406. * Types Answer 4:: Abbey Road
  5407. * Types Answer 5:: Friday the 13th
  5408. * Types Answer 6:: Leap years
  5409. * Types Answer 7:: Erroneous donut
  5410. * Types Answer 8:: Dividing intervals
  5411. * Types Answer 9:: Squaring intervals
  5412. * Types Answer 10:: Fermat's primality test
  5413. * Types Answer 11:: pi * 10^7 seconds
  5414. * Types Answer 12:: Abbey Road on CD
  5415. * Types Answer 13:: Not quite pi * 10^7 seconds
  5416. * Types Answer 14:: Supercomputers and c
  5417. * Types Answer 15:: Sam the Slug
  5418. * Algebra Answer 1:: Squares and square roots
  5419. * Algebra Answer 2:: Building polynomial from roots
  5420. * Algebra Answer 3:: Integral of x sin(pi x)
  5421. * Algebra Answer 4:: Simpson's rule
  5422. * Rewrites Answer 1:: Multiplying by conjugate
  5423. * Rewrites Answer 2:: Alternative fib rule
  5424. * Rewrites Answer 3:: Rewriting opt(a) + opt(b) x
  5425. * Rewrites Answer 4:: Sequence of integers
  5426. * Rewrites Answer 5:: Number of terms in sum
  5427. * Rewrites Answer 6:: Defining 0^0 = 1
  5428. * Rewrites Answer 7:: Truncated Taylor series
  5429. * Programming Answer 1:: Fresnel's C(x)
  5430. * Programming Answer 2:: Negate third stack element
  5431. * Programming Answer 3:: Compute sin(x) / x, etc.
  5432. * Programming Answer 4:: Average value of a list
  5433. * Programming Answer 5:: Continued fraction phi
  5434. * Programming Answer 6:: Matrix Fibonacci numbers
  5435. * Programming Answer 7:: Harmonic number greater than 4
  5436. * Programming Answer 8:: Newton's method
  5437. * Programming Answer 9:: Digamma function
  5438. * Programming Answer 10:: Unpacking a polynomial
  5439. * Programming Answer 11:: Recursive Stirling numbers
  5440. * Programming Answer 12:: Stirling numbers with rewrites
  5441. @end menu
  5442. @c The following kludgery prevents the individual answers from
  5443. @c being entered on the table of contents.
  5444. @tex
  5445. \global\let\oldwrite=\write
  5446. \gdef\skipwrite#1#2{\let\write=\oldwrite}
  5447. \global\let\oldchapternofonts=\chapternofonts
  5448. \gdef\chapternofonts{\let\write=\skipwrite\oldchapternofonts}
  5449. @end tex
  5450. @node RPN Answer 1, RPN Answer 2, Answers to Exercises, Answers to Exercises
  5451. @subsection RPN Tutorial Exercise 1
  5452. @noindent
  5453. @kbd{1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -}
  5454. The result is @c{$1 - (2 \times (3 + 4)) = -13$}
  5455. @cite{1 - (2 * (3 + 4)) = -13}.
  5456. @node RPN Answer 2, RPN Answer 3, RPN Answer 1, Answers to Exercises
  5457. @subsection RPN Tutorial Exercise 2
  5458. @noindent
  5459. @c{$2\times4 + 7\times9.5 + {5\over4} = 75.75$}
  5460. @cite{2*4 + 7*9.5 + 5/4 = 75.75}
  5461. After computing the intermediate term @c{$2\times4 = 8$}
  5462. @cite{2*4 = 8}, you can leave
  5463. that result on the stack while you compute the second term. With
  5464. both of these results waiting on the stack you can then compute the
  5465. final term, then press @kbd{+ +} to add everything up.
  5466. @smallexample
  5467. @group
  5468. 2: 2 1: 8 3: 8 2: 8
  5469. 1: 4 . 2: 7 1: 66.5
  5470. . 1: 9.5 .
  5471. .
  5472. 2 @key{RET} 4 * 7 @key{RET} 9.5 *
  5473. @end group
  5474. @end smallexample
  5475. @noindent
  5476. @smallexample
  5477. @group
  5478. 4: 8 3: 8 2: 8 1: 75.75
  5479. 3: 66.5 2: 66.5 1: 67.75 .
  5480. 2: 5 1: 1.25 .
  5481. 1: 4 .
  5482. .
  5483. 5 @key{RET} 4 / + +
  5484. @end group
  5485. @end smallexample
  5486. Alternatively, you could add the first two terms before going on
  5487. with the third term.
  5488. @smallexample
  5489. @group
  5490. 2: 8 1: 74.5 3: 74.5 2: 74.5 1: 75.75
  5491. 1: 66.5 . 2: 5 1: 1.25 .
  5492. . 1: 4 .
  5493. .
  5494. ... + 5 @key{RET} 4 / +
  5495. @end group
  5496. @end smallexample
  5497. On an old-style RPN calculator this second method would have the
  5498. advantage of using only three stack levels. But since Calc's stack
  5499. can grow arbitrarily large this isn't really an issue. Which method
  5500. you choose is purely a matter of taste.
  5501. @node RPN Answer 3, RPN Answer 4, RPN Answer 2, Answers to Exercises
  5502. @subsection RPN Tutorial Exercise 3
  5503. @noindent
  5504. The @key{TAB} key provides a way to operate on the number in level 2.
  5505. @smallexample
  5506. @group
  5507. 3: 10 3: 10 4: 10 3: 10 3: 10
  5508. 2: 20 2: 30 3: 30 2: 30 2: 21
  5509. 1: 30 1: 20 2: 20 1: 21 1: 30
  5510. . . 1: 1 . .
  5511. .
  5512. @key{TAB} 1 + @key{TAB}
  5513. @end group
  5514. @end smallexample
  5515. Similarly, @kbd{M-@key{TAB}} gives you access to the number in level 3.
  5516. @smallexample
  5517. @group
  5518. 3: 10 3: 21 3: 21 3: 30 3: 11
  5519. 2: 21 2: 30 2: 30 2: 11 2: 21
  5520. 1: 30 1: 10 1: 11 1: 21 1: 30
  5521. . . . . .
  5522. M-@key{TAB} 1 + M-@key{TAB} M-@key{TAB}
  5523. @end group
  5524. @end smallexample
  5525. @node RPN Answer 4, Algebraic Answer 1, RPN Answer 3, Answers to Exercises
  5526. @subsection RPN Tutorial Exercise 4
  5527. @noindent
  5528. Either @kbd{( 2 , 3 )} or @kbd{( 2 @key{SPC} 3 )} would have worked,
  5529. but using both the comma and the space at once yields:
  5530. @smallexample
  5531. @group
  5532. 1: ( ... 2: ( ... 1: (2, ... 2: (2, ... 2: (2, ...
  5533. . 1: 2 . 1: (2, ... 1: (2, 3)
  5534. . . .
  5535. ( 2 , @key{SPC} 3 )
  5536. @end group
  5537. @end smallexample
  5538. Joe probably tried to type @kbd{@key{TAB} @key{DEL}} to swap the
  5539. extra incomplete object to the top of the stack and delete it.
  5540. But a feature of Calc is that @key{DEL} on an incomplete object
  5541. deletes just one component out of that object, so he had to press
  5542. @key{DEL} twice to finish the job.
  5543. @smallexample
  5544. @group
  5545. 2: (2, ... 2: (2, 3) 2: (2, 3) 1: (2, 3)
  5546. 1: (2, 3) 1: (2, ... 1: ( ... .
  5547. . . .
  5548. @key{TAB} @key{DEL} @key{DEL}
  5549. @end group
  5550. @end smallexample
  5551. (As it turns out, deleting the second-to-top stack entry happens often
  5552. enough that Calc provides a special key, @kbd{M-@key{DEL}}, to do just that.
  5553. @kbd{M-@key{DEL}} is just like @kbd{@key{TAB} @key{DEL}}, except that it doesn't exhibit
  5554. the ``feature'' that tripped poor Joe.)
  5555. @node Algebraic Answer 1, Algebraic Answer 2, RPN Answer 4, Answers to Exercises
  5556. @subsection Algebraic Entry Tutorial Exercise 1
  5557. @noindent
  5558. Type @kbd{' sqrt($) @key{RET}}.
  5559. If the @kbd{Q} key is broken, you could use @kbd{' $^0.5 @key{RET}}.
  5560. Or, RPN style, @kbd{0.5 ^}.
  5561. (Actually, @samp{$^1:2}, using the fraction one-half as the power, is
  5562. a closer equivalent, since @samp{9^0.5} yields @cite{3.0} whereas
  5563. @samp{sqrt(9)} and @samp{9^1:2} yield the exact integer @cite{3}.)
  5564. @node Algebraic Answer 2, Algebraic Answer 3, Algebraic Answer 1, Answers to Exercises
  5565. @subsection Algebraic Entry Tutorial Exercise 2
  5566. @noindent
  5567. In the formula @samp{2 x (1+y)}, @samp{x} was interpreted as a function
  5568. name with @samp{1+y} as its argument. Assigning a value to a variable
  5569. has no relation to a function by the same name. Joe needed to use an
  5570. explicit @samp{*} symbol here: @samp{2 x*(1+y)}.
  5571. @node Algebraic Answer 3, Modes Answer 1, Algebraic Answer 2, Answers to Exercises
  5572. @subsection Algebraic Entry Tutorial Exercise 3
  5573. @noindent
  5574. The result from @kbd{1 @key{RET} 0 /} will be the formula @cite{1 / 0}.
  5575. The ``function'' @samp{/} cannot be evaluated when its second argument
  5576. is zero, so it is left in symbolic form. When you now type @kbd{0 *},
  5577. the result will be zero because Calc uses the general rule that ``zero
  5578. times anything is zero.''
  5579. @c [fix-ref Infinities]
  5580. The @kbd{m i} command enables an @dfn{infinite mode} in which @cite{1 / 0}
  5581. results in a special symbol that represents ``infinity.'' If you
  5582. multiply infinity by zero, Calc uses another special new symbol to
  5583. show that the answer is ``indeterminate.'' @xref{Infinities}, for
  5584. further discussion of infinite and indeterminate values.
  5585. @node Modes Answer 1, Modes Answer 2, Algebraic Answer 3, Answers to Exercises
  5586. @subsection Modes Tutorial Exercise 1
  5587. @noindent
  5588. Calc always stores its numbers in decimal, so even though one-third has
  5589. an exact base-3 representation (@samp{3#0.1}), it is still stored as
  5590. 0.3333333 (chopped off after 12 or however many decimal digits) inside
  5591. the calculator's memory. When this inexact number is converted back
  5592. to base 3 for display, it may still be slightly inexact. When we
  5593. multiply this number by 3, we get 0.999999, also an inexact value.
  5594. When Calc displays a number in base 3, it has to decide how many digits
  5595. to show. If the current precision is 12 (decimal) digits, that corresponds
  5596. to @samp{12 / log10(3) = 25.15} base-3 digits. Because 25.15 is not an
  5597. exact integer, Calc shows only 25 digits, with the result that stored
  5598. numbers carry a little bit of extra information that may not show up on
  5599. the screen. When Joe entered @samp{3#0.2}, the stored number 0.666666
  5600. happened to round to a pleasing value when it lost that last 0.15 of a
  5601. digit, but it was still inexact in Calc's memory. When he divided by 2,
  5602. he still got the dreaded inexact value 0.333333. (Actually, he divided
  5603. 0.666667 by 2 to get 0.333334, which is why he got something a little
  5604. higher than @code{3#0.1} instead of a little lower.)
  5605. If Joe didn't want to be bothered with all this, he could have typed
  5606. @kbd{M-24 d n} to display with one less digit than the default. (If
  5607. you give @kbd{d n} a negative argument, it uses default-minus-that,
  5608. so @kbd{M-- d n} would be an easier way to get the same effect.) Those
  5609. inexact results would still be lurking there, but they would now be
  5610. rounded to nice, natural-looking values for display purposes. (Remember,
  5611. @samp{0.022222} in base 3 is like @samp{0.099999} in base 10; rounding
  5612. off one digit will round the number up to @samp{0.1}.) Depending on the
  5613. nature of your work, this hiding of the inexactness may be a benefit or
  5614. a danger. With the @kbd{d n} command, Calc gives you the choice.
  5615. Incidentally, another consequence of all this is that if you type
  5616. @kbd{M-30 d n} to display more digits than are ``really there,''
  5617. you'll see garbage digits at the end of the number. (In decimal
  5618. display mode, with decimally-stored numbers, these garbage digits are
  5619. always zero so they vanish and you don't notice them.) Because Calc
  5620. rounds off that 0.15 digit, there is the danger that two numbers could
  5621. be slightly different internally but still look the same. If you feel
  5622. uneasy about this, set the @kbd{d n} precision to be a little higher
  5623. than normal; you'll get ugly garbage digits, but you'll always be able
  5624. to tell two distinct numbers apart.
  5625. An interesting side note is that most computers store their
  5626. floating-point numbers in binary, and convert to decimal for display.
  5627. Thus everyday programs have the same problem: Decimal 0.1 cannot be
  5628. represented exactly in binary (try it: @kbd{0.1 d 2}), so @samp{0.1 * 10}
  5629. comes out as an inexact approximation to 1 on some machines (though
  5630. they generally arrange to hide it from you by rounding off one digit as
  5631. we did above). Because Calc works in decimal instead of binary, you can
  5632. be sure that numbers that look exact @emph{are} exact as long as you stay
  5633. in decimal display mode.
  5634. It's not hard to show that any number that can be represented exactly
  5635. in binary, octal, or hexadecimal is also exact in decimal, so the kinds
  5636. of problems we saw in this exercise are likely to be severe only when
  5637. you use a relatively unusual radix like 3.
  5638. @node Modes Answer 2, Modes Answer 3, Modes Answer 1, Answers to Exercises
  5639. @subsection Modes Tutorial Exercise 2
  5640. If the radix is 15 or higher, we can't use the letter @samp{e} to mark
  5641. the exponent because @samp{e} is interpreted as a digit. When Calc
  5642. needs to display scientific notation in a high radix, it writes
  5643. @samp{16#F.E8F*16.^15}. You can enter a number like this as an
  5644. algebraic entry. Also, pressing @kbd{e} without any digits before it
  5645. normally types @kbd{1e}, but in a high radix it types @kbd{16.^} and
  5646. puts you in algebraic entry: @kbd{16#f.e8f @key{RET} e 15 @key{RET} *} is another
  5647. way to enter this number.
  5648. The reason Calc puts a decimal point in the @samp{16.^} is to prevent
  5649. huge integers from being generated if the exponent is large (consider
  5650. @samp{16#1.23*16^1000}, where we compute @samp{16^1000} as a giant
  5651. exact integer and then throw away most of the digits when we multiply
  5652. it by the floating-point @samp{16#1.23}). While this wouldn't normally
  5653. matter for display purposes, it could give you a nasty surprise if you
  5654. copied that number into a file and later moved it back into Calc.
  5655. @node Modes Answer 3, Modes Answer 4, Modes Answer 2, Answers to Exercises
  5656. @subsection Modes Tutorial Exercise 3
  5657. @noindent
  5658. The answer he got was @cite{0.5000000000006399}.
  5659. The problem is not that the square operation is inexact, but that the
  5660. sine of 45 that was already on the stack was accurate to only 12 places.
  5661. Arbitrary-precision calculations still only give answers as good as
  5662. their inputs.
  5663. The real problem is that there is no 12-digit number which, when
  5664. squared, comes out to 0.5 exactly. The @kbd{f [} and @kbd{f ]}
  5665. commands decrease or increase a number by one unit in the last
  5666. place (according to the current precision). They are useful for
  5667. determining facts like this.
  5668. @smallexample
  5669. @group
  5670. 1: 0.707106781187 1: 0.500000000001
  5671. . .
  5672. 45 S 2 ^
  5673. @end group
  5674. @end smallexample
  5675. @noindent
  5676. @smallexample
  5677. @group
  5678. 1: 0.707106781187 1: 0.707106781186 1: 0.499999999999
  5679. . . .
  5680. U @key{DEL} f [ 2 ^
  5681. @end group
  5682. @end smallexample
  5683. A high-precision calculation must be carried out in high precision
  5684. all the way. The only number in the original problem which was known
  5685. exactly was the quantity 45 degrees, so the precision must be raised
  5686. before anything is done after the number 45 has been entered in order
  5687. for the higher precision to be meaningful.
  5688. @node Modes Answer 4, Arithmetic Answer 1, Modes Answer 3, Answers to Exercises
  5689. @subsection Modes Tutorial Exercise 4
  5690. @noindent
  5691. Many calculations involve real-world quantities, like the width and
  5692. height of a piece of wood or the volume of a jar. Such quantities
  5693. can't be measured exactly anyway, and if the data that is input to
  5694. a calculation is inexact, doing exact arithmetic on it is a waste
  5695. of time.
  5696. Fractions become unwieldy after too many calculations have been
  5697. done with them. For example, the sum of the reciprocals of the
  5698. integers from 1 to 10 is 7381:2520. The sum from 1 to 30 is
  5699. 9304682830147:2329089562800. After a point it will take a long
  5700. time to add even one more term to this sum, but a floating-point
  5701. calculation of the sum will not have this problem.
  5702. Also, rational numbers cannot express the results of all calculations.
  5703. There is no fractional form for the square root of two, so if you type
  5704. @w{@kbd{2 Q}}, Calc has no choice but to give you a floating-point answer.
  5705. @node Arithmetic Answer 1, Arithmetic Answer 2, Modes Answer 4, Answers to Exercises
  5706. @subsection Arithmetic Tutorial Exercise 1
  5707. @noindent
  5708. Dividing two integers that are larger than the current precision may
  5709. give a floating-point result that is inaccurate even when rounded
  5710. down to an integer. Consider @cite{123456789 / 2} when the current
  5711. precision is 6 digits. The true answer is @cite{61728394.5}, but
  5712. with a precision of 6 this will be rounded to @c{$12345700.0/2.0 = 61728500.0$}
  5713. @cite{12345700.@: / 2.@: = 61728500.}.
  5714. The result, when converted to an integer, will be off by 106.
  5715. Here are two solutions: Raise the precision enough that the
  5716. floating-point round-off error is strictly to the right of the
  5717. decimal point. Or, convert to fraction mode so that @cite{123456789 / 2}
  5718. produces the exact fraction @cite{123456789:2}, which can be rounded
  5719. down by the @kbd{F} command without ever switching to floating-point
  5720. format.
  5721. @node Arithmetic Answer 2, Vector Answer 1, Arithmetic Answer 1, Answers to Exercises
  5722. @subsection Arithmetic Tutorial Exercise 2
  5723. @noindent
  5724. @kbd{27 @key{RET} 9 B} could give the exact result @cite{3:2}, but it
  5725. does a floating-point calculation instead and produces @cite{1.5}.
  5726. Calc will find an exact result for a logarithm if the result is an integer
  5727. or the reciprocal of an integer. But there is no efficient way to search
  5728. the space of all possible rational numbers for an exact answer, so Calc
  5729. doesn't try.
  5730. @node Vector Answer 1, Vector Answer 2, Arithmetic Answer 2, Answers to Exercises
  5731. @subsection Vector Tutorial Exercise 1
  5732. @noindent
  5733. Duplicate the vector, compute its length, then divide the vector
  5734. by its length: @kbd{@key{RET} A /}.
  5735. @smallexample
  5736. @group
  5737. 1: [1, 2, 3] 2: [1, 2, 3] 1: [0.27, 0.53, 0.80] 1: 1.
  5738. . 1: 3.74165738677 . .
  5739. .
  5740. r 1 @key{RET} A / A
  5741. @end group
  5742. @end smallexample
  5743. The final @kbd{A} command shows that the normalized vector does
  5744. indeed have unit length.
  5745. @node Vector Answer 2, Matrix Answer 1, Vector Answer 1, Answers to Exercises
  5746. @subsection Vector Tutorial Exercise 2
  5747. @noindent
  5748. The average position is equal to the sum of the products of the
  5749. positions times their corresponding probabilities. This is the
  5750. definition of the dot product operation. So all you need to do
  5751. is to put the two vectors on the stack and press @kbd{*}.
  5752. @node Matrix Answer 1, Matrix Answer 2, Vector Answer 2, Answers to Exercises
  5753. @subsection Matrix Tutorial Exercise 1
  5754. @noindent
  5755. The trick is to multiply by a vector of ones. Use @kbd{r 4 [1 1 1] *} to
  5756. get the row sum. Similarly, use @kbd{[1 1] r 4 *} to get the column sum.
  5757. @node Matrix Answer 2, Matrix Answer 3, Matrix Answer 1, Answers to Exercises
  5758. @subsection Matrix Tutorial Exercise 2
  5759. @ifinfo
  5760. @example
  5761. @group
  5762. x + a y = 6
  5763. x + b y = 10
  5764. @end group
  5765. @end example
  5766. @end ifinfo
  5767. @tex
  5768. \turnoffactive
  5769. \beforedisplay
  5770. $$ \eqalign{ x &+ a y = 6 \cr
  5771. x &+ b y = 10}
  5772. $$
  5773. \afterdisplay
  5774. @end tex
  5775. Just enter the righthand side vector, then divide by the lefthand side
  5776. matrix as usual.
  5777. @smallexample
  5778. @group
  5779. 1: [6, 10] 2: [6, 10] 1: [6 - 4 a / (b - a), 4 / (b - a) ]
  5780. . 1: [ [ 1, a ] .
  5781. [ 1, b ] ]
  5782. .
  5783. ' [6 10] @key{RET} ' [1 a; 1 b] @key{RET} /
  5784. @end group
  5785. @end smallexample
  5786. This can be made more readable using @kbd{d B} to enable ``big'' display
  5787. mode:
  5788. @smallexample
  5789. @group
  5790. 4 a 4
  5791. 1: [6 - -----, -----]
  5792. b - a b - a
  5793. @end group
  5794. @end smallexample
  5795. Type @kbd{d N} to return to ``normal'' display mode afterwards.
  5796. @node Matrix Answer 3, List Answer 1, Matrix Answer 2, Answers to Exercises
  5797. @subsection Matrix Tutorial Exercise 3
  5798. @noindent
  5799. To solve @c{$A^T A \, X = A^T B$}
  5800. @cite{trn(A) * A * X = trn(A) * B}, first we compute
  5801. @c{$A' = A^T A$}
  5802. @cite{A2 = trn(A) * A} and @c{$B' = A^T B$}
  5803. @cite{B2 = trn(A) * B}; now, we have a
  5804. system @c{$A' X = B'$}
  5805. @cite{A2 * X = B2} which we can solve using Calc's @samp{/}
  5806. command.
  5807. @ifinfo
  5808. @example
  5809. @group
  5810. a + 2b + 3c = 6
  5811. 4a + 5b + 6c = 2
  5812. 7a + 6b = 3
  5813. 2a + 4b + 6c = 11
  5814. @end group
  5815. @end example
  5816. @end ifinfo
  5817. @tex
  5818. \turnoffactive
  5819. \beforedisplayh
  5820. $$ \openup1\jot \tabskip=0pt plus1fil
  5821. \halign to\displaywidth{\tabskip=0pt
  5822. $\hfil#$&$\hfil{}#{}$&
  5823. $\hfil#$&$\hfil{}#{}$&
  5824. $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
  5825. a&+&2b&+&3c&=6 \cr
  5826. 4a&+&5b&+&6c&=2 \cr
  5827. 7a&+&6b& & &=3 \cr
  5828. 2a&+&4b&+&6c&=11 \cr}
  5829. $$
  5830. \afterdisplayh
  5831. @end tex
  5832. The first step is to enter the coefficient matrix. We'll store it in
  5833. quick variable number 7 for later reference. Next, we compute the
  5834. @c{$B'$}
  5835. @cite{B2} vector.
  5836. @smallexample
  5837. @group
  5838. 1: [ [ 1, 2, 3 ] 2: [ [ 1, 4, 7, 2 ] 1: [57, 84, 96]
  5839. [ 4, 5, 6 ] [ 2, 5, 6, 4 ] .
  5840. [ 7, 6, 0 ] [ 3, 6, 0, 6 ] ]
  5841. [ 2, 4, 6 ] ] 1: [6, 2, 3, 11]
  5842. . .
  5843. ' [1 2 3; 4 5 6; 7 6 0; 2 4 6] @key{RET} s 7 v t [6 2 3 11] *
  5844. @end group
  5845. @end smallexample
  5846. @noindent
  5847. Now we compute the matrix @c{$A'$}
  5848. @cite{A2} and divide.
  5849. @smallexample
  5850. @group
  5851. 2: [57, 84, 96] 1: [-11.64, 14.08, -3.64]
  5852. 1: [ [ 70, 72, 39 ] .
  5853. [ 72, 81, 60 ]
  5854. [ 39, 60, 81 ] ]
  5855. .
  5856. r 7 v t r 7 * /
  5857. @end group
  5858. @end smallexample
  5859. @noindent
  5860. (The actual computed answer will be slightly inexact due to
  5861. round-off error.)
  5862. Notice that the answers are similar to those for the @c{$3\times3$}
  5863. @asis{3x3} system
  5864. solved in the text. That's because the fourth equation that was
  5865. added to the system is almost identical to the first one multiplied
  5866. by two. (If it were identical, we would have gotten the exact same
  5867. answer since the @c{$4\times3$}
  5868. @asis{4x3} system would be equivalent to the original @c{$3\times3$}
  5869. @asis{3x3}
  5870. system.)
  5871. Since the first and fourth equations aren't quite equivalent, they
  5872. can't both be satisfied at once. Let's plug our answers back into
  5873. the original system of equations to see how well they match.
  5874. @smallexample
  5875. @group
  5876. 2: [-11.64, 14.08, -3.64] 1: [5.6, 2., 3., 11.2]
  5877. 1: [ [ 1, 2, 3 ] .
  5878. [ 4, 5, 6 ]
  5879. [ 7, 6, 0 ]
  5880. [ 2, 4, 6 ] ]
  5881. .
  5882. r 7 @key{TAB} *
  5883. @end group
  5884. @end smallexample
  5885. @noindent
  5886. This is reasonably close to our original @cite{B} vector,
  5887. @cite{[6, 2, 3, 11]}.
  5888. @node List Answer 1, List Answer 2, Matrix Answer 3, Answers to Exercises
  5889. @subsection List Tutorial Exercise 1
  5890. @noindent
  5891. We can use @kbd{v x} to build a vector of integers. This needs to be
  5892. adjusted to get the range of integers we desire. Mapping @samp{-}
  5893. across the vector will accomplish this, although it turns out the
  5894. plain @samp{-} key will work just as well.
  5895. @smallexample
  5896. @group
  5897. 2: 2 2: 2
  5898. 1: [1, 2, 3, 4, 5, 6, 7, 8, 9] 1: [-4, -3, -2, -1, 0, 1, 2, 3, 4]
  5899. . .
  5900. 2 v x 9 @key{RET} 5 V M - or 5 -
  5901. @end group
  5902. @end smallexample
  5903. @noindent
  5904. Now we use @kbd{V M ^} to map the exponentiation operator across the
  5905. vector.
  5906. @smallexample
  5907. @group
  5908. 1: [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16]
  5909. .
  5910. V M ^
  5911. @end group
  5912. @end smallexample
  5913. @node List Answer 2, List Answer 3, List Answer 1, Answers to Exercises
  5914. @subsection List Tutorial Exercise 2
  5915. @noindent
  5916. Given @cite{x} and @cite{y} vectors in quick variables 1 and 2 as before,
  5917. the first job is to form the matrix that describes the problem.
  5918. @ifinfo
  5919. @example
  5920. m*x + b*1 = y
  5921. @end example
  5922. @end ifinfo
  5923. @tex
  5924. \turnoffactive
  5925. \beforedisplay
  5926. $$ m \times x + b \times 1 = y $$
  5927. \afterdisplay
  5928. @end tex
  5929. Thus we want a @c{$19\times2$}
  5930. @asis{19x2} matrix with our @cite{x} vector as one column and
  5931. ones as the other column. So, first we build the column of ones, then
  5932. we combine the two columns to form our @cite{A} matrix.
  5933. @smallexample
  5934. @group
  5935. 2: [1.34, 1.41, 1.49, ... ] 1: [ [ 1.34, 1 ]
  5936. 1: [1, 1, 1, ...] [ 1.41, 1 ]
  5937. . [ 1.49, 1 ]
  5938. @dots{}
  5939. r 1 1 v b 19 @key{RET} M-2 v p v t s 3
  5940. @end group
  5941. @end smallexample
  5942. @noindent
  5943. Now we compute @c{$A^T y$}
  5944. @cite{trn(A) * y} and @c{$A^T A$}
  5945. @cite{trn(A) * A} and divide.
  5946. @smallexample
  5947. @group
  5948. 1: [33.36554, 13.613] 2: [33.36554, 13.613]
  5949. . 1: [ [ 98.0003, 41.63 ]
  5950. [ 41.63, 19 ] ]
  5951. .
  5952. v t r 2 * r 3 v t r 3 *
  5953. @end group
  5954. @end smallexample
  5955. @noindent
  5956. (Hey, those numbers look familiar!)
  5957. @smallexample
  5958. @group
  5959. 1: [0.52141679, -0.425978]
  5960. .
  5961. /
  5962. @end group
  5963. @end smallexample
  5964. Since we were solving equations of the form @c{$m \times x + b \times 1 = y$}
  5965. @cite{m*x + b*1 = y}, these
  5966. numbers should be @cite{m} and @cite{b}, respectively. Sure enough, they
  5967. agree exactly with the result computed using @kbd{V M} and @kbd{V R}!
  5968. The moral of this story: @kbd{V M} and @kbd{V R} will probably solve
  5969. your problem, but there is often an easier way using the higher-level
  5970. arithmetic functions!
  5971. @c [fix-ref Curve Fitting]
  5972. In fact, there is a built-in @kbd{a F} command that does least-squares
  5973. fits. @xref{Curve Fitting}.
  5974. @node List Answer 3, List Answer 4, List Answer 2, Answers to Exercises
  5975. @subsection List Tutorial Exercise 3
  5976. @noindent
  5977. Move to one end of the list and press @kbd{C-@@} (or @kbd{C-@key{SPC}} or
  5978. whatever) to set the mark, then move to the other end of the list
  5979. and type @w{@kbd{M-# g}}.
  5980. @smallexample
  5981. @group
  5982. 1: [2.3, 6, 22, 15.1, 7, 15, 14, 7.5, 2.5]
  5983. .
  5984. @end group
  5985. @end smallexample
  5986. To make things interesting, let's assume we don't know at a glance
  5987. how many numbers are in this list. Then we could type:
  5988. @smallexample
  5989. @group
  5990. 2: [2.3, 6, 22, ... ] 2: [2.3, 6, 22, ... ]
  5991. 1: [2.3, 6, 22, ... ] 1: 126356422.5
  5992. . .
  5993. @key{RET} V R *
  5994. @end group
  5995. @end smallexample
  5996. @noindent
  5997. @smallexample
  5998. @group
  5999. 2: 126356422.5 2: 126356422.5 1: 7.94652913734
  6000. 1: [2.3, 6, 22, ... ] 1: 9 .
  6001. . .
  6002. @key{TAB} v l I ^
  6003. @end group
  6004. @end smallexample
  6005. @noindent
  6006. (The @kbd{I ^} command computes the @var{n}th root of a number.
  6007. You could also type @kbd{& ^} to take the reciprocal of 9 and
  6008. then raise the number to that power.)
  6009. @node List Answer 4, List Answer 5, List Answer 3, Answers to Exercises
  6010. @subsection List Tutorial Exercise 4
  6011. @noindent
  6012. A number @cite{j} is a divisor of @cite{n} if @c{$n \mathbin{\hbox{\code{\%}}} j = 0$}
  6013. @samp{n % j = 0}. The first
  6014. step is to get a vector that identifies the divisors.
  6015. @smallexample
  6016. @group
  6017. 2: 30 2: [0, 0, 0, 2, ...] 1: [1, 1, 1, 0, ...]
  6018. 1: [1, 2, 3, 4, ...] 1: 0 .
  6019. . .
  6020. 30 @key{RET} v x 30 @key{RET} s 1 V M % 0 V M a = s 2
  6021. @end group
  6022. @end smallexample
  6023. @noindent
  6024. This vector has 1's marking divisors of 30 and 0's marking non-divisors.
  6025. The zeroth divisor function is just the total number of divisors.
  6026. The first divisor function is the sum of the divisors.
  6027. @smallexample
  6028. @group
  6029. 1: 8 3: 8 2: 8 2: 8
  6030. 2: [1, 2, 3, 4, ...] 1: [1, 2, 3, 0, ...] 1: 72
  6031. 1: [1, 1, 1, 0, ...] . .
  6032. .
  6033. V R + r 1 r 2 V M * V R +
  6034. @end group
  6035. @end smallexample
  6036. @noindent
  6037. Once again, the last two steps just compute a dot product for which
  6038. a simple @kbd{*} would have worked equally well.
  6039. @node List Answer 5, List Answer 6, List Answer 4, Answers to Exercises
  6040. @subsection List Tutorial Exercise 5
  6041. @noindent
  6042. The obvious first step is to obtain the list of factors with @kbd{k f}.
  6043. This list will always be in sorted order, so if there are duplicates
  6044. they will be right next to each other. A suitable method is to compare
  6045. the list with a copy of itself shifted over by one.
  6046. @smallexample
  6047. @group
  6048. 1: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19, 0]
  6049. . 1: [3, 7, 7, 7, 19, 0] 1: [0, 3, 7, 7, 7, 19]
  6050. . .
  6051. 19551 k f @key{RET} 0 | @key{TAB} 0 @key{TAB} |
  6052. @end group
  6053. @end smallexample
  6054. @noindent
  6055. @smallexample
  6056. @group
  6057. 1: [0, 0, 1, 1, 0, 0] 1: 2 1: 0
  6058. . . .
  6059. V M a = V R + 0 a =
  6060. @end group
  6061. @end smallexample
  6062. @noindent
  6063. Note that we have to arrange for both vectors to have the same length
  6064. so that the mapping operation works; no prime factor will ever be
  6065. zero, so adding zeros on the left and right is safe. From then on
  6066. the job is pretty straightforward.
  6067. Incidentally, Calc provides the @c{\dfn{M\"obius} $\mu$}
  6068. @dfn{Moebius mu} function which is
  6069. zero if and only if its argument is square-free. It would be a much
  6070. more convenient way to do the above test in practice.
  6071. @node List Answer 6, List Answer 7, List Answer 5, Answers to Exercises
  6072. @subsection List Tutorial Exercise 6
  6073. @noindent
  6074. First use @kbd{v x 6 @key{RET}} to get a list of integers, then @kbd{V M v x}
  6075. to get a list of lists of integers!
  6076. @node List Answer 7, List Answer 8, List Answer 6, Answers to Exercises
  6077. @subsection List Tutorial Exercise 7
  6078. @noindent
  6079. Here's one solution. First, compute the triangular list from the previous
  6080. exercise and type @kbd{1 -} to subtract one from all the elements.
  6081. @smallexample
  6082. @group
  6083. 1: [ [0],
  6084. [0, 1],
  6085. [0, 1, 2],
  6086. @dots{}
  6087. 1 -
  6088. @end group
  6089. @end smallexample
  6090. The numbers down the lefthand edge of the list we desire are called
  6091. the ``triangular numbers'' (now you know why!). The @cite{n}th
  6092. triangular number is the sum of the integers from 1 to @cite{n}, and
  6093. can be computed directly by the formula @c{$n (n+1) \over 2$}
  6094. @cite{n * (n+1) / 2}.
  6095. @smallexample
  6096. @group
  6097. 2: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
  6098. 1: [0, 1, 2, 3, 4, 5] 1: [0, 1, 3, 6, 10, 15]
  6099. . .
  6100. v x 6 @key{RET} 1 - V M ' $ ($+1)/2 @key{RET}
  6101. @end group
  6102. @end smallexample
  6103. @noindent
  6104. Adding this list to the above list of lists produces the desired
  6105. result:
  6106. @smallexample
  6107. @group
  6108. 1: [ [0],
  6109. [1, 2],
  6110. [3, 4, 5],
  6111. [6, 7, 8, 9],
  6112. [10, 11, 12, 13, 14],
  6113. [15, 16, 17, 18, 19, 20] ]
  6114. .
  6115. V M +
  6116. @end group
  6117. @end smallexample
  6118. If we did not know the formula for triangular numbers, we could have
  6119. computed them using a @kbd{V U +} command. We could also have
  6120. gotten them the hard way by mapping a reduction across the original
  6121. triangular list.
  6122. @smallexample
  6123. @group
  6124. 2: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
  6125. 1: [ [0], [0, 1], ... ] 1: [0, 1, 3, 6, 10, 15]
  6126. . .
  6127. @key{RET} V M V R +
  6128. @end group
  6129. @end smallexample
  6130. @noindent
  6131. (This means ``map a @kbd{V R +} command across the vector,'' and
  6132. since each element of the main vector is itself a small vector,
  6133. @kbd{V R +} computes the sum of its elements.)
  6134. @node List Answer 8, List Answer 9, List Answer 7, Answers to Exercises
  6135. @subsection List Tutorial Exercise 8
  6136. @noindent
  6137. The first step is to build a list of values of @cite{x}.
  6138. @smallexample
  6139. @group
  6140. 1: [1, 2, 3, ..., 21] 1: [0, 1, 2, ..., 20] 1: [0, 0.25, 0.5, ..., 5]
  6141. . . .
  6142. v x 21 @key{RET} 1 - 4 / s 1
  6143. @end group
  6144. @end smallexample
  6145. Next, we compute the Bessel function values.
  6146. @smallexample
  6147. @group
  6148. 1: [0., 0.124, 0.242, ..., -0.328]
  6149. .
  6150. V M ' besJ(1,$) @key{RET}
  6151. @end group
  6152. @end smallexample
  6153. @noindent
  6154. (Another way to do this would be @kbd{1 @key{TAB} V M f j}.)
  6155. A way to isolate the maximum value is to compute the maximum using
  6156. @kbd{V R X}, then compare all the Bessel values with that maximum.
  6157. @smallexample
  6158. @group
  6159. 2: [0., 0.124, 0.242, ... ] 1: [0, 0, 0, ... ] 2: [0, 0, 0, ... ]
  6160. 1: 0.5801562 . 1: 1
  6161. . .
  6162. @key{RET} V R X V M a = @key{RET} V R + @key{DEL}
  6163. @end group
  6164. @end smallexample
  6165. @noindent
  6166. It's a good idea to verify, as in the last step above, that only
  6167. one value is equal to the maximum. (After all, a plot of @c{$\sin x$}
  6168. @cite{sin(x)}
  6169. might have many points all equal to the maximum value, 1.)
  6170. The vector we have now has a single 1 in the position that indicates
  6171. the maximum value of @cite{x}. Now it is a simple matter to convert
  6172. this back into the corresponding value itself.
  6173. @smallexample
  6174. @group
  6175. 2: [0, 0, 0, ... ] 1: [0, 0., 0., ... ] 1: 1.75
  6176. 1: [0, 0.25, 0.5, ... ] . .
  6177. .
  6178. r 1 V M * V R +
  6179. @end group
  6180. @end smallexample
  6181. If @kbd{a =} had produced more than one @cite{1} value, this method
  6182. would have given the sum of all maximum @cite{x} values; not very
  6183. useful! In this case we could have used @kbd{v m} (@code{calc-mask-vector})
  6184. instead. This command deletes all elements of a ``data'' vector that
  6185. correspond to zeros in a ``mask'' vector, leaving us with, in this
  6186. example, a vector of maximum @cite{x} values.
  6187. The built-in @kbd{a X} command maximizes a function using more
  6188. efficient methods. Just for illustration, let's use @kbd{a X}
  6189. to maximize @samp{besJ(1,x)} over this same interval.
  6190. @smallexample
  6191. @group
  6192. 2: besJ(1, x) 1: [1.84115, 0.581865]
  6193. 1: [0 .. 5] .
  6194. .
  6195. ' besJ(1,x), [0..5] @key{RET} a X x @key{RET}
  6196. @end group
  6197. @end smallexample
  6198. @noindent
  6199. The output from @kbd{a X} is a vector containing the value of @cite{x}
  6200. that maximizes the function, and the function's value at that maximum.
  6201. As you can see, our simple search got quite close to the right answer.
  6202. @node List Answer 9, List Answer 10, List Answer 8, Answers to Exercises
  6203. @subsection List Tutorial Exercise 9
  6204. @noindent
  6205. Step one is to convert our integer into vector notation.
  6206. @smallexample
  6207. @group
  6208. 1: 25129925999 3: 25129925999
  6209. . 2: 10
  6210. 1: [11, 10, 9, ..., 1, 0]
  6211. .
  6212. 25129925999 @key{RET} 10 @key{RET} 12 @key{RET} v x 12 @key{RET} -
  6213. @end group
  6214. @end smallexample
  6215. @noindent
  6216. @smallexample
  6217. @group
  6218. 1: 25129925999 1: [0, 2, 25, 251, 2512, ... ]
  6219. 2: [100000000000, ... ] .
  6220. .
  6221. V M ^ s 1 V M \
  6222. @end group
  6223. @end smallexample
  6224. @noindent
  6225. (Recall, the @kbd{\} command computes an integer quotient.)
  6226. @smallexample
  6227. @group
  6228. 1: [0, 2, 5, 1, 2, 9, 9, 2, 5, 9, 9, 9]
  6229. .
  6230. 10 V M % s 2
  6231. @end group
  6232. @end smallexample
  6233. Next we must increment this number. This involves adding one to
  6234. the last digit, plus handling carries. There is a carry to the
  6235. left out of a digit if that digit is a nine and all the digits to
  6236. the right of it are nines.
  6237. @smallexample
  6238. @group
  6239. 1: [0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1] 1: [1, 1, 1, 0, 0, 1, ... ]
  6240. . .
  6241. 9 V M a = v v
  6242. @end group
  6243. @end smallexample
  6244. @noindent
  6245. @smallexample
  6246. @group
  6247. 1: [1, 1, 1, 0, 0, 0, ... ] 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
  6248. . .
  6249. V U * v v 1 |
  6250. @end group
  6251. @end smallexample
  6252. @noindent
  6253. Accumulating @kbd{*} across a vector of ones and zeros will preserve
  6254. only the initial run of ones. These are the carries into all digits
  6255. except the rightmost digit. Concatenating a one on the right takes
  6256. care of aligning the carries properly, and also adding one to the
  6257. rightmost digit.
  6258. @smallexample
  6259. @group
  6260. 2: [0, 0, 0, 0, ... ] 1: [0, 0, 2, 5, 1, 2, 9, 9, 2, 6, 0, 0, 0]
  6261. 1: [0, 0, 2, 5, ... ] .
  6262. .
  6263. 0 r 2 | V M + 10 V M %
  6264. @end group
  6265. @end smallexample
  6266. @noindent
  6267. Here we have concatenated 0 to the @emph{left} of the original number;
  6268. this takes care of shifting the carries by one with respect to the
  6269. digits that generated them.
  6270. Finally, we must convert this list back into an integer.
  6271. @smallexample
  6272. @group
  6273. 3: [0, 0, 2, 5, ... ] 2: [0, 0, 2, 5, ... ]
  6274. 2: 1000000000000 1: [1000000000000, 100000000000, ... ]
  6275. 1: [100000000000, ... ] .
  6276. .
  6277. 10 @key{RET} 12 ^ r 1 |
  6278. @end group
  6279. @end smallexample
  6280. @noindent
  6281. @smallexample
  6282. @group
  6283. 1: [0, 0, 20000000000, 5000000000, ... ] 1: 25129926000
  6284. . .
  6285. V M * V R +
  6286. @end group
  6287. @end smallexample
  6288. @noindent
  6289. Another way to do this final step would be to reduce the formula
  6290. @w{@samp{10 $$ + $}} across the vector of digits.
  6291. @smallexample
  6292. @group
  6293. 1: [0, 0, 2, 5, ... ] 1: 25129926000
  6294. . .
  6295. V R ' 10 $$ + $ @key{RET}
  6296. @end group
  6297. @end smallexample
  6298. @node List Answer 10, List Answer 11, List Answer 9, Answers to Exercises
  6299. @subsection List Tutorial Exercise 10
  6300. @noindent
  6301. For the list @cite{[a, b, c, d]}, the result is @cite{((a = b) = c) = d},
  6302. which will compare @cite{a} and @cite{b} to produce a 1 or 0, which is
  6303. then compared with @cite{c} to produce another 1 or 0, which is then
  6304. compared with @cite{d}. This is not at all what Joe wanted.
  6305. Here's a more correct method:
  6306. @smallexample
  6307. @group
  6308. 1: [7, 7, 7, 8, 7] 2: [7, 7, 7, 8, 7]
  6309. . 1: 7
  6310. .
  6311. ' [7,7,7,8,7] @key{RET} @key{RET} v r 1 @key{RET}
  6312. @end group
  6313. @end smallexample
  6314. @noindent
  6315. @smallexample
  6316. @group
  6317. 1: [1, 1, 1, 0, 1] 1: 0
  6318. . .
  6319. V M a = V R *
  6320. @end group
  6321. @end smallexample
  6322. @node List Answer 11, List Answer 12, List Answer 10, Answers to Exercises
  6323. @subsection List Tutorial Exercise 11
  6324. @noindent
  6325. The circle of unit radius consists of those points @cite{(x,y)} for which
  6326. @cite{x^2 + y^2 < 1}. We start by generating a vector of @cite{x^2}
  6327. and a vector of @cite{y^2}.
  6328. We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
  6329. commands.
  6330. @smallexample
  6331. @group
  6332. 2: [2., 2., ..., 2.] 2: [2., 2., ..., 2.]
  6333. 1: [2., 2., ..., 2.] 1: [1.16, 1.98, ..., 0.81]
  6334. . .
  6335. v . t . 2. v b 100 @key{RET} @key{RET} V M k r
  6336. @end group
  6337. @end smallexample
  6338. @noindent
  6339. @smallexample
  6340. @group
  6341. 2: [2., 2., ..., 2.] 1: [0.026, 0.96, ..., 0.036]
  6342. 1: [0.026, 0.96, ..., 0.036] 2: [0.53, 0.81, ..., 0.094]
  6343. . .
  6344. 1 - 2 V M ^ @key{TAB} V M k r 1 - 2 V M ^
  6345. @end group
  6346. @end smallexample
  6347. Now we sum the @cite{x^2} and @cite{y^2} values, compare with 1 to
  6348. get a vector of 1/0 truth values, then sum the truth values.
  6349. @smallexample
  6350. @group
  6351. 1: [0.56, 1.78, ..., 0.13] 1: [1, 0, ..., 1] 1: 84
  6352. . . .
  6353. + 1 V M a < V R +
  6354. @end group
  6355. @end smallexample
  6356. @noindent
  6357. The ratio @cite{84/100} should approximate the ratio @c{$\pi/4$}
  6358. @cite{pi/4}.
  6359. @smallexample
  6360. @group
  6361. 1: 0.84 1: 3.36 2: 3.36 1: 1.0695
  6362. . . 1: 3.14159 .
  6363. 100 / 4 * P /
  6364. @end group
  6365. @end smallexample
  6366. @noindent
  6367. Our estimate, 3.36, is off by about 7%. We could get a better estimate
  6368. by taking more points (say, 1000), but it's clear that this method is
  6369. not very efficient!
  6370. (Naturally, since this example uses random numbers your own answer
  6371. will be slightly different from the one shown here!)
  6372. If you typed @kbd{v .} and @kbd{t .} before, type them again to
  6373. return to full-sized display of vectors.
  6374. @node List Answer 12, List Answer 13, List Answer 11, Answers to Exercises
  6375. @subsection List Tutorial Exercise 12
  6376. @noindent
  6377. This problem can be made a lot easier by taking advantage of some
  6378. symmetries. First of all, after some thought it's clear that the
  6379. @cite{y} axis can be ignored altogether. Just pick a random @cite{x}
  6380. component for one end of the match, pick a random direction @c{$\theta$}
  6381. @cite{theta},
  6382. and see if @cite{x} and @c{$x + \cos \theta$}
  6383. @cite{x + cos(theta)} (which is the @cite{x}
  6384. coordinate of the other endpoint) cross a line. The lines are at
  6385. integer coordinates, so this happens when the two numbers surround
  6386. an integer.
  6387. Since the two endpoints are equivalent, we may as well choose the leftmost
  6388. of the two endpoints as @cite{x}. Then @cite{theta} is an angle pointing
  6389. to the right, in the range -90 to 90 degrees. (We could use radians, but
  6390. it would feel like cheating to refer to @c{$\pi/2$}
  6391. @cite{pi/2} radians while trying
  6392. to estimate @c{$\pi$}
  6393. @cite{pi}!)
  6394. In fact, since the field of lines is infinite we can choose the
  6395. coordinates 0 and 1 for the lines on either side of the leftmost
  6396. endpoint. The rightmost endpoint will be between 0 and 1 if the
  6397. match does not cross a line, or between 1 and 2 if it does. So:
  6398. Pick random @cite{x} and @c{$\theta$}
  6399. @cite{theta}, compute @c{$x + \cos \theta$}
  6400. @cite{x + cos(theta)},
  6401. and count how many of the results are greater than one. Simple!
  6402. We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
  6403. commands.
  6404. @smallexample
  6405. @group
  6406. 1: [0.52, 0.71, ..., 0.72] 2: [0.52, 0.71, ..., 0.72]
  6407. . 1: [78.4, 64.5, ..., -42.9]
  6408. .
  6409. v . t . 1. v b 100 @key{RET} V M k r 180. v b 100 @key{RET} V M k r 90 -
  6410. @end group
  6411. @end smallexample
  6412. @noindent
  6413. (The next step may be slow, depending on the speed of your computer.)
  6414. @smallexample
  6415. @group
  6416. 2: [0.52, 0.71, ..., 0.72] 1: [0.72, 1.14, ..., 1.45]
  6417. 1: [0.20, 0.43, ..., 0.73] .
  6418. .
  6419. m d V M C +
  6420. @end group
  6421. @end smallexample
  6422. @noindent
  6423. @smallexample
  6424. @group
  6425. 1: [0, 1, ..., 1] 1: 0.64 1: 3.125
  6426. . . .
  6427. 1 V M a > V R + 100 / 2 @key{TAB} /
  6428. @end group
  6429. @end smallexample
  6430. Let's try the third method, too. We'll use random integers up to
  6431. one million. The @kbd{k r} command with an integer argument picks
  6432. a random integer.
  6433. @smallexample
  6434. @group
  6435. 2: [1000000, 1000000, ..., 1000000] 2: [78489, 527587, ..., 814975]
  6436. 1: [1000000, 1000000, ..., 1000000] 1: [324014, 358783, ..., 955450]
  6437. . .
  6438. 1000000 v b 100 @key{RET} @key{RET} V M k r @key{TAB} V M k r
  6439. @end group
  6440. @end smallexample
  6441. @noindent
  6442. @smallexample
  6443. @group
  6444. 1: [1, 1, ..., 25] 1: [1, 1, ..., 0] 1: 0.56
  6445. . . .
  6446. V M k g 1 V M a = V R + 100 /
  6447. @end group
  6448. @end smallexample
  6449. @noindent
  6450. @smallexample
  6451. @group
  6452. 1: 10.714 1: 3.273
  6453. . .
  6454. 6 @key{TAB} / Q
  6455. @end group
  6456. @end smallexample
  6457. For a proof of this property of the GCD function, see section 4.5.2,
  6458. exercise 10, of Knuth's @emph{Art of Computer Programming}, volume II.
  6459. If you typed @kbd{v .} and @kbd{t .} before, type them again to
  6460. return to full-sized display of vectors.
  6461. @node List Answer 13, List Answer 14, List Answer 12, Answers to Exercises
  6462. @subsection List Tutorial Exercise 13
  6463. @noindent
  6464. First, we put the string on the stack as a vector of ASCII codes.
  6465. @smallexample
  6466. @group
  6467. 1: [84, 101, 115, ..., 51]
  6468. .
  6469. "Testing, 1, 2, 3 @key{RET}
  6470. @end group
  6471. @end smallexample
  6472. @noindent
  6473. Note that the @kbd{"} key, like @kbd{$}, initiates algebraic entry so
  6474. there was no need to type an apostrophe. Also, Calc didn't mind that
  6475. we omitted the closing @kbd{"}. (The same goes for all closing delimiters
  6476. like @kbd{)} and @kbd{]} at the end of a formula.
  6477. We'll show two different approaches here. In the first, we note that
  6478. if the input vector is @cite{[a, b, c, d]}, then the hash code is
  6479. @cite{3 (3 (3a + b) + c) + d = 27a + 9b + 3c + d}. In other words,
  6480. it's a sum of descending powers of three times the ASCII codes.
  6481. @smallexample
  6482. @group
  6483. 2: [84, 101, 115, ..., 51] 2: [84, 101, 115, ..., 51]
  6484. 1: 16 1: [15, 14, 13, ..., 0]
  6485. . .
  6486. @key{RET} v l v x 16 @key{RET} -
  6487. @end group
  6488. @end smallexample
  6489. @noindent
  6490. @smallexample
  6491. @group
  6492. 2: [84, 101, 115, ..., 51] 1: 1960915098 1: 121
  6493. 1: [14348907, ..., 1] . .
  6494. .
  6495. 3 @key{TAB} V M ^ * 511 %
  6496. @end group
  6497. @end smallexample
  6498. @noindent
  6499. Once again, @kbd{*} elegantly summarizes most of the computation.
  6500. But there's an even more elegant approach: Reduce the formula
  6501. @kbd{3 $$ + $} across the vector. Recall that this represents a
  6502. function of two arguments that computes its first argument times three
  6503. plus its second argument.
  6504. @smallexample
  6505. @group
  6506. 1: [84, 101, 115, ..., 51] 1: 1960915098
  6507. . .
  6508. "Testing, 1, 2, 3 @key{RET} V R ' 3$$+$ @key{RET}
  6509. @end group
  6510. @end smallexample
  6511. @noindent
  6512. If you did the decimal arithmetic exercise, this will be familiar.
  6513. Basically, we're turning a base-3 vector of digits into an integer,
  6514. except that our ``digits'' are much larger than real digits.
  6515. Instead of typing @kbd{511 %} again to reduce the result, we can be
  6516. cleverer still and notice that rather than computing a huge integer
  6517. and taking the modulo at the end, we can take the modulo at each step
  6518. without affecting the result. While this means there are more
  6519. arithmetic operations, the numbers we operate on remain small so
  6520. the operations are faster.
  6521. @smallexample
  6522. @group
  6523. 1: [84, 101, 115, ..., 51] 1: 121
  6524. . .
  6525. "Testing, 1, 2, 3 @key{RET} V R ' (3$$+$)%511 @key{RET}
  6526. @end group
  6527. @end smallexample
  6528. Why does this work? Think about a two-step computation:
  6529. @w{@cite{3 (3a + b) + c}}. Taking a result modulo 511 basically means
  6530. subtracting off enough 511's to put the result in the desired range.
  6531. So the result when we take the modulo after every step is,
  6532. @ifinfo
  6533. @example
  6534. 3 (3 a + b - 511 m) + c - 511 n
  6535. @end example
  6536. @end ifinfo
  6537. @tex
  6538. \turnoffactive
  6539. \beforedisplay
  6540. $$ 3 (3 a + b - 511 m) + c - 511 n $$
  6541. \afterdisplay
  6542. @end tex
  6543. @noindent
  6544. for some suitable integers @cite{m} and @cite{n}. Expanding out by
  6545. the distributive law yields
  6546. @ifinfo
  6547. @example
  6548. 9 a + 3 b + c - 511*3 m - 511 n
  6549. @end example
  6550. @end ifinfo
  6551. @tex
  6552. \turnoffactive
  6553. \beforedisplay
  6554. $$ 9 a + 3 b + c - 511\times3 m - 511 n $$
  6555. \afterdisplay
  6556. @end tex
  6557. @noindent
  6558. The @cite{m} term in the latter formula is redundant because any
  6559. contribution it makes could just as easily be made by the @cite{n}
  6560. term. So we can take it out to get an equivalent formula with
  6561. @cite{n' = 3m + n},
  6562. @ifinfo
  6563. @example
  6564. 9 a + 3 b + c - 511 n'
  6565. @end example
  6566. @end ifinfo
  6567. @tex
  6568. \turnoffactive
  6569. \beforedisplay
  6570. $$ 9 a + 3 b + c - 511 n' $$
  6571. \afterdisplay
  6572. @end tex
  6573. @noindent
  6574. which is just the formula for taking the modulo only at the end of
  6575. the calculation. Therefore the two methods are essentially the same.
  6576. Later in the tutorial we will encounter @dfn{modulo forms}, which
  6577. basically automate the idea of reducing every intermediate result
  6578. modulo some value @var{m}.
  6579. @node List Answer 14, Types Answer 1, List Answer 13, Answers to Exercises
  6580. @subsection List Tutorial Exercise 14
  6581. We want to use @kbd{H V U} to nest a function which adds a random
  6582. step to an @cite{(x,y)} coordinate. The function is a bit long, but
  6583. otherwise the problem is quite straightforward.
  6584. @smallexample
  6585. @group
  6586. 2: [0, 0] 1: [ [ 0, 0 ]
  6587. 1: 50 [ 0.4288, -0.1695 ]
  6588. . [ -0.4787, -0.9027 ]
  6589. ...
  6590. [0,0] 50 H V U ' <# + [random(2.0)-1, random(2.0)-1]> @key{RET}
  6591. @end group
  6592. @end smallexample
  6593. Just as the text recommended, we used @samp{< >} nameless function
  6594. notation to keep the two @code{random} calls from being evaluated
  6595. before nesting even begins.
  6596. We now have a vector of @cite{[x, y]} sub-vectors, which by Calc's
  6597. rules acts like a matrix. We can transpose this matrix and unpack
  6598. to get a pair of vectors, @cite{x} and @cite{y}, suitable for graphing.
  6599. @smallexample
  6600. @group
  6601. 2: [ 0, 0.4288, -0.4787, ... ]
  6602. 1: [ 0, -0.1696, -0.9027, ... ]
  6603. .
  6604. v t v u g f
  6605. @end group
  6606. @end smallexample
  6607. Incidentally, because the @cite{x} and @cite{y} are completely
  6608. independent in this case, we could have done two separate commands
  6609. to create our @cite{x} and @cite{y} vectors of numbers directly.
  6610. To make a random walk of unit steps, we note that @code{sincos} of
  6611. a random direction exactly gives us an @cite{[x, y]} step of unit
  6612. length; in fact, the new nesting function is even briefer, though
  6613. we might want to lower the precision a bit for it.
  6614. @smallexample
  6615. @group
  6616. 2: [0, 0] 1: [ [ 0, 0 ]
  6617. 1: 50 [ 0.1318, 0.9912 ]
  6618. . [ -0.5965, 0.3061 ]
  6619. ...
  6620. [0,0] 50 m d p 6 @key{RET} H V U ' <# + sincos(random(360.0))> @key{RET}
  6621. @end group
  6622. @end smallexample
  6623. Another @kbd{v t v u g f} sequence will graph this new random walk.
  6624. An interesting twist on these random walk functions would be to use
  6625. complex numbers instead of 2-vectors to represent points on the plane.
  6626. In the first example, we'd use something like @samp{random + random*(0,1)},
  6627. and in the second we could use polar complex numbers with random phase
  6628. angles. (This exercise was first suggested in this form by Randal
  6629. Schwartz.)
  6630. @node Types Answer 1, Types Answer 2, List Answer 14, Answers to Exercises
  6631. @subsection Types Tutorial Exercise 1
  6632. @noindent
  6633. If the number is the square root of @c{$\pi$}
  6634. @cite{pi} times a rational number,
  6635. then its square, divided by @c{$\pi$}
  6636. @cite{pi}, should be a rational number.
  6637. @smallexample
  6638. @group
  6639. 1: 1.26508260337 1: 0.509433962268 1: 2486645810:4881193627
  6640. . . .
  6641. 2 ^ P / c F
  6642. @end group
  6643. @end smallexample
  6644. @noindent
  6645. Technically speaking this is a rational number, but not one that is
  6646. likely to have arisen in the original problem. More likely, it just
  6647. happens to be the fraction which most closely represents some
  6648. irrational number to within 12 digits.
  6649. But perhaps our result was not quite exact. Let's reduce the
  6650. precision slightly and try again:
  6651. @smallexample
  6652. @group
  6653. 1: 0.509433962268 1: 27:53
  6654. . .
  6655. U p 10 @key{RET} c F
  6656. @end group
  6657. @end smallexample
  6658. @noindent
  6659. Aha! It's unlikely that an irrational number would equal a fraction
  6660. this simple to within ten digits, so our original number was probably
  6661. @c{$\sqrt{27 \pi / 53}$}
  6662. @cite{sqrt(27 pi / 53)}.
  6663. Notice that we didn't need to re-round the number when we reduced the
  6664. precision. Remember, arithmetic operations always round their inputs
  6665. to the current precision before they begin.
  6666. @node Types Answer 2, Types Answer 3, Types Answer 1, Answers to Exercises
  6667. @subsection Types Tutorial Exercise 2
  6668. @noindent
  6669. @samp{inf / inf = nan}. Perhaps @samp{1} is the ``obvious'' answer.
  6670. But if @w{@samp{17 inf = inf}}, then @samp{17 inf / inf = inf / inf = 17}, too.
  6671. @samp{exp(inf) = inf}. It's tempting to say that the exponential
  6672. of infinity must be ``bigger'' than ``regular'' infinity, but as
  6673. far as Calc is concerned all infinities are as just as big.
  6674. In other words, as @cite{x} goes to infinity, @cite{e^x} also goes
  6675. to infinity, but the fact the @cite{e^x} grows much faster than
  6676. @cite{x} is not relevant here.
  6677. @samp{exp(-inf) = 0}. Here we have a finite answer even though
  6678. the input is infinite.
  6679. @samp{sqrt(-inf) = (0, 1) inf}. Remember that @cite{(0, 1)}
  6680. represents the imaginary number @cite{i}. Here's a derivation:
  6681. @samp{sqrt(-inf) = @w{sqrt((-1) * inf)} = sqrt(-1) * sqrt(inf)}.
  6682. The first part is, by definition, @cite{i}; the second is @code{inf}
  6683. because, once again, all infinities are the same size.
  6684. @samp{sqrt(uinf) = uinf}. In fact, we do know something about the
  6685. direction because @code{sqrt} is defined to return a value in the
  6686. right half of the complex plane. But Calc has no notation for this,
  6687. so it settles for the conservative answer @code{uinf}.
  6688. @samp{abs(uinf) = inf}. No matter which direction @cite{x} points,
  6689. @samp{abs(x)} always points along the positive real axis.
  6690. @samp{ln(0) = -inf}. Here we have an infinite answer to a finite
  6691. input. As in the @cite{1 / 0} case, Calc will only use infinities
  6692. here if you have turned on ``infinite'' mode. Otherwise, it will
  6693. treat @samp{ln(0)} as an error.
  6694. @node Types Answer 3, Types Answer 4, Types Answer 2, Answers to Exercises
  6695. @subsection Types Tutorial Exercise 3
  6696. @noindent
  6697. We can make @samp{inf - inf} be any real number we like, say,
  6698. @cite{a}, just by claiming that we added @cite{a} to the first
  6699. infinity but not to the second. This is just as true for complex
  6700. values of @cite{a}, so @code{nan} can stand for a complex number.
  6701. (And, similarly, @code{uinf} can stand for an infinity that points
  6702. in any direction in the complex plane, such as @samp{(0, 1) inf}).
  6703. In fact, we can multiply the first @code{inf} by two. Surely
  6704. @w{@samp{2 inf - inf = inf}}, but also @samp{2 inf - inf = inf - inf = nan}.
  6705. So @code{nan} can even stand for infinity. Obviously it's just
  6706. as easy to make it stand for minus infinity as for plus infinity.
  6707. The moral of this story is that ``infinity'' is a slippery fish
  6708. indeed, and Calc tries to handle it by having a very simple model
  6709. for infinities (only the direction counts, not the ``size''); but
  6710. Calc is careful to write @code{nan} any time this simple model is
  6711. unable to tell what the true answer is.
  6712. @node Types Answer 4, Types Answer 5, Types Answer 3, Answers to Exercises
  6713. @subsection Types Tutorial Exercise 4
  6714. @smallexample
  6715. @group
  6716. 2: 0@@ 47' 26" 1: 0@@ 2' 47.411765"
  6717. 1: 17 .
  6718. .
  6719. 0@@ 47' 26" @key{RET} 17 /
  6720. @end group
  6721. @end smallexample
  6722. @noindent
  6723. The average song length is two minutes and 47.4 seconds.
  6724. @smallexample
  6725. @group
  6726. 2: 0@@ 2' 47.411765" 1: 0@@ 3' 7.411765" 1: 0@@ 53' 6.000005"
  6727. 1: 0@@ 0' 20" . .
  6728. .
  6729. 20" + 17 *
  6730. @end group
  6731. @end smallexample
  6732. @noindent
  6733. The album would be 53 minutes and 6 seconds long.
  6734. @node Types Answer 5, Types Answer 6, Types Answer 4, Answers to Exercises
  6735. @subsection Types Tutorial Exercise 5
  6736. @noindent
  6737. Let's suppose it's January 14, 1991. The easiest thing to do is
  6738. to keep trying 13ths of months until Calc reports a Friday.
  6739. We can do this by manually entering dates, or by using @kbd{t I}:
  6740. @smallexample
  6741. @group
  6742. 1: <Wed Feb 13, 1991> 1: <Wed Mar 13, 1991> 1: <Sat Apr 13, 1991>
  6743. . . .
  6744. ' <2/13> @key{RET} @key{DEL} ' <3/13> @key{RET} t I
  6745. @end group
  6746. @end smallexample
  6747. @noindent
  6748. (Calc assumes the current year if you don't say otherwise.)
  6749. This is getting tedious---we can keep advancing the date by typing
  6750. @kbd{t I} over and over again, but let's automate the job by using
  6751. vector mapping. The @kbd{t I} command actually takes a second
  6752. ``how-many-months'' argument, which defaults to one. This
  6753. argument is exactly what we want to map over:
  6754. @smallexample
  6755. @group
  6756. 2: <Sat Apr 13, 1991> 1: [<Mon May 13, 1991>, <Thu Jun 13, 1991>,
  6757. 1: [1, 2, 3, 4, 5, 6] <Sat Jul 13, 1991>, <Tue Aug 13, 1991>,
  6758. . <Fri Sep 13, 1991>, <Sun Oct 13, 1991>]
  6759. .
  6760. v x 6 @key{RET} V M t I
  6761. @end group
  6762. @end smallexample
  6763. @ifinfo
  6764. @noindent
  6765. Et voila, September 13, 1991 is a Friday.
  6766. @end ifinfo
  6767. @tex
  6768. \noindent
  6769. {\it Et voil{\accent"12 a}}, September 13, 1991 is a Friday.
  6770. @end tex
  6771. @smallexample
  6772. @group
  6773. 1: 242
  6774. .
  6775. ' <sep 13> - <jan 14> @key{RET}
  6776. @end group
  6777. @end smallexample
  6778. @noindent
  6779. And the answer to our original question: 242 days to go.
  6780. @node Types Answer 6, Types Answer 7, Types Answer 5, Answers to Exercises
  6781. @subsection Types Tutorial Exercise 6
  6782. @noindent
  6783. The full rule for leap years is that they occur in every year divisible
  6784. by four, except that they don't occur in years divisible by 100, except
  6785. that they @emph{do} in years divisible by 400. We could work out the
  6786. answer by carefully counting the years divisible by four and the
  6787. exceptions, but there is a much simpler way that works even if we
  6788. don't know the leap year rule.
  6789. Let's assume the present year is 1991. Years have 365 days, except
  6790. that leap years (whenever they occur) have 366 days. So let's count
  6791. the number of days between now and then, and compare that to the
  6792. number of years times 365. The number of extra days we find must be
  6793. equal to the number of leap years there were.
  6794. @smallexample
  6795. @group
  6796. 1: <Mon Jan 1, 10001> 2: <Mon Jan 1, 10001> 1: 2925593
  6797. . 1: <Tue Jan 1, 1991> .
  6798. .
  6799. ' <jan 1 10001> @key{RET} ' <jan 1 1991> @key{RET} -
  6800. @end group
  6801. @end smallexample
  6802. @noindent
  6803. @smallexample
  6804. @group
  6805. 3: 2925593 2: 2925593 2: 2925593 1: 1943
  6806. 2: 10001 1: 8010 1: 2923650 .
  6807. 1: 1991 . .
  6808. .
  6809. 10001 @key{RET} 1991 - 365 * -
  6810. @end group
  6811. @end smallexample
  6812. @c [fix-ref Date Forms]
  6813. @noindent
  6814. There will be 1943 leap years before the year 10001. (Assuming,
  6815. of course, that the algorithm for computing leap years remains
  6816. unchanged for that long. @xref{Date Forms}, for some interesting
  6817. background information in that regard.)
  6818. @node Types Answer 7, Types Answer 8, Types Answer 6, Answers to Exercises
  6819. @subsection Types Tutorial Exercise 7
  6820. @noindent
  6821. The relative errors must be converted to absolute errors so that
  6822. @samp{+/-} notation may be used.
  6823. @smallexample
  6824. @group
  6825. 1: 1. 2: 1.
  6826. . 1: 0.2
  6827. .
  6828. 20 @key{RET} .05 * 4 @key{RET} .05 *
  6829. @end group
  6830. @end smallexample
  6831. Now we simply chug through the formula.
  6832. @smallexample
  6833. @group
  6834. 1: 19.7392088022 1: 394.78 +/- 19.739 1: 6316.5 +/- 706.21
  6835. . . .
  6836. 2 P 2 ^ * 20 p 1 * 4 p .2 @key{RET} 2 ^ *
  6837. @end group
  6838. @end smallexample
  6839. It turns out the @kbd{v u} command will unpack an error form as
  6840. well as a vector. This saves us some retyping of numbers.
  6841. @smallexample
  6842. @group
  6843. 3: 6316.5 +/- 706.21 2: 6316.5 +/- 706.21
  6844. 2: 6316.5 1: 0.1118
  6845. 1: 706.21 .
  6846. .
  6847. @key{RET} v u @key{TAB} /
  6848. @end group
  6849. @end smallexample
  6850. @noindent
  6851. Thus the volume is 6316 cubic centimeters, within about 11 percent.
  6852. @node Types Answer 8, Types Answer 9, Types Answer 7, Answers to Exercises
  6853. @subsection Types Tutorial Exercise 8
  6854. @noindent
  6855. The first answer is pretty simple: @samp{1 / (0 .. 10) = (0.1 .. inf)}.
  6856. Since a number in the interval @samp{(0 .. 10)} can get arbitrarily
  6857. close to zero, its reciprocal can get arbitrarily large, so the answer
  6858. is an interval that effectively means, ``any number greater than 0.1''
  6859. but with no upper bound.
  6860. The second answer, similarly, is @samp{1 / (-10 .. 0) = (-inf .. -0.1)}.
  6861. Calc normally treats division by zero as an error, so that the formula
  6862. @w{@samp{1 / 0}} is left unsimplified. Our third problem,
  6863. @w{@samp{1 / [0 .. 10]}}, also (potentially) divides by zero because zero
  6864. is now a member of the interval. So Calc leaves this one unevaluated, too.
  6865. If you turn on ``infinite'' mode by pressing @kbd{m i}, you will
  6866. instead get the answer @samp{[0.1 .. inf]}, which includes infinity
  6867. as a possible value.
  6868. The fourth calculation, @samp{1 / (-10 .. 10)}, has the same problem.
  6869. Zero is buried inside the interval, but it's still a possible value.
  6870. It's not hard to see that the actual result of @samp{1 / (-10 .. 10)}
  6871. will be either greater than @i{0.1}, or less than @i{-0.1}. Thus
  6872. the interval goes from minus infinity to plus infinity, with a ``hole''
  6873. in it from @i{-0.1} to @i{0.1}. Calc doesn't have any way to
  6874. represent this, so it just reports @samp{[-inf .. inf]} as the answer.
  6875. It may be disappointing to hear ``the answer lies somewhere between
  6876. minus infinity and plus infinity, inclusive,'' but that's the best
  6877. that interval arithmetic can do in this case.
  6878. @node Types Answer 9, Types Answer 10, Types Answer 8, Answers to Exercises
  6879. @subsection Types Tutorial Exercise 9
  6880. @smallexample
  6881. @group
  6882. 1: [-3 .. 3] 2: [-3 .. 3] 2: [0 .. 9]
  6883. . 1: [0 .. 9] 1: [-9 .. 9]
  6884. . .
  6885. [ 3 n .. 3 ] @key{RET} 2 ^ @key{TAB} @key{RET} *
  6886. @end group
  6887. @end smallexample
  6888. @noindent
  6889. In the first case the result says, ``if a number is between @i{-3} and
  6890. 3, its square is between 0 and 9.'' The second case says, ``the product
  6891. of two numbers each between @i{-3} and 3 is between @i{-9} and 9.''
  6892. An interval form is not a number; it is a symbol that can stand for
  6893. many different numbers. Two identical-looking interval forms can stand
  6894. for different numbers.
  6895. The same issue arises when you try to square an error form.
  6896. @node Types Answer 10, Types Answer 11, Types Answer 9, Answers to Exercises
  6897. @subsection Types Tutorial Exercise 10
  6898. @noindent
  6899. Testing the first number, we might arbitrarily choose 17 for @cite{x}.
  6900. @smallexample
  6901. @group
  6902. 1: 17 mod 811749613 2: 17 mod 811749613 1: 533694123 mod 811749613
  6903. . 811749612 .
  6904. .
  6905. 17 M 811749613 @key{RET} 811749612 ^
  6906. @end group
  6907. @end smallexample
  6908. @noindent
  6909. Since 533694123 is (considerably) different from 1, the number 811749613
  6910. must not be prime.
  6911. It's awkward to type the number in twice as we did above. There are
  6912. various ways to avoid this, and algebraic entry is one. In fact, using
  6913. a vector mapping operation we can perform several tests at once. Let's
  6914. use this method to test the second number.
  6915. @smallexample
  6916. @group
  6917. 2: [17, 42, 100000] 1: [1 mod 15485863, 1 mod ... ]
  6918. 1: 15485863 .
  6919. .
  6920. [17 42 100000] 15485863 @key{RET} V M ' ($$ mod $)^($-1) @key{RET}
  6921. @end group
  6922. @end smallexample
  6923. @noindent
  6924. The result is three ones (modulo @cite{n}), so it's very probable that
  6925. 15485863 is prime. (In fact, this number is the millionth prime.)
  6926. Note that the functions @samp{($$^($-1)) mod $} or @samp{$$^($-1) % $}
  6927. would have been hopelessly inefficient, since they would have calculated
  6928. the power using full integer arithmetic.
  6929. Calc has a @kbd{k p} command that does primality testing. For small
  6930. numbers it does an exact test; for large numbers it uses a variant
  6931. of the Fermat test we used here. You can use @kbd{k p} repeatedly
  6932. to prove that a large integer is prime with any desired probability.
  6933. @node Types Answer 11, Types Answer 12, Types Answer 10, Answers to Exercises
  6934. @subsection Types Tutorial Exercise 11
  6935. @noindent
  6936. There are several ways to insert a calculated number into an HMS form.
  6937. One way to convert a number of seconds to an HMS form is simply to
  6938. multiply the number by an HMS form representing one second:
  6939. @smallexample
  6940. @group
  6941. 1: 31415926.5359 2: 31415926.5359 1: 8726@@ 38' 46.5359"
  6942. . 1: 0@@ 0' 1" .
  6943. .
  6944. P 1e7 * 0@@ 0' 1" *
  6945. @end group
  6946. @end smallexample
  6947. @noindent
  6948. @smallexample
  6949. @group
  6950. 2: 8726@@ 38' 46.5359" 1: 6@@ 6' 2.5359" mod 24@@ 0' 0"
  6951. 1: 15@@ 27' 16" mod 24@@ 0' 0" .
  6952. .
  6953. x time @key{RET} +
  6954. @end group
  6955. @end smallexample
  6956. @noindent
  6957. It will be just after six in the morning.
  6958. The algebraic @code{hms} function can also be used to build an
  6959. HMS form:
  6960. @smallexample
  6961. @group
  6962. 1: hms(0, 0, 10000000. pi) 1: 8726@@ 38' 46.5359"
  6963. . .
  6964. ' hms(0, 0, 1e7 pi) @key{RET} =
  6965. @end group
  6966. @end smallexample
  6967. @noindent
  6968. The @kbd{=} key is necessary to evaluate the symbol @samp{pi} to
  6969. the actual number 3.14159...
  6970. @node Types Answer 12, Types Answer 13, Types Answer 11, Answers to Exercises
  6971. @subsection Types Tutorial Exercise 12
  6972. @noindent
  6973. As we recall, there are 17 songs of about 2 minutes and 47 seconds
  6974. each.
  6975. @smallexample
  6976. @group
  6977. 2: 0@@ 2' 47" 1: [0@@ 3' 7" .. 0@@ 3' 47"]
  6978. 1: [0@@ 0' 20" .. 0@@ 1' 0"] .
  6979. .
  6980. [ 0@@ 20" .. 0@@ 1' ] +
  6981. @end group
  6982. @end smallexample
  6983. @noindent
  6984. @smallexample
  6985. @group
  6986. 1: [0@@ 52' 59." .. 1@@ 4' 19."]
  6987. .
  6988. 17 *
  6989. @end group
  6990. @end smallexample
  6991. @noindent
  6992. No matter how long it is, the album will fit nicely on one CD.
  6993. @node Types Answer 13, Types Answer 14, Types Answer 12, Answers to Exercises
  6994. @subsection Types Tutorial Exercise 13
  6995. @noindent
  6996. Type @kbd{' 1 yr @key{RET} u c s @key{RET}}. The answer is 31557600 seconds.
  6997. @node Types Answer 14, Types Answer 15, Types Answer 13, Answers to Exercises
  6998. @subsection Types Tutorial Exercise 14
  6999. @noindent
  7000. How long will it take for a signal to get from one end of the computer
  7001. to the other?
  7002. @smallexample
  7003. @group
  7004. 1: m / c 1: 3.3356 ns
  7005. . .
  7006. ' 1 m / c @key{RET} u c ns @key{RET}
  7007. @end group
  7008. @end smallexample
  7009. @noindent
  7010. (Recall, @samp{c} is a ``unit'' corresponding to the speed of light.)
  7011. @smallexample
  7012. @group
  7013. 1: 3.3356 ns 1: 0.81356 ns / ns 1: 0.81356
  7014. 2: 4.1 ns . .
  7015. .
  7016. ' 4.1 ns @key{RET} / u s
  7017. @end group
  7018. @end smallexample
  7019. @noindent
  7020. Thus a signal could take up to 81 percent of a clock cycle just to
  7021. go from one place to another inside the computer, assuming the signal
  7022. could actually attain the full speed of light. Pretty tight!
  7023. @node Types Answer 15, Algebra Answer 1, Types Answer 14, Answers to Exercises
  7024. @subsection Types Tutorial Exercise 15
  7025. @noindent
  7026. The speed limit is 55 miles per hour on most highways. We want to
  7027. find the ratio of Sam's speed to the US speed limit.
  7028. @smallexample
  7029. @group
  7030. 1: 55 mph 2: 55 mph 3: 11 hr mph / yd
  7031. . 1: 5 yd / hr .
  7032. .
  7033. ' 55 mph @key{RET} ' 5 yd/hr @key{RET} /
  7034. @end group
  7035. @end smallexample
  7036. The @kbd{u s} command cancels out these units to get a plain
  7037. number. Now we take the logarithm base two to find the final
  7038. answer, assuming that each successive pill doubles his speed.
  7039. @smallexample
  7040. @group
  7041. 1: 19360. 2: 19360. 1: 14.24
  7042. . 1: 2 .
  7043. .
  7044. u s 2 B
  7045. @end group
  7046. @end smallexample
  7047. @noindent
  7048. Thus Sam can take up to 14 pills without a worry.
  7049. @node Algebra Answer 1, Algebra Answer 2, Types Answer 15, Answers to Exercises
  7050. @subsection Algebra Tutorial Exercise 1
  7051. @noindent
  7052. @c [fix-ref Declarations]
  7053. The result @samp{sqrt(x)^2} is simplified back to @cite{x} by the
  7054. Calculator, but @samp{sqrt(x^2)} is not. (Consider what happens
  7055. if @w{@cite{x = -4}}.) If @cite{x} is real, this formula could be
  7056. simplified to @samp{abs(x)}, but for general complex arguments even
  7057. that is not safe. (@xref{Declarations}, for a way to tell Calc
  7058. that @cite{x} is known to be real.)
  7059. @node Algebra Answer 2, Algebra Answer 3, Algebra Answer 1, Answers to Exercises
  7060. @subsection Algebra Tutorial Exercise 2
  7061. @noindent
  7062. Suppose our roots are @cite{[a, b, c]}. We want a polynomial which
  7063. is zero when @cite{x} is any of these values. The trivial polynomial
  7064. @cite{x-a} is zero when @cite{x=a}, so the product @cite{(x-a)(x-b)(x-c)}
  7065. will do the job. We can use @kbd{a c x} to write this in a more
  7066. familiar form.
  7067. @smallexample
  7068. @group
  7069. 1: 34 x - 24 x^3 1: [1.19023, -1.19023, 0]
  7070. . .
  7071. r 2 a P x @key{RET}
  7072. @end group
  7073. @end smallexample
  7074. @noindent
  7075. @smallexample
  7076. @group
  7077. 1: [x - 1.19023, x + 1.19023, x] 1: (x - 1.19023) (x + 1.19023) x
  7078. . .
  7079. V M ' x-$ @key{RET} V R *
  7080. @end group
  7081. @end smallexample
  7082. @noindent
  7083. @smallexample
  7084. @group
  7085. 1: x^3 - 1.41666 x 1: 34 x - 24 x^3
  7086. . .
  7087. a c x @key{RET} 24 n * a x
  7088. @end group
  7089. @end smallexample
  7090. @noindent
  7091. Sure enough, our answer (multiplied by a suitable constant) is the
  7092. same as the original polynomial.
  7093. @node Algebra Answer 3, Algebra Answer 4, Algebra Answer 2, Answers to Exercises
  7094. @subsection Algebra Tutorial Exercise 3
  7095. @smallexample
  7096. @group
  7097. 1: x sin(pi x) 1: (sin(pi x) - pi x cos(pi x)) / pi^2
  7098. . .
  7099. ' x sin(pi x) @key{RET} m r a i x @key{RET}
  7100. @end group
  7101. @end smallexample
  7102. @noindent
  7103. @smallexample
  7104. @group
  7105. 1: [y, 1]
  7106. 2: (sin(pi x) - pi x cos(pi x)) / pi^2
  7107. .
  7108. ' [y,1] @key{RET} @key{TAB}
  7109. @end group
  7110. @end smallexample
  7111. @noindent
  7112. @smallexample
  7113. @group
  7114. 1: [(sin(pi y) - pi y cos(pi y)) / pi^2, (sin(pi) - pi cos(pi)) / pi^2]
  7115. .
  7116. V M $ @key{RET}
  7117. @end group
  7118. @end smallexample
  7119. @noindent
  7120. @smallexample
  7121. @group
  7122. 1: (sin(pi y) - pi y cos(pi y)) / pi^2 + (pi cos(pi) - sin(pi)) / pi^2
  7123. .
  7124. V R -
  7125. @end group
  7126. @end smallexample
  7127. @noindent
  7128. @smallexample
  7129. @group
  7130. 1: (sin(3.14159 y) - 3.14159 y cos(3.14159 y)) / 9.8696 - 0.3183
  7131. .
  7132. =
  7133. @end group
  7134. @end smallexample
  7135. @noindent
  7136. @smallexample
  7137. @group
  7138. 1: [0., -0.95493, 0.63662, -1.5915, 1.2732]
  7139. .
  7140. v x 5 @key{RET} @key{TAB} V M $ @key{RET}
  7141. @end group
  7142. @end smallexample
  7143. @node Algebra Answer 4, Rewrites Answer 1, Algebra Answer 3, Answers to Exercises
  7144. @subsection Algebra Tutorial Exercise 4
  7145. @noindent
  7146. The hard part is that @kbd{V R +} is no longer sufficient to add up all
  7147. the contributions from the slices, since the slices have varying
  7148. coefficients. So first we must come up with a vector of these
  7149. coefficients. Here's one way:
  7150. @smallexample
  7151. @group
  7152. 2: -1 2: 3 1: [4, 2, ..., 4]
  7153. 1: [1, 2, ..., 9] 1: [-1, 1, ..., -1] .
  7154. . .
  7155. 1 n v x 9 @key{RET} V M ^ 3 @key{TAB} -
  7156. @end group
  7157. @end smallexample
  7158. @noindent
  7159. @smallexample
  7160. @group
  7161. 1: [4, 2, ..., 4, 1] 1: [1, 4, 2, ..., 4, 1]
  7162. . .
  7163. 1 | 1 @key{TAB} |
  7164. @end group
  7165. @end smallexample
  7166. @noindent
  7167. Now we compute the function values. Note that for this method we need
  7168. eleven values, including both endpoints of the desired interval.
  7169. @smallexample
  7170. @group
  7171. 2: [1, 4, 2, ..., 4, 1]
  7172. 1: [1, 1.1, 1.2, ... , 1.8, 1.9, 2.]
  7173. .
  7174. 11 @key{RET} 1 @key{RET} .1 @key{RET} C-u v x
  7175. @end group
  7176. @end smallexample
  7177. @noindent
  7178. @smallexample
  7179. @group
  7180. 2: [1, 4, 2, ..., 4, 1]
  7181. 1: [0., 0.084941, 0.16993, ... ]
  7182. .
  7183. ' sin(x) ln(x) @key{RET} m r p 5 @key{RET} V M $ @key{RET}
  7184. @end group
  7185. @end smallexample
  7186. @noindent
  7187. Once again this calls for @kbd{V M * V R +}; a simple @kbd{*} does the
  7188. same thing.
  7189. @smallexample
  7190. @group
  7191. 1: 11.22 1: 1.122 1: 0.374
  7192. . . .
  7193. * .1 * 3 /
  7194. @end group
  7195. @end smallexample
  7196. @noindent
  7197. Wow! That's even better than the result from the Taylor series method.
  7198. @node Rewrites Answer 1, Rewrites Answer 2, Algebra Answer 4, Answers to Exercises
  7199. @subsection Rewrites Tutorial Exercise 1
  7200. @noindent
  7201. We'll use Big mode to make the formulas more readable.
  7202. @smallexample
  7203. @group
  7204. ___
  7205. 2 + V 2
  7206. 1: (2 + sqrt(2)) / (1 + sqrt(2)) 1: --------
  7207. . ___
  7208. 1 + V 2
  7209. .
  7210. ' (2+sqrt(2)) / (1+sqrt(2)) @key{RET} d B
  7211. @end group
  7212. @end smallexample
  7213. @noindent
  7214. Multiplying by the conjugate helps because @cite{(a+b) (a-b) = a^2 - b^2}.
  7215. @smallexample
  7216. @group
  7217. ___ ___
  7218. 1: (2 + V 2 ) (V 2 - 1)
  7219. .
  7220. a r a/(b+c) := a*(b-c) / (b^2-c^2) @key{RET}
  7221. @end group
  7222. @end smallexample
  7223. @noindent
  7224. @smallexample
  7225. @group
  7226. ___ ___
  7227. 1: 2 + V 2 - 2 1: V 2
  7228. . .
  7229. a r a*(b+c) := a*b + a*c a s
  7230. @end group
  7231. @end smallexample
  7232. @noindent
  7233. (We could have used @kbd{a x} instead of a rewrite rule for the
  7234. second step.)
  7235. The multiply-by-conjugate rule turns out to be useful in many
  7236. different circumstances, such as when the denominator involves
  7237. sines and cosines or the imaginary constant @code{i}.
  7238. @node Rewrites Answer 2, Rewrites Answer 3, Rewrites Answer 1, Answers to Exercises
  7239. @subsection Rewrites Tutorial Exercise 2
  7240. @noindent
  7241. Here is the rule set:
  7242. @smallexample
  7243. @group
  7244. [ fib(n) := fib(n, 1, 1) :: integer(n) :: n >= 1,
  7245. fib(1, x, y) := x,
  7246. fib(n, x, y) := fib(n-1, y, x+y) ]
  7247. @end group
  7248. @end smallexample
  7249. @noindent
  7250. The first rule turns a one-argument @code{fib} that people like to write
  7251. into a three-argument @code{fib} that makes computation easier. The
  7252. second rule converts back from three-argument form once the computation
  7253. is done. The third rule does the computation itself. It basically
  7254. says that if @cite{x} and @cite{y} are two consecutive Fibonacci numbers,
  7255. then @cite{y} and @cite{x+y} are the next (overlapping) pair of Fibonacci
  7256. numbers.
  7257. Notice that because the number @cite{n} was ``validated'' by the
  7258. conditions on the first rule, there is no need to put conditions on
  7259. the other rules because the rule set would never get that far unless
  7260. the input were valid. That further speeds computation, since no
  7261. extra conditions need to be checked at every step.
  7262. Actually, a user with a nasty sense of humor could enter a bad
  7263. three-argument @code{fib} call directly, say, @samp{fib(0, 1, 1)},
  7264. which would get the rules into an infinite loop. One thing that would
  7265. help keep this from happening by accident would be to use something like
  7266. @samp{ZzFib} instead of @code{fib} as the name of the three-argument
  7267. function.
  7268. @node Rewrites Answer 3, Rewrites Answer 4, Rewrites Answer 2, Answers to Exercises
  7269. @subsection Rewrites Tutorial Exercise 3
  7270. @noindent
  7271. He got an infinite loop. First, Calc did as expected and rewrote
  7272. @w{@samp{2 + 3 x}} to @samp{f(2, 3, x)}. Then it looked for ways to
  7273. apply the rule again, and found that @samp{f(2, 3, x)} looks like
  7274. @samp{a + b x} with @w{@samp{a = 0}} and @samp{b = 1}, so it rewrote to
  7275. @samp{f(0, 1, f(2, 3, x))}. It then wrapped another @samp{f(0, 1, ...)}
  7276. around that, and so on, ad infinitum. Joe should have used @kbd{M-1 a r}
  7277. to make sure the rule applied only once.
  7278. (Actually, even the first step didn't work as he expected. What Calc
  7279. really gives for @kbd{M-1 a r} in this situation is @samp{f(3 x, 1, 2)},
  7280. treating 2 as the ``variable,'' and @samp{3 x} as a constant being added
  7281. to it. While this may seem odd, it's just as valid a solution as the
  7282. ``obvious'' one. One way to fix this would be to add the condition
  7283. @samp{:: variable(x)} to the rule, to make sure the thing that matches
  7284. @samp{x} is indeed a variable, or to change @samp{x} to @samp{quote(x)}
  7285. on the lefthand side, so that the rule matches the actual variable
  7286. @samp{x} rather than letting @samp{x} stand for something else.)
  7287. @node Rewrites Answer 4, Rewrites Answer 5, Rewrites Answer 3, Answers to Exercises
  7288. @subsection Rewrites Tutorial Exercise 4
  7289. @noindent
  7290. @ignore
  7291. @starindex
  7292. @end ignore
  7293. @tindex seq
  7294. Here is a suitable set of rules to solve the first part of the problem:
  7295. @smallexample
  7296. @group
  7297. [ seq(n, c) := seq(n/2, c+1) :: n%2 = 0,
  7298. seq(n, c) := seq(3n+1, c+1) :: n%2 = 1 :: n > 1 ]
  7299. @end group
  7300. @end smallexample
  7301. Given the initial formula @samp{seq(6, 0)}, application of these
  7302. rules produces the following sequence of formulas:
  7303. @example
  7304. seq( 3, 1)
  7305. seq(10, 2)
  7306. seq( 5, 3)
  7307. seq(16, 4)
  7308. seq( 8, 5)
  7309. seq( 4, 6)
  7310. seq( 2, 7)
  7311. seq( 1, 8)
  7312. @end example
  7313. @noindent
  7314. whereupon neither of the rules match, and rewriting stops.
  7315. We can pretty this up a bit with a couple more rules:
  7316. @smallexample
  7317. @group
  7318. [ seq(n) := seq(n, 0),
  7319. seq(1, c) := c,
  7320. ... ]
  7321. @end group
  7322. @end smallexample
  7323. @noindent
  7324. Now, given @samp{seq(6)} as the starting configuration, we get 8
  7325. as the result.
  7326. The change to return a vector is quite simple:
  7327. @smallexample
  7328. @group
  7329. [ seq(n) := seq(n, []) :: integer(n) :: n > 0,
  7330. seq(1, v) := v | 1,
  7331. seq(n, v) := seq(n/2, v | n) :: n%2 = 0,
  7332. seq(n, v) := seq(3n+1, v | n) :: n%2 = 1 ]
  7333. @end group
  7334. @end smallexample
  7335. @noindent
  7336. Given @samp{seq(6)}, the result is @samp{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
  7337. Notice that the @cite{n > 1} guard is no longer necessary on the last
  7338. rule since the @cite{n = 1} case is now detected by another rule.
  7339. But a guard has been added to the initial rule to make sure the
  7340. initial value is suitable before the computation begins.
  7341. While still a good idea, this guard is not as vitally important as it
  7342. was for the @code{fib} function, since calling, say, @samp{seq(x, [])}
  7343. will not get into an infinite loop. Calc will not be able to prove
  7344. the symbol @samp{x} is either even or odd, so none of the rules will
  7345. apply and the rewrites will stop right away.
  7346. @node Rewrites Answer 5, Rewrites Answer 6, Rewrites Answer 4, Answers to Exercises
  7347. @subsection Rewrites Tutorial Exercise 5
  7348. @noindent
  7349. @ignore
  7350. @starindex
  7351. @end ignore
  7352. @tindex nterms
  7353. If @cite{x} is the sum @cite{a + b}, then `@t{nterms(}@var{x}@t{)}' must
  7354. be `@t{nterms(}@var{a}@t{)}' plus `@t{nterms(}@var{b}@t{)}'. If @cite{x}
  7355. is not a sum, then `@t{nterms(}@var{x}@t{)}' = 1.
  7356. @smallexample
  7357. @group
  7358. [ nterms(a + b) := nterms(a) + nterms(b),
  7359. nterms(x) := 1 ]
  7360. @end group
  7361. @end smallexample
  7362. @noindent
  7363. Here we have taken advantage of the fact that earlier rules always
  7364. match before later rules; @samp{nterms(x)} will only be tried if we
  7365. already know that @samp{x} is not a sum.
  7366. @node Rewrites Answer 6, Rewrites Answer 7, Rewrites Answer 5, Answers to Exercises
  7367. @subsection Rewrites Tutorial Exercise 6
  7368. Just put the rule @samp{0^0 := 1} into @code{EvalRules}. For example,
  7369. before making this definition we have:
  7370. @smallexample
  7371. @group
  7372. 2: [-2, -1, 0, 1, 2] 1: [1, 1, 0^0, 1, 1]
  7373. 1: 0 .
  7374. .
  7375. v x 5 @key{RET} 3 - 0 V M ^
  7376. @end group
  7377. @end smallexample
  7378. @noindent
  7379. But then:
  7380. @smallexample
  7381. @group
  7382. 2: [-2, -1, 0, 1, 2] 1: [1, 1, 1, 1, 1]
  7383. 1: 0 .
  7384. .
  7385. U ' 0^0:=1 @key{RET} s t EvalRules @key{RET} V M ^
  7386. @end group
  7387. @end smallexample
  7388. Perhaps more surprisingly, this rule still works with infinite mode
  7389. turned on. Calc tries @code{EvalRules} before any built-in rules for
  7390. a function. This allows you to override the default behavior of any
  7391. Calc feature: Even though Calc now wants to evaluate @cite{0^0} to
  7392. @code{nan}, your rule gets there first and evaluates it to 1 instead.
  7393. Just for kicks, try adding the rule @code{2+3 := 6} to @code{EvalRules}.
  7394. What happens? (Be sure to remove this rule afterward, or you might get
  7395. a nasty surprise when you use Calc to balance your checkbook!)
  7396. @node Rewrites Answer 7, Programming Answer 1, Rewrites Answer 6, Answers to Exercises
  7397. @subsection Rewrites Tutorial Exercise 7
  7398. @noindent
  7399. Here is a rule set that will do the job:
  7400. @smallexample
  7401. @group
  7402. [ a*(b + c) := a*b + a*c,
  7403. opt(a) O(x^n) + opt(b) O(x^m) := O(x^n) :: n <= m
  7404. :: constant(a) :: constant(b),
  7405. opt(a) O(x^n) + opt(b) x^m := O(x^n) :: n <= m
  7406. :: constant(a) :: constant(b),
  7407. a O(x^n) := O(x^n) :: constant(a),
  7408. x^opt(m) O(x^n) := O(x^(n+m)),
  7409. O(x^n) O(x^m) := O(x^(n+m)) ]
  7410. @end group
  7411. @end smallexample
  7412. If we really want the @kbd{+} and @kbd{*} keys to operate naturally
  7413. on power series, we should put these rules in @code{EvalRules}. For
  7414. testing purposes, it is better to put them in a different variable,
  7415. say, @code{O}, first.
  7416. The first rule just expands products of sums so that the rest of the
  7417. rules can assume they have an expanded-out polynomial to work with.
  7418. Note that this rule does not mention @samp{O} at all, so it will
  7419. apply to any product-of-sum it encounters---this rule may surprise
  7420. you if you put it into @code{EvalRules}!
  7421. In the second rule, the sum of two O's is changed to the smaller O.
  7422. The optional constant coefficients are there mostly so that
  7423. @samp{O(x^2) - O(x^3)} and @samp{O(x^3) - O(x^2)} are handled
  7424. as well as @samp{O(x^2) + O(x^3)}.
  7425. The third rule absorbs higher powers of @samp{x} into O's.
  7426. The fourth rule says that a constant times a negligible quantity
  7427. is still negligible. (This rule will also match @samp{O(x^3) / 4},
  7428. with @samp{a = 1/4}.)
  7429. The fifth rule rewrites, for example, @samp{x^2 O(x^3)} to @samp{O(x^5)}.
  7430. (It is easy to see that if one of these forms is negligible, the other
  7431. is, too.) Notice the @samp{x^opt(m)} to pick up terms like
  7432. @w{@samp{x O(x^3)}}. Optional powers will match @samp{x} as @samp{x^1}
  7433. but not 1 as @samp{x^0}. This turns out to be exactly what we want here.
  7434. The sixth rule is the corresponding rule for products of two O's.
  7435. Another way to solve this problem would be to create a new ``data type''
  7436. that represents truncated power series. We might represent these as
  7437. function calls @samp{series(@var{coefs}, @var{x})} where @var{coefs} is
  7438. a vector of coefficients for @cite{x^0}, @cite{x^1}, @cite{x^2}, and so
  7439. on. Rules would exist for sums and products of such @code{series}
  7440. objects, and as an optional convenience could also know how to combine a
  7441. @code{series} object with a normal polynomial. (With this, and with a
  7442. rule that rewrites @samp{O(x^n)} to the equivalent @code{series} form,
  7443. you could still enter power series in exactly the same notation as
  7444. before.) Operations on such objects would probably be more efficient,
  7445. although the objects would be a bit harder to read.
  7446. @c [fix-ref Compositions]
  7447. Some other symbolic math programs provide a power series data type
  7448. similar to this. Mathematica, for example, has an object that looks
  7449. like @samp{PowerSeries[@var{x}, @var{x0}, @var{coefs}, @var{nmin},
  7450. @var{nmax}, @var{den}]}, where @var{x0} is the point about which the
  7451. power series is taken (we've been assuming this was always zero),
  7452. and @var{nmin}, @var{nmax}, and @var{den} allow pseudo-power-series
  7453. with fractional or negative powers. Also, the @code{PowerSeries}
  7454. objects have a special display format that makes them look like
  7455. @samp{2 x^2 + O(x^4)} when they are printed out. (@xref{Compositions},
  7456. for a way to do this in Calc, although for something as involved as
  7457. this it would probably be better to write the formatting routine
  7458. in Lisp.)
  7459. @node Programming Answer 1, Programming Answer 2, Rewrites Answer 7, Answers to Exercises
  7460. @subsection Programming Tutorial Exercise 1
  7461. @noindent
  7462. Just enter the formula @samp{ninteg(sin(t)/t, t, 0, x)}, type
  7463. @kbd{Z F}, and answer the questions. Since this formula contains two
  7464. variables, the default argument list will be @samp{(t x)}. We want to
  7465. change this to @samp{(x)} since @cite{t} is really a dummy variable
  7466. to be used within @code{ninteg}.
  7467. The exact keystrokes are @kbd{Z F s Si @key{RET} @key{RET} C-b C-b @key{DEL} @key{DEL} @key{RET} y}.
  7468. (The @kbd{C-b C-b @key{DEL} @key{DEL}} are what fix the argument list.)
  7469. @node Programming Answer 2, Programming Answer 3, Programming Answer 1, Answers to Exercises
  7470. @subsection Programming Tutorial Exercise 2
  7471. @noindent
  7472. One way is to move the number to the top of the stack, operate on
  7473. it, then move it back: @kbd{C-x ( M-@key{TAB} n M-@key{TAB} M-@key{TAB} C-x )}.
  7474. Another way is to negate the top three stack entries, then negate
  7475. again the top two stack entries: @kbd{C-x ( M-3 n M-2 n C-x )}.
  7476. Finally, it turns out that a negative prefix argument causes a
  7477. command like @kbd{n} to operate on the specified stack entry only,
  7478. which is just what we want: @kbd{C-x ( M-- 3 n C-x )}.
  7479. Just for kicks, let's also do it algebraically:
  7480. @w{@kbd{C-x ( ' -$$$, $$, $ @key{RET} C-x )}}.
  7481. @node Programming Answer 3, Programming Answer 4, Programming Answer 2, Answers to Exercises
  7482. @subsection Programming Tutorial Exercise 3
  7483. @noindent
  7484. Each of these functions can be computed using the stack, or using
  7485. algebraic entry, whichever way you prefer:
  7486. @noindent
  7487. Computing @c{$\displaystyle{\sin x \over x}$}
  7488. @cite{sin(x) / x}:
  7489. Using the stack: @kbd{C-x ( @key{RET} S @key{TAB} / C-x )}.
  7490. Using algebraic entry: @kbd{C-x ( ' sin($)/$ @key{RET} C-x )}.
  7491. @noindent
  7492. Computing the logarithm:
  7493. Using the stack: @kbd{C-x ( @key{TAB} B C-x )}
  7494. Using algebraic entry: @kbd{C-x ( ' log($,$$) @key{RET} C-x )}.
  7495. @noindent
  7496. Computing the vector of integers:
  7497. Using the stack: @kbd{C-x ( 1 @key{RET} 1 C-u v x C-x )}. (Recall that
  7498. @kbd{C-u v x} takes the vector size, starting value, and increment
  7499. from the stack.)
  7500. Alternatively: @kbd{C-x ( ~ v x C-x )}. (The @kbd{~} key pops a
  7501. number from the stack and uses it as the prefix argument for the
  7502. next command.)
  7503. Using algebraic entry: @kbd{C-x ( ' index($) @key{RET} C-x )}.
  7504. @node Programming Answer 4, Programming Answer 5, Programming Answer 3, Answers to Exercises
  7505. @subsection Programming Tutorial Exercise 4
  7506. @noindent
  7507. Here's one way: @kbd{C-x ( @key{RET} V R + @key{TAB} v l / C-x )}.
  7508. @node Programming Answer 5, Programming Answer 6, Programming Answer 4, Answers to Exercises
  7509. @subsection Programming Tutorial Exercise 5
  7510. @smallexample
  7511. @group
  7512. 2: 1 1: 1.61803398502 2: 1.61803398502
  7513. 1: 20 . 1: 1.61803398875
  7514. . .
  7515. 1 @key{RET} 20 Z < & 1 + Z > I H P
  7516. @end group
  7517. @end smallexample
  7518. @noindent
  7519. This answer is quite accurate.
  7520. @node Programming Answer 6, Programming Answer 7, Programming Answer 5, Answers to Exercises
  7521. @subsection Programming Tutorial Exercise 6
  7522. @noindent
  7523. Here is the matrix:
  7524. @example
  7525. [ [ 0, 1 ] * [a, b] = [b, a + b]
  7526. [ 1, 1 ] ]
  7527. @end example
  7528. @noindent
  7529. Thus @samp{[0, 1; 1, 1]^n * [1, 1]} computes Fibonacci numbers @cite{n+1}
  7530. and @cite{n+2}. Here's one program that does the job:
  7531. @example
  7532. C-x ( ' [0, 1; 1, 1] ^ ($-1) * [1, 1] @key{RET} v u @key{DEL} C-x )
  7533. @end example
  7534. @noindent
  7535. This program is quite efficient because Calc knows how to raise a
  7536. matrix (or other value) to the power @cite{n} in only @c{$\log_2 n$}
  7537. @cite{log(n,2)}
  7538. steps. For example, this program can compute the 1000th Fibonacci
  7539. number (a 209-digit integer!) in about 10 steps; even though the
  7540. @kbd{Z < ... Z >} solution had much simpler steps, it would have
  7541. required so many steps that it would not have been practical.
  7542. @node Programming Answer 7, Programming Answer 8, Programming Answer 6, Answers to Exercises
  7543. @subsection Programming Tutorial Exercise 7
  7544. @noindent
  7545. The trick here is to compute the harmonic numbers differently, so that
  7546. the loop counter itself accumulates the sum of reciprocals. We use
  7547. a separate variable to hold the integer counter.
  7548. @smallexample
  7549. @group
  7550. 1: 1 2: 1 1: .
  7551. . 1: 4
  7552. .
  7553. 1 t 1 1 @key{RET} 4 Z ( t 2 r 1 1 + s 1 & Z )
  7554. @end group
  7555. @end smallexample
  7556. @noindent
  7557. The body of the loop goes as follows: First save the harmonic sum
  7558. so far in variable 2. Then delete it from the stack; the for loop
  7559. itself will take care of remembering it for us. Next, recall the
  7560. count from variable 1, add one to it, and feed its reciprocal to
  7561. the for loop to use as the step value. The for loop will increase
  7562. the ``loop counter'' by that amount and keep going until the
  7563. loop counter exceeds 4.
  7564. @smallexample
  7565. @group
  7566. 2: 31 3: 31
  7567. 1: 3.99498713092 2: 3.99498713092
  7568. . 1: 4.02724519544
  7569. .
  7570. r 1 r 2 @key{RET} 31 & +
  7571. @end group
  7572. @end smallexample
  7573. Thus we find that the 30th harmonic number is 3.99, and the 31st
  7574. harmonic number is 4.02.
  7575. @node Programming Answer 8, Programming Answer 9, Programming Answer 7, Answers to Exercises
  7576. @subsection Programming Tutorial Exercise 8
  7577. @noindent
  7578. The first step is to compute the derivative @cite{f'(x)} and thus
  7579. the formula @c{$\displaystyle{x - {f(x) \over f'(x)}}$}
  7580. @cite{x - f(x)/f'(x)}.
  7581. (Because this definition is long, it will be repeated in concise form
  7582. below. You can use @w{@kbd{M-# m}} to load it from there. While you are
  7583. entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
  7584. keystrokes without executing them. In the following diagrams we'll
  7585. pretend Calc actually executed the keystrokes as you typed them,
  7586. just for purposes of illustration.)
  7587. @smallexample
  7588. @group
  7589. 2: sin(cos(x)) - 0.5 3: 4.5
  7590. 1: 4.5 2: sin(cos(x)) - 0.5
  7591. . 1: -(sin(x) cos(cos(x)))
  7592. .
  7593. ' sin(cos(x))-0.5 @key{RET} 4.5 m r C-x ( Z ` @key{TAB} @key{RET} a d x @key{RET}
  7594. @end group
  7595. @end smallexample
  7596. @noindent
  7597. @smallexample
  7598. @group
  7599. 2: 4.5
  7600. 1: x + (sin(cos(x)) - 0.5) / sin(x) cos(cos(x))
  7601. .
  7602. / ' x @key{RET} @key{TAB} - t 1
  7603. @end group
  7604. @end smallexample
  7605. Now, we enter the loop. We'll use a repeat loop with a 20-repetition
  7606. limit just in case the method fails to converge for some reason.
  7607. (Normally, the @w{@kbd{Z /}} command will stop the loop before all 20
  7608. repetitions are done.)
  7609. @smallexample
  7610. @group
  7611. 1: 4.5 3: 4.5 2: 4.5
  7612. . 2: x + (sin(cos(x)) ... 1: 5.24196456928
  7613. 1: 4.5 .
  7614. .
  7615. 20 Z < @key{RET} r 1 @key{TAB} s l x @key{RET}
  7616. @end group
  7617. @end smallexample
  7618. This is the new guess for @cite{x}. Now we compare it with the
  7619. old one to see if we've converged.
  7620. @smallexample
  7621. @group
  7622. 3: 5.24196 2: 5.24196 1: 5.24196 1: 5.26345856348
  7623. 2: 5.24196 1: 0 . .
  7624. 1: 4.5 .
  7625. .
  7626. @key{RET} M-@key{TAB} a = Z / Z > Z ' C-x )
  7627. @end group
  7628. @end smallexample
  7629. The loop converges in just a few steps to this value. To check
  7630. the result, we can simply substitute it back into the equation.
  7631. @smallexample
  7632. @group
  7633. 2: 5.26345856348
  7634. 1: 0.499999999997
  7635. .
  7636. @key{RET} ' sin(cos($)) @key{RET}
  7637. @end group
  7638. @end smallexample
  7639. Let's test the new definition again:
  7640. @smallexample
  7641. @group
  7642. 2: x^2 - 9 1: 3.
  7643. 1: 1 .
  7644. .
  7645. ' x^2-9 @key{RET} 1 X
  7646. @end group
  7647. @end smallexample
  7648. Once again, here's the full Newton's Method definition:
  7649. @example
  7650. @group
  7651. C-x ( Z ` @key{TAB} @key{RET} a d x @key{RET} / ' x @key{RET} @key{TAB} - t 1
  7652. 20 Z < @key{RET} r 1 @key{TAB} s l x @key{RET}
  7653. @key{RET} M-@key{TAB} a = Z /
  7654. Z >
  7655. Z '
  7656. C-x )
  7657. @end group
  7658. @end example
  7659. @c [fix-ref Nesting and Fixed Points]
  7660. It turns out that Calc has a built-in command for applying a formula
  7661. repeatedly until it converges to a number. @xref{Nesting and Fixed Points},
  7662. to see how to use it.
  7663. @c [fix-ref Root Finding]
  7664. Also, of course, @kbd{a R} is a built-in command that uses Newton's
  7665. method (among others) to look for numerical solutions to any equation.
  7666. @xref{Root Finding}.
  7667. @node Programming Answer 9, Programming Answer 10, Programming Answer 8, Answers to Exercises
  7668. @subsection Programming Tutorial Exercise 9
  7669. @noindent
  7670. The first step is to adjust @cite{z} to be greater than 5. A simple
  7671. ``for'' loop will do the job here. If @cite{z} is less than 5, we
  7672. reduce the problem using @c{$\psi(z) = \psi(z+1) - 1/z$}
  7673. @cite{psi(z) = psi(z+1) - 1/z}. We go
  7674. on to compute @c{$\psi(z+1)$}
  7675. @cite{psi(z+1)}, and remember to add back a factor of
  7676. @cite{-1/z} when we're done. This step is repeated until @cite{z > 5}.
  7677. (Because this definition is long, it will be repeated in concise form
  7678. below. You can use @w{@kbd{M-# m}} to load it from there. While you are
  7679. entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
  7680. keystrokes without executing them. In the following diagrams we'll
  7681. pretend Calc actually executed the keystrokes as you typed them,
  7682. just for purposes of illustration.)
  7683. @smallexample
  7684. @group
  7685. 1: 1. 1: 1.
  7686. . .
  7687. 1.0 @key{RET} C-x ( Z ` s 1 0 t 2
  7688. @end group
  7689. @end smallexample
  7690. Here, variable 1 holds @cite{z} and variable 2 holds the adjustment
  7691. factor. If @cite{z < 5}, we use a loop to increase it.
  7692. (By the way, we started with @samp{1.0} instead of the integer 1 because
  7693. otherwise the calculation below will try to do exact fractional arithmetic,
  7694. and will never converge because fractions compare equal only if they
  7695. are exactly equal, not just equal to within the current precision.)
  7696. @smallexample
  7697. @group
  7698. 3: 1. 2: 1. 1: 6.
  7699. 2: 1. 1: 1 .
  7700. 1: 5 .
  7701. .
  7702. @key{RET} 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
  7703. @end group
  7704. @end smallexample
  7705. Now we compute the initial part of the sum: @c{$\ln z - {1 \over 2z}$}
  7706. @cite{ln(z) - 1/2z}
  7707. minus the adjustment factor.
  7708. @smallexample
  7709. @group
  7710. 2: 1.79175946923 2: 1.7084261359 1: -0.57490719743
  7711. 1: 0.0833333333333 1: 2.28333333333 .
  7712. . .
  7713. L r 1 2 * & - r 2 -
  7714. @end group
  7715. @end smallexample
  7716. Now we evaluate the series. We'll use another ``for'' loop counting
  7717. up the value of @cite{2 n}. (Calc does have a summation command,
  7718. @kbd{a +}, but we'll use loops just to get more practice with them.)
  7719. @smallexample
  7720. @group
  7721. 3: -0.5749 3: -0.5749 4: -0.5749 2: -0.5749
  7722. 2: 2 2: 1:6 3: 1:6 1: 2.3148e-3
  7723. 1: 40 1: 2 2: 2 .
  7724. . . 1: 36.
  7725. .
  7726. 2 @key{RET} 40 Z ( @key{RET} k b @key{TAB} @key{RET} r 1 @key{TAB} ^ * /
  7727. @end group
  7728. @end smallexample
  7729. @noindent
  7730. @smallexample
  7731. @group
  7732. 3: -0.5749 3: -0.5772 2: -0.5772 1: -0.577215664892
  7733. 2: -0.5749 2: -0.5772 1: 0 .
  7734. 1: 2.3148e-3 1: -0.5749 .
  7735. . .
  7736. @key{TAB} @key{RET} M-@key{TAB} - @key{RET} M-@key{TAB} a = Z / 2 Z ) Z ' C-x )
  7737. @end group
  7738. @end smallexample
  7739. This is the value of @c{$-\gamma$}
  7740. @cite{- gamma}, with a slight bit of roundoff error.
  7741. To get a full 12 digits, let's use a higher precision:
  7742. @smallexample
  7743. @group
  7744. 2: -0.577215664892 2: -0.577215664892
  7745. 1: 1. 1: -0.577215664901532
  7746. 1. @key{RET} p 16 @key{RET} X
  7747. @end group
  7748. @end smallexample
  7749. Here's the complete sequence of keystrokes:
  7750. @example
  7751. @group
  7752. C-x ( Z ` s 1 0 t 2
  7753. @key{RET} 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
  7754. L r 1 2 * & - r 2 -
  7755. 2 @key{RET} 40 Z ( @key{RET} k b @key{TAB} @key{RET} r 1 @key{TAB} ^ * /
  7756. @key{TAB} @key{RET} M-@key{TAB} - @key{RET} M-@key{TAB} a = Z /
  7757. 2 Z )
  7758. Z '
  7759. C-x )
  7760. @end group
  7761. @end example
  7762. @node Programming Answer 10, Programming Answer 11, Programming Answer 9, Answers to Exercises
  7763. @subsection Programming Tutorial Exercise 10
  7764. @noindent
  7765. Taking the derivative of a term of the form @cite{x^n} will produce
  7766. a term like @c{$n x^{n-1}$}
  7767. @cite{n x^(n-1)}. Taking the derivative of a constant
  7768. produces zero. From this it is easy to see that the @cite{n}th
  7769. derivative of a polynomial, evaluated at @cite{x = 0}, will equal the
  7770. coefficient on the @cite{x^n} term times @cite{n!}.
  7771. (Because this definition is long, it will be repeated in concise form
  7772. below. You can use @w{@kbd{M-# m}} to load it from there. While you are
  7773. entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
  7774. keystrokes without executing them. In the following diagrams we'll
  7775. pretend Calc actually executed the keystrokes as you typed them,
  7776. just for purposes of illustration.)
  7777. @smallexample
  7778. @group
  7779. 2: 5 x^4 + (x + 1)^2 3: 5 x^4 + (x + 1)^2
  7780. 1: 6 2: 0
  7781. . 1: 6
  7782. .
  7783. ' 5 x^4 + (x+1)^2 @key{RET} 6 C-x ( Z ` [ ] t 1 0 @key{TAB}
  7784. @end group
  7785. @end smallexample
  7786. @noindent
  7787. Variable 1 will accumulate the vector of coefficients.
  7788. @smallexample
  7789. @group
  7790. 2: 0 3: 0 2: 5 x^4 + ...
  7791. 1: 5 x^4 + ... 2: 5 x^4 + ... 1: 1
  7792. . 1: 1 .
  7793. .
  7794. Z ( @key{TAB} @key{RET} 0 s l x @key{RET} M-@key{TAB} ! / s | 1
  7795. @end group
  7796. @end smallexample
  7797. @noindent
  7798. Note that @kbd{s | 1} appends the top-of-stack value to the vector
  7799. in a variable; it is completely analogous to @kbd{s + 1}. We could
  7800. have written instead, @kbd{r 1 @key{TAB} | t 1}.
  7801. @smallexample
  7802. @group
  7803. 1: 20 x^3 + 2 x + 2 1: 0 1: [1, 2, 1, 0, 5, 0, 0]
  7804. . . .
  7805. a d x @key{RET} 1 Z ) @key{DEL} r 1 Z ' C-x )
  7806. @end group
  7807. @end smallexample
  7808. To convert back, a simple method is just to map the coefficients
  7809. against a table of powers of @cite{x}.
  7810. @smallexample
  7811. @group
  7812. 2: [1, 2, 1, 0, 5, 0, 0] 2: [1, 2, 1, 0, 5, 0, 0]
  7813. 1: 6 1: [0, 1, 2, 3, 4, 5, 6]
  7814. . .
  7815. 6 @key{RET} 1 + 0 @key{RET} 1 C-u v x
  7816. @end group
  7817. @end smallexample
  7818. @noindent
  7819. @smallexample
  7820. @group
  7821. 2: [1, 2, 1, 0, 5, 0, 0] 2: 1 + 2 x + x^2 + 5 x^4
  7822. 1: [1, x, x^2, x^3, ... ] .
  7823. .
  7824. ' x @key{RET} @key{TAB} V M ^ *
  7825. @end group
  7826. @end smallexample
  7827. Once again, here are the whole polynomial to/from vector programs:
  7828. @example
  7829. @group
  7830. C-x ( Z ` [ ] t 1 0 @key{TAB}
  7831. Z ( @key{TAB} @key{RET} 0 s l x @key{RET} M-@key{TAB} ! / s | 1
  7832. a d x @key{RET}
  7833. 1 Z ) r 1
  7834. Z '
  7835. C-x )
  7836. C-x ( 1 + 0 @key{RET} 1 C-u v x ' x @key{RET} @key{TAB} V M ^ * C-x )
  7837. @end group
  7838. @end example
  7839. @node Programming Answer 11, Programming Answer 12, Programming Answer 10, Answers to Exercises
  7840. @subsection Programming Tutorial Exercise 11
  7841. @noindent
  7842. First we define a dummy program to go on the @kbd{z s} key. The true
  7843. @w{@kbd{z s}} key is supposed to take two numbers from the stack and
  7844. return one number, so @key{DEL} as a dummy definition will make
  7845. sure the stack comes out right.
  7846. @smallexample
  7847. @group
  7848. 2: 4 1: 4 2: 4
  7849. 1: 2 . 1: 2
  7850. . .
  7851. 4 @key{RET} 2 C-x ( @key{DEL} C-x ) Z K s @key{RET} 2
  7852. @end group
  7853. @end smallexample
  7854. The last step replaces the 2 that was eaten during the creation
  7855. of the dummy @kbd{z s} command. Now we move on to the real
  7856. definition. The recurrence needs to be rewritten slightly,
  7857. to the form @cite{s(n,m) = s(n-1,m-1) - (n-1) s(n-1,m)}.
  7858. (Because this definition is long, it will be repeated in concise form
  7859. below. You can use @kbd{M-# m} to load it from there.)
  7860. @smallexample
  7861. @group
  7862. 2: 4 4: 4 3: 4 2: 4
  7863. 1: 2 3: 2 2: 2 1: 2
  7864. . 2: 4 1: 0 .
  7865. 1: 2 .
  7866. .
  7867. C-x ( M-2 @key{RET} a = Z [ @key{DEL} @key{DEL} 1 Z :
  7868. @end group
  7869. @end smallexample
  7870. @noindent
  7871. @smallexample
  7872. @group
  7873. 4: 4 2: 4 2: 3 4: 3 4: 3 3: 3
  7874. 3: 2 1: 2 1: 2 3: 2 3: 2 2: 2
  7875. 2: 2 . . 2: 3 2: 3 1: 3
  7876. 1: 0 1: 2 1: 1 .
  7877. . . .
  7878. @key{RET} 0 a = Z [ @key{DEL} @key{DEL} 0 Z : @key{TAB} 1 - @key{TAB} M-2 @key{RET} 1 - z s
  7879. @end group
  7880. @end smallexample
  7881. @noindent
  7882. (Note that the value 3 that our dummy @kbd{z s} produces is not correct;
  7883. it is merely a placeholder that will do just as well for now.)
  7884. @smallexample
  7885. @group
  7886. 3: 3 4: 3 3: 3 2: 3 1: -6
  7887. 2: 3 3: 3 2: 3 1: 9 .
  7888. 1: 2 2: 3 1: 3 .
  7889. . 1: 2 .
  7890. .
  7891. M-@key{TAB} M-@key{TAB} @key{TAB} @key{RET} M-@key{TAB} z s * -
  7892. @end group
  7893. @end smallexample
  7894. @noindent
  7895. @smallexample
  7896. @group
  7897. 1: -6 2: 4 1: 11 2: 11
  7898. . 1: 2 . 1: 11
  7899. . .
  7900. Z ] Z ] C-x ) Z K s @key{RET} @key{DEL} 4 @key{RET} 2 z s M-@key{RET} k s
  7901. @end group
  7902. @end smallexample
  7903. Even though the result that we got during the definition was highly
  7904. bogus, once the definition is complete the @kbd{z s} command gets
  7905. the right answers.
  7906. Here's the full program once again:
  7907. @example
  7908. @group
  7909. C-x ( M-2 @key{RET} a =
  7910. Z [ @key{DEL} @key{DEL} 1
  7911. Z : @key{RET} 0 a =
  7912. Z [ @key{DEL} @key{DEL} 0
  7913. Z : @key{TAB} 1 - @key{TAB} M-2 @key{RET} 1 - z s
  7914. M-@key{TAB} M-@key{TAB} @key{TAB} @key{RET} M-@key{TAB} z s * -
  7915. Z ]
  7916. Z ]
  7917. C-x )
  7918. @end group
  7919. @end example
  7920. You can read this definition using @kbd{M-# m} (@code{read-kbd-macro})
  7921. followed by @kbd{Z K s}, without having to make a dummy definition
  7922. first, because @code{read-kbd-macro} doesn't need to execute the
  7923. definition as it reads it in. For this reason, @code{M-# m} is often
  7924. the easiest way to create recursive programs in Calc.
  7925. @node Programming Answer 12, , Programming Answer 11, Answers to Exercises
  7926. @subsection Programming Tutorial Exercise 12
  7927. @noindent
  7928. This turns out to be a much easier way to solve the problem. Let's
  7929. denote Stirling numbers as calls of the function @samp{s}.
  7930. First, we store the rewrite rules corresponding to the definition of
  7931. Stirling numbers in a convenient variable:
  7932. @smallexample
  7933. s e StirlingRules @key{RET}
  7934. [ s(n,n) := 1 :: n >= 0,
  7935. s(n,0) := 0 :: n > 0,
  7936. s(n,m) := s(n-1,m-1) - (n-1) s(n-1,m) :: n >= m :: m >= 1 ]
  7937. C-c C-c
  7938. @end smallexample
  7939. Now, it's just a matter of applying the rules:
  7940. @smallexample
  7941. @group
  7942. 2: 4 1: s(4, 2) 1: 11
  7943. 1: 2 . .
  7944. .
  7945. 4 @key{RET} 2 C-x ( ' s($$,$) @key{RET} a r StirlingRules @key{RET} C-x )
  7946. @end group
  7947. @end smallexample
  7948. As in the case of the @code{fib} rules, it would be useful to put these
  7949. rules in @code{EvalRules} and to add a @samp{:: remember} condition to
  7950. the last rule.
  7951. @c This ends the table-of-contents kludge from above:
  7952. @tex
  7953. \global\let\chapternofonts=\oldchapternofonts
  7954. @end tex
  7955. @c [reference]
  7956. @node Introduction, Data Types, Tutorial, Top
  7957. @chapter Introduction
  7958. @noindent
  7959. This chapter is the beginning of the Calc reference manual.
  7960. It covers basic concepts such as the stack, algebraic and
  7961. numeric entry, undo, numeric prefix arguments, etc.
  7962. @c [when-split]
  7963. @c (Chapter 2, the Tutorial, has been printed in a separate volume.)
  7964. @menu
  7965. * Basic Commands::
  7966. * Help Commands::
  7967. * Stack Basics::
  7968. * Numeric Entry::
  7969. * Algebraic Entry::
  7970. * Quick Calculator::
  7971. * Keypad Mode::
  7972. * Prefix Arguments::
  7973. * Undo::
  7974. * Error Messages::
  7975. * Multiple Calculators::
  7976. * Troubleshooting Commands::
  7977. @end menu
  7978. @node Basic Commands, Help Commands, Introduction, Introduction
  7979. @section Basic Commands
  7980. @noindent
  7981. @pindex calc
  7982. @pindex calc-mode
  7983. @cindex Starting the Calculator
  7984. @cindex Running the Calculator
  7985. To start the Calculator in its standard interface, type @kbd{M-x calc}.
  7986. By default this creates a pair of small windows, @samp{*Calculator*}
  7987. and @samp{*Calc Trail*}. The former displays the contents of the
  7988. Calculator stack and is manipulated exclusively through Calc commands.
  7989. It is possible (though not usually necessary) to create several Calc
  7990. Mode buffers each of which has an independent stack, undo list, and
  7991. mode settings. There is exactly one Calc Trail buffer; it records a
  7992. list of the results of all calculations that have been done. The
  7993. Calc Trail buffer uses a variant of Calc Mode, so Calculator commands
  7994. still work when the trail buffer's window is selected. It is possible
  7995. to turn the trail window off, but the @samp{*Calc Trail*} buffer itself
  7996. still exists and is updated silently. @xref{Trail Commands}.@refill
  7997. @kindex M-# c
  7998. @kindex M-# M-#
  7999. @ignore
  8000. @mindex @null
  8001. @end ignore
  8002. @kindex M-# #
  8003. In most installations, the @kbd{M-# c} key sequence is a more
  8004. convenient way to start the Calculator. Also, @kbd{M-# M-#} and
  8005. @kbd{M-# #} are synonyms for @kbd{M-# c} unless you last used Calc
  8006. in its ``keypad'' mode.
  8007. @kindex x
  8008. @kindex M-x
  8009. @pindex calc-execute-extended-command
  8010. Most Calc commands use one or two keystrokes. Lower- and upper-case
  8011. letters are distinct. Commands may also be entered in full @kbd{M-x} form;
  8012. for some commands this is the only form. As a convenience, the @kbd{x}
  8013. key (@code{calc-execute-extended-command})
  8014. is like @kbd{M-x} except that it enters the initial string @samp{calc-}
  8015. for you. For example, the following key sequences are equivalent:
  8016. @kbd{S}, @kbd{M-x calc-sin @key{RET}}, @kbd{x sin @key{RET}}.@refill
  8017. @cindex Extensions module
  8018. @cindex @file{calc-ext} module
  8019. The Calculator exists in many parts. When you type @kbd{M-# c}, the
  8020. Emacs ``auto-load'' mechanism will bring in only the first part, which
  8021. contains the basic arithmetic functions. The other parts will be
  8022. auto-loaded the first time you use the more advanced commands like trig
  8023. functions or matrix operations. This is done to improve the response time
  8024. of the Calculator in the common case when all you need to do is a
  8025. little arithmetic. If for some reason the Calculator fails to load an
  8026. extension module automatically, you can force it to load all the
  8027. extensions by using the @kbd{M-# L} (@code{calc-load-everything})
  8028. command. @xref{Mode Settings}.@refill
  8029. If you type @kbd{M-x calc} or @kbd{M-# c} with any numeric prefix argument,
  8030. the Calculator is loaded if necessary, but it is not actually started.
  8031. If the argument is positive, the @file{calc-ext} extensions are also
  8032. loaded if necessary. User-written Lisp code that wishes to make use
  8033. of Calc's arithmetic routines can use @samp{(calc 0)} or @samp{(calc 1)}
  8034. to auto-load the Calculator.@refill
  8035. @kindex M-# b
  8036. @pindex full-calc
  8037. If you type @kbd{M-# b}, then next time you use @kbd{M-# c} you
  8038. will get a Calculator that uses the full height of the Emacs screen.
  8039. When full-screen mode is on, @kbd{M-# c} runs the @code{full-calc}
  8040. command instead of @code{calc}. From the Unix shell you can type
  8041. @samp{emacs -f full-calc} to start a new Emacs specifically for use
  8042. as a calculator. When Calc is started from the Emacs command line
  8043. like this, Calc's normal ``quit'' commands actually quit Emacs itself.
  8044. @kindex M-# o
  8045. @pindex calc-other-window
  8046. The @kbd{M-# o} command is like @kbd{M-# c} except that the Calc
  8047. window is not actually selected. If you are already in the Calc
  8048. window, @kbd{M-# o} switches you out of it. (The regular Emacs
  8049. @kbd{C-x o} command would also work for this, but it has a
  8050. tendency to drop you into the Calc Trail window instead, which
  8051. @kbd{M-# o} takes care not to do.)
  8052. @ignore
  8053. @mindex M-# q
  8054. @end ignore
  8055. For one quick calculation, you can type @kbd{M-# q} (@code{quick-calc})
  8056. which prompts you for a formula (like @samp{2+3/4}). The result is
  8057. displayed at the bottom of the Emacs screen without ever creating
  8058. any special Calculator windows. @xref{Quick Calculator}.
  8059. @ignore
  8060. @mindex M-# k
  8061. @end ignore
  8062. Finally, if you are using the X window system you may want to try
  8063. @kbd{M-# k} (@code{calc-keypad}) which runs Calc with a
  8064. ``calculator keypad'' picture as well as a stack display. Click on
  8065. the keys with the mouse to operate the calculator. @xref{Keypad Mode}.
  8066. @kindex q
  8067. @pindex calc-quit
  8068. @cindex Quitting the Calculator
  8069. @cindex Exiting the Calculator
  8070. The @kbd{q} key (@code{calc-quit}) exits Calc Mode and closes the
  8071. Calculator's window(s). It does not delete the Calculator buffers.
  8072. If you type @kbd{M-x calc} again, the Calculator will reappear with the
  8073. contents of the stack intact. Typing @kbd{M-# c} or @kbd{M-# M-#}
  8074. again from inside the Calculator buffer is equivalent to executing
  8075. @code{calc-quit}; you can think of @kbd{M-# M-#} as toggling the
  8076. Calculator on and off.@refill
  8077. @kindex M-# x
  8078. The @kbd{M-# x} command also turns the Calculator off, no matter which
  8079. user interface (standard, Keypad, or Embedded) is currently active.
  8080. It also cancels @code{calc-edit} mode if used from there.
  8081. @kindex d @key{SPC}
  8082. @pindex calc-refresh
  8083. @cindex Refreshing a garbled display
  8084. @cindex Garbled displays, refreshing
  8085. The @kbd{d @key{SPC}} key sequence (@code{calc-refresh}) redraws the contents
  8086. of the Calculator buffer from memory. Use this if the contents of the
  8087. buffer have been damaged somehow.
  8088. @ignore
  8089. @mindex o
  8090. @end ignore
  8091. The @kbd{o} key (@code{calc-realign}) moves the cursor back to its
  8092. ``home'' position at the bottom of the Calculator buffer.
  8093. @kindex <
  8094. @kindex >
  8095. @pindex calc-scroll-left
  8096. @pindex calc-scroll-right
  8097. @cindex Horizontal scrolling
  8098. @cindex Scrolling
  8099. @cindex Wide text, scrolling
  8100. The @kbd{<} and @kbd{>} keys are bound to @code{calc-scroll-left} and
  8101. @code{calc-scroll-right}. These are just like the normal horizontal
  8102. scrolling commands except that they scroll one half-screen at a time by
  8103. default. (Calc formats its output to fit within the bounds of the
  8104. window whenever it can.)@refill
  8105. @kindex @{
  8106. @kindex @}
  8107. @pindex calc-scroll-down
  8108. @pindex calc-scroll-up
  8109. @cindex Vertical scrolling
  8110. The @kbd{@{} and @kbd{@}} keys are bound to @code{calc-scroll-down}
  8111. and @code{calc-scroll-up}. They scroll up or down by one-half the
  8112. height of the Calc window.@refill
  8113. @kindex M-# 0
  8114. @pindex calc-reset
  8115. The @kbd{M-# 0} command (@code{calc-reset}; that's @kbd{M-#} followed
  8116. by a zero) resets the Calculator to its default state. This clears
  8117. the stack, resets all the modes, clears the caches (@pxref{Caches}),
  8118. and so on. (It does @emph{not} erase the values of any variables.)
  8119. With a numeric prefix argument, @kbd{M-# 0} preserves the contents
  8120. of the stack but resets everything else.
  8121. @pindex calc-version
  8122. The @kbd{M-x calc-version} command displays the current version number
  8123. of Calc and the name of the person who installed it on your system.
  8124. (This information is also present in the @samp{*Calc Trail*} buffer,
  8125. and in the output of the @kbd{h h} command.)
  8126. @node Help Commands, Stack Basics, Basic Commands, Introduction
  8127. @section Help Commands
  8128. @noindent
  8129. @cindex Help commands
  8130. @kindex ?
  8131. @pindex calc-help
  8132. The @kbd{?} key (@code{calc-help}) displays a series of brief help messages.
  8133. Some keys (such as @kbd{b} and @kbd{d}) are prefix keys, like Emacs'
  8134. @key{ESC} and @kbd{C-x} prefixes. You can type
  8135. @kbd{?} after a prefix to see a list of commands beginning with that
  8136. prefix. (If the message includes @samp{[MORE]}, press @kbd{?} again
  8137. to see additional commands for that prefix.)
  8138. @kindex h h
  8139. @pindex calc-full-help
  8140. The @kbd{h h} (@code{calc-full-help}) command displays all the @kbd{?}
  8141. responses at once. When printed, this makes a nice, compact (three pages)
  8142. summary of Calc keystrokes.
  8143. In general, the @kbd{h} key prefix introduces various commands that
  8144. provide help within Calc. Many of the @kbd{h} key functions are
  8145. Calc-specific analogues to the @kbd{C-h} functions for Emacs help.
  8146. @kindex h i
  8147. @kindex M-# i
  8148. @kindex i
  8149. @pindex calc-info
  8150. The @kbd{h i} (@code{calc-info}) command runs the Emacs Info system
  8151. to read this manual on-line. This is basically the same as typing
  8152. @kbd{C-h i} (the regular way to run the Info system), then, if Info
  8153. is not already in the Calc manual, selecting the beginning of the
  8154. manual. The @kbd{M-# i} command is another way to read the Calc
  8155. manual; it is different from @kbd{h i} in that it works any time,
  8156. not just inside Calc. The plain @kbd{i} key is also equivalent to
  8157. @kbd{h i}, though this key is obsolete and may be replaced with a
  8158. different command in a future version of Calc.
  8159. @kindex h t
  8160. @kindex M-# t
  8161. @pindex calc-tutorial
  8162. The @kbd{h t} (@code{calc-tutorial}) command runs the Info system on
  8163. the Tutorial section of the Calc manual. It is like @kbd{h i},
  8164. except that it selects the starting node of the tutorial rather
  8165. than the beginning of the whole manual. (It actually selects the
  8166. node ``Interactive Tutorial'' which tells a few things about
  8167. using the Info system before going on to the actual tutorial.)
  8168. The @kbd{M-# t} key is equivalent to @kbd{h t} (but it works at
  8169. all times).
  8170. @kindex h s
  8171. @kindex M-# s
  8172. @pindex calc-info-summary
  8173. The @kbd{h s} (@code{calc-info-summary}) command runs the Info system
  8174. on the Summary node of the Calc manual. @xref{Summary}. The @kbd{M-# s}
  8175. key is equivalent to @kbd{h s}.
  8176. @kindex h k
  8177. @pindex calc-describe-key
  8178. The @kbd{h k} (@code{calc-describe-key}) command looks up a key
  8179. sequence in the Calc manual. For example, @kbd{h k H a S} looks
  8180. up the documentation on the @kbd{H a S} (@code{calc-solve-for})
  8181. command. This works by looking up the textual description of
  8182. the key(s) in the Key Index of the manual, then jumping to the
  8183. node indicated by the index.
  8184. Most Calc commands do not have traditional Emacs documentation
  8185. strings, since the @kbd{h k} command is both more convenient and
  8186. more instructive. This means the regular Emacs @kbd{C-h k}
  8187. (@code{describe-key}) command will not be useful for Calc keystrokes.
  8188. @kindex h c
  8189. @pindex calc-describe-key-briefly
  8190. The @kbd{h c} (@code{calc-describe-key-briefly}) command reads a
  8191. key sequence and displays a brief one-line description of it at
  8192. the bottom of the screen. It looks for the key sequence in the
  8193. Summary node of the Calc manual; if it doesn't find the sequence
  8194. there, it acts just like its regular Emacs counterpart @kbd{C-h c}
  8195. (@code{describe-key-briefly}). For example, @kbd{h c H a S}
  8196. gives the description:
  8197. @smallexample
  8198. H a S runs calc-solve-for: a `H a S' v => fsolve(a,v) (?=notes)
  8199. @end smallexample
  8200. @noindent
  8201. which means the command @kbd{H a S} or @kbd{H M-x calc-solve-for}
  8202. takes a value @cite{a} from the stack, prompts for a value @cite{v},
  8203. then applies the algebraic function @code{fsolve} to these values.
  8204. The @samp{?=notes} message means you can now type @kbd{?} to see
  8205. additional notes from the summary that apply to this command.
  8206. @kindex h f
  8207. @pindex calc-describe-function
  8208. The @kbd{h f} (@code{calc-describe-function}) command looks up an
  8209. algebraic function or a command name in the Calc manual. The
  8210. prompt initially contains @samp{calcFunc-}; follow this with an
  8211. algebraic function name to look up that function in the Function
  8212. Index. Or, backspace and enter a command name beginning with
  8213. @samp{calc-} to look it up in the Command Index. This command
  8214. will also look up operator symbols that can appear in algebraic
  8215. formulas, like @samp{%} and @samp{=>}.
  8216. @kindex h v
  8217. @pindex calc-describe-variable
  8218. The @kbd{h v} (@code{calc-describe-variable}) command looks up a
  8219. variable in the Calc manual. The prompt initially contains the
  8220. @samp{var-} prefix; just add a variable name like @code{pi} or
  8221. @code{PlotRejects}.
  8222. @kindex h b
  8223. @pindex describe-bindings
  8224. The @kbd{h b} (@code{calc-describe-bindings}) command is just like
  8225. @kbd{C-h b}, except that only local (Calc-related) key bindings are
  8226. listed.
  8227. @kindex h n
  8228. The @kbd{h n} or @kbd{h C-n} (@code{calc-view-news}) command displays
  8229. the ``news'' or change history of Calc. This is kept in the file
  8230. @file{README}, which Calc looks for in the same directory as the Calc
  8231. source files.
  8232. @kindex h C-c
  8233. @kindex h C-d
  8234. @kindex h C-w
  8235. The @kbd{h C-c}, @kbd{h C-d}, and @kbd{h C-w} keys display copying,
  8236. distribution, and warranty information about Calc. These work by
  8237. pulling up the appropriate parts of the ``Copying'' or ``Reporting
  8238. Bugs'' sections of the manual.
  8239. @node Stack Basics, Numeric Entry, Help Commands, Introduction
  8240. @section Stack Basics
  8241. @noindent
  8242. @cindex Stack basics
  8243. @c [fix-tut RPN Calculations and the Stack]
  8244. Calc uses RPN notation. If you are not familar with RPN, @pxref{RPN
  8245. Tutorial}.
  8246. To add the numbers 1 and 2 in Calc you would type the keys:
  8247. @kbd{1 @key{RET} 2 +}.
  8248. (@key{RET} corresponds to the @key{ENTER} key on most calculators.)
  8249. The first three keystrokes ``push'' the numbers 1 and 2 onto the stack. The
  8250. @kbd{+} key always ``pops'' the top two numbers from the stack, adds them,
  8251. and pushes the result (3) back onto the stack. This number is ready for
  8252. further calculations: @kbd{5 -} pushes 5 onto the stack, then pops the
  8253. 3 and 5, subtracts them, and pushes the result (@i{-2}).@refill
  8254. Note that the ``top'' of the stack actually appears at the @emph{bottom}
  8255. of the buffer. A line containing a single @samp{.} character signifies
  8256. the end of the buffer; Calculator commands operate on the number(s)
  8257. directly above this line. The @kbd{d t} (@code{calc-truncate-stack})
  8258. command allows you to move the @samp{.} marker up and down in the stack;
  8259. @pxref{Truncating the Stack}.
  8260. @kindex d l
  8261. @pindex calc-line-numbering
  8262. Stack elements are numbered consecutively, with number 1 being the top of
  8263. the stack. These line numbers are ordinarily displayed on the lefthand side
  8264. of the window. The @kbd{d l} (@code{calc-line-numbering}) command controls
  8265. whether these numbers appear. (Line numbers may be turned off since they
  8266. slow the Calculator down a bit and also clutter the display.)
  8267. @kindex o
  8268. @pindex calc-realign
  8269. The unshifted letter @kbd{o} (@code{calc-realign}) command repositions
  8270. the cursor to its top-of-stack ``home'' position. It also undoes any
  8271. horizontal scrolling in the window. If you give it a numeric prefix
  8272. argument, it instead moves the cursor to the specified stack element.
  8273. The @key{RET} (or equivalent @key{SPC}) key is only required to separate
  8274. two consecutive numbers.
  8275. (After all, if you typed @kbd{1 2} by themselves the Calculator
  8276. would enter the number 12.) If you press @key{RET} or @key{SPC} @emph{not}
  8277. right after typing a number, the key duplicates the number on the top of
  8278. the stack. @kbd{@key{RET} *} is thus a handy way to square a number.@refill
  8279. The @key{DEL} key pops and throws away the top number on the stack.
  8280. The @key{TAB} key swaps the top two objects on the stack.
  8281. @xref{Stack and Trail}, for descriptions of these and other stack-related
  8282. commands.@refill
  8283. @node Numeric Entry, Algebraic Entry, Stack Basics, Introduction
  8284. @section Numeric Entry
  8285. @noindent
  8286. @kindex 0-9
  8287. @kindex .
  8288. @kindex e
  8289. @cindex Numeric entry
  8290. @cindex Entering numbers
  8291. Pressing a digit or other numeric key begins numeric entry using the
  8292. minibuffer. The number is pushed on the stack when you press the @key{RET}
  8293. or @key{SPC} keys. If you press any other non-numeric key, the number is
  8294. pushed onto the stack and the appropriate operation is performed. If
  8295. you press a numeric key which is not valid, the key is ignored.
  8296. @cindex Minus signs
  8297. @cindex Negative numbers, entering
  8298. @kindex _
  8299. There are three different concepts corresponding to the word ``minus,''
  8300. typified by @cite{a-b} (subtraction), @cite{-x}
  8301. (change-sign), and @cite{-5} (negative number). Calc uses three
  8302. different keys for these operations, respectively:
  8303. @kbd{-}, @kbd{n}, and @kbd{_} (the underscore). The @kbd{-} key subtracts
  8304. the two numbers on the top of the stack. The @kbd{n} key changes the sign
  8305. of the number on the top of the stack or the number currently being entered.
  8306. The @kbd{_} key begins entry of a negative number or changes the sign of
  8307. the number currently being entered. The following sequences all enter the
  8308. number @i{-5} onto the stack: @kbd{0 @key{RET} 5 -}, @kbd{5 n @key{RET}},
  8309. @kbd{5 @key{RET} n}, @kbd{_ 5 @key{RET}}, @kbd{5 _ @key{RET}}.@refill
  8310. Some other keys are active during numeric entry, such as @kbd{#} for
  8311. non-decimal numbers, @kbd{:} for fractions, and @kbd{@@} for HMS forms.
  8312. These notations are described later in this manual with the corresponding
  8313. data types. @xref{Data Types}.
  8314. During numeric entry, the only editing key available is @key{DEL}.
  8315. @node Algebraic Entry, Quick Calculator, Numeric Entry, Introduction
  8316. @section Algebraic Entry
  8317. @noindent
  8318. @kindex '
  8319. @pindex calc-algebraic-entry
  8320. @cindex Algebraic notation
  8321. @cindex Formulas, entering
  8322. Calculations can also be entered in algebraic form. This is accomplished
  8323. by typing the apostrophe key, @kbd{'}, followed by the expression in
  8324. standard format: @kbd{@key{'} 2+3*4 @key{RET}} computes
  8325. @c{$2+(3\times4) = 14$}
  8326. @cite{2+(3*4) = 14} and pushes that on the stack. If you wish you can
  8327. ignore the RPN aspect of Calc altogether and simply enter algebraic
  8328. expressions in this way. You may want to use @key{DEL} every so often to
  8329. clear previous results off the stack.@refill
  8330. You can press the apostrophe key during normal numeric entry to switch
  8331. the half-entered number into algebraic entry mode. One reason to do this
  8332. would be to use the full Emacs cursor motion and editing keys, which are
  8333. available during algebraic entry but not during numeric entry.
  8334. In the same vein, during either numeric or algebraic entry you can
  8335. press @kbd{`} (backquote) to switch to @code{calc-edit} mode, where
  8336. you complete your half-finished entry in a separate buffer.
  8337. @xref{Editing Stack Entries}.
  8338. @kindex m a
  8339. @pindex calc-algebraic-mode
  8340. @cindex Algebraic mode
  8341. If you prefer algebraic entry, you can use the command @kbd{m a}
  8342. (@code{calc-algebraic-mode}) to set Algebraic mode. In this mode,
  8343. digits and other keys that would normally start numeric entry instead
  8344. start full algebraic entry; as long as your formula begins with a digit
  8345. you can omit the apostrophe. Open parentheses and square brackets also
  8346. begin algebraic entry. You can still do RPN calculations in this mode,
  8347. but you will have to press @key{RET} to terminate every number:
  8348. @kbd{2 @key{RET} 3 @key{RET} * 4 @key{RET} +} would accomplish the same
  8349. thing as @kbd{2*3+4 @key{RET}}.@refill
  8350. @cindex Incomplete algebraic mode
  8351. If you give a numeric prefix argument like @kbd{C-u} to the @kbd{m a}
  8352. command, it enables Incomplete Algebraic mode; this is like regular
  8353. Algebraic mode except that it applies to the @kbd{(} and @kbd{[} keys
  8354. only. Numeric keys still begin a numeric entry in this mode.
  8355. @kindex m t
  8356. @pindex calc-total-algebraic-mode
  8357. @cindex Total algebraic mode
  8358. The @kbd{m t} (@code{calc-total-algebraic-mode}) gives you an even
  8359. stronger algebraic-entry mode, in which @emph{all} regular letter and
  8360. punctuation keys begin algebraic entry. Use this if you prefer typing
  8361. @w{@kbd{sqrt( )}} instead of @kbd{Q}, @w{@kbd{factor( )}} instead of
  8362. @kbd{a f}, and so on. To type regular Calc commands when you are in
  8363. ``total'' algebraic mode, hold down the @key{META} key. Thus @kbd{M-q}
  8364. is the command to quit Calc, @kbd{M-p} sets the precision, and
  8365. @kbd{M-m t} (or @kbd{M-m M-t}, if you prefer) turns total algebraic
  8366. mode back off again. Meta keys also terminate algebraic entry, so
  8367. that @kbd{2+3 M-S} is equivalent to @kbd{2+3 @key{RET} M-S}. The symbol
  8368. @samp{Alg*} will appear in the mode line whenever you are in this mode.
  8369. Pressing @kbd{'} (the apostrophe) a second time re-enters the previous
  8370. algebraic formula. You can then use the normal Emacs editing keys to
  8371. modify this formula to your liking before pressing @key{RET}.
  8372. @kindex $
  8373. @cindex Formulas, referring to stack
  8374. Within a formula entered from the keyboard, the symbol @kbd{$}
  8375. represents the number on the top of the stack. If an entered formula
  8376. contains any @kbd{$} characters, the Calculator replaces the top of
  8377. stack with that formula rather than simply pushing the formula onto the
  8378. stack. Thus, @kbd{' 1+2 @key{RET}} pushes 3 on the stack, and @kbd{$*2
  8379. @key{RET}} replaces it with 6. Note that the @kbd{$} key always
  8380. initiates algebraic entry; the @kbd{'} is unnecessary if @kbd{$} is the
  8381. first character in the new formula.@refill
  8382. Higher stack elements can be accessed from an entered formula with the
  8383. symbols @kbd{$$}, @kbd{$$$}, and so on. The number of stack elements
  8384. removed (to be replaced by the entered values) equals the number of dollar
  8385. signs in the longest such symbol in the formula. For example, @samp{$$+$$$}
  8386. adds the second and third stack elements, replacing the top three elements
  8387. with the answer. (All information about the top stack element is thus lost
  8388. since no single @samp{$} appears in this formula.)@refill
  8389. A slightly different way to refer to stack elements is with a dollar
  8390. sign followed by a number: @samp{$1}, @samp{$2}, and so on are much
  8391. like @samp{$}, @samp{$$}, etc., except that stack entries referred
  8392. to numerically are not replaced by the algebraic entry. That is, while
  8393. @samp{$+1} replaces 5 on the stack with 6, @samp{$1+1} leaves the 5
  8394. on the stack and pushes an additional 6.
  8395. If a sequence of formulas are entered separated by commas, each formula
  8396. is pushed onto the stack in turn. For example, @samp{1,2,3} pushes
  8397. those three numbers onto the stack (leaving the 3 at the top), and
  8398. @samp{$+1,$-1} replaces a 5 on the stack with 4 followed by 6. Also,
  8399. @samp{$,$$} exchanges the top two elements of the stack, just like the
  8400. @key{TAB} key.
  8401. You can finish an algebraic entry with @kbd{M-=} or @kbd{M-@key{RET}} instead
  8402. of @key{RET}. This uses @kbd{=} to evaluate the variables in each
  8403. formula that goes onto the stack. (Thus @kbd{' pi @key{RET}} pushes
  8404. the variable @samp{pi}, but @kbd{' pi M-@key{RET}} pushes 3.1415.)
  8405. If you finish your algebraic entry by pressing @key{LFD} (or @kbd{C-j})
  8406. instead of @key{RET}, Calc disables the default simplifications
  8407. (as if by @kbd{m O}; @pxref{Simplification Modes}) while the entry
  8408. is being pushed on the stack. Thus @kbd{' 1+2 @key{RET}} pushes 3
  8409. on the stack, but @kbd{' 1+2 @key{LFD}} pushes the formula @cite{1+2};
  8410. you might then press @kbd{=} when it is time to evaluate this formula.
  8411. @node Quick Calculator, Prefix Arguments, Algebraic Entry, Introduction
  8412. @section ``Quick Calculator'' Mode
  8413. @noindent
  8414. @kindex M-# q
  8415. @pindex quick-calc
  8416. @cindex Quick Calculator
  8417. There is another way to invoke the Calculator if all you need to do
  8418. is make one or two quick calculations. Type @kbd{M-# q} (or
  8419. @kbd{M-x quick-calc}), then type any formula as an algebraic entry.
  8420. The Calculator will compute the result and display it in the echo
  8421. area, without ever actually putting up a Calc window.
  8422. You can use the @kbd{$} character in a Quick Calculator formula to
  8423. refer to the previous Quick Calculator result. Older results are
  8424. not retained; the Quick Calculator has no effect on the full
  8425. Calculator's stack or trail. If you compute a result and then
  8426. forget what it was, just run @code{M-# q} again and enter
  8427. @samp{$} as the formula.
  8428. If this is the first time you have used the Calculator in this Emacs
  8429. session, the @kbd{M-# q} command will create the @code{*Calculator*}
  8430. buffer and perform all the usual initializations; it simply will
  8431. refrain from putting that buffer up in a new window. The Quick
  8432. Calculator refers to the @code{*Calculator*} buffer for all mode
  8433. settings. Thus, for example, to set the precision that the Quick
  8434. Calculator uses, simply run the full Calculator momentarily and use
  8435. the regular @kbd{p} command.
  8436. If you use @code{M-# q} from inside the Calculator buffer, the
  8437. effect is the same as pressing the apostrophe key (algebraic entry).
  8438. The result of a Quick calculation is placed in the Emacs ``kill ring''
  8439. as well as being displayed. A subsequent @kbd{C-y} command will
  8440. yank the result into the editing buffer. You can also use this
  8441. to yank the result into the next @kbd{M-# q} input line as a more
  8442. explicit alternative to @kbd{$} notation, or to yank the result
  8443. into the Calculator stack after typing @kbd{M-# c}.
  8444. If you finish your formula by typing @key{LFD} (or @kbd{C-j}) instead
  8445. of @key{RET}, the result is inserted immediately into the current
  8446. buffer rather than going into the kill ring.
  8447. Quick Calculator results are actually evaluated as if by the @kbd{=}
  8448. key (which replaces variable names by their stored values, if any).
  8449. If the formula you enter is an assignment to a variable using the
  8450. @samp{:=} operator, say, @samp{foo := 2 + 3} or @samp{foo := foo + 1},
  8451. then the result of the evaluation is stored in that Calc variable.
  8452. @xref{Store and Recall}.
  8453. If the result is an integer and the current display radix is decimal,
  8454. the number will also be displayed in hex and octal formats. If the
  8455. integer is in the range from 1 to 126, it will also be displayed as
  8456. an ASCII character.
  8457. For example, the quoted character @samp{"x"} produces the vector
  8458. result @samp{[120]} (because 120 is the ASCII code of the lower-case
  8459. `x'; @pxref{Strings}). Since this is a vector, not an integer, it
  8460. is displayed only according to the current mode settings. But
  8461. running Quick Calc again and entering @samp{120} will produce the
  8462. result @samp{120 (16#78, 8#170, x)} which shows the number in its
  8463. decimal, hexadecimal, octal, and ASCII forms.
  8464. Please note that the Quick Calculator is not any faster at loading
  8465. or computing the answer than the full Calculator; the name ``quick''
  8466. merely refers to the fact that it's much less hassle to use for
  8467. small calculations.
  8468. @node Prefix Arguments, Undo, Quick Calculator, Introduction
  8469. @section Numeric Prefix Arguments
  8470. @noindent
  8471. Many Calculator commands use numeric prefix arguments. Some, such as
  8472. @kbd{d s} (@code{calc-sci-notation}), set a parameter to the value of
  8473. the prefix argument or use a default if you don't use a prefix.
  8474. Others (like @kbd{d f} (@code{calc-fix-notation})) require an argument
  8475. and prompt for a number if you don't give one as a prefix.@refill
  8476. As a rule, stack-manipulation commands accept a numeric prefix argument
  8477. which is interpreted as an index into the stack. A positive argument
  8478. operates on the top @var{n} stack entries; a negative argument operates
  8479. on the @var{n}th stack entry in isolation; and a zero argument operates
  8480. on the entire stack.
  8481. Most commands that perform computations (such as the arithmetic and
  8482. scientific functions) accept a numeric prefix argument that allows the
  8483. operation to be applied across many stack elements. For unary operations
  8484. (that is, functions of one argument like absolute value or complex
  8485. conjugate), a positive prefix argument applies that function to the top
  8486. @var{n} stack entries simultaneously, and a negative argument applies it
  8487. to the @var{n}th stack entry only. For binary operations (functions of
  8488. two arguments like addition, GCD, and vector concatenation), a positive
  8489. prefix argument ``reduces'' the function across the top @var{n}
  8490. stack elements (for example, @kbd{C-u 5 +} sums the top 5 stack entries;
  8491. @pxref{Reducing and Mapping}), and a negative argument maps the next-to-top
  8492. @var{n} stack elements with the top stack element as a second argument
  8493. (for example, @kbd{7 c-u -5 +} adds 7 to the top 5 stack elements).
  8494. This feature is not available for operations which use the numeric prefix
  8495. argument for some other purpose.
  8496. Numeric prefixes are specified the same way as always in Emacs: Press
  8497. a sequence of @key{META}-digits, or press @key{ESC} followed by digits,
  8498. or press @kbd{C-u} followed by digits. Some commands treat plain
  8499. @kbd{C-u} (without any actual digits) specially.@refill
  8500. @kindex ~
  8501. @pindex calc-num-prefix
  8502. You can type @kbd{~} (@code{calc-num-prefix}) to pop an integer from the
  8503. top of the stack and enter it as the numeric prefix for the next command.
  8504. For example, @kbd{C-u 16 p} sets the precision to 16 digits; an alternate
  8505. (silly) way to do this would be @kbd{2 @key{RET} 4 ^ ~ p}, i.e., compute 2
  8506. to the fourth power and set the precision to that value.@refill
  8507. Conversely, if you have typed a numeric prefix argument the @kbd{~} key
  8508. pushes it onto the stack in the form of an integer.
  8509. @node Undo, Error Messages, Prefix Arguments, Introduction
  8510. @section Undoing Mistakes
  8511. @noindent
  8512. @kindex U
  8513. @kindex C-_
  8514. @pindex calc-undo
  8515. @cindex Mistakes, undoing
  8516. @cindex Undoing mistakes
  8517. @cindex Errors, undoing
  8518. The shift-@kbd{U} key (@code{calc-undo}) undoes the most recent operation.
  8519. If that operation added or dropped objects from the stack, those objects
  8520. are removed or restored. If it was a ``store'' operation, you are
  8521. queried whether or not to restore the variable to its original value.
  8522. The @kbd{U} key may be pressed any number of times to undo successively
  8523. farther back in time; with a numeric prefix argument it undoes a
  8524. specified number of operations. The undo history is cleared only by the
  8525. @kbd{q} (@code{calc-quit}) command. (Recall that @kbd{M-# c} is
  8526. synonymous with @code{calc-quit} while inside the Calculator; this
  8527. also clears the undo history.)
  8528. Currently the mode-setting commands (like @code{calc-precision}) are not
  8529. undoable. You can undo past a point where you changed a mode, but you
  8530. will need to reset the mode yourself.
  8531. @kindex D
  8532. @pindex calc-redo
  8533. @cindex Redoing after an Undo
  8534. The shift-@kbd{D} key (@code{calc-redo}) redoes an operation that was
  8535. mistakenly undone. Pressing @kbd{U} with a negative prefix argument is
  8536. equivalent to executing @code{calc-redo}. You can redo any number of
  8537. times, up to the number of recent consecutive undo commands. Redo
  8538. information is cleared whenever you give any command that adds new undo
  8539. information, i.e., if you undo, then enter a number on the stack or make
  8540. any other change, then it will be too late to redo.
  8541. @kindex M-@key{RET}
  8542. @pindex calc-last-args
  8543. @cindex Last-arguments feature
  8544. @cindex Arguments, restoring
  8545. The @kbd{M-@key{RET}} key (@code{calc-last-args}) is like undo in that
  8546. it restores the arguments of the most recent command onto the stack;
  8547. however, it does not remove the result of that command. Given a numeric
  8548. prefix argument, this command applies to the @cite{n}th most recent
  8549. command which removed items from the stack; it pushes those items back
  8550. onto the stack.
  8551. The @kbd{K} (@code{calc-keep-args}) command provides a related function
  8552. to @kbd{M-@key{RET}}. @xref{Stack and Trail}.
  8553. It is also possible to recall previous results or inputs using the trail.
  8554. @xref{Trail Commands}.
  8555. The standard Emacs @kbd{C-_} undo key is recognized as a synonym for @kbd{U}.
  8556. @node Error Messages, Multiple Calculators, Undo, Introduction
  8557. @section Error Messages
  8558. @noindent
  8559. @kindex w
  8560. @pindex calc-why
  8561. @cindex Errors, messages
  8562. @cindex Why did an error occur?
  8563. Many situations that would produce an error message in other calculators
  8564. simply create unsimplified formulas in the Emacs Calculator. For example,
  8565. @kbd{1 @key{RET} 0 /} pushes the formula @cite{1 / 0}; @w{@kbd{0 L}} pushes
  8566. the formula @samp{ln(0)}. Floating-point overflow and underflow are also
  8567. reasons for this to happen.
  8568. When a function call must be left in symbolic form, Calc usually
  8569. produces a message explaining why. Messages that are probably
  8570. surprising or indicative of user errors are displayed automatically.
  8571. Other messages are simply kept in Calc's memory and are displayed only
  8572. if you type @kbd{w} (@code{calc-why}). You can also press @kbd{w} if
  8573. the same computation results in several messages. (The first message
  8574. will end with @samp{[w=more]} in this case.)
  8575. @kindex d w
  8576. @pindex calc-auto-why
  8577. The @kbd{d w} (@code{calc-auto-why}) command controls when error messages
  8578. are displayed automatically. (Calc effectively presses @kbd{w} for you
  8579. after your computation finishes.) By default, this occurs only for
  8580. ``important'' messages. The other possible modes are to report
  8581. @emph{all} messages automatically, or to report none automatically (so
  8582. that you must always press @kbd{w} yourself to see the messages).
  8583. @node Multiple Calculators, Troubleshooting Commands, Error Messages, Introduction
  8584. @section Multiple Calculators
  8585. @noindent
  8586. @pindex another-calc
  8587. It is possible to have any number of Calc Mode buffers at once.
  8588. Usually this is done by executing @kbd{M-x another-calc}, which
  8589. is similar to @kbd{M-# c} except that if a @samp{*Calculator*}
  8590. buffer already exists, a new, independent one with a name of the
  8591. form @samp{*Calculator*<@var{n}>} is created. You can also use the
  8592. command @code{calc-mode} to put any buffer into Calculator mode, but
  8593. this would ordinarily never be done.
  8594. The @kbd{q} (@code{calc-quit}) command does not destroy a Calculator buffer;
  8595. it only closes its window. Use @kbd{M-x kill-buffer} to destroy a
  8596. Calculator buffer.
  8597. Each Calculator buffer keeps its own stack, undo list, and mode settings
  8598. such as precision, angular mode, and display formats. In Emacs terms,
  8599. variables such as @code{calc-stack} are buffer-local variables. The
  8600. global default values of these variables are used only when a new
  8601. Calculator buffer is created. The @code{calc-quit} command saves
  8602. the stack and mode settings of the buffer being quit as the new defaults.
  8603. There is only one trail buffer, @samp{*Calc Trail*}, used by all
  8604. Calculator buffers.
  8605. @node Troubleshooting Commands, , Multiple Calculators, Introduction
  8606. @section Troubleshooting Commands
  8607. @noindent
  8608. This section describes commands you can use in case a computation
  8609. incorrectly fails or gives the wrong answer.
  8610. @xref{Reporting Bugs}, if you find a problem that appears to be due
  8611. to a bug or deficiency in Calc.
  8612. @menu
  8613. * Autoloading Problems::
  8614. * Recursion Depth::
  8615. * Caches::
  8616. * Debugging Calc::
  8617. @end menu
  8618. @node Autoloading Problems, Recursion Depth, Troubleshooting Commands, Troubleshooting Commands
  8619. @subsection Autoloading Problems
  8620. @noindent
  8621. The Calc program is split into many component files; components are
  8622. loaded automatically as you use various commands that require them.
  8623. Occasionally Calc may lose track of when a certain component is
  8624. necessary; typically this means you will type a command and it won't
  8625. work because some function you've never heard of was undefined.
  8626. @kindex M-# L
  8627. @pindex calc-load-everything
  8628. If this happens, the easiest workaround is to type @kbd{M-# L}
  8629. (@code{calc-load-everything}) to force all the parts of Calc to be
  8630. loaded right away. This will cause Emacs to take up a lot more
  8631. memory than it would otherwise, but it's guaranteed to fix the problem.
  8632. If you seem to run into this problem no matter what you do, or if
  8633. even the @kbd{M-# L} command crashes, Calc may have been improperly
  8634. installed. @xref{Installation}, for details of the installation
  8635. process.
  8636. @node Recursion Depth, Caches, Autoloading Problems, Troubleshooting Commands
  8637. @subsection Recursion Depth
  8638. @noindent
  8639. @kindex M
  8640. @kindex I M
  8641. @pindex calc-more-recursion-depth
  8642. @pindex calc-less-recursion-depth
  8643. @cindex Recursion depth
  8644. @cindex ``Computation got stuck'' message
  8645. @cindex @code{max-lisp-eval-depth}
  8646. @cindex @code{max-specpdl-size}
  8647. Calc uses recursion in many of its calculations. Emacs Lisp keeps a
  8648. variable @code{max-lisp-eval-depth} which limits the amount of recursion
  8649. possible in an attempt to recover from program bugs. If a calculation
  8650. ever halts incorrectly with the message ``Computation got stuck or
  8651. ran too long,'' use the @kbd{M} command (@code{calc-more-recursion-depth})
  8652. to increase this limit. (Of course, this will not help if the
  8653. calculation really did get stuck due to some problem inside Calc.)@refill
  8654. The limit is always increased (multiplied) by a factor of two. There
  8655. is also an @kbd{I M} (@code{calc-less-recursion-depth}) command which
  8656. decreases this limit by a factor of two, down to a minimum value of 200.
  8657. The default value is 1000.
  8658. These commands also double or halve @code{max-specpdl-size}, another
  8659. internal Lisp recursion limit. The minimum value for this limit is 600.
  8660. @node Caches, Debugging Calc, Recursion Depth, Troubleshooting Commands
  8661. @subsection Caches
  8662. @noindent
  8663. @cindex Caches
  8664. @cindex Flushing caches
  8665. Calc saves certain values after they have been computed once. For
  8666. example, the @kbd{P} (@code{calc-pi}) command initially ``knows'' the
  8667. constant @c{$\pi$}
  8668. @cite{pi} to about 20 decimal places; if the current precision
  8669. is greater than this, it will recompute @c{$\pi$}
  8670. @cite{pi} using a series
  8671. approximation. This value will not need to be recomputed ever again
  8672. unless you raise the precision still further. Many operations such as
  8673. logarithms and sines make use of similarly cached values such as
  8674. @c{$\pi \over 4$}
  8675. @cite{pi/4} and @c{$\ln 2$}
  8676. @cite{ln(2)}. The visible effect of caching is that
  8677. high-precision computations may seem to do extra work the first time.
  8678. Other things cached include powers of two (for the binary arithmetic
  8679. functions), matrix inverses and determinants, symbolic integrals, and
  8680. data points computed by the graphing commands.
  8681. @pindex calc-flush-caches
  8682. If you suspect a Calculator cache has become corrupt, you can use the
  8683. @code{calc-flush-caches} command to reset all caches to the empty state.
  8684. (This should only be necessary in the event of bugs in the Calculator.)
  8685. The @kbd{M-# 0} (with the zero key) command also resets caches along
  8686. with all other aspects of the Calculator's state.
  8687. @node Debugging Calc, , Caches, Troubleshooting Commands
  8688. @subsection Debugging Calc
  8689. @noindent
  8690. A few commands exist to help in the debugging of Calc commands.
  8691. @xref{Programming}, to see the various ways that you can write
  8692. your own Calc commands.
  8693. @kindex Z T
  8694. @pindex calc-timing
  8695. The @kbd{Z T} (@code{calc-timing}) command turns on and off a mode
  8696. in which the timing of slow commands is reported in the Trail.
  8697. Any Calc command that takes two seconds or longer writes a line
  8698. to the Trail showing how many seconds it took. This value is
  8699. accurate only to within one second.
  8700. All steps of executing a command are included; in particular, time
  8701. taken to format the result for display in the stack and trail is
  8702. counted. Some prompts also count time taken waiting for them to
  8703. be answered, while others do not; this depends on the exact
  8704. implementation of the command. For best results, if you are timing
  8705. a sequence that includes prompts or multiple commands, define a
  8706. keyboard macro to run the whole sequence at once. Calc's @kbd{X}
  8707. command (@pxref{Keyboard Macros}) will then report the time taken
  8708. to execute the whole macro.
  8709. Another advantage of the @kbd{X} command is that while it is
  8710. executing, the stack and trail are not updated from step to step.
  8711. So if you expect the output of your test sequence to leave a result
  8712. that may take a long time to format and you don't wish to count
  8713. this formatting time, end your sequence with a @key{DEL} keystroke
  8714. to clear the result from the stack. When you run the sequence with
  8715. @kbd{X}, Calc will never bother to format the large result.
  8716. Another thing @kbd{Z T} does is to increase the Emacs variable
  8717. @code{gc-cons-threshold} to a much higher value (two million; the
  8718. usual default in Calc is 250,000) for the duration of each command.
  8719. This generally prevents garbage collection during the timing of
  8720. the command, though it may cause your Emacs process to grow
  8721. abnormally large. (Garbage collection time is a major unpredictable
  8722. factor in the timing of Emacs operations.)
  8723. Another command that is useful when debugging your own Lisp
  8724. extensions to Calc is @kbd{M-x calc-pass-errors}, which disables
  8725. the error handler that changes the ``@code{max-lisp-eval-depth}
  8726. exceeded'' message to the much more friendly ``Computation got
  8727. stuck or ran too long.'' This handler interferes with the Emacs
  8728. Lisp debugger's @code{debug-on-error} mode. Errors are reported
  8729. in the handler itself rather than at the true location of the
  8730. error. After you have executed @code{calc-pass-errors}, Lisp
  8731. errors will be reported correctly but the user-friendly message
  8732. will be lost.
  8733. @node Data Types, Stack and Trail, Introduction, Top
  8734. @chapter Data Types
  8735. @noindent
  8736. This chapter discusses the various types of objects that can be placed
  8737. on the Calculator stack, how they are displayed, and how they are
  8738. entered. (@xref{Data Type Formats}, for information on how these data
  8739. types are represented as underlying Lisp objects.)@refill
  8740. Integers, fractions, and floats are various ways of describing real
  8741. numbers. HMS forms also for many purposes act as real numbers. These
  8742. types can be combined to form complex numbers, modulo forms, error forms,
  8743. or interval forms. (But these last four types cannot be combined
  8744. arbitrarily:@: error forms may not contain modulo forms, for example.)
  8745. Finally, all these types of numbers may be combined into vectors,
  8746. matrices, or algebraic formulas.
  8747. @menu
  8748. * Integers:: The most basic data type.
  8749. * Fractions:: This and above are called @dfn{rationals}.
  8750. * Floats:: This and above are called @dfn{reals}.
  8751. * Complex Numbers:: This and above are called @dfn{numbers}.
  8752. * Infinities::
  8753. * Vectors and Matrices::
  8754. * Strings::
  8755. * HMS Forms::
  8756. * Date Forms::
  8757. * Modulo Forms::
  8758. * Error Forms::
  8759. * Interval Forms::
  8760. * Incomplete Objects::
  8761. * Variables::
  8762. * Formulas::
  8763. @end menu
  8764. @node Integers, Fractions, Data Types, Data Types
  8765. @section Integers
  8766. @noindent
  8767. @cindex Integers
  8768. The Calculator stores integers to arbitrary precision. Addition,
  8769. subtraction, and multiplication of integers always yields an exact
  8770. integer result. (If the result of a division or exponentiation of
  8771. integers is not an integer, it is expressed in fractional or
  8772. floating-point form according to the current Fraction Mode.
  8773. @xref{Fraction Mode}.)
  8774. A decimal integer is represented as an optional sign followed by a
  8775. sequence of digits. Grouping (@pxref{Grouping Digits}) can be used to
  8776. insert a comma at every third digit for display purposes, but you
  8777. must not type commas during the entry of numbers.@refill
  8778. @kindex #
  8779. A non-decimal integer is represented as an optional sign, a radix
  8780. between 2 and 36, a @samp{#} symbol, and one or more digits. For radix 11
  8781. and above, the letters A through Z (upper- or lower-case) count as
  8782. digits and do not terminate numeric entry mode. @xref{Radix Modes}, for how
  8783. to set the default radix for display of integers. Numbers of any radix
  8784. may be entered at any time. If you press @kbd{#} at the beginning of a
  8785. number, the current display radix is used.@refill
  8786. @node Fractions, Floats, Integers, Data Types
  8787. @section Fractions
  8788. @noindent
  8789. @cindex Fractions
  8790. A @dfn{fraction} is a ratio of two integers. Fractions are traditionally
  8791. written ``2/3'' but Calc uses the notation @samp{2:3}. (The @kbd{/} key
  8792. performs RPN division; the following two sequences push the number
  8793. @samp{2:3} on the stack: @kbd{2 :@: 3 @key{RET}}, or @kbd{2 @key{RET} 3 /}
  8794. assuming Fraction Mode has been enabled.)
  8795. When the Calculator produces a fractional result it always reduces it to
  8796. simplest form, which may in fact be an integer.@refill
  8797. Fractions may also be entered in a three-part form, where @samp{2:3:4}
  8798. represents two-and-three-quarters. @xref{Fraction Formats}, for fraction
  8799. display formats.@refill
  8800. Non-decimal fractions are entered and displayed as
  8801. @samp{@var{radix}#@var{num}:@var{denom}} (or in the analogous three-part
  8802. form). The numerator and denominator always use the same radix.@refill
  8803. @node Floats, Complex Numbers, Fractions, Data Types
  8804. @section Floats
  8805. @noindent
  8806. @cindex Floating-point numbers
  8807. A floating-point number or @dfn{float} is a number stored in scientific
  8808. notation. The number of significant digits in the fractional part is
  8809. governed by the current floating precision (@pxref{Precision}). The
  8810. range of acceptable values is from @c{$10^{-3999999}$}
  8811. @cite{10^-3999999} (inclusive)
  8812. to @c{$10^{4000000}$}
  8813. @cite{10^4000000}
  8814. (exclusive), plus the corresponding negative
  8815. values and zero.
  8816. Calculations that would exceed the allowable range of values (such
  8817. as @samp{exp(exp(20))}) are left in symbolic form by Calc. The
  8818. messages ``floating-point overflow'' or ``floating-point underflow''
  8819. indicate that during the calculation a number would have been produced
  8820. that was too large or too close to zero, respectively, to be represented
  8821. by Calc. This does not necessarily mean the final result would have
  8822. overflowed, just that an overflow occurred while computing the result.
  8823. (In fact, it could report an underflow even though the final result
  8824. would have overflowed!)
  8825. If a rational number and a float are mixed in a calculation, the result
  8826. will in general be expressed as a float. Commands that require an integer
  8827. value (such as @kbd{k g} [@code{gcd}]) will also accept integer-valued
  8828. floats, i.e., floating-point numbers with nothing after the decimal point.
  8829. Floats are identified by the presence of a decimal point and/or an
  8830. exponent. In general a float consists of an optional sign, digits
  8831. including an optional decimal point, and an optional exponent consisting
  8832. of an @samp{e}, an optional sign, and up to seven exponent digits.
  8833. For example, @samp{23.5e-2} is 23.5 times ten to the minus-second power,
  8834. or 0.235.
  8835. Floating-point numbers are normally displayed in decimal notation with
  8836. all significant figures shown. Exceedingly large or small numbers are
  8837. displayed in scientific notation. Various other display options are
  8838. available. @xref{Float Formats}.
  8839. @cindex Accuracy of calculations
  8840. Floating-point numbers are stored in decimal, not binary. The result
  8841. of each operation is rounded to the nearest value representable in the
  8842. number of significant digits specified by the current precision,
  8843. rounding away from zero in the case of a tie. Thus (in the default
  8844. display mode) what you see is exactly what you get. Some operations such
  8845. as square roots and transcendental functions are performed with several
  8846. digits of extra precision and then rounded down, in an effort to make the
  8847. final result accurate to the full requested precision. However,
  8848. accuracy is not rigorously guaranteed. If you suspect the validity of a
  8849. result, try doing the same calculation in a higher precision. The
  8850. Calculator's arithmetic is not intended to be IEEE-conformant in any
  8851. way.@refill
  8852. While floats are always @emph{stored} in decimal, they can be entered
  8853. and displayed in any radix just like integers and fractions. The
  8854. notation @samp{@var{radix}#@var{ddd}.@var{ddd}} is a floating-point
  8855. number whose digits are in the specified radix. Note that the @samp{.}
  8856. is more aptly referred to as a ``radix point'' than as a decimal
  8857. point in this case. The number @samp{8#123.4567} is defined as
  8858. @samp{8#1234567 * 8^-4}. If the radix is 14 or less, you can use
  8859. @samp{e} notation to write a non-decimal number in scientific notation.
  8860. The exponent is written in decimal, and is considered to be a power
  8861. of the radix: @samp{8#1234567e-4}. If the radix is 15 or above, the
  8862. letter @samp{e} is a digit, so scientific notation must be written
  8863. out, e.g., @samp{16#123.4567*16^2}. The first two exercises of the
  8864. Modes Tutorial explore some of the properties of non-decimal floats.
  8865. @node Complex Numbers, Infinities, Floats, Data Types
  8866. @section Complex Numbers
  8867. @noindent
  8868. @cindex Complex numbers
  8869. There are two supported formats for complex numbers: rectangular and
  8870. polar. The default format is rectangular, displayed in the form
  8871. @samp{(@var{real},@var{imag})} where @var{real} is the real part and
  8872. @var{imag} is the imaginary part, each of which may be any real number.
  8873. Rectangular complex numbers can also be displayed in @samp{@var{a}+@var{b}i}
  8874. notation; @pxref{Complex Formats}.@refill
  8875. Polar complex numbers are displayed in the form `@t{(}@var{r}@t{;}@c{$\theta$}
  8876. @var{theta}@t{)}'
  8877. where @var{r} is the nonnegative magnitude and @c{$\theta$}
  8878. @var{theta} is the argument
  8879. or phase angle. The range of @c{$\theta$}
  8880. @var{theta} depends on the current angular
  8881. mode (@pxref{Angular Modes}); it is generally between @i{-180} and
  8882. @i{+180} degrees or the equivalent range in radians.@refill
  8883. Complex numbers are entered in stages using incomplete objects.
  8884. @xref{Incomplete Objects}.
  8885. Operations on rectangular complex numbers yield rectangular complex
  8886. results, and similarly for polar complex numbers. Where the two types
  8887. are mixed, or where new complex numbers arise (as for the square root of
  8888. a negative real), the current @dfn{Polar Mode} is used to determine the
  8889. type. @xref{Polar Mode}.
  8890. A complex result in which the imaginary part is zero (or the phase angle
  8891. is 0 or 180 degrees or @c{$\pi$}
  8892. @cite{pi} radians) is automatically converted to a real
  8893. number.
  8894. @node Infinities, Vectors and Matrices, Complex Numbers, Data Types
  8895. @section Infinities
  8896. @noindent
  8897. @cindex Infinity
  8898. @cindex @code{inf} variable
  8899. @cindex @code{uinf} variable
  8900. @cindex @code{nan} variable
  8901. @vindex inf
  8902. @vindex uinf
  8903. @vindex nan
  8904. The word @code{inf} represents the mathematical concept of @dfn{infinity}.
  8905. Calc actually has three slightly different infinity-like values:
  8906. @code{inf}, @code{uinf}, and @code{nan}. These are just regular
  8907. variable names (@pxref{Variables}); you should avoid using these
  8908. names for your own variables because Calc gives them special
  8909. treatment. Infinities, like all variable names, are normally
  8910. entered using algebraic entry.
  8911. Mathematically speaking, it is not rigorously correct to treat
  8912. ``infinity'' as if it were a number, but mathematicians often do
  8913. so informally. When they say that @samp{1 / inf = 0}, what they
  8914. really mean is that @cite{1 / x}, as @cite{x} becomes larger and
  8915. larger, becomes arbitrarily close to zero. So you can imagine
  8916. that if @cite{x} got ``all the way to infinity,'' then @cite{1 / x}
  8917. would go all the way to zero. Similarly, when they say that
  8918. @samp{exp(inf) = inf}, they mean that @c{$e^x$}
  8919. @cite{exp(x)} grows without
  8920. bound as @cite{x} grows. The symbol @samp{-inf} likewise stands
  8921. for an infinitely negative real value; for example, we say that
  8922. @samp{exp(-inf) = 0}. You can have an infinity pointing in any
  8923. direction on the complex plane: @samp{sqrt(-inf) = i inf}.
  8924. The same concept of limits can be used to define @cite{1 / 0}. We
  8925. really want the value that @cite{1 / x} approaches as @cite{x}
  8926. approaches zero. But if all we have is @cite{1 / 0}, we can't
  8927. tell which direction @cite{x} was coming from. If @cite{x} was
  8928. positive and decreasing toward zero, then we should say that
  8929. @samp{1 / 0 = inf}. But if @cite{x} was negative and increasing
  8930. toward zero, the answer is @samp{1 / 0 = -inf}. In fact, @cite{x}
  8931. could be an imaginary number, giving the answer @samp{i inf} or
  8932. @samp{-i inf}. Calc uses the special symbol @samp{uinf} to mean
  8933. @dfn{undirected infinity}, i.e., a value which is infinitely
  8934. large but with an unknown sign (or direction on the complex plane).
  8935. Calc actually has three modes that say how infinities are handled.
  8936. Normally, infinities never arise from calculations that didn't
  8937. already have them. Thus, @cite{1 / 0} is treated simply as an
  8938. error and left unevaluated. The @kbd{m i} (@code{calc-infinite-mode})
  8939. command (@pxref{Infinite Mode}) enables a mode in which
  8940. @cite{1 / 0} evaluates to @code{uinf} instead. There is also
  8941. an alternative type of infinite mode which says to treat zeros
  8942. as if they were positive, so that @samp{1 / 0 = inf}. While this
  8943. is less mathematically correct, it may be the answer you want in
  8944. some cases.
  8945. Since all infinities are ``as large'' as all others, Calc simplifies,
  8946. e.g., @samp{5 inf} to @samp{inf}. Another example is
  8947. @samp{5 - inf = -inf}, where the @samp{-inf} is so large that
  8948. adding a finite number like five to it does not affect it.
  8949. Note that @samp{a - inf} also results in @samp{-inf}; Calc assumes
  8950. that variables like @code{a} always stand for finite quantities.
  8951. Just to show that infinities really are all the same size,
  8952. note that @samp{sqrt(inf) = inf^2 = exp(inf) = inf} in Calc's
  8953. notation.
  8954. It's not so easy to define certain formulas like @samp{0 * inf} and
  8955. @samp{inf / inf}. Depending on where these zeros and infinities
  8956. came from, the answer could be literally anything. The latter
  8957. formula could be the limit of @cite{x / x} (giving a result of one),
  8958. or @cite{2 x / x} (giving two), or @cite{x^2 / x} (giving @code{inf}),
  8959. or @cite{x / x^2} (giving zero). Calc uses the symbol @code{nan}
  8960. to represent such an @dfn{indeterminate} value. (The name ``nan''
  8961. comes from analogy with the ``NAN'' concept of IEEE standard
  8962. arithmetic; it stands for ``Not A Number.'' This is somewhat of a
  8963. misnomer, since @code{nan} @emph{does} stand for some number or
  8964. infinity, it's just that @emph{which} number it stands for
  8965. cannot be determined.) In Calc's notation, @samp{0 * inf = nan}
  8966. and @samp{inf / inf = nan}. A few other common indeterminate
  8967. expressions are @samp{inf - inf} and @samp{inf ^ 0}. Also,
  8968. @samp{0 / 0 = nan} if you have turned on ``infinite mode''
  8969. (as described above).
  8970. Infinities are especially useful as parts of @dfn{intervals}.
  8971. @xref{Interval Forms}.
  8972. @node Vectors and Matrices, Strings, Infinities, Data Types
  8973. @section Vectors and Matrices
  8974. @noindent
  8975. @cindex Vectors
  8976. @cindex Plain vectors
  8977. @cindex Matrices
  8978. The @dfn{vector} data type is flexible and general. A vector is simply a
  8979. list of zero or more data objects. When these objects are numbers, the
  8980. whole is a vector in the mathematical sense. When these objects are
  8981. themselves vectors of equal (nonzero) length, the whole is a @dfn{matrix}.
  8982. A vector which is not a matrix is referred to here as a @dfn{plain vector}.
  8983. A vector is displayed as a list of values separated by commas and enclosed
  8984. in square brackets: @samp{[1, 2, 3]}. Thus the following is a 2 row by
  8985. 3 column matrix: @samp{[[1, 2, 3], [4, 5, 6]]}. Vectors, like complex
  8986. numbers, are entered as incomplete objects. @xref{Incomplete Objects}.
  8987. During algebraic entry, vectors are entered all at once in the usual
  8988. brackets-and-commas form. Matrices may be entered algebraically as nested
  8989. vectors, or using the shortcut notation @w{@samp{[1, 2, 3; 4, 5, 6]}},
  8990. with rows separated by semicolons. The commas may usually be omitted
  8991. when entering vectors: @samp{[1 2 3]}. Curly braces may be used in
  8992. place of brackets: @samp{@{1, 2, 3@}}, but the commas are required in
  8993. this case.
  8994. Traditional vector and matrix arithmetic is also supported;
  8995. @pxref{Basic Arithmetic} and @pxref{Matrix Functions}.
  8996. Many other operations are applied to vectors element-wise. For example,
  8997. the complex conjugate of a vector is a vector of the complex conjugates
  8998. of its elements.@refill
  8999. @ignore
  9000. @starindex
  9001. @end ignore
  9002. @tindex vec
  9003. Algebraic functions for building vectors include @samp{vec(a, b, c)}
  9004. to build @samp{[a, b, c]}, @samp{cvec(a, n, m)} to build an @c{$n\times m$}
  9005. @asis{@var{n}x@var{m}}
  9006. matrix of @samp{a}s, and @samp{index(n)} to build a vector of integers
  9007. from 1 to @samp{n}.
  9008. @node Strings, HMS Forms, Vectors and Matrices, Data Types
  9009. @section Strings
  9010. @noindent
  9011. @kindex "
  9012. @cindex Strings
  9013. @cindex Character strings
  9014. Character strings are not a special data type in the Calculator.
  9015. Rather, a string is represented simply as a vector all of whose
  9016. elements are integers in the range 0 to 255 (ASCII codes). You can
  9017. enter a string at any time by pressing the @kbd{"} key. Quotation
  9018. marks and backslashes are written @samp{\"} and @samp{\\}, respectively,
  9019. inside strings. Other notations introduced by backslashes are:
  9020. @example
  9021. @group
  9022. \a 7 \^@@ 0
  9023. \b 8 \^a-z 1-26
  9024. \e 27 \^[ 27
  9025. \f 12 \^\\ 28
  9026. \n 10 \^] 29
  9027. \r 13 \^^ 30
  9028. \t 9 \^_ 31
  9029. \^? 127
  9030. @end group
  9031. @end example
  9032. @noindent
  9033. Finally, a backslash followed by three octal digits produces any
  9034. character from its ASCII code.
  9035. @kindex d "
  9036. @pindex calc-display-strings
  9037. Strings are normally displayed in vector-of-integers form. The
  9038. @w{@kbd{d "}} (@code{calc-display-strings}) command toggles a mode in
  9039. which any vectors of small integers are displayed as quoted strings
  9040. instead.
  9041. The backslash notations shown above are also used for displaying
  9042. strings. Characters 128 and above are not translated by Calc; unless
  9043. you have an Emacs modified for 8-bit fonts, these will show up in
  9044. backslash-octal-digits notation. For characters below 32, and
  9045. for character 127, Calc uses the backslash-letter combination if
  9046. there is one, or otherwise uses a @samp{\^} sequence.
  9047. The only Calc feature that uses strings is @dfn{compositions};
  9048. @pxref{Compositions}. Strings also provide a convenient
  9049. way to do conversions between ASCII characters and integers.
  9050. @ignore
  9051. @starindex
  9052. @end ignore
  9053. @tindex string
  9054. There is a @code{string} function which provides a different display
  9055. format for strings. Basically, @samp{string(@var{s})}, where @var{s}
  9056. is a vector of integers in the proper range, is displayed as the
  9057. corresponding string of characters with no surrounding quotation
  9058. marks or other modifications. Thus @samp{string("ABC")} (or
  9059. @samp{string([65 66 67])}) will look like @samp{ABC} on the stack.
  9060. This happens regardless of whether @w{@kbd{d "}} has been used. The
  9061. only way to turn it off is to use @kbd{d U} (unformatted language
  9062. mode) which will display @samp{string("ABC")} instead.
  9063. Control characters are displayed somewhat differently by @code{string}.
  9064. Characters below 32, and character 127, are shown using @samp{^} notation
  9065. (same as shown above, but without the backslash). The quote and
  9066. backslash characters are left alone, as are characters 128 and above.
  9067. @ignore
  9068. @starindex
  9069. @end ignore
  9070. @tindex bstring
  9071. The @code{bstring} function is just like @code{string} except that
  9072. the resulting string is breakable across multiple lines if it doesn't
  9073. fit all on one line. Potential break points occur at every space
  9074. character in the string.
  9075. @node HMS Forms, Date Forms, Strings, Data Types
  9076. @section HMS Forms
  9077. @noindent
  9078. @cindex Hours-minutes-seconds forms
  9079. @cindex Degrees-minutes-seconds forms
  9080. @dfn{HMS} stands for Hours-Minutes-Seconds; when used as an angular
  9081. argument, the interpretation is Degrees-Minutes-Seconds. All functions
  9082. that operate on angles accept HMS forms. These are interpreted as
  9083. degrees regardless of the current angular mode. It is also possible to
  9084. use HMS as the angular mode so that calculated angles are expressed in
  9085. degrees, minutes, and seconds.
  9086. @kindex @@
  9087. @ignore
  9088. @mindex @null
  9089. @end ignore
  9090. @kindex ' (HMS forms)
  9091. @ignore
  9092. @mindex @null
  9093. @end ignore
  9094. @kindex " (HMS forms)
  9095. @ignore
  9096. @mindex @null
  9097. @end ignore
  9098. @kindex h (HMS forms)
  9099. @ignore
  9100. @mindex @null
  9101. @end ignore
  9102. @kindex o (HMS forms)
  9103. @ignore
  9104. @mindex @null
  9105. @end ignore
  9106. @kindex m (HMS forms)
  9107. @ignore
  9108. @mindex @null
  9109. @end ignore
  9110. @kindex s (HMS forms)
  9111. The default format for HMS values is
  9112. @samp{@var{hours}@@ @var{mins}' @var{secs}"}. During entry, the letters
  9113. @samp{h} (for ``hours'') or
  9114. @samp{o} (approximating the ``degrees'' symbol) are accepted as well as
  9115. @samp{@@}, @samp{m} is accepted in place of @samp{'}, and @samp{s} is
  9116. accepted in place of @samp{"}.
  9117. The @var{hours} value is an integer (or integer-valued float).
  9118. The @var{mins} value is an integer or integer-valued float between 0 and 59.
  9119. The @var{secs} value is a real number between 0 (inclusive) and 60
  9120. (exclusive). A positive HMS form is interpreted as @var{hours} +
  9121. @var{mins}/60 + @var{secs}/3600. A negative HMS form is interpreted
  9122. as @i{- @var{hours}} @i{-} @var{mins}/60 @i{-} @var{secs}/3600.
  9123. Display format for HMS forms is quite flexible. @xref{HMS Formats}.@refill
  9124. HMS forms can be added and subtracted. When they are added to numbers,
  9125. the numbers are interpreted according to the current angular mode. HMS
  9126. forms can also be multiplied and divided by real numbers. Dividing
  9127. two HMS forms produces a real-valued ratio of the two angles.
  9128. @pindex calc-time
  9129. @cindex Time of day
  9130. Just for kicks, @kbd{M-x calc-time} pushes the current time of day on
  9131. the stack as an HMS form.
  9132. @node Date Forms, Modulo Forms, HMS Forms, Data Types
  9133. @section Date Forms
  9134. @noindent
  9135. @cindex Date forms
  9136. A @dfn{date form} represents a date and possibly an associated time.
  9137. Simple date arithmetic is supported: Adding a number to a date
  9138. produces a new date shifted by that many days; adding an HMS form to
  9139. a date shifts it by that many hours. Subtracting two date forms
  9140. computes the number of days between them (represented as a simple
  9141. number). Many other operations, such as multiplying two date forms,
  9142. are nonsensical and are not allowed by Calc.
  9143. Date forms are entered and displayed enclosed in @samp{< >} brackets.
  9144. The default format is, e.g., @samp{<Wed Jan 9, 1991>} for dates,
  9145. or @samp{<3:32:20pm Wed Jan 9, 1991>} for dates with times.
  9146. Input is flexible; date forms can be entered in any of the usual
  9147. notations for dates and times. @xref{Date Formats}.
  9148. Date forms are stored internally as numbers, specifically the number
  9149. of days since midnight on the morning of January 1 of the year 1 AD.
  9150. If the internal number is an integer, the form represents a date only;
  9151. if the internal number is a fraction or float, the form represents
  9152. a date and time. For example, @samp{<6:00am Wed Jan 9, 1991>}
  9153. is represented by the number 726842.25. The standard precision of
  9154. 12 decimal digits is enough to ensure that a (reasonable) date and
  9155. time can be stored without roundoff error.
  9156. If the current precision is greater than 12, date forms will keep
  9157. additional digits in the seconds position. For example, if the
  9158. precision is 15, the seconds will keep three digits after the
  9159. decimal point. Decreasing the precision below 12 may cause the
  9160. time part of a date form to become inaccurate. This can also happen
  9161. if astronomically high years are used, though this will not be an
  9162. issue in everyday (or even everymillenium) use. Note that date
  9163. forms without times are stored as exact integers, so roundoff is
  9164. never an issue for them.
  9165. You can use the @kbd{v p} (@code{calc-pack}) and @kbd{v u}
  9166. (@code{calc-unpack}) commands to get at the numerical representation
  9167. of a date form. @xref{Packing and Unpacking}.
  9168. Date forms can go arbitrarily far into the future or past. Negative
  9169. year numbers represent years BC. Calc uses a combination of the
  9170. Gregorian and Julian calendars, following the history of Great
  9171. Britain and the British colonies. This is the same calendar that
  9172. is used by the @code{cal} program in most Unix implementations.
  9173. @cindex Julian calendar
  9174. @cindex Gregorian calendar
  9175. Some historical background: The Julian calendar was created by
  9176. Julius Caesar in the year 46 BC as an attempt to fix the gradual
  9177. drift caused by the lack of leap years in the calendar used
  9178. until that time. The Julian calendar introduced an extra day in
  9179. all years divisible by four. After some initial confusion, the
  9180. calendar was adopted around the year we call 8 AD. Some centuries
  9181. later it became apparent that the Julian year of 365.25 days was
  9182. itself not quite right. In 1582 Pope Gregory XIII introduced the
  9183. Gregorian calendar, which added the new rule that years divisible
  9184. by 100, but not by 400, were not to be considered leap years
  9185. despite being divisible by four. Many countries delayed adoption
  9186. of the Gregorian calendar because of religious differences;
  9187. in Britain it was put off until the year 1752, by which time
  9188. the Julian calendar had fallen eleven days behind the true
  9189. seasons. So the switch to the Gregorian calendar in early
  9190. September 1752 introduced a discontinuity: The day after
  9191. Sep 2, 1752 is Sep 14, 1752. Calc follows this convention.
  9192. To take another example, Russia waited until 1918 before
  9193. adopting the new calendar, and thus needed to remove thirteen
  9194. days (between Feb 1, 1918 and Feb 14, 1918). This means that
  9195. Calc's reckoning will be inconsistent with Russian history between
  9196. 1752 and 1918, and similarly for various other countries.
  9197. Today's timekeepers introduce an occasional ``leap second'' as
  9198. well, but Calc does not take these minor effects into account.
  9199. (If it did, it would have to report a non-integer number of days
  9200. between, say, @samp{<12:00am Mon Jan 1, 1900>} and
  9201. @samp{<12:00am Sat Jan 1, 2000>}.)
  9202. Calc uses the Julian calendar for all dates before the year 1752,
  9203. including dates BC when the Julian calendar technically had not
  9204. yet been invented. Thus the claim that day number @i{-10000} is
  9205. called ``August 16, 28 BC'' should be taken with a grain of salt.
  9206. Please note that there is no ``year 0''; the day before
  9207. @samp{<Sat Jan 1, +1>} is @samp{<Fri Dec 31, -1>}. These are
  9208. days 0 and @i{-1} respectively in Calc's internal numbering scheme.
  9209. @cindex Julian day counting
  9210. Another day counting system in common use is, confusingly, also
  9211. called ``Julian.'' It was invented in 1583 by Joseph Justus
  9212. Scaliger, who named it in honor of his father Julius Caesar
  9213. Scaliger. For obscure reasons he chose to start his day
  9214. numbering on Jan 1, 4713 BC at noon, which in Calc's scheme
  9215. is @i{-1721423.5} (recall that Calc starts at midnight instead
  9216. of noon). Thus to convert a Calc date code obtained by
  9217. unpacking a date form into a Julian day number, simply add
  9218. 1721423.5. The Julian code for @samp{6:00am Jan 9, 1991}
  9219. is 2448265.75. The built-in @kbd{t J} command performs
  9220. this conversion for you.
  9221. @cindex Unix time format
  9222. The Unix operating system measures time as an integer number of
  9223. seconds since midnight, Jan 1, 1970. To convert a Calc date
  9224. value into a Unix time stamp, first subtract 719164 (the code
  9225. for @samp{<Jan 1, 1970>}), then multiply by 86400 (the number of
  9226. seconds in a day) and press @kbd{R} to round to the nearest
  9227. integer. If you have a date form, you can simply subtract the
  9228. day @samp{<Jan 1, 1970>} instead of unpacking and subtracting
  9229. 719164. Likewise, divide by 86400 and add @samp{<Jan 1, 1970>}
  9230. to convert from Unix time to a Calc date form. (Note that
  9231. Unix normally maintains the time in the GMT time zone; you may
  9232. need to subtract five hours to get New York time, or eight hours
  9233. for California time. The same is usually true of Julian day
  9234. counts.) The built-in @kbd{t U} command performs these
  9235. conversions.
  9236. @node Modulo Forms, Error Forms, Date Forms, Data Types
  9237. @section Modulo Forms
  9238. @noindent
  9239. @cindex Modulo forms
  9240. A @dfn{modulo form} is a real number which is taken modulo (i.e., within
  9241. an integer multiple of) some value @var{M}. Arithmetic modulo @var{M}
  9242. often arises in number theory. Modulo forms are written
  9243. `@var{a} @t{mod} @var{M}',
  9244. where @var{a} and @var{M} are real numbers or HMS forms, and
  9245. @c{$0 \le a < M$}
  9246. @cite{0 <= a < @var{M}}.
  9247. In many applications @cite{a} and @cite{M} will be
  9248. integers but this is not required.@refill
  9249. Modulo forms are not to be confused with the modulo operator @samp{%}.
  9250. The expression @samp{27 % 10} means to compute 27 modulo 10 to produce
  9251. the result 7. Further computations treat this 7 as just a regular integer.
  9252. The expression @samp{27 mod 10} produces the result @samp{7 mod 10};
  9253. further computations with this value are again reduced modulo 10 so that
  9254. the result always lies in the desired range.
  9255. When two modulo forms with identical @cite{M}'s are added or multiplied,
  9256. the Calculator simply adds or multiplies the values, then reduces modulo
  9257. @cite{M}. If one argument is a modulo form and the other a plain number,
  9258. the plain number is treated like a compatible modulo form. It is also
  9259. possible to raise modulo forms to powers; the result is the value raised
  9260. to the power, then reduced modulo @cite{M}. (When all values involved
  9261. are integers, this calculation is done much more efficiently than
  9262. actually computing the power and then reducing.)
  9263. @cindex Modulo division
  9264. Two modulo forms `@var{a} @t{mod} @var{M}' and `@var{b} @t{mod} @var{M}'
  9265. can be divided if @cite{a}, @cite{b}, and @cite{M} are all
  9266. integers. The result is the modulo form which, when multiplied by
  9267. `@var{b} @t{mod} @var{M}', produces `@var{a} @t{mod} @var{M}'. If
  9268. there is no solution to this equation (which can happen only when
  9269. @cite{M} is non-prime), or if any of the arguments are non-integers, the
  9270. division is left in symbolic form. Other operations, such as square
  9271. roots, are not yet supported for modulo forms. (Note that, although
  9272. @w{`@t{(}@var{a} @t{mod} @var{M}@t{)^.5}'} will compute a ``modulo square root''
  9273. in the sense of reducing @c{$\sqrt a$}
  9274. @cite{sqrt(a)} modulo @cite{M}, this is not a
  9275. useful definition from the number-theoretical point of view.)@refill
  9276. @ignore
  9277. @mindex M
  9278. @end ignore
  9279. @kindex M (modulo forms)
  9280. @ignore
  9281. @mindex mod
  9282. @end ignore
  9283. @tindex mod (operator)
  9284. To create a modulo form during numeric entry, press the shift-@kbd{M}
  9285. key to enter the word @samp{mod}. As a special convenience, pressing
  9286. shift-@kbd{M} a second time automatically enters the value of @cite{M}
  9287. that was most recently used before. During algebraic entry, either
  9288. type @samp{mod} by hand or press @kbd{M-m} (that's @kbd{@key{META}-m}).
  9289. Once again, pressing this a second time enters the current modulo.@refill
  9290. You can also use @kbd{v p} and @kbd{%} to modify modulo forms.
  9291. @xref{Building Vectors}. @xref{Basic Arithmetic}.
  9292. It is possible to mix HMS forms and modulo forms. For example, an
  9293. HMS form modulo 24 could be used to manipulate clock times; an HMS
  9294. form modulo 360 would be suitable for angles. Making the modulo @cite{M}
  9295. also be an HMS form eliminates troubles that would arise if the angular
  9296. mode were inadvertently set to Radians, in which case
  9297. @w{@samp{2@@ 0' 0" mod 24}} would be interpreted as two degrees modulo
  9298. 24 radians!
  9299. Modulo forms cannot have variables or formulas for components. If you
  9300. enter the formula @samp{(x + 2) mod 5}, Calc propagates the modulus
  9301. to each of the coefficients: @samp{(1 mod 5) x + (2 mod 5)}.
  9302. @ignore
  9303. @starindex
  9304. @end ignore
  9305. @tindex makemod
  9306. The algebraic function @samp{makemod(a, m)} builds the modulo form
  9307. @w{@samp{a mod m}}.
  9308. @node Error Forms, Interval Forms, Modulo Forms, Data Types
  9309. @section Error Forms
  9310. @noindent
  9311. @cindex Error forms
  9312. @cindex Standard deviations
  9313. An @dfn{error form} is a number with an associated standard
  9314. deviation, as in @samp{2.3 +/- 0.12}. The notation
  9315. `@var{x} @t{+/-} @c{$\sigma$}
  9316. @asis{sigma}' stands for an uncertain value which follows a normal or
  9317. Gaussian distribution of mean @cite{x} and standard deviation or
  9318. ``error'' @c{$\sigma$}
  9319. @cite{sigma}. Both the mean and the error can be either numbers or
  9320. formulas. Generally these are real numbers but the mean may also be
  9321. complex. If the error is negative or complex, it is changed to its
  9322. absolute value. An error form with zero error is converted to a
  9323. regular number by the Calculator.@refill
  9324. All arithmetic and transcendental functions accept error forms as input.
  9325. Operations on the mean-value part work just like operations on regular
  9326. numbers. The error part for any function @cite{f(x)} (such as @c{$\sin x$}
  9327. @cite{sin(x)})
  9328. is defined by the error of @cite{x} times the derivative of @cite{f}
  9329. evaluated at the mean value of @cite{x}. For a two-argument function
  9330. @cite{f(x,y)} (such as addition) the error is the square root of the sum
  9331. of the squares of the errors due to @cite{x} and @cite{y}.
  9332. @tex
  9333. $$ \eqalign{
  9334. f(x \hbox{\code{ +/- }} \sigma)
  9335. &= f(x) \hbox{\code{ +/- }} \sigma \left| {df(x) \over dx} \right| \cr
  9336. f(x \hbox{\code{ +/- }} \sigma_x, y \hbox{\code{ +/- }} \sigma_y)
  9337. &= f(x,y) \hbox{\code{ +/- }}
  9338. \sqrt{\left(\sigma_x \left| {\partial f(x,y) \over \partial x}
  9339. \right| \right)^2
  9340. +\left(\sigma_y \left| {\partial f(x,y) \over \partial y}
  9341. \right| \right)^2 } \cr
  9342. } $$
  9343. @end tex
  9344. Note that this
  9345. definition assumes the errors in @cite{x} and @cite{y} are uncorrelated.
  9346. A side effect of this definition is that @samp{(2 +/- 1) * (2 +/- 1)}
  9347. is not the same as @samp{(2 +/- 1)^2}; the former represents the product
  9348. of two independent values which happen to have the same probability
  9349. distributions, and the latter is the product of one random value with itself.
  9350. The former will produce an answer with less error, since on the average
  9351. the two independent errors can be expected to cancel out.@refill
  9352. Consult a good text on error analysis for a discussion of the proper use
  9353. of standard deviations. Actual errors often are neither Gaussian-distributed
  9354. nor uncorrelated, and the above formulas are valid only when errors
  9355. are small. As an example, the error arising from
  9356. `@t{sin(}@var{x} @t{+/-} @c{$\sigma$}
  9357. @var{sigma}@t{)}' is
  9358. `@c{$\sigma$\nobreak}
  9359. @var{sigma} @t{abs(cos(}@var{x}@t{))}'. When @cite{x} is close to zero,
  9360. @c{$\cos x$}
  9361. @cite{cos(x)} is
  9362. close to one so the error in the sine is close to @c{$\sigma$}
  9363. @cite{sigma}; this makes sense, since @c{$\sin x$}
  9364. @cite{sin(x)} is approximately @cite{x} near zero, so a given
  9365. error in @cite{x} will produce about the same error in the sine. Likewise,
  9366. near 90 degrees @c{$\cos x$}
  9367. @cite{cos(x)} is nearly zero and so the computed error is
  9368. small: The sine curve is nearly flat in that region, so an error in @cite{x}
  9369. has relatively little effect on the value of @c{$\sin x$}
  9370. @cite{sin(x)}. However, consider
  9371. @samp{sin(90 +/- 1000)}. The cosine of 90 is zero, so Calc will report
  9372. zero error! We get an obviously wrong result because we have violated
  9373. the small-error approximation underlying the error analysis. If the error
  9374. in @cite{x} had been small, the error in @c{$\sin x$}
  9375. @cite{sin(x)} would indeed have been negligible.@refill
  9376. @ignore
  9377. @mindex p
  9378. @end ignore
  9379. @kindex p (error forms)
  9380. @tindex +/-
  9381. To enter an error form during regular numeric entry, use the @kbd{p}
  9382. (``plus-or-minus'') key to type the @samp{+/-} symbol. (If you try actually
  9383. typing @samp{+/-} the @kbd{+} key will be interpreted as the Calculator's
  9384. @kbd{+} command!) Within an algebraic formula, you can press @kbd{M-p} to
  9385. type the @samp{+/-} symbol, or type it out by hand.
  9386. Error forms and complex numbers can be mixed; the formulas shown above
  9387. are used for complex numbers, too; note that if the error part evaluates
  9388. to a complex number its absolute value (or the square root of the sum of
  9389. the squares of the absolute values of the two error contributions) is
  9390. used. Mathematically, this corresponds to a radially symmetric Gaussian
  9391. distribution of numbers on the complex plane. However, note that Calc
  9392. considers an error form with real components to represent a real number,
  9393. not a complex distribution around a real mean.
  9394. Error forms may also be composed of HMS forms. For best results, both
  9395. the mean and the error should be HMS forms if either one is.
  9396. @ignore
  9397. @starindex
  9398. @end ignore
  9399. @tindex sdev
  9400. The algebraic function @samp{sdev(a, b)} builds the error form @samp{a +/- b}.
  9401. @node Interval Forms, Incomplete Objects, Error Forms, Data Types
  9402. @section Interval Forms
  9403. @noindent
  9404. @cindex Interval forms
  9405. An @dfn{interval} is a subset of consecutive real numbers. For example,
  9406. the interval @samp{[2 ..@: 4]} represents all the numbers from 2 to 4,
  9407. inclusive. If you multiply it by the interval @samp{[0.5 ..@: 2]} you
  9408. obtain @samp{[1 ..@: 8]}. This calculation represents the fact that if
  9409. you multiply some number in the range @samp{[2 ..@: 4]} by some other
  9410. number in the range @samp{[0.5 ..@: 2]}, your result will lie in the range
  9411. from 1 to 8. Interval arithmetic is used to get a worst-case estimate
  9412. of the possible range of values a computation will produce, given the
  9413. set of possible values of the input.
  9414. @ifinfo
  9415. Calc supports several varieties of intervals, including @dfn{closed}
  9416. intervals of the type shown above, @dfn{open} intervals such as
  9417. @samp{(2 ..@: 4)}, which represents the range of numbers from 2 to 4
  9418. @emph{exclusive}, and @dfn{semi-open} intervals in which one end
  9419. uses a round parenthesis and the other a square bracket. In mathematical
  9420. terms,
  9421. @samp{[2 ..@: 4]} means @cite{2 <= x <= 4}, whereas
  9422. @samp{[2 ..@: 4)} represents @cite{2 <= x < 4},
  9423. @samp{(2 ..@: 4]} represents @cite{2 < x <= 4}, and
  9424. @samp{(2 ..@: 4)} represents @cite{2 < x < 4}.@refill
  9425. @end ifinfo
  9426. @tex
  9427. Calc supports several varieties of intervals, including \dfn{closed}
  9428. intervals of the type shown above, \dfn{open} intervals such as
  9429. \samp{(2 ..\: 4)}, which represents the range of numbers from 2 to 4
  9430. \emph{exclusive}, and \dfn{semi-open} intervals in which one end
  9431. uses a round parenthesis and the other a square bracket. In mathematical
  9432. terms,
  9433. $$ \eqalign{
  9434. [2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 \le x \le 4 \cr
  9435. [2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 \le x < 4 \cr
  9436. (2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 < x \le 4 \cr
  9437. (2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 < x < 4 \cr
  9438. } $$
  9439. @end tex
  9440. The lower and upper limits of an interval must be either real numbers
  9441. (or HMS or date forms), or symbolic expressions which are assumed to be
  9442. real-valued, or @samp{-inf} and @samp{inf}. In general the lower limit
  9443. must be less than the upper limit. A closed interval containing only
  9444. one value, @samp{[3 ..@: 3]}, is converted to a plain number (3)
  9445. automatically. An interval containing no values at all (such as
  9446. @samp{[3 ..@: 2]} or @samp{[2 ..@: 2)}) can be represented but is not
  9447. guaranteed to behave well when used in arithmetic. Note that the
  9448. interval @samp{[3 .. inf)} represents all real numbers greater than
  9449. or equal to 3, and @samp{(-inf .. inf)} represents all real numbers.
  9450. In fact, @samp{[-inf .. inf]} represents all real numbers including
  9451. the real infinities.
  9452. Intervals are entered in the notation shown here, either as algebraic
  9453. formulas, or using incomplete forms. (@xref{Incomplete Objects}.)
  9454. In algebraic formulas, multiple periods in a row are collected from
  9455. left to right, so that @samp{1...1e2} is interpreted as @samp{1.0 ..@: 1e2}
  9456. rather than @samp{1 ..@: 0.1e2}. Add spaces or zeros if you want to
  9457. get the other interpretation. If you omit the lower or upper limit,
  9458. a default of @samp{-inf} or @samp{inf} (respectively) is furnished.
  9459. ``Infinite mode'' also affects operations on intervals
  9460. (@pxref{Infinities}). Calc will always introduce an open infinity,
  9461. as in @samp{1 / (0 .. 2] = [0.5 .. inf)}. But closed infinities,
  9462. @w{@samp{1 / [0 .. 2] = [0.5 .. inf]}}, arise only in infinite mode;
  9463. otherwise they are left unevaluated. Note that the ``direction'' of
  9464. a zero is not an issue in this case since the zero is always assumed
  9465. to be continuous with the rest of the interval. For intervals that
  9466. contain zero inside them Calc is forced to give the result,
  9467. @samp{1 / (-2 .. 2) = [-inf .. inf]}.
  9468. While it may seem that intervals and error forms are similar, they are
  9469. based on entirely different concepts of inexact quantities. An error
  9470. form `@var{x} @t{+/-} @c{$\sigma$}
  9471. @var{sigma}' means a variable is random, and its value could
  9472. be anything but is ``probably'' within one @c{$\sigma$}
  9473. @var{sigma} of the mean value @cite{x}.
  9474. An interval `@t{[}@var{a} @t{..@:} @var{b}@t{]}' means a variable's value
  9475. is unknown, but guaranteed to lie in the specified range. Error forms
  9476. are statistical or ``average case'' approximations; interval arithmetic
  9477. tends to produce ``worst case'' bounds on an answer.@refill
  9478. Intervals may not contain complex numbers, but they may contain
  9479. HMS forms or date forms.
  9480. @xref{Set Operations}, for commands that interpret interval forms
  9481. as subsets of the set of real numbers.
  9482. @ignore
  9483. @starindex
  9484. @end ignore
  9485. @tindex intv
  9486. The algebraic function @samp{intv(n, a, b)} builds an interval form
  9487. from @samp{a} to @samp{b}; @samp{n} is an integer code which must
  9488. be 0 for @samp{(..)}, 1 for @samp{(..]}, 2 for @samp{[..)}, or
  9489. 3 for @samp{[..]}.
  9490. Please note that in fully rigorous interval arithmetic, care would be
  9491. taken to make sure that the computation of the lower bound rounds toward
  9492. minus infinity, while upper bound computations round toward plus
  9493. infinity. Calc's arithmetic always uses a round-to-nearest mode,
  9494. which means that roundoff errors could creep into an interval
  9495. calculation to produce intervals slightly smaller than they ought to
  9496. be. For example, entering @samp{[1..2]} and pressing @kbd{Q 2 ^}
  9497. should yield the interval @samp{[1..2]} again, but in fact it yields the
  9498. (slightly too small) interval @samp{[1..1.9999999]} due to roundoff
  9499. error.
  9500. @node Incomplete Objects, Variables, Interval Forms, Data Types
  9501. @section Incomplete Objects
  9502. @noindent
  9503. @ignore
  9504. @mindex [ ]
  9505. @end ignore
  9506. @kindex [
  9507. @ignore
  9508. @mindex ( )
  9509. @end ignore
  9510. @kindex (
  9511. @kindex ,
  9512. @ignore
  9513. @mindex @null
  9514. @end ignore
  9515. @kindex ]
  9516. @ignore
  9517. @mindex @null
  9518. @end ignore
  9519. @kindex )
  9520. @cindex Incomplete vectors
  9521. @cindex Incomplete complex numbers
  9522. @cindex Incomplete interval forms
  9523. When @kbd{(} or @kbd{[} is typed to begin entering a complex number or
  9524. vector, respectively, the effect is to push an @dfn{incomplete} complex
  9525. number or vector onto the stack. The @kbd{,} key adds the value(s) at
  9526. the top of the stack onto the current incomplete object. The @kbd{)}
  9527. and @kbd{]} keys ``close'' the incomplete object after adding any values
  9528. on the top of the stack in front of the incomplete object.
  9529. As a result, the sequence of keystrokes @kbd{[ 2 , 3 @key{RET} 2 * , 9 ]}
  9530. pushes the vector @samp{[2, 6, 9]} onto the stack. Likewise, @kbd{( 1 , 2 Q )}
  9531. pushes the complex number @samp{(1, 1.414)} (approximately).
  9532. If several values lie on the stack in front of the incomplete object,
  9533. all are collected and appended to the object. Thus the @kbd{,} key
  9534. is redundant: @kbd{[ 2 @key{RET} 3 @key{RET} 2 * 9 ]}. Some people
  9535. prefer the equivalent @key{SPC} key to @key{RET}.@refill
  9536. As a special case, typing @kbd{,} immediately after @kbd{(}, @kbd{[}, or
  9537. @kbd{,} adds a zero or duplicates the preceding value in the list being
  9538. formed. Typing @key{DEL} during incomplete entry removes the last item
  9539. from the list.
  9540. @kindex ;
  9541. The @kbd{;} key is used in the same way as @kbd{,} to create polar complex
  9542. numbers: @kbd{( 1 ; 2 )}. When entering a vector, @kbd{;} is useful for
  9543. creating a matrix. In particular, @kbd{[ [ 1 , 2 ; 3 , 4 ; 5 , 6 ] ]} is
  9544. equivalent to @kbd{[ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ]}.
  9545. @kindex ..
  9546. @pindex calc-dots
  9547. Incomplete entry is also used to enter intervals. For example,
  9548. @kbd{[ 2 ..@: 4 )} enters a semi-open interval. Note that when you type
  9549. the first period, it will be interpreted as a decimal point, but when
  9550. you type a second period immediately afterward, it is re-interpreted as
  9551. part of the interval symbol. Typing @kbd{..} corresponds to executing
  9552. the @code{calc-dots} command.
  9553. If you find incomplete entry distracting, you may wish to enter vectors
  9554. and complex numbers as algebraic formulas by pressing the apostrophe key.
  9555. @node Variables, Formulas, Incomplete Objects, Data Types
  9556. @section Variables
  9557. @noindent
  9558. @cindex Variables, in formulas
  9559. A @dfn{variable} is somewhere between a storage register on a conventional
  9560. calculator, and a variable in a programming language. (In fact, a Calc
  9561. variable is really just an Emacs Lisp variable that contains a Calc number
  9562. or formula.) A variable's name is normally composed of letters and digits.
  9563. Calc also allows apostrophes and @code{#} signs in variable names.
  9564. The Calc variable @code{foo} corresponds to the Emacs Lisp variable
  9565. @code{var-foo}. Commands like @kbd{s s} (@code{calc-store}) that operate
  9566. on variables can be made to use any arbitrary Lisp variable simply by
  9567. backspacing over the @samp{var-} prefix in the minibuffer.@refill
  9568. In a command that takes a variable name, you can either type the full
  9569. name of a variable, or type a single digit to use one of the special
  9570. convenience variables @code{var-q0} through @code{var-q9}. For example,
  9571. @kbd{3 s s 2} stores the number 3 in variable @code{var-q2}, and
  9572. @w{@kbd{3 s s foo @key{RET}}} stores that number in variable
  9573. @code{var-foo}.@refill
  9574. To push a variable itself (as opposed to the variable's value) on the
  9575. stack, enter its name as an algebraic expression using the apostrophe
  9576. (@key{'}) key. Variable names in algebraic formulas implicitly have
  9577. @samp{var-} prefixed to their names. The @samp{#} character in variable
  9578. names used in algebraic formulas corresponds to a dash @samp{-} in the
  9579. Lisp variable name. If the name contains any dashes, the prefix @samp{var-}
  9580. is @emph{not} automatically added. Thus the two formulas @samp{foo + 1}
  9581. and @samp{var#foo + 1} both refer to the same variable.
  9582. @kindex =
  9583. @pindex calc-evaluate
  9584. @cindex Evaluation of variables in a formula
  9585. @cindex Variables, evaluation
  9586. @cindex Formulas, evaluation
  9587. The @kbd{=} (@code{calc-evaluate}) key ``evaluates'' a formula by
  9588. replacing all variables in the formula which have been given values by a
  9589. @code{calc-store} or @code{calc-let} command by their stored values.
  9590. Other variables are left alone. Thus a variable that has not been
  9591. stored acts like an abstract variable in algebra; a variable that has
  9592. been stored acts more like a register in a traditional calculator.
  9593. With a positive numeric prefix argument, @kbd{=} evaluates the top
  9594. @var{n} stack entries; with a negative argument, @kbd{=} evaluates
  9595. the @var{n}th stack entry.
  9596. @cindex @code{e} variable
  9597. @cindex @code{pi} variable
  9598. @cindex @code{i} variable
  9599. @cindex @code{phi} variable
  9600. @cindex @code{gamma} variable
  9601. @vindex e
  9602. @vindex pi
  9603. @vindex i
  9604. @vindex phi
  9605. @vindex gamma
  9606. A few variables are called @dfn{special constants}. Their names are
  9607. @samp{e}, @samp{pi}, @samp{i}, @samp{phi}, and @samp{gamma}.
  9608. (@xref{Scientific Functions}.) When they are evaluated with @kbd{=},
  9609. their values are calculated if necessary according to the current precision
  9610. or complex polar mode. If you wish to use these symbols for other purposes,
  9611. simply undefine or redefine them using @code{calc-store}.@refill
  9612. The variables @samp{inf}, @samp{uinf}, and @samp{nan} stand for
  9613. infinite or indeterminate values. It's best not to use them as
  9614. regular variables, since Calc uses special algebraic rules when
  9615. it manipulates them. Calc displays a warning message if you store
  9616. a value into any of these special variables.
  9617. @xref{Store and Recall}, for a discussion of commands dealing with variables.
  9618. @node Formulas, , Variables, Data Types
  9619. @section Formulas
  9620. @noindent
  9621. @cindex Formulas
  9622. @cindex Expressions
  9623. @cindex Operators in formulas
  9624. @cindex Precedence of operators
  9625. When you press the apostrophe key you may enter any expression or formula
  9626. in algebraic form. (Calc uses the terms ``expression'' and ``formula''
  9627. interchangeably.) An expression is built up of numbers, variable names,
  9628. and function calls, combined with various arithmetic operators.
  9629. Parentheses may
  9630. be used to indicate grouping. Spaces are ignored within formulas, except
  9631. that spaces are not permitted within variable names or numbers.
  9632. Arithmetic operators, in order from highest to lowest precedence, and
  9633. with their equivalent function names, are:
  9634. @samp{_} [@code{subscr}] (subscripts);
  9635. postfix @samp{%} [@code{percent}] (as in @samp{25% = 0.25});
  9636. prefix @samp{+} and @samp{-} [@code{neg}] (as in @samp{-x})
  9637. and prefix @samp{!} [@code{lnot}] (logical ``not,'' as in @samp{!x});
  9638. @samp{+/-} [@code{sdev}] (the standard deviation symbol) and
  9639. @samp{mod} [@code{makemod}] (the symbol for modulo forms);
  9640. postfix @samp{!} [@code{fact}] (factorial, as in @samp{n!})
  9641. and postfix @samp{!!} [@code{dfact}] (double factorial);
  9642. @samp{^} [@code{pow}] (raised-to-the-power-of);
  9643. @samp{*} [@code{mul}];
  9644. @samp{/} [@code{div}], @samp{%} [@code{mod}] (modulo), and
  9645. @samp{\} [@code{idiv}] (integer division);
  9646. infix @samp{+} [@code{add}] and @samp{-} [@code{sub}] (as in @samp{x-y});
  9647. @samp{|} [@code{vconcat}] (vector concatenation);
  9648. relations @samp{=} [@code{eq}], @samp{!=} [@code{neq}], @samp{<} [@code{lt}],
  9649. @samp{>} [@code{gt}], @samp{<=} [@code{leq}], and @samp{>=} [@code{geq}];
  9650. @samp{&&} [@code{land}] (logical ``and'');
  9651. @samp{||} [@code{lor}] (logical ``or'');
  9652. the C-style ``if'' operator @samp{a?b:c} [@code{if}];
  9653. @samp{!!!} [@code{pnot}] (rewrite pattern ``not'');
  9654. @samp{&&&} [@code{pand}] (rewrite pattern ``and'');
  9655. @samp{|||} [@code{por}] (rewrite pattern ``or'');
  9656. @samp{:=} [@code{assign}] (for assignments and rewrite rules);
  9657. @samp{::} [@code{condition}] (rewrite pattern condition);
  9658. @samp{=>} [@code{evalto}].
  9659. Note that, unlike in usual computer notation, multiplication binds more
  9660. strongly than division: @samp{a*b/c*d} is equivalent to @c{$a b \over c d$}
  9661. @cite{(a*b)/(c*d)}.
  9662. @cindex Multiplication, implicit
  9663. @cindex Implicit multiplication
  9664. The multiplication sign @samp{*} may be omitted in many cases. In particular,
  9665. if the righthand side is a number, variable name, or parenthesized
  9666. expression, the @samp{*} may be omitted. Implicit multiplication has the
  9667. same precedence as the explicit @samp{*} operator. The one exception to
  9668. the rule is that a variable name followed by a parenthesized expression,
  9669. as in @samp{f(x)},
  9670. is interpreted as a function call, not an implicit @samp{*}. In many
  9671. cases you must use a space if you omit the @samp{*}: @samp{2a} is the
  9672. same as @samp{2*a}, and @samp{a b} is the same as @samp{a*b}, but @samp{ab}
  9673. is a variable called @code{ab}, @emph{not} the product of @samp{a} and
  9674. @samp{b}! Also note that @samp{f (x)} is still a function call.@refill
  9675. @cindex Implicit comma in vectors
  9676. The rules are slightly different for vectors written with square brackets.
  9677. In vectors, the space character is interpreted (like the comma) as a
  9678. separator of elements of the vector. Thus @w{@samp{[ 2a b+c d ]}} is
  9679. equivalent to @samp{[2*a, b+c, d]}, whereas @samp{2a b+c d} is equivalent
  9680. to @samp{2*a*b + c*d}.
  9681. Note that spaces around the brackets, and around explicit commas, are
  9682. ignored. To force spaces to be interpreted as multiplication you can
  9683. enclose a formula in parentheses as in @samp{[(a b) 2(c d)]}, which is
  9684. interpreted as @samp{[a*b, 2*c*d]}. An implicit comma is also inserted
  9685. between @samp{][}, as in the matrix @samp{[[1 2][3 4]]}.@refill
  9686. Vectors that contain commas (not embedded within nested parentheses or
  9687. brackets) do not treat spaces specially: @samp{[a b, 2 c d]} is a vector
  9688. of two elements. Also, if it would be an error to treat spaces as
  9689. separators, but not otherwise, then Calc will ignore spaces:
  9690. @w{@samp{[a - b]}} is a vector of one element, but @w{@samp{[a -b]}} is
  9691. a vector of two elements. Finally, vectors entered with curly braces
  9692. instead of square brackets do not give spaces any special treatment.
  9693. When Calc displays a vector that does not contain any commas, it will
  9694. insert parentheses if necessary to make the meaning clear:
  9695. @w{@samp{[(a b)]}}.
  9696. The expression @samp{5%-2} is ambiguous; is this five-percent minus two,
  9697. or five modulo minus-two? Calc always interprets the leftmost symbol as
  9698. an infix operator preferentially (modulo, in this case), so you would
  9699. need to write @samp{(5%)-2} to get the former interpretation.
  9700. @cindex Function call notation
  9701. A function call is, e.g., @samp{sin(1+x)}. Function names follow the same
  9702. rules as variable names except that the default prefix @samp{calcFunc-} is
  9703. used (instead of @samp{var-}) for the internal Lisp form.
  9704. Most mathematical Calculator commands like
  9705. @code{calc-sin} have function equivalents like @code{sin}.
  9706. If no Lisp function is defined for a function called by a formula, the
  9707. call is left as it is during algebraic manipulation: @samp{f(x+y)} is
  9708. left alone. Beware that many innocent-looking short names like @code{in}
  9709. and @code{re} have predefined meanings which could surprise you; however,
  9710. single letters or single letters followed by digits are always safe to
  9711. use for your own function names. @xref{Function Index}.@refill
  9712. In the documentation for particular commands, the notation @kbd{H S}
  9713. (@code{calc-sinh}) [@code{sinh}] means that the key sequence @kbd{H S}, the
  9714. command @kbd{M-x calc-sinh}, and the algebraic function @code{sinh(x)} all
  9715. represent the same operation.@refill
  9716. Commands that interpret (``parse'') text as algebraic formulas include
  9717. algebraic entry (@kbd{'}), editing commands like @kbd{`} which parse
  9718. the contents of the editing buffer when you finish, the @kbd{M-# g}
  9719. and @w{@kbd{M-# r}} commands, the @kbd{C-y} command, the X window system
  9720. ``paste'' mouse operation, and Embedded Mode. All of these operations
  9721. use the same rules for parsing formulas; in particular, language modes
  9722. (@pxref{Language Modes}) affect them all in the same way.
  9723. When you read a large amount of text into the Calculator (say a vector
  9724. which represents a big set of rewrite rules; @pxref{Rewrite Rules}),
  9725. you may wish to include comments in the text. Calc's formula parser
  9726. ignores the symbol @samp{%%} and anything following it on a line:
  9727. @example
  9728. [ a + b, %% the sum of "a" and "b"
  9729. c + d,
  9730. %% last line is coming up:
  9731. e + f ]
  9732. @end example
  9733. @noindent
  9734. This is parsed exactly the same as @samp{[ a + b, c + d, e + f ]}.
  9735. @xref{Syntax Tables}, for a way to create your own operators and other
  9736. input notations. @xref{Compositions}, for a way to create new display
  9737. formats.
  9738. @xref{Algebra}, for commands for manipulating formulas symbolically.
  9739. @node Stack and Trail, Mode Settings, Data Types, Top
  9740. @chapter Stack and Trail Commands
  9741. @noindent
  9742. This chapter describes the Calc commands for manipulating objects on the
  9743. stack and in the trail buffer. (These commands operate on objects of any
  9744. type, such as numbers, vectors, formulas, and incomplete objects.)
  9745. @menu
  9746. * Stack Manipulation::
  9747. * Editing Stack Entries::
  9748. * Trail Commands::
  9749. * Keep Arguments::
  9750. @end menu
  9751. @node Stack Manipulation, Editing Stack Entries, Stack and Trail, Stack and Trail
  9752. @section Stack Manipulation Commands
  9753. @noindent
  9754. @kindex @key{RET}
  9755. @kindex @key{SPC}
  9756. @pindex calc-enter
  9757. @cindex Duplicating stack entries
  9758. To duplicate the top object on the stack, press @key{RET} or @key{SPC}
  9759. (two equivalent keys for the @code{calc-enter} command).
  9760. Given a positive numeric prefix argument, these commands duplicate
  9761. several elements at the top of the stack.
  9762. Given a negative argument,
  9763. these commands duplicate the specified element of the stack.
  9764. Given an argument of zero, they duplicate the entire stack.
  9765. For example, with @samp{10 20 30} on the stack,
  9766. @key{RET} creates @samp{10 20 30 30},
  9767. @kbd{C-u 2 @key{RET}} creates @samp{10 20 30 20 30},
  9768. @kbd{C-u - 2 @key{RET}} creates @samp{10 20 30 20}, and
  9769. @kbd{C-u 0 @key{RET}} creates @samp{10 20 30 10 20 30}.@refill
  9770. @kindex @key{LFD}
  9771. @pindex calc-over
  9772. The @key{LFD} (@code{calc-over}) command (on a key marked Line-Feed if you
  9773. have it, else on @kbd{C-j}) is like @code{calc-enter}
  9774. except that the sign of the numeric prefix argument is interpreted
  9775. oppositely. Also, with no prefix argument the default argument is 2.
  9776. Thus with @samp{10 20 30} on the stack, @key{LFD} and @kbd{C-u 2 @key{LFD}}
  9777. are both equivalent to @kbd{C-u - 2 @key{RET}}, producing
  9778. @samp{10 20 30 20}.@refill
  9779. @kindex @key{DEL}
  9780. @kindex C-d
  9781. @pindex calc-pop
  9782. @cindex Removing stack entries
  9783. @cindex Deleting stack entries
  9784. To remove the top element from the stack, press @key{DEL} (@code{calc-pop}).
  9785. The @kbd{C-d} key is a synonym for @key{DEL}.
  9786. (If the top element is an incomplete object with at least one element, the
  9787. last element is removed from it.) Given a positive numeric prefix argument,
  9788. several elements are removed. Given a negative argument, the specified
  9789. element of the stack is deleted. Given an argument of zero, the entire
  9790. stack is emptied.
  9791. For example, with @samp{10 20 30} on the stack,
  9792. @key{DEL} leaves @samp{10 20},
  9793. @kbd{C-u 2 @key{DEL}} leaves @samp{10},
  9794. @kbd{C-u - 2 @key{DEL}} leaves @samp{10 30}, and
  9795. @kbd{C-u 0 @key{DEL}} leaves an empty stack.@refill
  9796. @kindex M-@key{DEL}
  9797. @pindex calc-pop-above
  9798. The @kbd{M-@key{DEL}} (@code{calc-pop-above}) command is to @key{DEL} what
  9799. @key{LFD} is to @key{RET}: It interprets the sign of the numeric
  9800. prefix argument in the opposite way, and the default argument is 2.
  9801. Thus @kbd{M-@key{DEL}} by itself removes the second-from-top stack element,
  9802. leaving the first, third, fourth, and so on; @kbd{M-3 M-@key{DEL}} deletes
  9803. the third stack element.
  9804. @kindex @key{TAB}
  9805. @pindex calc-roll-down
  9806. To exchange the top two elements of the stack, press @key{TAB}
  9807. (@code{calc-roll-down}). Given a positive numeric prefix argument, the
  9808. specified number of elements at the top of the stack are rotated downward.
  9809. Given a negative argument, the entire stack is rotated downward the specified
  9810. number of times. Given an argument of zero, the entire stack is reversed
  9811. top-for-bottom.
  9812. For example, with @samp{10 20 30 40 50} on the stack,
  9813. @key{TAB} creates @samp{10 20 30 50 40},
  9814. @kbd{C-u 3 @key{TAB}} creates @samp{10 20 50 30 40},
  9815. @kbd{C-u - 2 @key{TAB}} creates @samp{40 50 10 20 30}, and
  9816. @kbd{C-u 0 @key{TAB}} creates @samp{50 40 30 20 10}.@refill
  9817. @kindex M-@key{TAB}
  9818. @pindex calc-roll-up
  9819. The command @kbd{M-@key{TAB}} (@code{calc-roll-up}) is analogous to @key{TAB}
  9820. except that it rotates upward instead of downward. Also, the default
  9821. with no prefix argument is to rotate the top 3 elements.
  9822. For example, with @samp{10 20 30 40 50} on the stack,
  9823. @kbd{M-@key{TAB}} creates @samp{10 20 40 50 30},
  9824. @kbd{C-u 4 M-@key{TAB}} creates @samp{10 30 40 50 20},
  9825. @kbd{C-u - 2 M-@key{TAB}} creates @samp{30 40 50 10 20}, and
  9826. @kbd{C-u 0 M-@key{TAB}} creates @samp{50 40 30 20 10}.@refill
  9827. A good way to view the operation of @key{TAB} and @kbd{M-@key{TAB}} is in
  9828. terms of moving a particular element to a new position in the stack.
  9829. With a positive argument @var{n}, @key{TAB} moves the top stack
  9830. element down to level @var{n}, making room for it by pulling all the
  9831. intervening stack elements toward the top. @kbd{M-@key{TAB}} moves the
  9832. element at level @var{n} up to the top. (Compare with @key{LFD},
  9833. which copies instead of moving the element in level @var{n}.)
  9834. With a negative argument @i{-@var{n}}, @key{TAB} rotates the stack
  9835. to move the object in level @var{n} to the deepest place in the
  9836. stack, and the object in level @i{@var{n}+1} to the top. @kbd{M-@key{TAB}}
  9837. rotates the deepest stack element to be in level @i{n}, also
  9838. putting the top stack element in level @i{@var{n}+1}.
  9839. @xref{Selecting Subformulas}, for a way to apply these commands to
  9840. any portion of a vector or formula on the stack.
  9841. @node Editing Stack Entries, Trail Commands, Stack Manipulation, Stack and Trail
  9842. @section Editing Stack Entries
  9843. @noindent
  9844. @kindex `
  9845. @pindex calc-edit
  9846. @pindex calc-edit-finish
  9847. @cindex Editing the stack with Emacs
  9848. The backquote, @kbd{`} (@code{calc-edit}) command creates a temporary
  9849. buffer (@samp{*Calc Edit*}) for editing the top-of-stack value using
  9850. regular Emacs commands. With a numeric prefix argument, it edits the
  9851. specified number of stack entries at once. (An argument of zero edits
  9852. the entire stack; a negative argument edits one specific stack entry.)
  9853. When you are done editing, press @kbd{M-# M-#} to finish and return
  9854. to Calc. The @key{RET} and @key{LFD} keys also work to finish most
  9855. sorts of editing, though in some cases Calc leaves @key{RET} with its
  9856. usual meaning (``insert a newline'') if it's a situation where you
  9857. might want to insert new lines into the editing buffer. The traditional
  9858. Emacs ``finish'' key sequence, @kbd{C-c C-c}, also works to finish
  9859. editing and may be easier to type, depending on your keyboard.
  9860. When you finish editing, the Calculator parses the lines of text in
  9861. the @samp{*Calc Edit*} buffer as numbers or formulas, replaces the
  9862. original stack elements in the original buffer with these new values,
  9863. then kills the @samp{*Calc Edit*} buffer. The original Calculator buffer
  9864. continues to exist during editing, but for best results you should be
  9865. careful not to change it until you have finished the edit. You can
  9866. also cancel the edit by pressing @kbd{M-# x}.
  9867. The formula is normally reevaluated as it is put onto the stack.
  9868. For example, editing @samp{a + 2} to @samp{3 + 2} and pressing
  9869. @kbd{M-# M-#} will push 5 on the stack. If you use @key{LFD} to
  9870. finish, Calc will put the result on the stack without evaluating it.
  9871. If you give a prefix argument to @kbd{M-# M-#} (or @kbd{C-c C-c}),
  9872. Calc will not kill the @samp{*Calc Edit*} buffer. You can switch
  9873. back to that buffer and continue editing if you wish. However, you
  9874. should understand that if you initiated the edit with @kbd{`}, the
  9875. @kbd{M-# M-#} operation will be programmed to replace the top of the
  9876. stack with the new edited value, and it will do this even if you have
  9877. rearranged the stack in the meanwhile. This is not so much of a problem
  9878. with other editing commands, though, such as @kbd{s e}
  9879. (@code{calc-edit-variable}; @pxref{Operations on Variables}).
  9880. If the @code{calc-edit} command involves more than one stack entry,
  9881. each line of the @samp{*Calc Edit*} buffer is interpreted as a
  9882. separate formula. Otherwise, the entire buffer is interpreted as
  9883. one formula, with line breaks ignored. (You can use @kbd{C-o} or
  9884. @kbd{C-q C-j} to insert a newline in the buffer without pressing @key{RET}.)
  9885. The @kbd{`} key also works during numeric or algebraic entry. The
  9886. text entered so far is moved to the @code{*Calc Edit*} buffer for
  9887. more extensive editing than is convenient in the minibuffer.
  9888. @node Trail Commands, Keep Arguments, Editing Stack Entries, Stack and Trail
  9889. @section Trail Commands
  9890. @noindent
  9891. @cindex Trail buffer
  9892. The commands for manipulating the Calc Trail buffer are two-key sequences
  9893. beginning with the @kbd{t} prefix.
  9894. @kindex t d
  9895. @pindex calc-trail-display
  9896. The @kbd{t d} (@code{calc-trail-display}) command turns display of the
  9897. trail on and off. Normally the trail display is toggled on if it was off,
  9898. off if it was on. With a numeric prefix of zero, this command always
  9899. turns the trail off; with a prefix of one, it always turns the trail on.
  9900. The other trail-manipulation commands described here automatically turn
  9901. the trail on. Note that when the trail is off values are still recorded
  9902. there; they are simply not displayed. To set Emacs to turn the trail
  9903. off by default, type @kbd{t d} and then save the mode settings with
  9904. @kbd{m m} (@code{calc-save-modes}).
  9905. @kindex t i
  9906. @pindex calc-trail-in
  9907. @kindex t o
  9908. @pindex calc-trail-out
  9909. The @kbd{t i} (@code{calc-trail-in}) and @kbd{t o}
  9910. (@code{calc-trail-out}) commands switch the cursor into and out of the
  9911. Calc Trail window. In practice they are rarely used, since the commands
  9912. shown below are a more convenient way to move around in the
  9913. trail, and they work ``by remote control'' when the cursor is still
  9914. in the Calculator window.@refill
  9915. @cindex Trail pointer
  9916. There is a @dfn{trail pointer} which selects some entry of the trail at
  9917. any given time. The trail pointer looks like a @samp{>} symbol right
  9918. before the selected number. The following commands operate on the
  9919. trail pointer in various ways.
  9920. @kindex t y
  9921. @pindex calc-trail-yank
  9922. @cindex Retrieving previous results
  9923. The @kbd{t y} (@code{calc-trail-yank}) command reads the selected value in
  9924. the trail and pushes it onto the Calculator stack. It allows you to
  9925. re-use any previously computed value without retyping. With a numeric
  9926. prefix argument @var{n}, it yanks the value @var{n} lines above the current
  9927. trail pointer.
  9928. @kindex t <
  9929. @pindex calc-trail-scroll-left
  9930. @kindex t >
  9931. @pindex calc-trail-scroll-right
  9932. The @kbd{t <} (@code{calc-trail-scroll-left}) and @kbd{t >}
  9933. (@code{calc-trail-scroll-right}) commands horizontally scroll the trail
  9934. window left or right by one half of its width.@refill
  9935. @kindex t n
  9936. @pindex calc-trail-next
  9937. @kindex t p
  9938. @pindex calc-trail-previous
  9939. @kindex t f
  9940. @pindex calc-trail-forward
  9941. @kindex t b
  9942. @pindex calc-trail-backward
  9943. The @kbd{t n} (@code{calc-trail-next}) and @kbd{t p}
  9944. (@code{calc-trail-previous)} commands move the trail pointer down or up
  9945. one line. The @kbd{t f} (@code{calc-trail-forward}) and @kbd{t b}
  9946. (@code{calc-trail-backward}) commands move the trail pointer down or up
  9947. one screenful at a time. All of these commands accept numeric prefix
  9948. arguments to move several lines or screenfuls at a time.@refill
  9949. @kindex t [
  9950. @pindex calc-trail-first
  9951. @kindex t ]
  9952. @pindex calc-trail-last
  9953. @kindex t h
  9954. @pindex calc-trail-here
  9955. The @kbd{t [} (@code{calc-trail-first}) and @kbd{t ]}
  9956. (@code{calc-trail-last}) commands move the trail pointer to the first or
  9957. last line of the trail. The @kbd{t h} (@code{calc-trail-here}) command
  9958. moves the trail pointer to the cursor position; unlike the other trail
  9959. commands, @kbd{t h} works only when Calc Trail is the selected window.@refill
  9960. @kindex t s
  9961. @pindex calc-trail-isearch-forward
  9962. @kindex t r
  9963. @pindex calc-trail-isearch-backward
  9964. @ifinfo
  9965. The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
  9966. (@code{calc-trail-isearch-backward}) commands perform an incremental
  9967. search forward or backward through the trail. You can press @key{RET}
  9968. to terminate the search; the trail pointer moves to the current line.
  9969. If you cancel the search with @kbd{C-g}, the trail pointer stays where
  9970. it was when the search began.@refill
  9971. @end ifinfo
  9972. @tex
  9973. The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
  9974. (@code{calc-trail-isearch-backward}) com\-mands perform an incremental
  9975. search forward or backward through the trail. You can press @key{RET}
  9976. to terminate the search; the trail pointer moves to the current line.
  9977. If you cancel the search with @kbd{C-g}, the trail pointer stays where
  9978. it was when the search began.
  9979. @end tex
  9980. @kindex t m
  9981. @pindex calc-trail-marker
  9982. The @kbd{t m} (@code{calc-trail-marker}) command allows you to enter a
  9983. line of text of your own choosing into the trail. The text is inserted
  9984. after the line containing the trail pointer; this usually means it is
  9985. added to the end of the trail. Trail markers are useful mainly as the
  9986. targets for later incremental searches in the trail.
  9987. @kindex t k
  9988. @pindex calc-trail-kill
  9989. The @kbd{t k} (@code{calc-trail-kill}) command removes the selected line
  9990. from the trail. The line is saved in the Emacs kill ring suitable for
  9991. yanking into another buffer, but it is not easy to yank the text back
  9992. into the trail buffer. With a numeric prefix argument, this command
  9993. kills the @var{n} lines below or above the selected one.
  9994. The @kbd{t .} (@code{calc-full-trail-vectors}) command is described
  9995. elsewhere; @pxref{Vector and Matrix Formats}.
  9996. @node Keep Arguments, , Trail Commands, Stack and Trail
  9997. @section Keep Arguments
  9998. @noindent
  9999. @kindex K
  10000. @pindex calc-keep-args
  10001. The @kbd{K} (@code{calc-keep-args}) command acts like a prefix for
  10002. the following command. It prevents that command from removing its
  10003. arguments from the stack. For example, after @kbd{2 @key{RET} 3 +},
  10004. the stack contains the sole number 5, but after @kbd{2 @key{RET} 3 K +},
  10005. the stack contains the arguments and the result: @samp{2 3 5}.
  10006. This works for all commands that take arguments off the stack. As
  10007. another example, @kbd{K a s} simplifies a formula, pushing the
  10008. simplified version of the formula onto the stack after the original
  10009. formula (rather than replacing the original formula).
  10010. Note that you could get the same effect by typing @kbd{@key{RET} a s},
  10011. copying the formula and then simplifying the copy. One difference
  10012. is that for a very large formula the time taken to format the
  10013. intermediate copy in @kbd{@key{RET} a s} could be noticeable; @kbd{K a s}
  10014. would avoid this extra work.
  10015. Even stack manipulation commands are affected. @key{TAB} works by
  10016. popping two values and pushing them back in the opposite order,
  10017. so @kbd{2 @key{RET} 3 K @key{TAB}} produces @samp{2 3 3 2}.
  10018. A few Calc commands provide other ways of doing the same thing.
  10019. For example, @kbd{' sin($)} replaces the number on the stack with
  10020. its sine using algebraic entry; to push the sine and keep the
  10021. original argument you could use either @kbd{' sin($1)} or
  10022. @kbd{K ' sin($)}. @xref{Algebraic Entry}. Also, the @kbd{s s}
  10023. command is effectively the same as @kbd{K s t}. @xref{Storing Variables}.
  10024. Keyboard macros may interact surprisingly with the @kbd{K} prefix.
  10025. If you have defined a keyboard macro to be, say, @samp{Q +} to add
  10026. one number to the square root of another, then typing @kbd{K X} will
  10027. execute @kbd{K Q +}, probably not what you expected. The @kbd{K}
  10028. prefix will apply to just the first command in the macro rather than
  10029. the whole macro.
  10030. If you execute a command and then decide you really wanted to keep
  10031. the argument, you can press @kbd{M-@key{RET}} (@code{calc-last-args}).
  10032. This command pushes the last arguments that were popped by any command
  10033. onto the stack. Note that the order of things on the stack will be
  10034. different than with @kbd{K}: @kbd{2 @key{RET} 3 + M-@key{RET}} leaves
  10035. @samp{5 2 3} on the stack instead of @samp{2 3 5}. @xref{Undo}.
  10036. @node Mode Settings, Arithmetic, Stack and Trail, Top
  10037. @chapter Mode Settings
  10038. @noindent
  10039. This chapter describes commands that set modes in the Calculator.
  10040. They do not affect the contents of the stack, although they may change
  10041. the @emph{appearance} or @emph{interpretation} of the stack's contents.
  10042. @menu
  10043. * General Mode Commands::
  10044. * Precision::
  10045. * Inverse and Hyperbolic::
  10046. * Calculation Modes::
  10047. * Simplification Modes::
  10048. * Declarations::
  10049. * Display Modes::
  10050. * Language Modes::
  10051. * Modes Variable::
  10052. * Calc Mode Line::
  10053. @end menu
  10054. @node General Mode Commands, Precision, Mode Settings, Mode Settings
  10055. @section General Mode Commands
  10056. @noindent
  10057. @kindex m m
  10058. @pindex calc-save-modes
  10059. @cindex Continuous memory
  10060. @cindex Saving mode settings
  10061. @cindex Permanent mode settings
  10062. @cindex @file{.emacs} file, mode settings
  10063. You can save all of the current mode settings in your @file{.emacs} file
  10064. with the @kbd{m m} (@code{calc-save-modes}) command. This will cause
  10065. Emacs to reestablish these modes each time it starts up. The modes saved
  10066. in the file include everything controlled by the @kbd{m} and @kbd{d}
  10067. prefix keys, the current precision and binary word size, whether or not
  10068. the trail is displayed, the current height of the Calc window, and more.
  10069. The current interface (used when you type @kbd{M-# M-#}) is also saved.
  10070. If there were already saved mode settings in the file, they are replaced.
  10071. Otherwise, the new mode information is appended to the end of the file.
  10072. @kindex m R
  10073. @pindex calc-mode-record-mode
  10074. The @kbd{m R} (@code{calc-mode-record-mode}) command tells Calc to
  10075. record the new mode settings (as if by pressing @kbd{m m}) every
  10076. time a mode setting changes. If Embedded Mode is enabled, other
  10077. options are available; @pxref{Mode Settings in Embedded Mode}.
  10078. @kindex m F
  10079. @pindex calc-settings-file-name
  10080. The @kbd{m F} (@code{calc-settings-file-name}) command allows you to
  10081. choose a different place than your @file{.emacs} file for @kbd{m m},
  10082. @kbd{Z P}, and similar commands to save permanent information.
  10083. You are prompted for a file name. All Calc modes are then reset to
  10084. their default values, then settings from the file you named are loaded
  10085. if this file exists, and this file becomes the one that Calc will
  10086. use in the future for commands like @kbd{m m}. The default settings
  10087. file name is @file{~/.emacs}. You can see the current file name by
  10088. giving a blank response to the @kbd{m F} prompt. See also the
  10089. discussion of the @code{calc-settings-file} variable; @pxref{Installation}.
  10090. If the file name you give contains the string @samp{.emacs} anywhere
  10091. inside it, @kbd{m F} will not automatically load the new file. This
  10092. is because you are presumably switching to your @file{~/.emacs} file,
  10093. which may contain other things you don't want to reread. You can give
  10094. a numeric prefix argument of 1 to @kbd{m F} to force it to read the
  10095. file no matter what its name. Conversely, an argument of @i{-1} tells
  10096. @kbd{m F} @emph{not} to read the new file. An argument of 2 or @i{-2}
  10097. tells @kbd{m F} not to reset the modes to their defaults beforehand,
  10098. which is useful if you intend your new file to have a variant of the
  10099. modes present in the file you were using before.
  10100. @kindex m x
  10101. @pindex calc-always-load-extensions
  10102. The @kbd{m x} (@code{calc-always-load-extensions}) command enables a mode
  10103. in which the first use of Calc loads the entire program, including all
  10104. extensions modules. Otherwise, the extensions modules will not be loaded
  10105. until the various advanced Calc features are used. Since this mode only
  10106. has effect when Calc is first loaded, @kbd{m x} is usually followed by
  10107. @kbd{m m} to make the mode-setting permanent. To load all of Calc just
  10108. once, rather than always in the future, you can press @kbd{M-# L}.
  10109. @kindex m S
  10110. @pindex calc-shift-prefix
  10111. The @kbd{m S} (@code{calc-shift-prefix}) command enables a mode in which
  10112. all of Calc's letter prefix keys may be typed shifted as well as unshifted.
  10113. If you are typing, say, @kbd{a S} (@code{calc-solve-for}) quite often
  10114. you might find it easier to turn this mode on so that you can type
  10115. @kbd{A S} instead. When this mode is enabled, the commands that used to
  10116. be on those single shifted letters (e.g., @kbd{A} (@code{calc-abs})) can
  10117. now be invoked by pressing the shifted letter twice: @kbd{A A}. Note
  10118. that the @kbd{v} prefix key always works both shifted and unshifted, and
  10119. the @kbd{z} and @kbd{Z} prefix keys are always distinct. Also, the @kbd{h}
  10120. prefix is not affected by this mode. Press @kbd{m S} again to disable
  10121. shifted-prefix mode.
  10122. @node Precision, Inverse and Hyperbolic, General Mode Commands, Mode Settings
  10123. @section Precision
  10124. @noindent
  10125. @kindex p
  10126. @pindex calc-precision
  10127. @cindex Precision of calculations
  10128. The @kbd{p} (@code{calc-precision}) command controls the precision to
  10129. which floating-point calculations are carried. The precision must be
  10130. at least 3 digits and may be arbitrarily high, within the limits of
  10131. memory and time. This affects only floats: Integer and rational
  10132. calculations are always carried out with as many digits as necessary.
  10133. The @kbd{p} key prompts for the current precision. If you wish you
  10134. can instead give the precision as a numeric prefix argument.
  10135. Many internal calculations are carried to one or two digits higher
  10136. precision than normal. Results are rounded down afterward to the
  10137. current precision. Unless a special display mode has been selected,
  10138. floats are always displayed with their full stored precision, i.e.,
  10139. what you see is what you get. Reducing the current precision does not
  10140. round values already on the stack, but those values will be rounded
  10141. down before being used in any calculation. The @kbd{c 0} through
  10142. @kbd{c 9} commands (@pxref{Conversions}) can be used to round an
  10143. existing value to a new precision.@refill
  10144. @cindex Accuracy of calculations
  10145. It is important to distinguish the concepts of @dfn{precision} and
  10146. @dfn{accuracy}. In the normal usage of these words, the number
  10147. 123.4567 has a precision of 7 digits but an accuracy of 4 digits.
  10148. The precision is the total number of digits not counting leading
  10149. or trailing zeros (regardless of the position of the decimal point).
  10150. The accuracy is simply the number of digits after the decimal point
  10151. (again not counting trailing zeros). In Calc you control the precision,
  10152. not the accuracy of computations. If you were to set the accuracy
  10153. instead, then calculations like @samp{exp(100)} would generate many
  10154. more digits than you would typically need, while @samp{exp(-100)} would
  10155. probably round to zero! In Calc, both these computations give you
  10156. exactly 12 (or the requested number of) significant digits.
  10157. The only Calc features that deal with accuracy instead of precision
  10158. are fixed-point display mode for floats (@kbd{d f}; @pxref{Float Formats}),
  10159. and the rounding functions like @code{floor} and @code{round}
  10160. (@pxref{Integer Truncation}). Also, @kbd{c 0} through @kbd{c 9}
  10161. deal with both precision and accuracy depending on the magnitudes
  10162. of the numbers involved.
  10163. If you need to work with a particular fixed accuracy (say, dollars and
  10164. cents with two digits after the decimal point), one solution is to work
  10165. with integers and an ``implied'' decimal point. For example, $8.99
  10166. divided by 6 would be entered @kbd{899 @key{RET} 6 /}, yielding 149.833
  10167. (actually $1.49833 with our implied decimal point); pressing @kbd{R}
  10168. would round this to 150 cents, i.e., $1.50.
  10169. @xref{Floats}, for still more on floating-point precision and related
  10170. issues.
  10171. @node Inverse and Hyperbolic, Calculation Modes, Precision, Mode Settings
  10172. @section Inverse and Hyperbolic Flags
  10173. @noindent
  10174. @kindex I
  10175. @pindex calc-inverse
  10176. There is no single-key equivalent to the @code{calc-arcsin} function.
  10177. Instead, you must first press @kbd{I} (@code{calc-inverse}) to set
  10178. the @dfn{Inverse Flag}, then press @kbd{S} (@code{calc-sin}).
  10179. The @kbd{I} key actually toggles the Inverse Flag. When this flag
  10180. is set, the word @samp{Inv} appears in the mode line.@refill
  10181. @kindex H
  10182. @pindex calc-hyperbolic
  10183. Likewise, the @kbd{H} key (@code{calc-hyperbolic}) sets or clears the
  10184. Hyperbolic Flag, which transforms @code{calc-sin} into @code{calc-sinh}.
  10185. If both of these flags are set at once, the effect will be
  10186. @code{calc-arcsinh}. (The Hyperbolic flag is also used by some
  10187. non-trigonometric commands; for example @kbd{H L} computes a base-10,
  10188. instead of base-@i{e}, logarithm.)@refill
  10189. Command names like @code{calc-arcsin} are provided for completeness, and
  10190. may be executed with @kbd{x} or @kbd{M-x}. Their effect is simply to
  10191. toggle the Inverse and/or Hyperbolic flags and then execute the
  10192. corresponding base command (@code{calc-sin} in this case).
  10193. The Inverse and Hyperbolic flags apply only to the next Calculator
  10194. command, after which they are automatically cleared. (They are also
  10195. cleared if the next keystroke is not a Calc command.) Digits you
  10196. type after @kbd{I} or @kbd{H} (or @kbd{K}) are treated as prefix
  10197. arguments for the next command, not as numeric entries. The same
  10198. is true of @kbd{C-u}, but not of the minus sign (@kbd{K -} means to
  10199. subtract and keep arguments).
  10200. The third Calc prefix flag, @kbd{K} (keep-arguments), is discussed
  10201. elsewhere. @xref{Keep Arguments}.
  10202. @node Calculation Modes, Simplification Modes, Inverse and Hyperbolic, Mode Settings
  10203. @section Calculation Modes
  10204. @noindent
  10205. The commands in this section are two-key sequences beginning with
  10206. the @kbd{m} prefix. (That's the letter @kbd{m}, not the @key{META} key.)
  10207. The @samp{m a} (@code{calc-algebraic-mode}) command is described elsewhere
  10208. (@pxref{Algebraic Entry}).
  10209. @menu
  10210. * Angular Modes::
  10211. * Polar Mode::
  10212. * Fraction Mode::
  10213. * Infinite Mode::
  10214. * Symbolic Mode::
  10215. * Matrix Mode::
  10216. * Automatic Recomputation::
  10217. * Working Message::
  10218. @end menu
  10219. @node Angular Modes, Polar Mode, Calculation Modes, Calculation Modes
  10220. @subsection Angular Modes
  10221. @noindent
  10222. @cindex Angular mode
  10223. The Calculator supports three notations for angles: radians, degrees,
  10224. and degrees-minutes-seconds. When a number is presented to a function
  10225. like @code{sin} that requires an angle, the current angular mode is
  10226. used to interpret the number as either radians or degrees. If an HMS
  10227. form is presented to @code{sin}, it is always interpreted as
  10228. degrees-minutes-seconds.
  10229. Functions that compute angles produce a number in radians, a number in
  10230. degrees, or an HMS form depending on the current angular mode. If the
  10231. result is a complex number and the current mode is HMS, the number is
  10232. instead expressed in degrees. (Complex-number calculations would
  10233. normally be done in radians mode, though. Complex numbers are converted
  10234. to degrees by calculating the complex result in radians and then
  10235. multiplying by 180 over @c{$\pi$}
  10236. @cite{pi}.)
  10237. @kindex m r
  10238. @pindex calc-radians-mode
  10239. @kindex m d
  10240. @pindex calc-degrees-mode
  10241. @kindex m h
  10242. @pindex calc-hms-mode
  10243. The @kbd{m r} (@code{calc-radians-mode}), @kbd{m d} (@code{calc-degrees-mode}),
  10244. and @kbd{m h} (@code{calc-hms-mode}) commands control the angular mode.
  10245. The current angular mode is displayed on the Emacs mode line.
  10246. The default angular mode is degrees.@refill
  10247. @node Polar Mode, Fraction Mode, Angular Modes, Calculation Modes
  10248. @subsection Polar Mode
  10249. @noindent
  10250. @cindex Polar mode
  10251. The Calculator normally ``prefers'' rectangular complex numbers in the
  10252. sense that rectangular form is used when the proper form can not be
  10253. decided from the input. This might happen by multiplying a rectangular
  10254. number by a polar one, by taking the square root of a negative real
  10255. number, or by entering @kbd{( 2 @key{SPC} 3 )}.
  10256. @kindex m p
  10257. @pindex calc-polar-mode
  10258. The @kbd{m p} (@code{calc-polar-mode}) command toggles complex-number
  10259. preference between rectangular and polar forms. In polar mode, all
  10260. of the above example situations would produce polar complex numbers.
  10261. @node Fraction Mode, Infinite Mode, Polar Mode, Calculation Modes
  10262. @subsection Fraction Mode
  10263. @noindent
  10264. @cindex Fraction mode
  10265. @cindex Division of integers
  10266. Division of two integers normally yields a floating-point number if the
  10267. result cannot be expressed as an integer. In some cases you would
  10268. rather get an exact fractional answer. One way to accomplish this is
  10269. to multiply fractions instead: @kbd{6 @key{RET} 1:4 *} produces @cite{3:2}
  10270. even though @kbd{6 @key{RET} 4 /} produces @cite{1.5}.
  10271. @kindex m f
  10272. @pindex calc-frac-mode
  10273. To set the Calculator to produce fractional results for normal integer
  10274. divisions, use the @kbd{m f} (@code{calc-frac-mode}) command.
  10275. For example, @cite{8/4} produces @cite{2} in either mode,
  10276. but @cite{6/4} produces @cite{3:2} in Fraction Mode, @cite{1.5} in
  10277. Float Mode.@refill
  10278. At any time you can use @kbd{c f} (@code{calc-float}) to convert a
  10279. fraction to a float, or @kbd{c F} (@code{calc-fraction}) to convert a
  10280. float to a fraction. @xref{Conversions}.
  10281. @node Infinite Mode, Symbolic Mode, Fraction Mode, Calculation Modes
  10282. @subsection Infinite Mode
  10283. @noindent
  10284. @cindex Infinite mode
  10285. The Calculator normally treats results like @cite{1 / 0} as errors;
  10286. formulas like this are left in unsimplified form. But Calc can be
  10287. put into a mode where such calculations instead produce ``infinite''
  10288. results.
  10289. @kindex m i
  10290. @pindex calc-infinite-mode
  10291. The @kbd{m i} (@code{calc-infinite-mode}) command turns this mode
  10292. on and off. When the mode is off, infinities do not arise except
  10293. in calculations that already had infinities as inputs. (One exception
  10294. is that infinite open intervals like @samp{[0 .. inf)} can be
  10295. generated; however, intervals closed at infinity (@samp{[0 .. inf]})
  10296. will not be generated when infinite mode is off.)
  10297. With infinite mode turned on, @samp{1 / 0} will generate @code{uinf},
  10298. an undirected infinity. @xref{Infinities}, for a discussion of the
  10299. difference between @code{inf} and @code{uinf}. Also, @cite{0 / 0}
  10300. evaluates to @code{nan}, the ``indeterminate'' symbol. Various other
  10301. functions can also return infinities in this mode; for example,
  10302. @samp{ln(0) = -inf}, and @samp{gamma(-7) = uinf}. Once again,
  10303. note that @samp{exp(inf) = inf} regardless of infinite mode because
  10304. this calculation has infinity as an input.
  10305. @cindex Positive infinite mode
  10306. The @kbd{m i} command with a numeric prefix argument of zero,
  10307. i.e., @kbd{C-u 0 m i}, turns on a ``positive infinite mode'' in
  10308. which zero is treated as positive instead of being directionless.
  10309. Thus, @samp{1 / 0 = inf} and @samp{-1 / 0 = -inf} in this mode.
  10310. Note that zero never actually has a sign in Calc; there are no
  10311. separate representations for @i{+0} and @i{-0}. Positive
  10312. infinite mode merely changes the interpretation given to the
  10313. single symbol, @samp{0}. One consequence of this is that, while
  10314. you might expect @samp{1 / -0 = -inf}, actually @samp{1 / -0}
  10315. is equivalent to @samp{1 / 0}, which is equal to positive @code{inf}.
  10316. @node Symbolic Mode, Matrix Mode, Infinite Mode, Calculation Modes
  10317. @subsection Symbolic Mode
  10318. @noindent
  10319. @cindex Symbolic mode
  10320. @cindex Inexact results
  10321. Calculations are normally performed numerically wherever possible.
  10322. For example, the @code{calc-sqrt} command, or @code{sqrt} function in an
  10323. algebraic expression, produces a numeric answer if the argument is a
  10324. number or a symbolic expression if the argument is an expression:
  10325. @kbd{2 Q} pushes 1.4142 but @kbd{@key{'} x+1 @key{RET} Q} pushes @samp{sqrt(x+1)}.
  10326. @kindex m s
  10327. @pindex calc-symbolic-mode
  10328. In @dfn{symbolic mode}, controlled by the @kbd{m s} (@code{calc-symbolic-mode})
  10329. command, functions which would produce inexact, irrational results are
  10330. left in symbolic form. Thus @kbd{16 Q} pushes 4, but @kbd{2 Q} pushes
  10331. @samp{sqrt(2)}.
  10332. @kindex N
  10333. @pindex calc-eval-num
  10334. The shift-@kbd{N} (@code{calc-eval-num}) command evaluates numerically
  10335. the expression at the top of the stack, by temporarily disabling
  10336. @code{calc-symbolic-mode} and executing @kbd{=} (@code{calc-evaluate}).
  10337. Given a numeric prefix argument, it also
  10338. sets the floating-point precision to the specified value for the duration
  10339. of the command.@refill
  10340. To evaluate a formula numerically without expanding the variables it
  10341. contains, you can use the key sequence @kbd{m s a v m s} (this uses
  10342. @code{calc-alg-evaluate}, which resimplifies but doesn't evaluate
  10343. variables.)
  10344. @node Matrix Mode, Automatic Recomputation, Symbolic Mode, Calculation Modes
  10345. @subsection Matrix and Scalar Modes
  10346. @noindent
  10347. @cindex Matrix mode
  10348. @cindex Scalar mode
  10349. Calc sometimes makes assumptions during algebraic manipulation that
  10350. are awkward or incorrect when vectors and matrices are involved.
  10351. Calc has two modes, @dfn{matrix mode} and @dfn{scalar mode}, which
  10352. modify its behavior around vectors in useful ways.
  10353. @kindex m v
  10354. @pindex calc-matrix-mode
  10355. Press @kbd{m v} (@code{calc-matrix-mode}) once to enter matrix mode.
  10356. In this mode, all objects are assumed to be matrices unless provably
  10357. otherwise. One major effect is that Calc will no longer consider
  10358. multiplication to be commutative. (Recall that in matrix arithmetic,
  10359. @samp{A*B} is not the same as @samp{B*A}.) This assumption affects
  10360. rewrite rules and algebraic simplification. Another effect of this
  10361. mode is that calculations that would normally produce constants like
  10362. 0 and 1 (e.g., @cite{a - a} and @cite{a / a}, respectively) will now
  10363. produce function calls that represent ``generic'' zero or identity
  10364. matrices: @samp{idn(0)}, @samp{idn(1)}. The @code{idn} function
  10365. @samp{idn(@var{a},@var{n})} returns @var{a} times an @var{n}x@var{n}
  10366. identity matrix; if @var{n} is omitted, it doesn't know what
  10367. dimension to use and so the @code{idn} call remains in symbolic
  10368. form. However, if this generic identity matrix is later combined
  10369. with a matrix whose size is known, it will be converted into
  10370. a true identity matrix of the appropriate size. On the other hand,
  10371. if it is combined with a scalar (as in @samp{idn(1) + 2}), Calc
  10372. will assume it really was a scalar after all and produce, e.g., 3.
  10373. Press @kbd{m v} a second time to get scalar mode. Here, objects are
  10374. assumed @emph{not} to be vectors or matrices unless provably so.
  10375. For example, normally adding a variable to a vector, as in
  10376. @samp{[x, y, z] + a}, will leave the sum in symbolic form because
  10377. as far as Calc knows, @samp{a} could represent either a number or
  10378. another 3-vector. In scalar mode, @samp{a} is assumed to be a
  10379. non-vector, and the addition is evaluated to @samp{[x+a, y+a, z+a]}.
  10380. Press @kbd{m v} a third time to return to the normal mode of operation.
  10381. If you press @kbd{m v} with a numeric prefix argument @var{n}, you
  10382. get a special ``dimensioned matrix mode'' in which matrices of
  10383. unknown size are assumed to be @var{n}x@var{n} square matrices.
  10384. Then, the function call @samp{idn(1)} will expand into an actual
  10385. matrix rather than representing a ``generic'' matrix.
  10386. @cindex Declaring scalar variables
  10387. Of course these modes are approximations to the true state of
  10388. affairs, which is probably that some quantities will be matrices
  10389. and others will be scalars. One solution is to ``declare''
  10390. certain variables or functions to be scalar-valued.
  10391. @xref{Declarations}, to see how to make declarations in Calc.
  10392. There is nothing stopping you from declaring a variable to be
  10393. scalar and then storing a matrix in it; however, if you do, the
  10394. results you get from Calc may not be valid. Suppose you let Calc
  10395. get the result @samp{[x+a, y+a, z+a]} shown above, and then stored
  10396. @samp{[1, 2, 3]} in @samp{a}. The result would not be the same as
  10397. for @samp{[x, y, z] + [1, 2, 3]}, but that's because you have broken
  10398. your earlier promise to Calc that @samp{a} would be scalar.
  10399. Another way to mix scalars and matrices is to use selections
  10400. (@pxref{Selecting Subformulas}). Use matrix mode when operating on
  10401. your formula normally; then, to apply scalar mode to a certain part
  10402. of the formula without affecting the rest just select that part,
  10403. change into scalar mode and press @kbd{=} to resimplify the part
  10404. under this mode, then change back to matrix mode before deselecting.
  10405. @node Automatic Recomputation, Working Message, Matrix Mode, Calculation Modes
  10406. @subsection Automatic Recomputation
  10407. @noindent
  10408. The @dfn{evaluates-to} operator, @samp{=>}, has the special
  10409. property that any @samp{=>} formulas on the stack are recomputed
  10410. whenever variable values or mode settings that might affect them
  10411. are changed. @xref{Evaluates-To Operator}.
  10412. @kindex m C
  10413. @pindex calc-auto-recompute
  10414. The @kbd{m C} (@code{calc-auto-recompute}) command turns this
  10415. automatic recomputation on and off. If you turn it off, Calc will
  10416. not update @samp{=>} operators on the stack (nor those in the
  10417. attached Embedded Mode buffer, if there is one). They will not
  10418. be updated unless you explicitly do so by pressing @kbd{=} or until
  10419. you press @kbd{m C} to turn recomputation back on. (While automatic
  10420. recomputation is off, you can think of @kbd{m C m C} as a command
  10421. to update all @samp{=>} operators while leaving recomputation off.)
  10422. To update @samp{=>} operators in an Embedded buffer while
  10423. automatic recomputation is off, use @w{@kbd{M-# u}}.
  10424. @xref{Embedded Mode}.
  10425. @node Working Message, , Automatic Recomputation, Calculation Modes
  10426. @subsection Working Messages
  10427. @noindent
  10428. @cindex Performance
  10429. @cindex Working messages
  10430. Since the Calculator is written entirely in Emacs Lisp, which is not
  10431. designed for heavy numerical work, many operations are quite slow.
  10432. The Calculator normally displays the message @samp{Working...} in the
  10433. echo area during any command that may be slow. In addition, iterative
  10434. operations such as square roots and trigonometric functions display the
  10435. intermediate result at each step. Both of these types of messages can
  10436. be disabled if you find them distracting.
  10437. @kindex m w
  10438. @pindex calc-working
  10439. Type @kbd{m w} (@code{calc-working}) with a numeric prefix of 0 to
  10440. disable all ``working'' messages. Use a numeric prefix of 1 to enable
  10441. only the plain @samp{Working...} message. Use a numeric prefix of 2 to
  10442. see intermediate results as well. With no numeric prefix this displays
  10443. the current mode.@refill
  10444. While it may seem that the ``working'' messages will slow Calc down
  10445. considerably, experiments have shown that their impact is actually
  10446. quite small. But if your terminal is slow you may find that it helps
  10447. to turn the messages off.
  10448. @node Simplification Modes, Declarations, Calculation Modes, Mode Settings
  10449. @section Simplification Modes
  10450. @noindent
  10451. The current @dfn{simplification mode} controls how numbers and formulas
  10452. are ``normalized'' when being taken from or pushed onto the stack.
  10453. Some normalizations are unavoidable, such as rounding floating-point
  10454. results to the current precision, and reducing fractions to simplest
  10455. form. Others, such as simplifying a formula like @cite{a+a} (or @cite{2+3}),
  10456. are done by default but can be turned off when necessary.
  10457. When you press a key like @kbd{+} when @cite{2} and @cite{3} are on the
  10458. stack, Calc pops these numbers, normalizes them, creates the formula
  10459. @cite{2+3}, normalizes it, and pushes the result. Of course the standard
  10460. rules for normalizing @cite{2+3} will produce the result @cite{5}.
  10461. Simplification mode commands consist of the lower-case @kbd{m} prefix key
  10462. followed by a shifted letter.
  10463. @kindex m O
  10464. @pindex calc-no-simplify-mode
  10465. The @kbd{m O} (@code{calc-no-simplify-mode}) command turns off all optional
  10466. simplifications. These would leave a formula like @cite{2+3} alone. In
  10467. fact, nothing except simple numbers are ever affected by normalization
  10468. in this mode.
  10469. @kindex m N
  10470. @pindex calc-num-simplify-mode
  10471. The @kbd{m N} (@code{calc-num-simplify-mode}) command turns off simplification
  10472. of any formulas except those for which all arguments are constants. For
  10473. example, @cite{1+2} is simplified to @cite{3}, and @cite{a+(2-2)} is
  10474. simplified to @cite{a+0} but no further, since one argument of the sum
  10475. is not a constant. Unfortunately, @cite{(a+2)-2} is @emph{not} simplified
  10476. because the top-level @samp{-} operator's arguments are not both
  10477. constant numbers (one of them is the formula @cite{a+2}).
  10478. A constant is a number or other numeric object (such as a constant
  10479. error form or modulo form), or a vector all of whose
  10480. elements are constant.@refill
  10481. @kindex m D
  10482. @pindex calc-default-simplify-mode
  10483. The @kbd{m D} (@code{calc-default-simplify-mode}) command restores the
  10484. default simplifications for all formulas. This includes many easy and
  10485. fast algebraic simplifications such as @cite{a+0} to @cite{a}, and
  10486. @cite{a + 2 a} to @cite{3 a}, as well as evaluating functions like
  10487. @cite{@t{deriv}(x^2, x)} to @cite{2 x}.
  10488. @kindex m B
  10489. @pindex calc-bin-simplify-mode
  10490. The @kbd{m B} (@code{calc-bin-simplify-mode}) mode applies the default
  10491. simplifications to a result and then, if the result is an integer,
  10492. uses the @kbd{b c} (@code{calc-clip}) command to clip the integer according
  10493. to the current binary word size. @xref{Binary Functions}. Real numbers
  10494. are rounded to the nearest integer and then clipped; other kinds of
  10495. results (after the default simplifications) are left alone.
  10496. @kindex m A
  10497. @pindex calc-alg-simplify-mode
  10498. The @kbd{m A} (@code{calc-alg-simplify-mode}) mode does algebraic
  10499. simplification; it applies all the default simplifications, and also
  10500. the more powerful (and slower) simplifications made by @kbd{a s}
  10501. (@code{calc-simplify}). @xref{Algebraic Simplifications}.
  10502. @kindex m E
  10503. @pindex calc-ext-simplify-mode
  10504. The @kbd{m E} (@code{calc-ext-simplify-mode}) mode does ``extended''
  10505. algebraic simplification, as by the @kbd{a e} (@code{calc-simplify-extended})
  10506. command. @xref{Unsafe Simplifications}.
  10507. @kindex m U
  10508. @pindex calc-units-simplify-mode
  10509. The @kbd{m U} (@code{calc-units-simplify-mode}) mode does units
  10510. simplification; it applies the command @kbd{u s}
  10511. (@code{calc-simplify-units}), which in turn
  10512. is a superset of @kbd{a s}. In this mode, variable names which
  10513. are identifiable as unit names (like @samp{mm} for ``millimeters'')
  10514. are simplified with their unit definitions in mind.@refill
  10515. A common technique is to set the simplification mode down to the lowest
  10516. amount of simplification you will allow to be applied automatically, then
  10517. use manual commands like @kbd{a s} and @kbd{c c} (@code{calc-clean}) to
  10518. perform higher types of simplifications on demand. @xref{Algebraic
  10519. Definitions}, for another sample use of no-simplification mode.@refill
  10520. @node Declarations, Display Modes, Simplification Modes, Mode Settings
  10521. @section Declarations
  10522. @noindent
  10523. A @dfn{declaration} is a statement you make that promises you will
  10524. use a certain variable or function in a restricted way. This may
  10525. give Calc the freedom to do things that it couldn't do if it had to
  10526. take the fully general situation into account.
  10527. @menu
  10528. * Declaration Basics::
  10529. * Kinds of Declarations::
  10530. * Functions for Declarations::
  10531. @end menu
  10532. @node Declaration Basics, Kinds of Declarations, Declarations, Declarations
  10533. @subsection Declaration Basics
  10534. @noindent
  10535. @kindex s d
  10536. @pindex calc-declare-variable
  10537. The @kbd{s d} (@code{calc-declare-variable}) command is the easiest
  10538. way to make a declaration for a variable. This command prompts for
  10539. the variable name, then prompts for the declaration. The default
  10540. at the declaration prompt is the previous declaration, if any.
  10541. You can edit this declaration, or press @kbd{C-k} to erase it and
  10542. type a new declaration. (Or, erase it and press @key{RET} to clear
  10543. the declaration, effectively ``undeclaring'' the variable.)
  10544. A declaration is in general a vector of @dfn{type symbols} and
  10545. @dfn{range} values. If there is only one type symbol or range value,
  10546. you can write it directly rather than enclosing it in a vector.
  10547. For example, @kbd{s d foo @key{RET} real @key{RET}} declares @code{foo} to
  10548. be a real number, and @kbd{s d bar @key{RET} [int, const, [1..6]] @key{RET}}
  10549. declares @code{bar} to be a constant integer between 1 and 6.
  10550. (Actually, you can omit the outermost brackets and Calc will
  10551. provide them for you: @kbd{s d bar @key{RET} int, const, [1..6] @key{RET}}.)
  10552. @cindex @code{Decls} variable
  10553. @vindex Decls
  10554. Declarations in Calc are kept in a special variable called @code{Decls}.
  10555. This variable encodes the set of all outstanding declarations in
  10556. the form of a matrix. Each row has two elements: A variable or
  10557. vector of variables declared by that row, and the declaration
  10558. specifier as described above. You can use the @kbd{s D} command to
  10559. edit this variable if you wish to see all the declarations at once.
  10560. @xref{Operations on Variables}, for a description of this command
  10561. and the @kbd{s p} command that allows you to save your declarations
  10562. permanently if you wish.
  10563. Items being declared can also be function calls. The arguments in
  10564. the call are ignored; the effect is to say that this function returns
  10565. values of the declared type for any valid arguments. The @kbd{s d}
  10566. command declares only variables, so if you wish to make a function
  10567. declaration you will have to edit the @code{Decls} matrix yourself.
  10568. For example, the declaration matrix
  10569. @smallexample
  10570. @group
  10571. [ [ foo, real ]
  10572. [ [j, k, n], int ]
  10573. [ f(1,2,3), [0 .. inf) ] ]
  10574. @end group
  10575. @end smallexample
  10576. @noindent
  10577. declares that @code{foo} represents a real number, @code{j}, @code{k}
  10578. and @code{n} represent integers, and the function @code{f} always
  10579. returns a real number in the interval shown.
  10580. @vindex All
  10581. If there is a declaration for the variable @code{All}, then that
  10582. declaration applies to all variables that are not otherwise declared.
  10583. It does not apply to function names. For example, using the row
  10584. @samp{[All, real]} says that all your variables are real unless they
  10585. are explicitly declared without @code{real} in some other row.
  10586. The @kbd{s d} command declares @code{All} if you give a blank
  10587. response to the variable-name prompt.
  10588. @node Kinds of Declarations, Functions for Declarations, Declaration Basics, Declarations
  10589. @subsection Kinds of Declarations
  10590. @noindent
  10591. The type-specifier part of a declaration (that is, the second prompt
  10592. in the @kbd{s d} command) can be a type symbol, an interval, or a
  10593. vector consisting of zero or more type symbols followed by zero or
  10594. more intervals or numbers that represent the set of possible values
  10595. for the variable.
  10596. @smallexample
  10597. @group
  10598. [ [ a, [1, 2, 3, 4, 5] ]
  10599. [ b, [1 .. 5] ]
  10600. [ c, [int, 1 .. 5] ] ]
  10601. @end group
  10602. @end smallexample
  10603. Here @code{a} is declared to contain one of the five integers shown;
  10604. @code{b} is any number in the interval from 1 to 5 (any real number
  10605. since we haven't specified), and @code{c} is any integer in that
  10606. interval. Thus the declarations for @code{a} and @code{c} are
  10607. nearly equivalent (see below).
  10608. The type-specifier can be the empty vector @samp{[]} to say that
  10609. nothing is known about a given variable's value. This is the same
  10610. as not declaring the variable at all except that it overrides any
  10611. @code{All} declaration which would otherwise apply.
  10612. The initial value of @code{Decls} is the empty vector @samp{[]}.
  10613. If @code{Decls} has no stored value or if the value stored in it
  10614. is not valid, it is ignored and there are no declarations as far
  10615. as Calc is concerned. (The @kbd{s d} command will replace such a
  10616. malformed value with a fresh empty matrix, @samp{[]}, before recording
  10617. the new declaration.) Unrecognized type symbols are ignored.
  10618. The following type symbols describe what sorts of numbers will be
  10619. stored in a variable:
  10620. @table @code
  10621. @item int
  10622. Integers.
  10623. @item numint
  10624. Numerical integers. (Integers or integer-valued floats.)
  10625. @item frac
  10626. Fractions. (Rational numbers which are not integers.)
  10627. @item rat
  10628. Rational numbers. (Either integers or fractions.)
  10629. @item float
  10630. Floating-point numbers.
  10631. @item real
  10632. Real numbers. (Integers, fractions, or floats. Actually,
  10633. intervals and error forms with real components also count as
  10634. reals here.)
  10635. @item pos
  10636. Positive real numbers. (Strictly greater than zero.)
  10637. @item nonneg
  10638. Nonnegative real numbers. (Greater than or equal to zero.)
  10639. @item number
  10640. Numbers. (Real or complex.)
  10641. @end table
  10642. Calc uses this information to determine when certain simplifications
  10643. of formulas are safe. For example, @samp{(x^y)^z} cannot be
  10644. simplified to @samp{x^(y z)} in general; for example,
  10645. @samp{((-3)^2)^1:2} is 3, but @samp{(-3)^(2*1:2) = (-3)^1} is @i{-3}.
  10646. However, this simplification @emph{is} safe if @code{z} is known
  10647. to be an integer, or if @code{x} is known to be a nonnegative
  10648. real number. If you have given declarations that allow Calc to
  10649. deduce either of these facts, Calc will perform this simplification
  10650. of the formula.
  10651. Calc can apply a certain amount of logic when using declarations.
  10652. For example, @samp{(x^y)^(2n+1)} will be simplified if @code{n}
  10653. has been declared @code{int}; Calc knows that an integer times an
  10654. integer, plus an integer, must always be an integer. (In fact,
  10655. Calc would simplify @samp{(-x)^(2n+1)} to @samp{-(x^(2n+1))} since
  10656. it is able to determine that @samp{2n+1} must be an odd integer.)
  10657. Similarly, @samp{(abs(x)^y)^z} will be simplified to @samp{abs(x)^(y z)}
  10658. because Calc knows that the @code{abs} function always returns a
  10659. nonnegative real. If you had a @code{myabs} function that also had
  10660. this property, you could get Calc to recognize it by adding the row
  10661. @samp{[myabs(), nonneg]} to the @code{Decls} matrix.
  10662. One instance of this simplification is @samp{sqrt(x^2)} (since the
  10663. @code{sqrt} function is effectively a one-half power). Normally
  10664. Calc leaves this formula alone. After the command
  10665. @kbd{s d x @key{RET} real @key{RET}}, however, it can simplify the formula to
  10666. @samp{abs(x)}. And after @kbd{s d x @key{RET} nonneg @key{RET}}, Calc can
  10667. simplify this formula all the way to @samp{x}.
  10668. If there are any intervals or real numbers in the type specifier,
  10669. they comprise the set of possible values that the variable or
  10670. function being declared can have. In particular, the type symbol
  10671. @code{real} is effectively the same as the range @samp{[-inf .. inf]}
  10672. (note that infinity is included in the range of possible values);
  10673. @code{pos} is the same as @samp{(0 .. inf]}, and @code{nonneg} is
  10674. the same as @samp{[0 .. inf]}. Saying @samp{[real, [-5 .. 5]]} is
  10675. redundant because the fact that the variable is real can be
  10676. deduced just from the interval, but @samp{[int, [-5 .. 5]]} and
  10677. @samp{[rat, [-5 .. 5]]} are useful combinations.
  10678. Note that the vector of intervals or numbers is in the same format
  10679. used by Calc's set-manipulation commands. @xref{Set Operations}.
  10680. The type specifier @samp{[1, 2, 3]} is equivalent to
  10681. @samp{[numint, 1, 2, 3]}, @emph{not} to @samp{[int, 1, 2, 3]}.
  10682. In other words, the range of possible values means only that
  10683. the variable's value must be numerically equal to a number in
  10684. that range, but not that it must be equal in type as well.
  10685. Calc's set operations act the same way; @samp{in(2, [1., 2., 3.])}
  10686. and @samp{in(1.5, [1:2, 3:2, 5:2])} both report ``true.''
  10687. If you use a conflicting combination of type specifiers, the
  10688. results are unpredictable. An example is @samp{[pos, [0 .. 5]]},
  10689. where the interval does not lie in the range described by the
  10690. type symbol.
  10691. ``Real'' declarations mostly affect simplifications involving powers
  10692. like the one described above. Another case where they are used
  10693. is in the @kbd{a P} command which returns a list of all roots of a
  10694. polynomial; if the variable has been declared real, only the real
  10695. roots (if any) will be included in the list.
  10696. ``Integer'' declarations are used for simplifications which are valid
  10697. only when certain values are integers (such as @samp{(x^y)^z}
  10698. shown above).
  10699. Another command that makes use of declarations is @kbd{a s}, when
  10700. simplifying equations and inequalities. It will cancel @code{x}
  10701. from both sides of @samp{a x = b x} only if it is sure @code{x}
  10702. is non-zero, say, because it has a @code{pos} declaration.
  10703. To declare specifically that @code{x} is real and non-zero,
  10704. use @samp{[[-inf .. 0), (0 .. inf]]}. (There is no way in the
  10705. current notation to say that @code{x} is nonzero but not necessarily
  10706. real.) The @kbd{a e} command does ``unsafe'' simplifications,
  10707. including cancelling @samp{x} from the equation when @samp{x} is
  10708. not known to be nonzero.
  10709. Another set of type symbols distinguish between scalars and vectors.
  10710. @table @code
  10711. @item scalar
  10712. The value is not a vector.
  10713. @item vector
  10714. The value is a vector.
  10715. @item matrix
  10716. The value is a matrix (a rectangular vector of vectors).
  10717. @end table
  10718. These type symbols can be combined with the other type symbols
  10719. described above; @samp{[int, matrix]} describes an object which
  10720. is a matrix of integers.
  10721. Scalar/vector declarations are used to determine whether certain
  10722. algebraic operations are safe. For example, @samp{[a, b, c] + x}
  10723. is normally not simplified to @samp{[a + x, b + x, c + x]}, but
  10724. it will be if @code{x} has been declared @code{scalar}. On the
  10725. other hand, multiplication is usually assumed to be commutative,
  10726. but the terms in @samp{x y} will never be exchanged if both @code{x}
  10727. and @code{y} are known to be vectors or matrices. (Calc currently
  10728. never distinguishes between @code{vector} and @code{matrix}
  10729. declarations.)
  10730. @xref{Matrix Mode}, for a discussion of ``matrix mode'' and
  10731. ``scalar mode,'' which are similar to declaring @samp{[All, matrix]}
  10732. or @samp{[All, scalar]} but much more convenient.
  10733. One more type symbol that is recognized is used with the @kbd{H a d}
  10734. command for taking total derivatives of a formula. @xref{Calculus}.
  10735. @table @code
  10736. @item const
  10737. The value is a constant with respect to other variables.
  10738. @end table
  10739. Calc does not check the declarations for a variable when you store
  10740. a value in it. However, storing @i{-3.5} in a variable that has
  10741. been declared @code{pos}, @code{int}, or @code{matrix} may have
  10742. unexpected effects; Calc may evaluate @samp{sqrt(x^2)} to @cite{3.5}
  10743. if it substitutes the value first, or to @cite{-3.5} if @code{x}
  10744. was declared @code{pos} and the formula @samp{sqrt(x^2)} is
  10745. simplified to @samp{x} before the value is substituted. Before
  10746. using a variable for a new purpose, it is best to use @kbd{s d}
  10747. or @kbd{s D} to check to make sure you don't still have an old
  10748. declaration for the variable that will conflict with its new meaning.
  10749. @node Functions for Declarations, , Kinds of Declarations, Declarations
  10750. @subsection Functions for Declarations
  10751. @noindent
  10752. Calc has a set of functions for accessing the current declarations
  10753. in a convenient manner. These functions return 1 if the argument
  10754. can be shown to have the specified property, or 0 if the argument
  10755. can be shown @emph{not} to have that property; otherwise they are
  10756. left unevaluated. These functions are suitable for use with rewrite
  10757. rules (@pxref{Conditional Rewrite Rules}) or programming constructs
  10758. (@pxref{Conditionals in Macros}). They can be entered only using
  10759. algebraic notation. @xref{Logical Operations}, for functions
  10760. that perform other tests not related to declarations.
  10761. For example, @samp{dint(17)} returns 1 because 17 is an integer, as
  10762. do @samp{dint(n)} and @samp{dint(2 n - 3)} if @code{n} has been declared
  10763. @code{int}, but @samp{dint(2.5)} and @samp{dint(n + 0.5)} return 0.
  10764. Calc consults knowledge of its own built-in functions as well as your
  10765. own declarations: @samp{dint(floor(x))} returns 1.
  10766. @ignore
  10767. @starindex
  10768. @end ignore
  10769. @tindex dint
  10770. @ignore
  10771. @starindex
  10772. @end ignore
  10773. @tindex dnumint
  10774. @ignore
  10775. @starindex
  10776. @end ignore
  10777. @tindex dnatnum
  10778. The @code{dint} function checks if its argument is an integer.
  10779. The @code{dnatnum} function checks if its argument is a natural
  10780. number, i.e., a nonnegative integer. The @code{dnumint} function
  10781. checks if its argument is numerically an integer, i.e., either an
  10782. integer or an integer-valued float. Note that these and the other
  10783. data type functions also accept vectors or matrices composed of
  10784. suitable elements, and that real infinities @samp{inf} and @samp{-inf}
  10785. are considered to be integers for the purposes of these functions.
  10786. @ignore
  10787. @starindex
  10788. @end ignore
  10789. @tindex drat
  10790. The @code{drat} function checks if its argument is rational, i.e.,
  10791. an integer or fraction. Infinities count as rational, but intervals
  10792. and error forms do not.
  10793. @ignore
  10794. @starindex
  10795. @end ignore
  10796. @tindex dreal
  10797. The @code{dreal} function checks if its argument is real. This
  10798. includes integers, fractions, floats, real error forms, and intervals.
  10799. @ignore
  10800. @starindex
  10801. @end ignore
  10802. @tindex dimag
  10803. The @code{dimag} function checks if its argument is imaginary,
  10804. i.e., is mathematically equal to a real number times @cite{i}.
  10805. @ignore
  10806. @starindex
  10807. @end ignore
  10808. @tindex dpos
  10809. @ignore
  10810. @starindex
  10811. @end ignore
  10812. @tindex dneg
  10813. @ignore
  10814. @starindex
  10815. @end ignore
  10816. @tindex dnonneg
  10817. The @code{dpos} function checks for positive (but nonzero) reals.
  10818. The @code{dneg} function checks for negative reals. The @code{dnonneg}
  10819. function checks for nonnegative reals, i.e., reals greater than or
  10820. equal to zero. Note that the @kbd{a s} command can simplify an
  10821. expression like @cite{x > 0} to 1 or 0 using @code{dpos}, and that
  10822. @kbd{a s} is effectively applied to all conditions in rewrite rules,
  10823. so the actual functions @code{dpos}, @code{dneg}, and @code{dnonneg}
  10824. are rarely necessary.
  10825. @ignore
  10826. @starindex
  10827. @end ignore
  10828. @tindex dnonzero
  10829. The @code{dnonzero} function checks that its argument is nonzero.
  10830. This includes all nonzero real or complex numbers, all intervals that
  10831. do not include zero, all nonzero modulo forms, vectors all of whose
  10832. elements are nonzero, and variables or formulas whose values can be
  10833. deduced to be nonzero. It does not include error forms, since they
  10834. represent values which could be anything including zero. (This is
  10835. also the set of objects considered ``true'' in conditional contexts.)
  10836. @ignore
  10837. @starindex
  10838. @end ignore
  10839. @tindex deven
  10840. @ignore
  10841. @starindex
  10842. @end ignore
  10843. @tindex dodd
  10844. The @code{deven} function returns 1 if its argument is known to be
  10845. an even integer (or integer-valued float); it returns 0 if its argument
  10846. is known not to be even (because it is known to be odd or a non-integer).
  10847. The @kbd{a s} command uses this to simplify a test of the form
  10848. @samp{x % 2 = 0}. There is also an analogous @code{dodd} function.
  10849. @ignore
  10850. @starindex
  10851. @end ignore
  10852. @tindex drange
  10853. The @code{drange} function returns a set (an interval or a vector
  10854. of intervals and/or numbers; @pxref{Set Operations}) that describes
  10855. the set of possible values of its argument. If the argument is
  10856. a variable or a function with a declaration, the range is copied
  10857. from the declaration. Otherwise, the possible signs of the
  10858. expression are determined using a method similar to @code{dpos},
  10859. etc., and a suitable set like @samp{[0 .. inf]} is returned. If
  10860. the expression is not provably real, the @code{drange} function
  10861. remains unevaluated.
  10862. @ignore
  10863. @starindex
  10864. @end ignore
  10865. @tindex dscalar
  10866. The @code{dscalar} function returns 1 if its argument is provably
  10867. scalar, or 0 if its argument is provably non-scalar. It is left
  10868. unevaluated if this cannot be determined. (If matrix mode or scalar
  10869. mode are in effect, this function returns 1 or 0, respectively,
  10870. if it has no other information.) When Calc interprets a condition
  10871. (say, in a rewrite rule) it considers an unevaluated formula to be
  10872. ``false.'' Thus, @samp{dscalar(a)} is ``true'' only if @code{a} is
  10873. provably scalar, and @samp{!dscalar(a)} is ``true'' only if @code{a}
  10874. is provably non-scalar; both are ``false'' if there is insufficient
  10875. information to tell.
  10876. @node Display Modes, Language Modes, Declarations, Mode Settings
  10877. @section Display Modes
  10878. @noindent
  10879. The commands in this section are two-key sequences beginning with the
  10880. @kbd{d} prefix. The @kbd{d l} (@code{calc-line-numbering}) and @kbd{d b}
  10881. (@code{calc-line-breaking}) commands are described elsewhere;
  10882. @pxref{Stack Basics} and @pxref{Normal Language Modes}, respectively.
  10883. Display formats for vectors and matrices are also covered elsewhere;
  10884. @pxref{Vector and Matrix Formats}.@refill
  10885. One thing all display modes have in common is their treatment of the
  10886. @kbd{H} prefix. This prefix causes any mode command that would normally
  10887. refresh the stack to leave the stack display alone. The word ``Dirty''
  10888. will appear in the mode line when Calc thinks the stack display may not
  10889. reflect the latest mode settings.
  10890. @kindex d @key{RET}
  10891. @pindex calc-refresh-top
  10892. The @kbd{d @key{RET}} (@code{calc-refresh-top}) command reformats the
  10893. top stack entry according to all the current modes. Positive prefix
  10894. arguments reformat the top @var{n} entries; negative prefix arguments
  10895. reformat the specified entry, and a prefix of zero is equivalent to
  10896. @kbd{d @key{SPC}} (@code{calc-refresh}), which reformats the entire stack.
  10897. For example, @kbd{H d s M-2 d @key{RET}} changes to scientific notation
  10898. but reformats only the top two stack entries in the new mode.
  10899. The @kbd{I} prefix has another effect on the display modes. The mode
  10900. is set only temporarily; the top stack entry is reformatted according
  10901. to that mode, then the original mode setting is restored. In other
  10902. words, @kbd{I d s} is equivalent to @kbd{H d s d @key{RET} H d (@var{old mode})}.
  10903. @menu
  10904. * Radix Modes::
  10905. * Grouping Digits::
  10906. * Float Formats::
  10907. * Complex Formats::
  10908. * Fraction Formats::
  10909. * HMS Formats::
  10910. * Date Formats::
  10911. * Truncating the Stack::
  10912. * Justification::
  10913. * Labels::
  10914. @end menu
  10915. @node Radix Modes, Grouping Digits, Display Modes, Display Modes
  10916. @subsection Radix Modes
  10917. @noindent
  10918. @cindex Radix display
  10919. @cindex Non-decimal numbers
  10920. @cindex Decimal and non-decimal numbers
  10921. Calc normally displays numbers in decimal (@dfn{base-10} or @dfn{radix-10})
  10922. notation. Calc can actually display in any radix from two (binary) to 36.
  10923. When the radix is above 10, the letters @code{A} to @code{Z} are used as
  10924. digits. When entering such a number, letter keys are interpreted as
  10925. potential digits rather than terminating numeric entry mode.
  10926. @kindex d 2
  10927. @kindex d 8
  10928. @kindex d 6
  10929. @kindex d 0
  10930. @cindex Hexadecimal integers
  10931. @cindex Octal integers
  10932. The key sequences @kbd{d 2}, @kbd{d 8}, @kbd{d 6}, and @kbd{d 0} select
  10933. binary, octal, hexadecimal, and decimal as the current display radix,
  10934. respectively. Numbers can always be entered in any radix, though the
  10935. current radix is used as a default if you press @kbd{#} without any initial
  10936. digits. A number entered without a @kbd{#} is @emph{always} interpreted
  10937. as decimal.@refill
  10938. @kindex d r
  10939. @pindex calc-radix
  10940. To set the radix generally, use @kbd{d r} (@code{calc-radix}) and enter
  10941. an integer from 2 to 36. You can specify the radix as a numeric prefix
  10942. argument; otherwise you will be prompted for it.
  10943. @kindex d z
  10944. @pindex calc-leading-zeros
  10945. @cindex Leading zeros
  10946. Integers normally are displayed with however many digits are necessary to
  10947. represent the integer and no more. The @kbd{d z} (@code{calc-leading-zeros})
  10948. command causes integers to be padded out with leading zeros according to the
  10949. current binary word size. (@xref{Binary Functions}, for a discussion of
  10950. word size.) If the absolute value of the word size is @cite{w}, all integers
  10951. are displayed with at least enough digits to represent @c{$2^w-1$}
  10952. @cite{(2^w)-1} in the
  10953. current radix. (Larger integers will still be displayed in their entirety.)
  10954. @node Grouping Digits, Float Formats, Radix Modes, Display Modes
  10955. @subsection Grouping Digits
  10956. @noindent
  10957. @kindex d g
  10958. @pindex calc-group-digits
  10959. @cindex Grouping digits
  10960. @cindex Digit grouping
  10961. Long numbers can be hard to read if they have too many digits. For
  10962. example, the factorial of 30 is 33 digits long! Press @kbd{d g}
  10963. (@code{calc-group-digits}) to enable @dfn{grouping} mode, in which digits
  10964. are displayed in clumps of 3 or 4 (depending on the current radix)
  10965. separated by commas.
  10966. The @kbd{d g} command toggles grouping on and off.
  10967. With a numerix prefix of 0, this command displays the current state of
  10968. the grouping flag; with an argument of minus one it disables grouping;
  10969. with a positive argument @cite{N} it enables grouping on every @cite{N}
  10970. digits. For floating-point numbers, grouping normally occurs only
  10971. before the decimal point. A negative prefix argument @cite{-N} enables
  10972. grouping every @cite{N} digits both before and after the decimal point.@refill
  10973. @kindex d ,
  10974. @pindex calc-group-char
  10975. The @kbd{d ,} (@code{calc-group-char}) command allows you to choose any
  10976. character as the grouping separator. The default is the comma character.
  10977. If you find it difficult to read vectors of large integers grouped with
  10978. commas, you may wish to use spaces or some other character instead.
  10979. This command takes the next character you type, whatever it is, and
  10980. uses it as the digit separator. As a special case, @kbd{d , \} selects
  10981. @samp{\,} (@TeX{}'s thin-space symbol) as the digit separator.
  10982. Please note that grouped numbers will not generally be parsed correctly
  10983. if re-read in textual form, say by the use of @kbd{M-# y} and @kbd{M-# g}.
  10984. (@xref{Kill and Yank}, for details on these commands.) One exception is
  10985. the @samp{\,} separator, which doesn't interfere with parsing because it
  10986. is ignored by @TeX{} language mode.
  10987. @node Float Formats, Complex Formats, Grouping Digits, Display Modes
  10988. @subsection Float Formats
  10989. @noindent
  10990. Floating-point quantities are normally displayed in standard decimal
  10991. form, with scientific notation used if the exponent is especially high
  10992. or low. All significant digits are normally displayed. The commands
  10993. in this section allow you to choose among several alternative display
  10994. formats for floats.
  10995. @kindex d n
  10996. @pindex calc-normal-notation
  10997. The @kbd{d n} (@code{calc-normal-notation}) command selects the normal
  10998. display format. All significant figures in a number are displayed.
  10999. With a positive numeric prefix, numbers are rounded if necessary to
  11000. that number of significant digits. With a negative numerix prefix,
  11001. the specified number of significant digits less than the current
  11002. precision is used. (Thus @kbd{C-u -2 d n} displays 10 digits if the
  11003. current precision is 12.)
  11004. @kindex d f
  11005. @pindex calc-fix-notation
  11006. The @kbd{d f} (@code{calc-fix-notation}) command selects fixed-point
  11007. notation. The numeric argument is the number of digits after the
  11008. decimal point, zero or more. This format will relax into scientific
  11009. notation if a nonzero number would otherwise have been rounded all the
  11010. way to zero. Specifying a negative number of digits is the same as
  11011. for a positive number, except that small nonzero numbers will be rounded
  11012. to zero rather than switching to scientific notation.
  11013. @kindex d s
  11014. @pindex calc-sci-notation
  11015. @cindex Scientific notation, display of
  11016. The @kbd{d s} (@code{calc-sci-notation}) command selects scientific
  11017. notation. A positive argument sets the number of significant figures
  11018. displayed, of which one will be before and the rest after the decimal
  11019. point. A negative argument works the same as for @kbd{d n} format.
  11020. The default is to display all significant digits.
  11021. @kindex d e
  11022. @pindex calc-eng-notation
  11023. @cindex Engineering notation, display of
  11024. The @kbd{d e} (@code{calc-eng-notation}) command selects engineering
  11025. notation. This is similar to scientific notation except that the
  11026. exponent is rounded down to a multiple of three, with from one to three
  11027. digits before the decimal point. An optional numeric prefix sets the
  11028. number of significant digits to display, as for @kbd{d s}.
  11029. It is important to distinguish between the current @emph{precision} and
  11030. the current @emph{display format}. After the commands @kbd{C-u 10 p}
  11031. and @kbd{C-u 6 d n} the Calculator computes all results to ten
  11032. significant figures but displays only six. (In fact, intermediate
  11033. calculations are often carried to one or two more significant figures,
  11034. but values placed on the stack will be rounded down to ten figures.)
  11035. Numbers are never actually rounded to the display precision for storage,
  11036. except by commands like @kbd{C-k} and @kbd{M-# y} which operate on the
  11037. actual displayed text in the Calculator buffer.
  11038. @kindex d .
  11039. @pindex calc-point-char
  11040. The @kbd{d .} (@code{calc-point-char}) command selects the character used
  11041. as a decimal point. Normally this is a period; users in some countries
  11042. may wish to change this to a comma. Note that this is only a display
  11043. style; on entry, periods must always be used to denote floating-point
  11044. numbers, and commas to separate elements in a list.
  11045. @node Complex Formats, Fraction Formats, Float Formats, Display Modes
  11046. @subsection Complex Formats
  11047. @noindent
  11048. @kindex d c
  11049. @pindex calc-complex-notation
  11050. There are three supported notations for complex numbers in rectangular
  11051. form. The default is as a pair of real numbers enclosed in parentheses
  11052. and separated by a comma: @samp{(a,b)}. The @kbd{d c}
  11053. (@code{calc-complex-notation}) command selects this style.@refill
  11054. @kindex d i
  11055. @pindex calc-i-notation
  11056. @kindex d j
  11057. @pindex calc-j-notation
  11058. The other notations are @kbd{d i} (@code{calc-i-notation}), in which
  11059. numbers are displayed in @samp{a+bi} form, and @kbd{d j}
  11060. (@code{calc-j-notation}) which displays the form @samp{a+bj} preferred
  11061. in some disciplines.@refill
  11062. @cindex @code{i} variable
  11063. @vindex i
  11064. Complex numbers are normally entered in @samp{(a,b)} format.
  11065. If you enter @samp{2+3i} as an algebraic formula, it will be stored as
  11066. the formula @samp{2 + 3 * i}. However, if you use @kbd{=} to evaluate
  11067. this formula and you have not changed the variable @samp{i}, the @samp{i}
  11068. will be interpreted as @samp{(0,1)} and the formula will be simplified
  11069. to @samp{(2,3)}. Other commands (like @code{calc-sin}) will @emph{not}
  11070. interpret the formula @samp{2 + 3 * i} as a complex number.
  11071. @xref{Variables}, under ``special constants.''@refill
  11072. @node Fraction Formats, HMS Formats, Complex Formats, Display Modes
  11073. @subsection Fraction Formats
  11074. @noindent
  11075. @kindex d o
  11076. @pindex calc-over-notation
  11077. Display of fractional numbers is controlled by the @kbd{d o}
  11078. (@code{calc-over-notation}) command. By default, a number like
  11079. eight thirds is displayed in the form @samp{8:3}. The @kbd{d o} command
  11080. prompts for a one- or two-character format. If you give one character,
  11081. that character is used as the fraction separator. Common separators are
  11082. @samp{:} and @samp{/}. (During input of numbers, the @kbd{:} key must be
  11083. used regardless of the display format; in particular, the @kbd{/} is used
  11084. for RPN-style division, @emph{not} for entering fractions.)
  11085. If you give two characters, fractions use ``integer-plus-fractional-part''
  11086. notation. For example, the format @samp{+/} would display eight thirds
  11087. as @samp{2+2/3}. If two colons are present in a number being entered,
  11088. the number is interpreted in this form (so that the entries @kbd{2:2:3}
  11089. and @kbd{8:3} are equivalent).
  11090. It is also possible to follow the one- or two-character format with
  11091. a number. For example: @samp{:10} or @samp{+/3}. In this case,
  11092. Calc adjusts all fractions that are displayed to have the specified
  11093. denominator, if possible. Otherwise it adjusts the denominator to
  11094. be a multiple of the specified value. For example, in @samp{:6} mode
  11095. the fraction @cite{1:6} will be unaffected, but @cite{2:3} will be
  11096. displayed as @cite{4:6}, @cite{1:2} will be displayed as @cite{3:6},
  11097. and @cite{1:8} will be displayed as @cite{3:24}. Integers are also
  11098. affected by this mode: 3 is displayed as @cite{18:6}. Note that the
  11099. format @samp{:1} writes fractions the same as @samp{:}, but it writes
  11100. integers as @cite{n:1}.
  11101. The fraction format does not affect the way fractions or integers are
  11102. stored, only the way they appear on the screen. The fraction format
  11103. never affects floats.
  11104. @node HMS Formats, Date Formats, Fraction Formats, Display Modes
  11105. @subsection HMS Formats
  11106. @noindent
  11107. @kindex d h
  11108. @pindex calc-hms-notation
  11109. The @kbd{d h} (@code{calc-hms-notation}) command controls the display of
  11110. HMS (hours-minutes-seconds) forms. It prompts for a string which
  11111. consists basically of an ``hours'' marker, optional punctuation, a
  11112. ``minutes'' marker, more optional punctuation, and a ``seconds'' marker.
  11113. Punctuation is zero or more spaces, commas, or semicolons. The hours
  11114. marker is one or more non-punctuation characters. The minutes and
  11115. seconds markers must be single non-punctuation characters.
  11116. The default HMS format is @samp{@@ ' "}, producing HMS values of the form
  11117. @samp{23@@ 30' 15.75"}. The format @samp{deg, ms} would display this same
  11118. value as @samp{23deg, 30m15.75s}. During numeric entry, the @kbd{h} or @kbd{o}
  11119. keys are recognized as synonyms for @kbd{@@} regardless of display format.
  11120. The @kbd{m} and @kbd{s} keys are recognized as synonyms for @kbd{'} and
  11121. @kbd{"}, respectively, but only if an @kbd{@@} (or @kbd{h} or @kbd{o}) has
  11122. already been typed; otherwise, they have their usual meanings
  11123. (@kbd{m-} prefix and @kbd{s-} prefix). Thus, @kbd{5 "}, @kbd{0 @@ 5 "}, and
  11124. @kbd{0 h 5 s} are some of the ways to enter the quantity ``five seconds.''
  11125. The @kbd{'} key is recognized as ``minutes'' only if @kbd{@@} (or @kbd{h} or
  11126. @kbd{o}) has already been pressed; otherwise it means to switch to algebraic
  11127. entry.
  11128. @node Date Formats, Truncating the Stack, HMS Formats, Display Modes
  11129. @subsection Date Formats
  11130. @noindent
  11131. @kindex d d
  11132. @pindex calc-date-notation
  11133. The @kbd{d d} (@code{calc-date-notation}) command controls the display
  11134. of date forms (@pxref{Date Forms}). It prompts for a string which
  11135. contains letters that represent the various parts of a date and time.
  11136. To show which parts should be omitted when the form represents a pure
  11137. date with no time, parts of the string can be enclosed in @samp{< >}
  11138. marks. If you don't include @samp{< >} markers in the format, Calc
  11139. guesses at which parts, if any, should be omitted when formatting
  11140. pure dates.
  11141. The default format is: @samp{<H:mm:SSpp >Www Mmm D, YYYY}.
  11142. An example string in this format is @samp{3:32pm Wed Jan 9, 1991}.
  11143. If you enter a blank format string, this default format is
  11144. reestablished.
  11145. Calc uses @samp{< >} notation for nameless functions as well as for
  11146. dates. @xref{Specifying Operators}. To avoid confusion with nameless
  11147. functions, your date formats should avoid using the @samp{#} character.
  11148. @menu
  11149. * Date Formatting Codes::
  11150. * Free-Form Dates::
  11151. * Standard Date Formats::
  11152. @end menu
  11153. @node Date Formatting Codes, Free-Form Dates, Date Formats, Date Formats
  11154. @subsubsection Date Formatting Codes
  11155. @noindent
  11156. When displaying a date, the current date format is used. All
  11157. characters except for letters and @samp{<} and @samp{>} are
  11158. copied literally when dates are formatted. The portion between
  11159. @samp{< >} markers is omitted for pure dates, or included for
  11160. date/time forms. Letters are interpreted according to the table
  11161. below.
  11162. When dates are read in during algebraic entry, Calc first tries to
  11163. match the input string to the current format either with or without
  11164. the time part. The punctuation characters (including spaces) must
  11165. match exactly; letter fields must correspond to suitable text in
  11166. the input. If this doesn't work, Calc checks if the input is a
  11167. simple number; if so, the number is interpreted as a number of days
  11168. since Jan 1, 1 AD. Otherwise, Calc tries a much more relaxed and
  11169. flexible algorithm which is described in the next section.
  11170. Weekday names are ignored during reading.
  11171. Two-digit year numbers are interpreted as lying in the range
  11172. from 1941 to 2039. Years outside that range are always
  11173. entered and displayed in full. Year numbers with a leading
  11174. @samp{+} sign are always interpreted exactly, allowing the
  11175. entry and display of the years 1 through 99 AD.
  11176. Here is a complete list of the formatting codes for dates:
  11177. @table @asis
  11178. @item Y
  11179. Year: ``91'' for 1991, ``7'' for 2007, ``+23'' for 23 AD.
  11180. @item YY
  11181. Year: ``91'' for 1991, ``07'' for 2007, ``+23'' for 23 AD.
  11182. @item BY
  11183. Year: ``91'' for 1991, `` 7'' for 2007, ``+23'' for 23 AD.
  11184. @item YYY
  11185. Year: ``1991'' for 1991, ``23'' for 23 AD.
  11186. @item YYYY
  11187. Year: ``1991'' for 1991, ``+23'' for 23 AD.
  11188. @item aa
  11189. Year: ``ad'' or blank.
  11190. @item AA
  11191. Year: ``AD'' or blank.
  11192. @item aaa
  11193. Year: ``ad '' or blank. (Note trailing space.)
  11194. @item AAA
  11195. Year: ``AD '' or blank.
  11196. @item aaaa
  11197. Year: ``a.d.'' or blank.
  11198. @item AAAA
  11199. Year: ``A.D.'' or blank.
  11200. @item bb
  11201. Year: ``bc'' or blank.
  11202. @item BB
  11203. Year: ``BC'' or blank.
  11204. @item bbb
  11205. Year: `` bc'' or blank. (Note leading space.)
  11206. @item BBB
  11207. Year: `` BC'' or blank.
  11208. @item bbbb
  11209. Year: ``b.c.'' or blank.
  11210. @item BBBB
  11211. Year: ``B.C.'' or blank.
  11212. @item M
  11213. Month: ``8'' for August.
  11214. @item MM
  11215. Month: ``08'' for August.
  11216. @item BM
  11217. Month: `` 8'' for August.
  11218. @item MMM
  11219. Month: ``AUG'' for August.
  11220. @item Mmm
  11221. Month: ``Aug'' for August.
  11222. @item mmm
  11223. Month: ``aug'' for August.
  11224. @item MMMM
  11225. Month: ``AUGUST'' for August.
  11226. @item Mmmm
  11227. Month: ``August'' for August.
  11228. @item D
  11229. Day: ``7'' for 7th day of month.
  11230. @item DD
  11231. Day: ``07'' for 7th day of month.
  11232. @item BD
  11233. Day: `` 7'' for 7th day of month.
  11234. @item W
  11235. Weekday: ``0'' for Sunday, ``6'' for Saturday.
  11236. @item WWW
  11237. Weekday: ``SUN'' for Sunday.
  11238. @item Www
  11239. Weekday: ``Sun'' for Sunday.
  11240. @item www
  11241. Weekday: ``sun'' for Sunday.
  11242. @item WWWW
  11243. Weekday: ``SUNDAY'' for Sunday.
  11244. @item Wwww
  11245. Weekday: ``Sunday'' for Sunday.
  11246. @item d
  11247. Day of year: ``34'' for Feb. 3.
  11248. @item ddd
  11249. Day of year: ``034'' for Feb. 3.
  11250. @item bdd
  11251. Day of year: `` 34'' for Feb. 3.
  11252. @item h
  11253. Hour: ``5'' for 5 AM; ``17'' for 5 PM.
  11254. @item hh
  11255. Hour: ``05'' for 5 AM; ``17'' for 5 PM.
  11256. @item bh
  11257. Hour: `` 5'' for 5 AM; ``17'' for 5 PM.
  11258. @item H
  11259. Hour: ``5'' for 5 AM and 5 PM.
  11260. @item HH
  11261. Hour: ``05'' for 5 AM and 5 PM.
  11262. @item BH
  11263. Hour: `` 5'' for 5 AM and 5 PM.
  11264. @item p
  11265. AM/PM: ``a'' or ``p''.
  11266. @item P
  11267. AM/PM: ``A'' or ``P''.
  11268. @item pp
  11269. AM/PM: ``am'' or ``pm''.
  11270. @item PP
  11271. AM/PM: ``AM'' or ``PM''.
  11272. @item pppp
  11273. AM/PM: ``a.m.'' or ``p.m.''.
  11274. @item PPPP
  11275. AM/PM: ``A.M.'' or ``P.M.''.
  11276. @item m
  11277. Minutes: ``7'' for 7.
  11278. @item mm
  11279. Minutes: ``07'' for 7.
  11280. @item bm
  11281. Minutes: `` 7'' for 7.
  11282. @item s
  11283. Seconds: ``7'' for 7; ``7.23'' for 7.23.
  11284. @item ss
  11285. Seconds: ``07'' for 7; ``07.23'' for 7.23.
  11286. @item bs
  11287. Seconds: `` 7'' for 7; `` 7.23'' for 7.23.
  11288. @item SS
  11289. Optional seconds: ``07'' for 7; blank for 0.
  11290. @item BS
  11291. Optional seconds: `` 7'' for 7; blank for 0.
  11292. @item N
  11293. Numeric date/time: ``726842.25'' for 6:00am Wed Jan 9, 1991.
  11294. @item n
  11295. Numeric date: ``726842'' for any time on Wed Jan 9, 1991.
  11296. @item J
  11297. Julian date/time: ``2448265.75'' for 6:00am Wed Jan 9, 1991.
  11298. @item j
  11299. Julian date: ``2448266'' for any time on Wed Jan 9, 1991.
  11300. @item U
  11301. Unix time: ``663400800'' for 6:00am Wed Jan 9, 1991.
  11302. @item X
  11303. Brackets suppression. An ``X'' at the front of the format
  11304. causes the surrounding @w{@samp{< >}} delimiters to be omitted
  11305. when formatting dates. Note that the brackets are still
  11306. required for algebraic entry.
  11307. @end table
  11308. If ``SS'' or ``BS'' (optional seconds) is preceded by a colon, the
  11309. colon is also omitted if the seconds part is zero.
  11310. If ``bb,'' ``bbb'' or ``bbbb'' or their upper-case equivalents
  11311. appear in the format, then negative year numbers are displayed
  11312. without a minus sign. Note that ``aa'' and ``bb'' are mutually
  11313. exclusive. Some typical usages would be @samp{YYYY AABB};
  11314. @samp{AAAYYYYBBB}; @samp{YYYYBBB}.
  11315. The formats ``YY,'' ``YYYY,'' ``MM,'' ``DD,'' ``ddd,'' ``hh,'' ``HH,''
  11316. ``mm,'' ``ss,'' and ``SS'' actually match any number of digits during
  11317. reading unless several of these codes are strung together with no
  11318. punctuation in between, in which case the input must have exactly as
  11319. many digits as there are letters in the format.
  11320. The ``j,'' ``J,'' and ``U'' formats do not make any time zone
  11321. adjustment. They effectively use @samp{julian(x,0)} and
  11322. @samp{unixtime(x,0)} to make the conversion; @pxref{Date Arithmetic}.
  11323. @node Free-Form Dates, Standard Date Formats, Date Formatting Codes, Date Formats
  11324. @subsubsection Free-Form Dates
  11325. @noindent
  11326. When reading a date form during algebraic entry, Calc falls back
  11327. on the algorithm described here if the input does not exactly
  11328. match the current date format. This algorithm generally
  11329. ``does the right thing'' and you don't have to worry about it,
  11330. but it is described here in full detail for the curious.
  11331. Calc does not distinguish between upper- and lower-case letters
  11332. while interpreting dates.
  11333. First, the time portion, if present, is located somewhere in the
  11334. text and then removed. The remaining text is then interpreted as
  11335. the date.
  11336. A time is of the form @samp{hh:mm:ss}, possibly with the seconds
  11337. part omitted and possibly with an AM/PM indicator added to indicate
  11338. 12-hour time. If the AM/PM is present, the minutes may also be
  11339. omitted. The AM/PM part may be any of the words @samp{am},
  11340. @samp{pm}, @samp{noon}, or @samp{midnight}; each of these may be
  11341. abbreviated to one letter, and the alternate forms @samp{a.m.},
  11342. @samp{p.m.}, and @samp{mid} are also understood. Obviously
  11343. @samp{noon} and @samp{midnight} are allowed only on 12:00:00.
  11344. The words @samp{noon}, @samp{mid}, and @samp{midnight} are also
  11345. recognized with no number attached.
  11346. If there is no AM/PM indicator, the time is interpreted in 24-hour
  11347. format.
  11348. To read the date portion, all words and numbers are isolated
  11349. from the string; other characters are ignored. All words must
  11350. be either month names or day-of-week names (the latter of which
  11351. are ignored). Names can be written in full or as three-letter
  11352. abbreviations.
  11353. Large numbers, or numbers with @samp{+} or @samp{-} signs,
  11354. are interpreted as years. If one of the other numbers is
  11355. greater than 12, then that must be the day and the remaining
  11356. number in the input is therefore the month. Otherwise, Calc
  11357. assumes the month, day and year are in the same order that they
  11358. appear in the current date format. If the year is omitted, the
  11359. current year is taken from the system clock.
  11360. If there are too many or too few numbers, or any unrecognizable
  11361. words, then the input is rejected.
  11362. If there are any large numbers (of five digits or more) other than
  11363. the year, they are ignored on the assumption that they are something
  11364. like Julian dates that were included along with the traditional
  11365. date components when the date was formatted.
  11366. One of the words @samp{ad}, @samp{a.d.}, @samp{bc}, or @samp{b.c.}
  11367. may optionally be used; the latter two are equivalent to a
  11368. minus sign on the year value.
  11369. If you always enter a four-digit year, and use a name instead
  11370. of a number for the month, there is no danger of ambiguity.
  11371. @node Standard Date Formats, , Free-Form Dates, Date Formats
  11372. @subsubsection Standard Date Formats
  11373. @noindent
  11374. There are actually ten standard date formats, numbered 0 through 9.
  11375. Entering a blank line at the @kbd{d d} command's prompt gives
  11376. you format number 1, Calc's usual format. You can enter any digit
  11377. to select the other formats.
  11378. To create your own standard date formats, give a numeric prefix
  11379. argument from 0 to 9 to the @w{@kbd{d d}} command. The format you
  11380. enter will be recorded as the new standard format of that
  11381. number, as well as becoming the new current date format.
  11382. You can save your formats permanently with the @w{@kbd{m m}}
  11383. command (@pxref{Mode Settings}).
  11384. @table @asis
  11385. @item 0
  11386. @samp{N} (Numerical format)
  11387. @item 1
  11388. @samp{<H:mm:SSpp >Www Mmm D, YYYY} (American format)
  11389. @item 2
  11390. @samp{D Mmm YYYY<, h:mm:SS>} (European format)
  11391. @item 3
  11392. @samp{Www Mmm BD< hh:mm:ss> YYYY} (Unix written date format)
  11393. @item 4
  11394. @samp{M/D/Y< H:mm:SSpp>} (American slashed format)
  11395. @item 5
  11396. @samp{D.M.Y< h:mm:SS>} (European dotted format)
  11397. @item 6
  11398. @samp{M-D-Y< H:mm:SSpp>} (American dashed format)
  11399. @item 7
  11400. @samp{D-M-Y< h:mm:SS>} (European dashed format)
  11401. @item 8
  11402. @samp{j<, h:mm:ss>} (Julian day plus time)
  11403. @item 9
  11404. @samp{YYddd< hh:mm:ss>} (Year-day format)
  11405. @end table
  11406. @node Truncating the Stack, Justification, Date Formats, Display Modes
  11407. @subsection Truncating the Stack
  11408. @noindent
  11409. @kindex d t
  11410. @pindex calc-truncate-stack
  11411. @cindex Truncating the stack
  11412. @cindex Narrowing the stack
  11413. The @kbd{d t} (@code{calc-truncate-stack}) command moves the @samp{.}@:
  11414. line that marks the top-of-stack up or down in the Calculator buffer.
  11415. The number right above that line is considered to the be at the top of
  11416. the stack. Any numbers below that line are ``hidden'' from all stack
  11417. operations. This is similar to the Emacs ``narrowing'' feature, except
  11418. that the values below the @samp{.} are @emph{visible}, just temporarily
  11419. frozen. This feature allows you to keep several independent calculations
  11420. running at once in different parts of the stack, or to apply a certain
  11421. command to an element buried deep in the stack.@refill
  11422. Pressing @kbd{d t} by itself moves the @samp{.} to the line the cursor
  11423. is on. Thus, this line and all those below it become hidden. To un-hide
  11424. these lines, move down to the end of the buffer and press @w{@kbd{d t}}.
  11425. With a positive numeric prefix argument @cite{n}, @kbd{d t} hides the
  11426. bottom @cite{n} values in the buffer. With a negative argument, it hides
  11427. all but the top @cite{n} values. With an argument of zero, it hides zero
  11428. values, i.e., moves the @samp{.} all the way down to the bottom.@refill
  11429. @kindex d [
  11430. @pindex calc-truncate-up
  11431. @kindex d ]
  11432. @pindex calc-truncate-down
  11433. The @kbd{d [} (@code{calc-truncate-up}) and @kbd{d ]}
  11434. (@code{calc-truncate-down}) commands move the @samp{.} up or down one
  11435. line at a time (or several lines with a prefix argument).@refill
  11436. @node Justification, Labels, Truncating the Stack, Display Modes
  11437. @subsection Justification
  11438. @noindent
  11439. @kindex d <
  11440. @pindex calc-left-justify
  11441. @kindex d =
  11442. @pindex calc-center-justify
  11443. @kindex d >
  11444. @pindex calc-right-justify
  11445. Values on the stack are normally left-justified in the window. You can
  11446. control this arrangement by typing @kbd{d <} (@code{calc-left-justify}),
  11447. @kbd{d >} (@code{calc-right-justify}), or @kbd{d =}
  11448. (@code{calc-center-justify}). For example, in right-justification mode,
  11449. stack entries are displayed flush-right against the right edge of the
  11450. window.@refill
  11451. If you change the width of the Calculator window you may have to type
  11452. @kbd{d @key{SPC}} (@code{calc-refresh}) to re-align right-justified or centered
  11453. text.
  11454. Right-justification is especially useful together with fixed-point
  11455. notation (see @code{d f}; @code{calc-fix-notation}). With these modes
  11456. together, the decimal points on numbers will always line up.
  11457. With a numeric prefix argument, the justification commands give you
  11458. a little extra control over the display. The argument specifies the
  11459. horizontal ``origin'' of a display line. It is also possible to
  11460. specify a maximum line width using the @kbd{d b} command (@pxref{Normal
  11461. Language Modes}). For reference, the precise rules for formatting and
  11462. breaking lines are given below. Notice that the interaction between
  11463. origin and line width is slightly different in each justification
  11464. mode.
  11465. In left-justified mode, the line is indented by a number of spaces
  11466. given by the origin (default zero). If the result is longer than the
  11467. maximum line width, if given, or too wide to fit in the Calc window
  11468. otherwise, then it is broken into lines which will fit; each broken
  11469. line is indented to the origin.
  11470. In right-justified mode, lines are shifted right so that the rightmost
  11471. character is just before the origin, or just before the current
  11472. window width if no origin was specified. If the line is too long
  11473. for this, then it is broken; the current line width is used, if
  11474. specified, or else the origin is used as a width if that is
  11475. specified, or else the line is broken to fit in the window.
  11476. In centering mode, the origin is the column number of the center of
  11477. each stack entry. If a line width is specified, lines will not be
  11478. allowed to go past that width; Calc will either indent less or
  11479. break the lines if necessary. If no origin is specified, half the
  11480. line width or Calc window width is used.
  11481. Note that, in each case, if line numbering is enabled the display
  11482. is indented an additional four spaces to make room for the line
  11483. number. The width of the line number is taken into account when
  11484. positioning according to the current Calc window width, but not
  11485. when positioning by explicit origins and widths. In the latter
  11486. case, the display is formatted as specified, and then uniformly
  11487. shifted over four spaces to fit the line numbers.
  11488. @node Labels, , Justification, Display Modes
  11489. @subsection Labels
  11490. @noindent
  11491. @kindex d @{
  11492. @pindex calc-left-label
  11493. The @kbd{d @{} (@code{calc-left-label}) command prompts for a string,
  11494. then displays that string to the left of every stack entry. If the
  11495. entries are left-justified (@pxref{Justification}), then they will
  11496. appear immediately after the label (unless you specified an origin
  11497. greater than the length of the label). If the entries are centered
  11498. or right-justified, the label appears on the far left and does not
  11499. affect the horizontal position of the stack entry.
  11500. Give a blank string (with @kbd{d @{ @key{RET}}) to turn the label off.
  11501. @kindex d @}
  11502. @pindex calc-right-label
  11503. The @kbd{d @}} (@code{calc-right-label}) command similarly adds a
  11504. label on the righthand side. It does not affect positioning of
  11505. the stack entries unless they are right-justified. Also, if both
  11506. a line width and an origin are given in right-justified mode, the
  11507. stack entry is justified to the origin and the righthand label is
  11508. justified to the line width.
  11509. One application of labels would be to add equation numbers to
  11510. formulas you are manipulating in Calc and then copying into a
  11511. document (possibly using Embedded Mode). The equations would
  11512. typically be centered, and the equation numbers would be on the
  11513. left or right as you prefer.
  11514. @node Language Modes, Modes Variable, Display Modes, Mode Settings
  11515. @section Language Modes
  11516. @noindent
  11517. The commands in this section change Calc to use a different notation for
  11518. entry and display of formulas, corresponding to the conventions of some
  11519. other common language such as Pascal or @TeX{}. Objects displayed on the
  11520. stack or yanked from the Calculator to an editing buffer will be formatted
  11521. in the current language; objects entered in algebraic entry or yanked from
  11522. another buffer will be interpreted according to the current language.
  11523. The current language has no effect on things written to or read from the
  11524. trail buffer, nor does it affect numeric entry. Only algebraic entry is
  11525. affected. You can make even algebraic entry ignore the current language
  11526. and use the standard notation by giving a numeric prefix, e.g., @kbd{C-u '}.
  11527. For example, suppose the formula @samp{2*a[1] + atan(a[2])} occurs in a C
  11528. program; elsewhere in the program you need the derivatives of this formula
  11529. with respect to @samp{a[1]} and @samp{a[2]}. First, type @kbd{d C}
  11530. to switch to C notation. Now use @code{C-u M-# g} to grab the formula
  11531. into the Calculator, @kbd{a d a[1] @key{RET}} to differentiate with respect
  11532. to the first variable, and @kbd{M-# y} to yank the formula for the derivative
  11533. back into your C program. Press @kbd{U} to undo the differentiation and
  11534. repeat with @kbd{a d a[2] @key{RET}} for the other derivative.
  11535. Without being switched into C mode first, Calc would have misinterpreted
  11536. the brackets in @samp{a[1]} and @samp{a[2]}, would not have known that
  11537. @code{atan} was equivalent to Calc's built-in @code{arctan} function,
  11538. and would have written the formula back with notations (like implicit
  11539. multiplication) which would not have been legal for a C program.
  11540. As another example, suppose you are maintaining a C program and a @TeX{}
  11541. document, each of which needs a copy of the same formula. You can grab the
  11542. formula from the program in C mode, switch to @TeX{} mode, and yank the
  11543. formula into the document in @TeX{} math-mode format.
  11544. Language modes are selected by typing the letter @kbd{d} followed by a
  11545. shifted letter key.
  11546. @menu
  11547. * Normal Language Modes::
  11548. * C FORTRAN Pascal::
  11549. * TeX Language Mode::
  11550. * Eqn Language Mode::
  11551. * Mathematica Language Mode::
  11552. * Maple Language Mode::
  11553. * Compositions::
  11554. * Syntax Tables::
  11555. @end menu
  11556. @node Normal Language Modes, C FORTRAN Pascal, Language Modes, Language Modes
  11557. @subsection Normal Language Modes
  11558. @noindent
  11559. @kindex d N
  11560. @pindex calc-normal-language
  11561. The @kbd{d N} (@code{calc-normal-language}) command selects the usual
  11562. notation for Calc formulas, as described in the rest of this manual.
  11563. Matrices are displayed in a multi-line tabular format, but all other
  11564. objects are written in linear form, as they would be typed from the
  11565. keyboard.
  11566. @kindex d O
  11567. @pindex calc-flat-language
  11568. @cindex Matrix display
  11569. The @kbd{d O} (@code{calc-flat-language}) command selects a language
  11570. identical with the normal one, except that matrices are written in
  11571. one-line form along with everything else. In some applications this
  11572. form may be more suitable for yanking data into other buffers.
  11573. @kindex d b
  11574. @pindex calc-line-breaking
  11575. @cindex Line breaking
  11576. @cindex Breaking up long lines
  11577. Even in one-line mode, long formulas or vectors will still be split
  11578. across multiple lines if they exceed the width of the Calculator window.
  11579. The @kbd{d b} (@code{calc-line-breaking}) command turns this line-breaking
  11580. feature on and off. (It works independently of the current language.)
  11581. If you give a numeric prefix argument of five or greater to the @kbd{d b}
  11582. command, that argument will specify the line width used when breaking
  11583. long lines.
  11584. @kindex d B
  11585. @pindex calc-big-language
  11586. The @kbd{d B} (@code{calc-big-language}) command selects a language
  11587. which uses textual approximations to various mathematical notations,
  11588. such as powers, quotients, and square roots:
  11589. @example
  11590. ____________
  11591. | a + 1 2
  11592. | ----- + c
  11593. \| b
  11594. @end example
  11595. @noindent
  11596. in place of @samp{sqrt((a+1)/b + c^2)}.
  11597. Subscripts like @samp{a_i} are displayed as actual subscripts in ``big''
  11598. mode. Double subscripts, @samp{a_i_j} (@samp{subscr(subscr(a, i), j)})
  11599. are displayed as @samp{a} with subscripts separated by commas:
  11600. @samp{i, j}. They must still be entered in the usual underscore
  11601. notation.
  11602. One slight ambiguity of Big notation is that
  11603. @example
  11604. 3
  11605. - -
  11606. 4
  11607. @end example
  11608. @noindent
  11609. can represent either the negative rational number @cite{-3:4}, or the
  11610. actual expression @samp{-(3/4)}; but the latter formula would normally
  11611. never be displayed because it would immediately be evaluated to
  11612. @cite{-3:4} or @cite{-0.75}, so this ambiguity is not a problem in
  11613. typical use.
  11614. Non-decimal numbers are displayed with subscripts. Thus there is no
  11615. way to tell the difference between @samp{16#C2} and @samp{C2_16},
  11616. though generally you will know which interpretation is correct.
  11617. Logarithms @samp{log(x,b)} and @samp{log10(x)} also use subscripts
  11618. in Big mode.
  11619. In Big mode, stack entries often take up several lines. To aid
  11620. readability, stack entries are separated by a blank line in this mode.
  11621. You may find it useful to expand the Calc window's height using
  11622. @kbd{C-x ^} (@code{enlarge-window}) or to make the Calc window the only
  11623. one on the screen with @kbd{C-x 1} (@code{delete-other-windows}).
  11624. Long lines are currently not rearranged to fit the window width in
  11625. Big mode, so you may need to use the @kbd{<} and @kbd{>} keys
  11626. to scroll across a wide formula. For really big formulas, you may
  11627. even need to use @kbd{@{} and @kbd{@}} to scroll up and down.
  11628. @kindex d U
  11629. @pindex calc-unformatted-language
  11630. The @kbd{d U} (@code{calc-unformatted-language}) command altogether disables
  11631. the use of operator notation in formulas. In this mode, the formula
  11632. shown above would be displayed:
  11633. @example
  11634. sqrt(add(div(add(a, 1), b), pow(c, 2)))
  11635. @end example
  11636. These four modes differ only in display format, not in the format
  11637. expected for algebraic entry. The standard Calc operators work in
  11638. all four modes, and unformatted notation works in any language mode
  11639. (except that Mathematica mode expects square brackets instead of
  11640. parentheses).
  11641. @node C FORTRAN Pascal, TeX Language Mode, Normal Language Modes, Language Modes
  11642. @subsection C, FORTRAN, and Pascal Modes
  11643. @noindent
  11644. @kindex d C
  11645. @pindex calc-c-language
  11646. @cindex C language
  11647. The @kbd{d C} (@code{calc-c-language}) command selects the conventions
  11648. of the C language for display and entry of formulas. This differs from
  11649. the normal language mode in a variety of (mostly minor) ways. In
  11650. particular, C language operators and operator precedences are used in
  11651. place of Calc's usual ones. For example, @samp{a^b} means @samp{xor(a,b)}
  11652. in C mode; a value raised to a power is written as a function call,
  11653. @samp{pow(a,b)}.
  11654. In C mode, vectors and matrices use curly braces instead of brackets.
  11655. Octal and hexadecimal values are written with leading @samp{0} or @samp{0x}
  11656. rather than using the @samp{#} symbol. Array subscripting is
  11657. translated into @code{subscr} calls, so that @samp{a[i]} in C
  11658. mode is the same as @samp{a_i} in normal mode. Assignments
  11659. turn into the @code{assign} function, which Calc normally displays
  11660. using the @samp{:=} symbol.
  11661. The variables @code{var-pi} and @code{var-e} would be displayed @samp{pi}
  11662. and @samp{e} in normal mode, but in C mode they are displayed as
  11663. @samp{M_PI} and @samp{M_E}, corresponding to the names of constants
  11664. typically provided in the @file{<math.h>} header. Functions whose
  11665. names are different in C are translated automatically for entry and
  11666. display purposes. For example, entering @samp{asin(x)} will push the
  11667. formula @samp{arcsin(x)} onto the stack; this formula will be displayed
  11668. as @samp{asin(x)} as long as C mode is in effect.
  11669. @kindex d P
  11670. @pindex calc-pascal-language
  11671. @cindex Pascal language
  11672. The @kbd{d P} (@code{calc-pascal-language}) command selects Pascal
  11673. conventions. Like C mode, Pascal mode interprets array brackets and uses
  11674. a different table of operators. Hexadecimal numbers are entered and
  11675. displayed with a preceding dollar sign. (Thus the regular meaning of
  11676. @kbd{$2} during algebraic entry does not work in Pascal mode, though
  11677. @kbd{$} (and @kbd{$$}, etc.) not followed by digits works the same as
  11678. always.) No special provisions are made for other non-decimal numbers,
  11679. vectors, and so on, since there is no universally accepted standard way
  11680. of handling these in Pascal.
  11681. @kindex d F
  11682. @pindex calc-fortran-language
  11683. @cindex FORTRAN language
  11684. The @kbd{d F} (@code{calc-fortran-language}) command selects FORTRAN
  11685. conventions. Various function names are transformed into FORTRAN
  11686. equivalents. Vectors are written as @samp{/1, 2, 3/}, and may be
  11687. entered this way or using square brackets. Since FORTRAN uses round
  11688. parentheses for both function calls and array subscripts, Calc displays
  11689. both in the same way; @samp{a(i)} is interpreted as a function call
  11690. upon reading, and subscripts must be entered as @samp{subscr(a, i)}.
  11691. Also, if the variable @code{a} has been declared to have type
  11692. @code{vector} or @code{matrix} then @samp{a(i)} will be parsed as a
  11693. subscript. (@xref{Declarations}.) Usually it doesn't matter, though;
  11694. if you enter the subscript expression @samp{a(i)} and Calc interprets
  11695. it as a function call, you'll never know the difference unless you
  11696. switch to another language mode or replace @code{a} with an actual
  11697. vector (or unless @code{a} happens to be the name of a built-in
  11698. function!).
  11699. Underscores are allowed in variable and function names in all of these
  11700. language modes. The underscore here is equivalent to the @samp{#} in
  11701. normal mode, or to hyphens in the underlying Emacs Lisp variable names.
  11702. FORTRAN and Pascal modes normally do not adjust the case of letters in
  11703. formulas. Most built-in Calc names use lower-case letters. If you use a
  11704. positive numeric prefix argument with @kbd{d P} or @kbd{d F}, these
  11705. modes will use upper-case letters exclusively for display, and will
  11706. convert to lower-case on input. With a negative prefix, these modes
  11707. convert to lower-case for display and input.
  11708. @node TeX Language Mode, Eqn Language Mode, C FORTRAN Pascal, Language Modes
  11709. @subsection @TeX{} Language Mode
  11710. @noindent
  11711. @kindex d T
  11712. @pindex calc-tex-language
  11713. @cindex TeX language
  11714. The @kbd{d T} (@code{calc-tex-language}) command selects the conventions
  11715. of ``math mode'' in the @TeX{} typesetting language, by Donald Knuth.
  11716. Formulas are entered
  11717. and displayed in @TeX{} notation, as in @samp{\sin\left( a \over b \right)}.
  11718. Math formulas are usually enclosed by @samp{$ $} signs in @TeX{}; these
  11719. should be omitted when interfacing with Calc. To Calc, the @samp{$} sign
  11720. has the same meaning it always does in algebraic formulas (a reference to
  11721. an existing entry on the stack).@refill
  11722. Complex numbers are displayed as in @samp{3 + 4i}. Fractions and
  11723. quotients are written using @code{\over};
  11724. binomial coefficients are written with @code{\choose}.
  11725. Interval forms are written with @code{\ldots}, and
  11726. error forms are written with @code{\pm}.
  11727. Absolute values are written as in @samp{|x + 1|}, and the floor and
  11728. ceiling functions are written with @code{\lfloor}, @code{\rfloor}, etc.
  11729. The words @code{\left} and @code{\right} are ignored when reading
  11730. formulas in @TeX{} mode. Both @code{inf} and @code{uinf} are written
  11731. as @code{\infty}; when read, @code{\infty} always translates to
  11732. @code{inf}.@refill
  11733. Function calls are written the usual way, with the function name followed
  11734. by the arguments in parentheses. However, functions for which @TeX{} has
  11735. special names (like @code{\sin}) will use curly braces instead of
  11736. parentheses for very simple arguments. During input, curly braces and
  11737. parentheses work equally well for grouping, but when the document is
  11738. formatted the curly braces will be invisible. Thus the printed result is
  11739. @c{$\sin{2 x}$}
  11740. @cite{sin 2x} but @c{$\sin(2 + x)$}
  11741. @cite{sin(2 + x)}.
  11742. Function and variable names not treated specially by @TeX{} are simply
  11743. written out as-is, which will cause them to come out in italic letters
  11744. in the printed document. If you invoke @kbd{d T} with a positive numeric
  11745. prefix argument, names of more than one character will instead be written
  11746. @samp{\hbox@{@var{name}@}}. The @samp{\hbox@{ @}} notation is ignored
  11747. during reading. If you use a negative prefix argument, such function
  11748. names are written @samp{\@var{name}}, and function names that begin
  11749. with @code{\} during reading have the @code{\} removed. (Note that
  11750. in this mode, long variable names are still written with @code{\hbox}.
  11751. However, you can always make an actual variable name like @code{\bar}
  11752. in any @TeX{} mode.)
  11753. During reading, text of the form @samp{\matrix@{ ...@: @}} is replaced
  11754. by @samp{[ ...@: ]}. The same also applies to @code{\pmatrix} and
  11755. @code{\bmatrix}. The symbol @samp{&} is interpreted as a comma,
  11756. and the symbols @samp{\cr} and @samp{\\} are interpreted as semicolons.
  11757. During output, matrices are displayed in @samp{\matrix@{ a & b \\ c & d@}}
  11758. format; you may need to edit this afterwards to change @code{\matrix}
  11759. to @code{\pmatrix} or @code{\\} to @code{\cr}.
  11760. Accents like @code{\tilde} and @code{\bar} translate into function
  11761. calls internally (@samp{tilde(x)}, @samp{bar(x)}). The @code{\underline}
  11762. sequence is treated as an accent. The @code{\vec} accent corresponds
  11763. to the function name @code{Vec}, because @code{vec} is the name of
  11764. a built-in Calc function. The following table shows the accents
  11765. in Calc, @TeX{}, and @dfn{eqn} (described in the next section):
  11766. @iftex
  11767. @begingroup
  11768. @let@calcindexershow=@calcindexernoshow @c Suppress marginal notes
  11769. @let@calcindexersh=@calcindexernoshow
  11770. @end iftex
  11771. @ignore
  11772. @starindex
  11773. @end ignore
  11774. @tindex acute
  11775. @ignore
  11776. @starindex
  11777. @end ignore
  11778. @tindex bar
  11779. @ignore
  11780. @starindex
  11781. @end ignore
  11782. @tindex breve
  11783. @ignore
  11784. @starindex
  11785. @end ignore
  11786. @tindex check
  11787. @ignore
  11788. @starindex
  11789. @end ignore
  11790. @tindex dot
  11791. @ignore
  11792. @starindex
  11793. @end ignore
  11794. @tindex dotdot
  11795. @ignore
  11796. @starindex
  11797. @end ignore
  11798. @tindex dyad
  11799. @ignore
  11800. @starindex
  11801. @end ignore
  11802. @tindex grave
  11803. @ignore
  11804. @starindex
  11805. @end ignore
  11806. @tindex hat
  11807. @ignore
  11808. @starindex
  11809. @end ignore
  11810. @tindex Prime
  11811. @ignore
  11812. @starindex
  11813. @end ignore
  11814. @tindex tilde
  11815. @ignore
  11816. @starindex
  11817. @end ignore
  11818. @tindex under
  11819. @ignore
  11820. @starindex
  11821. @end ignore
  11822. @tindex Vec
  11823. @iftex
  11824. @endgroup
  11825. @end iftex
  11826. @example
  11827. Calc TeX eqn
  11828. ---- --- ---
  11829. acute \acute
  11830. bar \bar bar
  11831. breve \breve
  11832. check \check
  11833. dot \dot dot
  11834. dotdot \ddot dotdot
  11835. dyad dyad
  11836. grave \grave
  11837. hat \hat hat
  11838. Prime prime
  11839. tilde \tilde tilde
  11840. under \underline under
  11841. Vec \vec vec
  11842. @end example
  11843. The @samp{=>} (evaluates-to) operator appears as a @code{\to} symbol:
  11844. @samp{@{@var{a} \to @var{b}@}}. @TeX{} defines @code{\to} as an
  11845. alias for @code{\rightarrow}. However, if the @samp{=>} is the
  11846. top-level expression being formatted, a slightly different notation
  11847. is used: @samp{\evalto @var{a} \to @var{b}}. The @code{\evalto}
  11848. word is ignored by Calc's input routines, and is undefined in @TeX{}.
  11849. You will typically want to include one of the following definitions
  11850. at the top of a @TeX{} file that uses @code{\evalto}:
  11851. @example
  11852. \def\evalto@{@}
  11853. \def\evalto#1\to@{@}
  11854. @end example
  11855. The first definition formats evaluates-to operators in the usual
  11856. way. The second causes only the @var{b} part to appear in the
  11857. printed document; the @var{a} part and the arrow are hidden.
  11858. Another definition you may wish to use is @samp{\let\to=\Rightarrow}
  11859. which causes @code{\to} to appear more like Calc's @samp{=>} symbol.
  11860. @xref{Evaluates-To Operator}, for a discussion of @code{evalto}.
  11861. The complete set of @TeX{} control sequences that are ignored during
  11862. reading is:
  11863. @example
  11864. \hbox \mbox \text \left \right
  11865. \, \> \: \; \! \quad \qquad \hfil \hfill
  11866. \displaystyle \textstyle \dsize \tsize
  11867. \scriptstyle \scriptscriptstyle \ssize \ssize
  11868. \rm \bf \it \sl \roman \bold \italic \slanted
  11869. \cal \mit \Cal \Bbb \frak \goth
  11870. \evalto
  11871. @end example
  11872. Note that, because these symbols are ignored, reading a @TeX{} formula
  11873. into Calc and writing it back out may lose spacing and font information.
  11874. Also, the ``discretionary multiplication sign'' @samp{\*} is read
  11875. the same as @samp{*}.
  11876. @ifinfo
  11877. The @TeX{} version of this manual includes some printed examples at the
  11878. end of this section.
  11879. @end ifinfo
  11880. @iftex
  11881. Here are some examples of how various Calc formulas are formatted in @TeX{}:
  11882. @example
  11883. @group
  11884. sin(a^2 / b_i)
  11885. \sin\left( {a^2 \over b_i} \right)
  11886. @end group
  11887. @end example
  11888. @tex
  11889. \let\rm\goodrm
  11890. $$ \sin\left( a^2 \over b_i \right) $$
  11891. @end tex
  11892. @sp 1
  11893. @example
  11894. @group
  11895. [(3, 4), 3:4, 3 +/- 4, [3 .. inf)]
  11896. [3 + 4i, @{3 \over 4@}, 3 \pm 4, [3 \ldots \infty)]
  11897. @end group
  11898. @end example
  11899. @tex
  11900. \turnoffactive
  11901. $$ [3 + 4i, {3 \over 4}, 3 \pm 4, [ 3 \ldots \infty)] $$
  11902. @end tex
  11903. @sp 1
  11904. @example
  11905. @group
  11906. [abs(a), abs(a / b), floor(a), ceil(a / b)]
  11907. [|a|, \left| a \over b \right|,
  11908. \lfloor a \rfloor, \left\lceil a \over b \right\rceil]
  11909. @end group
  11910. @end example
  11911. @tex
  11912. $$ [|a|, \left| a \over b \right|,
  11913. \lfloor a \rfloor, \left\lceil a \over b \right\rceil] $$
  11914. @end tex
  11915. @sp 1
  11916. @example
  11917. @group
  11918. [sin(a), sin(2 a), sin(2 + a), sin(a / b)]
  11919. [\sin@{a@}, \sin@{2 a@}, \sin(2 + a),
  11920. \sin\left( @{a \over b@} \right)]
  11921. @end group
  11922. @end example
  11923. @tex
  11924. \turnoffactive\let\rm\goodrm
  11925. $$ [\sin{a}, \sin{2 a}, \sin(2 + a), \sin\left( {a \over b} \right)] $$
  11926. @end tex
  11927. @sp 2
  11928. First with plain @kbd{d T}, then with @kbd{C-u d T}, then finally with
  11929. @kbd{C-u - d T} (using the example definition
  11930. @samp{\def\foo#1@{\tilde F(#1)@}}:
  11931. @example
  11932. @group
  11933. [f(a), foo(bar), sin(pi)]
  11934. [f(a), foo(bar), \sin{\pi}]
  11935. [f(a), \hbox@{foo@}(\hbox@{bar@}), \sin@{\pi@}]
  11936. [f(a), \foo@{\hbox@{bar@}@}, \sin@{\pi@}]
  11937. @end group
  11938. @end example
  11939. @tex
  11940. \let\rm\goodrm
  11941. $$ [f(a), foo(bar), \sin{\pi}] $$
  11942. $$ [f(a), \hbox{foo}(\hbox{bar}), \sin{\pi}] $$
  11943. $$ [f(a), \tilde F(\hbox{bar}), \sin{\pi}] $$
  11944. @end tex
  11945. @sp 2
  11946. First with @samp{\def\evalto@{@}}, then with @samp{\def\evalto#1\to@{@}}:
  11947. @example
  11948. @group
  11949. 2 + 3 => 5
  11950. \evalto 2 + 3 \to 5
  11951. @end group
  11952. @end example
  11953. @tex
  11954. \turnoffactive
  11955. $$ 2 + 3 \to 5 $$
  11956. $$ 5 $$
  11957. @end tex
  11958. @sp 2
  11959. First with standard @code{\to}, then with @samp{\let\to\Rightarrow}:
  11960. @example
  11961. @group
  11962. [2 + 3 => 5, a / 2 => (b + c) / 2]
  11963. [@{2 + 3 \to 5@}, @{@{a \over 2@} \to @{b + c \over 2@}@}]
  11964. @end group
  11965. @end example
  11966. @tex
  11967. \turnoffactive
  11968. $$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$
  11969. {\let\to\Rightarrow
  11970. $$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$}
  11971. @end tex
  11972. @sp 2
  11973. Matrices normally, then changing @code{\matrix} to @code{\pmatrix}:
  11974. @example
  11975. @group
  11976. [ [ a / b, 0 ], [ 0, 2^(x + 1) ] ]
  11977. \matrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
  11978. \pmatrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
  11979. @end group
  11980. @end example
  11981. @tex
  11982. \turnoffactive
  11983. $$ \matrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
  11984. $$ \pmatrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
  11985. @end tex
  11986. @sp 2
  11987. @end iftex
  11988. @node Eqn Language Mode, Mathematica Language Mode, TeX Language Mode, Language Modes
  11989. @subsection Eqn Language Mode
  11990. @noindent
  11991. @kindex d E
  11992. @pindex calc-eqn-language
  11993. @dfn{Eqn} is another popular formatter for math formulas. It is
  11994. designed for use with the TROFF text formatter, and comes standard
  11995. with many versions of Unix. The @kbd{d E} (@code{calc-eqn-language})
  11996. command selects @dfn{eqn} notation.
  11997. The @dfn{eqn} language's main idiosyncrasy is that whitespace plays
  11998. a significant part in the parsing of the language. For example,
  11999. @samp{sqrt x+1 + y} treats @samp{x+1} as the argument of the
  12000. @code{sqrt} operator. @dfn{Eqn} also understands more conventional
  12001. grouping using curly braces: @samp{sqrt@{x+1@} + y}. Braces are
  12002. required only when the argument contains spaces.
  12003. In Calc's @dfn{eqn} mode, however, curly braces are required to
  12004. delimit arguments of operators like @code{sqrt}. The first of the
  12005. above examples would treat only the @samp{x} as the argument of
  12006. @code{sqrt}, and in fact @samp{sin x+1} would be interpreted as
  12007. @samp{sin * x + 1}, because @code{sin} is not a special operator
  12008. in the @dfn{eqn} language. If you always surround the argument
  12009. with curly braces, Calc will never misunderstand.
  12010. Calc also understands parentheses as grouping characters. Another
  12011. peculiarity of @dfn{eqn}'s syntax makes it advisable to separate
  12012. words with spaces from any surrounding characters that aren't curly
  12013. braces, so Calc writes @samp{sin ( x + y )} in @dfn{eqn} mode.
  12014. (The spaces around @code{sin} are important to make @dfn{eqn}
  12015. recognize that @code{sin} should be typeset in a roman font, and
  12016. the spaces around @code{x} and @code{y} are a good idea just in
  12017. case the @dfn{eqn} document has defined special meanings for these
  12018. names, too.)
  12019. Powers and subscripts are written with the @code{sub} and @code{sup}
  12020. operators, respectively. Note that the caret symbol @samp{^} is
  12021. treated the same as a space in @dfn{eqn} mode, as is the @samp{~}
  12022. symbol (these are used to introduce spaces of various widths into
  12023. the typeset output of @dfn{eqn}).
  12024. As in @TeX{} mode, Calc's formatter omits parentheses around the
  12025. arguments of functions like @code{ln} and @code{sin} if they are
  12026. ``simple-looking''; in this case Calc surrounds the argument with
  12027. braces, separated by a @samp{~} from the function name: @samp{sin~@{x@}}.
  12028. Font change codes (like @samp{roman @var{x}}) and positioning codes
  12029. (like @samp{~} and @samp{down @var{n} @var{x}}) are ignored by the
  12030. @dfn{eqn} reader. Also ignored are the words @code{left}, @code{right},
  12031. @code{mark}, and @code{lineup}. Quotation marks in @dfn{eqn} mode input
  12032. are treated the same as curly braces: @samp{sqrt "1+x"} is equivalent to
  12033. @samp{sqrt @{1+x@}}; this is only an approximation to the true meaning
  12034. of quotes in @dfn{eqn}, but it is good enough for most uses.
  12035. Accent codes (@samp{@var{x} dot}) are handled by treating them as
  12036. function calls (@samp{dot(@var{x})}) internally. @xref{TeX Language
  12037. Mode}, for a table of these accent functions. The @code{prime} accent
  12038. is treated specially if it occurs on a variable or function name:
  12039. @samp{f prime prime @w{( x prime )}} is stored internally as
  12040. @samp{f'@w{'}(x')}. For example, taking the derivative of @samp{f(2 x)}
  12041. with @kbd{a d x} will produce @samp{2 f'(2 x)}, which @dfn{eqn} mode
  12042. will display as @samp{2 f prime ( 2 x )}.
  12043. Assignments are written with the @samp{<-} (left-arrow) symbol,
  12044. and @code{evalto} operators are written with @samp{->} or
  12045. @samp{evalto ... ->} (@pxref{TeX Language Mode}, for a discussion
  12046. of this). The regular Calc symbols @samp{:=} and @samp{=>} are also
  12047. recognized for these operators during reading.
  12048. Vectors in @dfn{eqn} mode use regular Calc square brackets, but
  12049. matrices are formatted as @samp{matrix @{ ccol @{ a above b @} ... @}}.
  12050. The words @code{lcol} and @code{rcol} are recognized as synonyms
  12051. for @code{ccol} during input, and are generated instead of @code{ccol}
  12052. if the matrix justification mode so specifies.
  12053. @node Mathematica Language Mode, Maple Language Mode, Eqn Language Mode, Language Modes
  12054. @subsection Mathematica Language Mode
  12055. @noindent
  12056. @kindex d M
  12057. @pindex calc-mathematica-language
  12058. @cindex Mathematica language
  12059. The @kbd{d M} (@code{calc-mathematica-language}) command selects the
  12060. conventions of Mathematica, a powerful and popular mathematical tool
  12061. from Wolfram Research, Inc. Notable differences in Mathematica mode
  12062. are that the names of built-in functions are capitalized, and function
  12063. calls use square brackets instead of parentheses. Thus the Calc
  12064. formula @samp{sin(2 x)} is entered and displayed @w{@samp{Sin[2 x]}} in
  12065. Mathematica mode.
  12066. Vectors and matrices use curly braces in Mathematica. Complex numbers
  12067. are written @samp{3 + 4 I}. The standard special constants in Calc are
  12068. written @code{Pi}, @code{E}, @code{I}, @code{GoldenRatio}, @code{EulerGamma},
  12069. @code{Infinity}, @code{ComplexInfinity}, and @code{Indeterminate} in
  12070. Mathematica mode.
  12071. Non-decimal numbers are written, e.g., @samp{16^^7fff}. Floating-point
  12072. numbers in scientific notation are written @samp{1.23*10.^3}.
  12073. Subscripts use double square brackets: @samp{a[[i]]}.@refill
  12074. @node Maple Language Mode, Compositions, Mathematica Language Mode, Language Modes
  12075. @subsection Maple Language Mode
  12076. @noindent
  12077. @kindex d W
  12078. @pindex calc-maple-language
  12079. @cindex Maple language
  12080. The @kbd{d W} (@code{calc-maple-language}) command selects the
  12081. conventions of Maple, another mathematical tool from the University
  12082. of Waterloo.
  12083. Maple's language is much like C. Underscores are allowed in symbol
  12084. names; square brackets are used for subscripts; explicit @samp{*}s for
  12085. multiplications are required. Use either @samp{^} or @samp{**} to
  12086. denote powers.
  12087. Maple uses square brackets for lists and curly braces for sets. Calc
  12088. interprets both notations as vectors, and displays vectors with square
  12089. brackets. This means Maple sets will be converted to lists when they
  12090. pass through Calc. As a special case, matrices are written as calls
  12091. to the function @code{matrix}, given a list of lists as the argument,
  12092. and can be read in this form or with all-capitals @code{MATRIX}.
  12093. The Maple interval notation @samp{2 .. 3} has no surrounding brackets;
  12094. Calc reads @samp{2 .. 3} as the closed interval @samp{[2 .. 3]}, and
  12095. writes any kind of interval as @samp{2 .. 3}. This means you cannot
  12096. see the difference between an open and a closed interval while in
  12097. Maple display mode.
  12098. Maple writes complex numbers as @samp{3 + 4*I}. Its special constants
  12099. are @code{Pi}, @code{E}, @code{I}, and @code{infinity} (all three of
  12100. @code{inf}, @code{uinf}, and @code{nan} display as @code{infinity}).
  12101. Floating-point numbers are written @samp{1.23*10.^3}.
  12102. Among things not currently handled by Calc's Maple mode are the
  12103. various quote symbols, procedures and functional operators, and
  12104. inert (@samp{&}) operators.
  12105. @node Compositions, Syntax Tables, Maple Language Mode, Language Modes
  12106. @subsection Compositions
  12107. @noindent
  12108. @cindex Compositions
  12109. There are several @dfn{composition functions} which allow you to get
  12110. displays in a variety of formats similar to those in Big language
  12111. mode. Most of these functions do not evaluate to anything; they are
  12112. placeholders which are left in symbolic form by Calc's evaluator but
  12113. are recognized by Calc's display formatting routines.
  12114. Two of these, @code{string} and @code{bstring}, are described elsewhere.
  12115. @xref{Strings}. For example, @samp{string("ABC")} is displayed as
  12116. @samp{ABC}. When viewed on the stack it will be indistinguishable from
  12117. the variable @code{ABC}, but internally it will be stored as
  12118. @samp{string([65, 66, 67])} and can still be manipulated this way; for
  12119. example, the selection and vector commands @kbd{j 1 v v j u} would
  12120. select the vector portion of this object and reverse the elements, then
  12121. deselect to reveal a string whose characters had been reversed.
  12122. The composition functions do the same thing in all language modes
  12123. (although their components will of course be formatted in the current
  12124. language mode). The one exception is Unformatted mode (@kbd{d U}),
  12125. which does not give the composition functions any special treatment.
  12126. The functions are discussed here because of their relationship to
  12127. the language modes.
  12128. @menu
  12129. * Composition Basics::
  12130. * Horizontal Compositions::
  12131. * Vertical Compositions::
  12132. * Other Compositions::
  12133. * Information about Compositions::
  12134. * User-Defined Compositions::
  12135. @end menu
  12136. @node Composition Basics, Horizontal Compositions, Compositions, Compositions
  12137. @subsubsection Composition Basics
  12138. @noindent
  12139. Compositions are generally formed by stacking formulas together
  12140. horizontally or vertically in various ways. Those formulas are
  12141. themselves compositions. @TeX{} users will find this analogous
  12142. to @TeX{}'s ``boxes.'' Each multi-line composition has a
  12143. @dfn{baseline}; horizontal compositions use the baselines to
  12144. decide how formulas should be positioned relative to one another.
  12145. For example, in the Big mode formula
  12146. @example
  12147. @group
  12148. 2
  12149. a + b
  12150. 17 + ------
  12151. c
  12152. @end group
  12153. @end example
  12154. @noindent
  12155. the second term of the sum is four lines tall and has line three as
  12156. its baseline. Thus when the term is combined with 17, line three
  12157. is placed on the same level as the baseline of 17.
  12158. @tex
  12159. \bigskip
  12160. @end tex
  12161. Another important composition concept is @dfn{precedence}. This is
  12162. an integer that represents the binding strength of various operators.
  12163. For example, @samp{*} has higher precedence (195) than @samp{+} (180),
  12164. which means that @samp{(a * b) + c} will be formatted without the
  12165. parentheses, but @samp{a * (b + c)} will keep the parentheses.
  12166. The operator table used by normal and Big language modes has the
  12167. following precedences:
  12168. @example
  12169. _ 1200 @r{(subscripts)}
  12170. % 1100 @r{(as in n}%@r{)}
  12171. - 1000 @r{(as in }-@r{n)}
  12172. ! 1000 @r{(as in }!@r{n)}
  12173. mod 400
  12174. +/- 300
  12175. !! 210 @r{(as in n}!!@r{)}
  12176. ! 210 @r{(as in n}!@r{)}
  12177. ^ 200
  12178. * 195 @r{(or implicit multiplication)}
  12179. / % \ 190
  12180. + - 180 @r{(as in a}+@r{b)}
  12181. | 170
  12182. < = 160 @r{(and other relations)}
  12183. && 110
  12184. || 100
  12185. ? : 90
  12186. !!! 85
  12187. &&& 80
  12188. ||| 75
  12189. := 50
  12190. :: 45
  12191. => 40
  12192. @end example
  12193. The general rule is that if an operator with precedence @cite{n}
  12194. occurs as an argument to an operator with precedence @cite{m}, then
  12195. the argument is enclosed in parentheses if @cite{n < m}. Top-level
  12196. expressions and expressions which are function arguments, vector
  12197. components, etc., are formatted with precedence zero (so that they
  12198. normally never get additional parentheses).
  12199. For binary left-associative operators like @samp{+}, the righthand
  12200. argument is actually formatted with one-higher precedence than shown
  12201. in the table. This makes sure @samp{(a + b) + c} omits the parentheses,
  12202. but the unnatural form @samp{a + (b + c)} keeps its parentheses.
  12203. Right-associative operators like @samp{^} format the lefthand argument
  12204. with one-higher precedence.
  12205. @ignore
  12206. @starindex
  12207. @end ignore
  12208. @tindex cprec
  12209. The @code{cprec} function formats an expression with an arbitrary
  12210. precedence. For example, @samp{cprec(abc, 185)} will combine into
  12211. sums and products as follows: @samp{7 + abc}, @samp{7 (abc)} (because
  12212. this @code{cprec} form has higher precedence than addition, but lower
  12213. precedence than multiplication).
  12214. @tex
  12215. \bigskip
  12216. @end tex
  12217. A final composition issue is @dfn{line breaking}. Calc uses two
  12218. different strategies for ``flat'' and ``non-flat'' compositions.
  12219. A non-flat composition is anything that appears on multiple lines
  12220. (not counting line breaking). Examples would be matrices and Big
  12221. mode powers and quotients. Non-flat compositions are displayed
  12222. exactly as specified. If they come out wider than the current
  12223. window, you must use horizontal scrolling (@kbd{<} and @kbd{>}) to
  12224. view them.
  12225. Flat compositions, on the other hand, will be broken across several
  12226. lines if they are too wide to fit the window. Certain points in a
  12227. composition are noted internally as @dfn{break points}. Calc's
  12228. general strategy is to fill each line as much as possible, then to
  12229. move down to the next line starting at the first break point that
  12230. didn't fit. However, the line breaker understands the hierarchical
  12231. structure of formulas. It will not break an ``inner'' formula if
  12232. it can use an earlier break point from an ``outer'' formula instead.
  12233. For example, a vector of sums might be formatted as:
  12234. @example
  12235. @group
  12236. [ a + b + c, d + e + f,
  12237. g + h + i, j + k + l, m ]
  12238. @end group
  12239. @end example
  12240. @noindent
  12241. If the @samp{m} can fit, then so, it seems, could the @samp{g}.
  12242. But Calc prefers to break at the comma since the comma is part
  12243. of a ``more outer'' formula. Calc would break at a plus sign
  12244. only if it had to, say, if the very first sum in the vector had
  12245. itself been too large to fit.
  12246. Of the composition functions described below, only @code{choriz}
  12247. generates break points. The @code{bstring} function (@pxref{Strings})
  12248. also generates breakable items: A break point is added after every
  12249. space (or group of spaces) except for spaces at the very beginning or
  12250. end of the string.
  12251. Composition functions themselves count as levels in the formula
  12252. hierarchy, so a @code{choriz} that is a component of a larger
  12253. @code{choriz} will be less likely to be broken. As a special case,
  12254. if a @code{bstring} occurs as a component of a @code{choriz} or
  12255. @code{choriz}-like object (such as a vector or a list of arguments
  12256. in a function call), then the break points in that @code{bstring}
  12257. will be on the same level as the break points of the surrounding
  12258. object.
  12259. @node Horizontal Compositions, Vertical Compositions, Composition Basics, Compositions
  12260. @subsubsection Horizontal Compositions
  12261. @noindent
  12262. @ignore
  12263. @starindex
  12264. @end ignore
  12265. @tindex choriz
  12266. The @code{choriz} function takes a vector of objects and composes
  12267. them horizontally. For example, @samp{choriz([17, a b/c, d])} formats
  12268. as @w{@samp{17a b / cd}} in normal language mode, or as
  12269. @example
  12270. @group
  12271. a b
  12272. 17---d
  12273. c
  12274. @end group
  12275. @end example
  12276. @noindent
  12277. in Big language mode. This is actually one case of the general
  12278. function @samp{choriz(@var{vec}, @var{sep}, @var{prec})}, where
  12279. either or both of @var{sep} and @var{prec} may be omitted.
  12280. @var{Prec} gives the @dfn{precedence} to use when formatting
  12281. each of the components of @var{vec}. The default precedence is
  12282. the precedence from the surrounding environment.
  12283. @var{Sep} is a string (i.e., a vector of character codes as might
  12284. be entered with @code{" "} notation) which should separate components
  12285. of the composition. Also, if @var{sep} is given, the line breaker
  12286. will allow lines to be broken after each occurrence of @var{sep}.
  12287. If @var{sep} is omitted, the composition will not be breakable
  12288. (unless any of its component compositions are breakable).
  12289. For example, @samp{2 choriz([a, b c, d = e], " + ", 180)} is
  12290. formatted as @samp{2 a + b c + (d = e)}. To get the @code{choriz}
  12291. to have precedence 180 ``outwards'' as well as ``inwards,''
  12292. enclose it in a @code{cprec} form: @samp{2 cprec(choriz(...), 180)}
  12293. formats as @samp{2 (a + b c + (d = e))}.
  12294. The baseline of a horizontal composition is the same as the
  12295. baselines of the component compositions, which are all aligned.
  12296. @node Vertical Compositions, Other Compositions, Horizontal Compositions, Compositions
  12297. @subsubsection Vertical Compositions
  12298. @noindent
  12299. @ignore
  12300. @starindex
  12301. @end ignore
  12302. @tindex cvert
  12303. The @code{cvert} function makes a vertical composition. Each
  12304. component of the vector is centered in a column. The baseline of
  12305. the result is by default the top line of the resulting composition.
  12306. For example, @samp{f(cvert([a, bb, ccc]), cvert([a^2 + 1, b^2]))}
  12307. formats in Big mode as
  12308. @example
  12309. @group
  12310. f( a , 2 )
  12311. bb a + 1
  12312. ccc 2
  12313. b
  12314. @end group
  12315. @end example
  12316. @ignore
  12317. @starindex
  12318. @end ignore
  12319. @tindex cbase
  12320. There are several special composition functions that work only as
  12321. components of a vertical composition. The @code{cbase} function
  12322. controls the baseline of the vertical composition; the baseline
  12323. will be the same as the baseline of whatever component is enclosed
  12324. in @code{cbase}. Thus @samp{f(cvert([a, cbase(bb), ccc]),
  12325. cvert([a^2 + 1, cbase(b^2)]))} displays as
  12326. @example
  12327. @group
  12328. 2
  12329. a + 1
  12330. a 2
  12331. f(bb , b )
  12332. ccc
  12333. @end group
  12334. @end example
  12335. @ignore
  12336. @starindex
  12337. @end ignore
  12338. @tindex ctbase
  12339. @ignore
  12340. @starindex
  12341. @end ignore
  12342. @tindex cbbase
  12343. There are also @code{ctbase} and @code{cbbase} functions which
  12344. make the baseline of the vertical composition equal to the top
  12345. or bottom line (rather than the baseline) of that component.
  12346. Thus @samp{cvert([cbase(a / b)]) + cvert([ctbase(a / b)]) +
  12347. cvert([cbbase(a / b)])} gives
  12348. @example
  12349. @group
  12350. a
  12351. a -
  12352. - + a + b
  12353. b -
  12354. b
  12355. @end group
  12356. @end example
  12357. There should be only one @code{cbase}, @code{ctbase}, or @code{cbbase}
  12358. function in a given vertical composition. These functions can also
  12359. be written with no arguments: @samp{ctbase()} is a zero-height object
  12360. which means the baseline is the top line of the following item, and
  12361. @samp{cbbase()} means the baseline is the bottom line of the preceding
  12362. item.
  12363. @ignore
  12364. @starindex
  12365. @end ignore
  12366. @tindex crule
  12367. The @code{crule} function builds a ``rule,'' or horizontal line,
  12368. across a vertical composition. By itself @samp{crule()} uses @samp{-}
  12369. characters to build the rule. You can specify any other character,
  12370. e.g., @samp{crule("=")}. The argument must be a character code or
  12371. vector of exactly one character code. It is repeated to match the
  12372. width of the widest item in the stack. For example, a quotient
  12373. with a thick line is @samp{cvert([a + 1, cbase(crule("=")), b^2])}:
  12374. @example
  12375. @group
  12376. a + 1
  12377. =====
  12378. 2
  12379. b
  12380. @end group
  12381. @end example
  12382. @ignore
  12383. @starindex
  12384. @end ignore
  12385. @tindex clvert
  12386. @ignore
  12387. @starindex
  12388. @end ignore
  12389. @tindex crvert
  12390. Finally, the functions @code{clvert} and @code{crvert} act exactly
  12391. like @code{cvert} except that the items are left- or right-justified
  12392. in the stack. Thus @samp{clvert([a, bb, ccc]) + crvert([a, bb, ccc])}
  12393. gives:
  12394. @example
  12395. @group
  12396. a + a
  12397. bb bb
  12398. ccc ccc
  12399. @end group
  12400. @end example
  12401. Like @code{choriz}, the vertical compositions accept a second argument
  12402. which gives the precedence to use when formatting the components.
  12403. Vertical compositions do not support separator strings.
  12404. @node Other Compositions, Information about Compositions, Vertical Compositions, Compositions
  12405. @subsubsection Other Compositions
  12406. @noindent
  12407. @ignore
  12408. @starindex
  12409. @end ignore
  12410. @tindex csup
  12411. The @code{csup} function builds a superscripted expression. For
  12412. example, @samp{csup(a, b)} looks the same as @samp{a^b} does in Big
  12413. language mode. This is essentially a horizontal composition of
  12414. @samp{a} and @samp{b}, where @samp{b} is shifted up so that its
  12415. bottom line is one above the baseline.
  12416. @ignore
  12417. @starindex
  12418. @end ignore
  12419. @tindex csub
  12420. Likewise, the @code{csub} function builds a subscripted expression.
  12421. This shifts @samp{b} down so that its top line is one below the
  12422. bottom line of @samp{a} (note that this is not quite analogous to
  12423. @code{csup}). Other arrangements can be obtained by using
  12424. @code{choriz} and @code{cvert} directly.
  12425. @ignore
  12426. @starindex
  12427. @end ignore
  12428. @tindex cflat
  12429. The @code{cflat} function formats its argument in ``flat'' mode,
  12430. as obtained by @samp{d O}, if the current language mode is normal
  12431. or Big. It has no effect in other language modes. For example,
  12432. @samp{a^(b/c)} is formatted by Big mode like @samp{csup(a, cflat(b/c))}
  12433. to improve its readability.
  12434. @ignore
  12435. @starindex
  12436. @end ignore
  12437. @tindex cspace
  12438. The @code{cspace} function creates horizontal space. For example,
  12439. @samp{cspace(4)} is effectively the same as @samp{string(" ")}.
  12440. A second string (i.e., vector of characters) argument is repeated
  12441. instead of the space character. For example, @samp{cspace(4, "ab")}
  12442. looks like @samp{abababab}. If the second argument is not a string,
  12443. it is formatted in the normal way and then several copies of that
  12444. are composed together: @samp{cspace(4, a^2)} yields
  12445. @example
  12446. @group
  12447. 2 2 2 2
  12448. a a a a
  12449. @end group
  12450. @end example
  12451. @noindent
  12452. If the number argument is zero, this is a zero-width object.
  12453. @ignore
  12454. @starindex
  12455. @end ignore
  12456. @tindex cvspace
  12457. The @code{cvspace} function creates vertical space, or a vertical
  12458. stack of copies of a certain string or formatted object. The
  12459. baseline is the center line of the resulting stack. A numerical
  12460. argument of zero will produce an object which contributes zero
  12461. height if used in a vertical composition.
  12462. @ignore
  12463. @starindex
  12464. @end ignore
  12465. @tindex ctspace
  12466. @ignore
  12467. @starindex
  12468. @end ignore
  12469. @tindex cbspace
  12470. There are also @code{ctspace} and @code{cbspace} functions which
  12471. create vertical space with the baseline the same as the baseline
  12472. of the top or bottom copy, respectively, of the second argument.
  12473. Thus @samp{cvspace(2, a/b) + ctspace(2, a/b) + cbspace(2, a/b)}
  12474. displays as:
  12475. @example
  12476. @group
  12477. a
  12478. -
  12479. a b
  12480. - a a
  12481. b + - + -
  12482. a b b
  12483. - a
  12484. b -
  12485. b
  12486. @end group
  12487. @end example
  12488. @node Information about Compositions, User-Defined Compositions, Other Compositions, Compositions
  12489. @subsubsection Information about Compositions
  12490. @noindent
  12491. The functions in this section are actual functions; they compose their
  12492. arguments according to the current language and other display modes,
  12493. then return a certain measurement of the composition as an integer.
  12494. @ignore
  12495. @starindex
  12496. @end ignore
  12497. @tindex cwidth
  12498. The @code{cwidth} function measures the width, in characters, of a
  12499. composition. For example, @samp{cwidth(a + b)} is 5, and
  12500. @samp{cwidth(a / b)} is 5 in normal mode, 1 in Big mode, and 11 in
  12501. @TeX{} mode (for @samp{@{a \over b@}}). The argument may involve
  12502. the composition functions described in this section.
  12503. @ignore
  12504. @starindex
  12505. @end ignore
  12506. @tindex cheight
  12507. The @code{cheight} function measures the height of a composition.
  12508. This is the total number of lines in the argument's printed form.
  12509. @ignore
  12510. @starindex
  12511. @end ignore
  12512. @tindex cascent
  12513. @ignore
  12514. @starindex
  12515. @end ignore
  12516. @tindex cdescent
  12517. The functions @code{cascent} and @code{cdescent} measure the amount
  12518. of the height that is above (and including) the baseline, or below
  12519. the baseline, respectively. Thus @samp{cascent(@var{x}) + cdescent(@var{x})}
  12520. always equals @samp{cheight(@var{x})}. For a one-line formula like
  12521. @samp{a + b}, @code{cascent} returns 1 and @code{cdescent} returns 0.
  12522. For @samp{a / b} in Big mode, @code{cascent} returns 2 and @code{cdescent}
  12523. returns 1. The only formula for which @code{cascent} will return zero
  12524. is @samp{cvspace(0)} or equivalents.
  12525. @node User-Defined Compositions, , Information about Compositions, Compositions
  12526. @subsubsection User-Defined Compositions
  12527. @noindent
  12528. @kindex Z C
  12529. @pindex calc-user-define-composition
  12530. The @kbd{Z C} (@code{calc-user-define-composition}) command lets you
  12531. define the display format for any algebraic function. You provide a
  12532. formula containing a certain number of argument variables on the stack.
  12533. Any time Calc formats a call to the specified function in the current
  12534. language mode and with that number of arguments, Calc effectively
  12535. replaces the function call with that formula with the arguments
  12536. replaced.
  12537. Calc builds the default argument list by sorting all the variable names
  12538. that appear in the formula into alphabetical order. You can edit this
  12539. argument list before pressing @key{RET} if you wish. Any variables in
  12540. the formula that do not appear in the argument list will be displayed
  12541. literally; any arguments that do not appear in the formula will not
  12542. affect the display at all.
  12543. You can define formats for built-in functions, for functions you have
  12544. defined with @kbd{Z F} (@pxref{Algebraic Definitions}), or for functions
  12545. which have no definitions but are being used as purely syntactic objects.
  12546. You can define different formats for each language mode, and for each
  12547. number of arguments, using a succession of @kbd{Z C} commands. When
  12548. Calc formats a function call, it first searches for a format defined
  12549. for the current language mode (and number of arguments); if there is
  12550. none, it uses the format defined for the Normal language mode. If
  12551. neither format exists, Calc uses its built-in standard format for that
  12552. function (usually just @samp{@var{func}(@var{args})}).
  12553. If you execute @kbd{Z C} with the number 0 on the stack instead of a
  12554. formula, any defined formats for the function in the current language
  12555. mode will be removed. The function will revert to its standard format.
  12556. For example, the default format for the binomial coefficient function
  12557. @samp{choose(n, m)} in the Big language mode is
  12558. @example
  12559. @group
  12560. n
  12561. ( )
  12562. m
  12563. @end group
  12564. @end example
  12565. @noindent
  12566. You might prefer the notation,
  12567. @example
  12568. @group
  12569. C
  12570. n m
  12571. @end group
  12572. @end example
  12573. @noindent
  12574. To define this notation, first make sure you are in Big mode,
  12575. then put the formula
  12576. @smallexample
  12577. choriz([cvert([cvspace(1), n]), C, cvert([cvspace(1), m])])
  12578. @end smallexample
  12579. @noindent
  12580. on the stack and type @kbd{Z C}. Answer the first prompt with
  12581. @code{choose}. The second prompt will be the default argument list
  12582. of @samp{(C m n)}. Edit this list to be @samp{(n m)} and press
  12583. @key{RET}. Now, try it out: For example, turn simplification
  12584. off with @kbd{m O} and enter @samp{choose(a,b) + choose(7,3)}
  12585. as an algebraic entry.
  12586. @example
  12587. @group
  12588. C + C
  12589. a b 7 3
  12590. @end group
  12591. @end example
  12592. As another example, let's define the usual notation for Stirling
  12593. numbers of the first kind, @samp{stir1(n, m)}. This is just like
  12594. the regular format for binomial coefficients but with square brackets
  12595. instead of parentheses.
  12596. @smallexample
  12597. choriz([string("["), cvert([n, cbase(cvspace(1)), m]), string("]")])
  12598. @end smallexample
  12599. Now type @kbd{Z C stir1 @key{RET}}, edit the argument list to
  12600. @samp{(n m)}, and type @key{RET}.
  12601. The formula provided to @kbd{Z C} usually will involve composition
  12602. functions, but it doesn't have to. Putting the formula @samp{a + b + c}
  12603. onto the stack and typing @kbd{Z C foo @key{RET} @key{RET}} would define
  12604. the function @samp{foo(x,y,z)} to display like @samp{x + y + z}.
  12605. This ``sum'' will act exactly like a real sum for all formatting
  12606. purposes (it will be parenthesized the same, and so on). However
  12607. it will be computationally unrelated to a sum. For example, the
  12608. formula @samp{2 * foo(1, 2, 3)} will display as @samp{2 (1 + 2 + 3)}.
  12609. Operator precedences have caused the ``sum'' to be written in
  12610. parentheses, but the arguments have not actually been summed.
  12611. (Generally a display format like this would be undesirable, since
  12612. it can easily be confused with a real sum.)
  12613. The special function @code{eval} can be used inside a @kbd{Z C}
  12614. composition formula to cause all or part of the formula to be
  12615. evaluated at display time. For example, if the formula is
  12616. @samp{a + eval(b + c)}, then @samp{foo(1, 2, 3)} will be displayed
  12617. as @samp{1 + 5}. Evaluation will use the default simplifications,
  12618. regardless of the current simplification mode. There are also
  12619. @code{evalsimp} and @code{evalextsimp} which simplify as if by
  12620. @kbd{a s} and @kbd{a e} (respectively). Note that these ``functions''
  12621. operate only in the context of composition formulas (and also in
  12622. rewrite rules, where they serve a similar purpose; @pxref{Rewrite
  12623. Rules}). On the stack, a call to @code{eval} will be left in
  12624. symbolic form.
  12625. It is not a good idea to use @code{eval} except as a last resort.
  12626. It can cause the display of formulas to be extremely slow. For
  12627. example, while @samp{eval(a + b)} might seem quite fast and simple,
  12628. there are several situations where it could be slow. For example,
  12629. @samp{a} and/or @samp{b} could be polar complex numbers, in which
  12630. case doing the sum requires trigonometry. Or, @samp{a} could be
  12631. the factorial @samp{fact(100)} which is unevaluated because you
  12632. have typed @kbd{m O}; @code{eval} will evaluate it anyway to
  12633. produce a large, unwieldy integer.
  12634. You can save your display formats permanently using the @kbd{Z P}
  12635. command (@pxref{Creating User Keys}).
  12636. @node Syntax Tables, , Compositions, Language Modes
  12637. @subsection Syntax Tables
  12638. @noindent
  12639. @cindex Syntax tables
  12640. @cindex Parsing formulas, customized
  12641. Syntax tables do for input what compositions do for output: They
  12642. allow you to teach custom notations to Calc's formula parser.
  12643. Calc keeps a separate syntax table for each language mode.
  12644. (Note that the Calc ``syntax tables'' discussed here are completely
  12645. unrelated to the syntax tables described in the Emacs manual.)
  12646. @kindex Z S
  12647. @pindex calc-edit-user-syntax
  12648. The @kbd{Z S} (@code{calc-edit-user-syntax}) command edits the
  12649. syntax table for the current language mode. If you want your
  12650. syntax to work in any language, define it in the normal language
  12651. mode. Type @kbd{M-# M-#} to finish editing the syntax table, or
  12652. @kbd{M-# x} to cancel the edit. The @kbd{m m} command saves all
  12653. the syntax tables along with the other mode settings;
  12654. @pxref{General Mode Commands}.
  12655. @menu
  12656. * Syntax Table Basics::
  12657. * Precedence in Syntax Tables::
  12658. * Advanced Syntax Patterns::
  12659. * Conditional Syntax Rules::
  12660. @end menu
  12661. @node Syntax Table Basics, Precedence in Syntax Tables, Syntax Tables, Syntax Tables
  12662. @subsubsection Syntax Table Basics
  12663. @noindent
  12664. @dfn{Parsing} is the process of converting a raw string of characters,
  12665. such as you would type in during algebraic entry, into a Calc formula.
  12666. Calc's parser works in two stages. First, the input is broken down
  12667. into @dfn{tokens}, such as words, numbers, and punctuation symbols
  12668. like @samp{+}, @samp{:=}, and @samp{+/-}. Space between tokens is
  12669. ignored (except when it serves to separate adjacent words). Next,
  12670. the parser matches this string of tokens against various built-in
  12671. syntactic patterns, such as ``an expression followed by @samp{+}
  12672. followed by another expression'' or ``a name followed by @samp{(},
  12673. zero or more expressions separated by commas, and @samp{)}.''
  12674. A @dfn{syntax table} is a list of user-defined @dfn{syntax rules},
  12675. which allow you to specify new patterns to define your own
  12676. favorite input notations. Calc's parser always checks the syntax
  12677. table for the current language mode, then the table for the normal
  12678. language mode, before it uses its built-in rules to parse an
  12679. algebraic formula you have entered. Each syntax rule should go on
  12680. its own line; it consists of a @dfn{pattern}, a @samp{:=} symbol,
  12681. and a Calc formula with an optional @dfn{condition}. (Syntax rules
  12682. resemble algebraic rewrite rules, but the notation for patterns is
  12683. completely different.)
  12684. A syntax pattern is a list of tokens, separated by spaces.
  12685. Except for a few special symbols, tokens in syntax patterns are
  12686. matched literally, from left to right. For example, the rule,
  12687. @example
  12688. foo ( ) := 2+3
  12689. @end example
  12690. @noindent
  12691. would cause Calc to parse the formula @samp{4+foo()*5} as if it
  12692. were @samp{4+(2+3)*5}. Notice that the parentheses were written
  12693. as two separate tokens in the rule. As a result, the rule works
  12694. for both @samp{foo()} and @w{@samp{foo ( )}}. If we had written
  12695. the rule as @samp{foo () := 2+3}, then Calc would treat @samp{()}
  12696. as a single, indivisible token, so that @w{@samp{foo( )}} would
  12697. not be recognized by the rule. (It would be parsed as a regular
  12698. zero-argument function call instead.) In fact, this rule would
  12699. also make trouble for the rest of Calc's parser: An unrelated
  12700. formula like @samp{bar()} would now be tokenized into @samp{bar ()}
  12701. instead of @samp{bar ( )}, so that the standard parser for function
  12702. calls would no longer recognize it!
  12703. While it is possible to make a token with a mixture of letters
  12704. and punctuation symbols, this is not recommended. It is better to
  12705. break it into several tokens, as we did with @samp{foo()} above.
  12706. The symbol @samp{#} in a syntax pattern matches any Calc expression.
  12707. On the righthand side, the things that matched the @samp{#}s can
  12708. be referred to as @samp{#1}, @samp{#2}, and so on (where @samp{#1}
  12709. matches the leftmost @samp{#} in the pattern). For example, these
  12710. rules match a user-defined function, prefix operator, infix operator,
  12711. and postfix operator, respectively:
  12712. @example
  12713. foo ( # ) := myfunc(#1)
  12714. foo # := myprefix(#1)
  12715. # foo # := myinfix(#1,#2)
  12716. # foo := mypostfix(#1)
  12717. @end example
  12718. Thus @samp{foo(3)} will parse as @samp{myfunc(3)}, and @samp{2+3 foo}
  12719. will parse as @samp{mypostfix(2+3)}.
  12720. It is important to write the first two rules in the order shown,
  12721. because Calc tries rules in order from first to last. If the
  12722. pattern @samp{foo #} came first, it would match anything that could
  12723. match the @samp{foo ( # )} rule, since an expression in parentheses
  12724. is itself a valid expression. Thus the @w{@samp{foo ( # )}} rule would
  12725. never get to match anything. Likewise, the last two rules must be
  12726. written in the order shown or else @samp{3 foo 4} will be parsed as
  12727. @samp{mypostfix(3) * 4}. (Of course, the best way to avoid these
  12728. ambiguities is not to use the same symbol in more than one way at
  12729. the same time! In case you're not convinced, try the following
  12730. exercise: How will the above rules parse the input @samp{foo(3,4)},
  12731. if at all? Work it out for yourself, then try it in Calc and see.)
  12732. Calc is quite flexible about what sorts of patterns are allowed.
  12733. The only rule is that every pattern must begin with a literal
  12734. token (like @samp{foo} in the first two patterns above), or with
  12735. a @samp{#} followed by a literal token (as in the last two
  12736. patterns). After that, any mixture is allowed, although putting
  12737. two @samp{#}s in a row will not be very useful since two
  12738. expressions with nothing between them will be parsed as one
  12739. expression that uses implicit multiplication.
  12740. As a more practical example, Maple uses the notation
  12741. @samp{sum(a(i), i=1..10)} for sums, which Calc's Maple mode doesn't
  12742. recognize at present. To handle this syntax, we simply add the
  12743. rule,
  12744. @example
  12745. sum ( # , # = # .. # ) := sum(#1,#2,#3,#4)
  12746. @end example
  12747. @noindent
  12748. to the Maple mode syntax table. As another example, C mode can't
  12749. read assignment operators like @samp{++} and @samp{*=}. We can
  12750. define these operators quite easily:
  12751. @example
  12752. # *= # := muleq(#1,#2)
  12753. # ++ := postinc(#1)
  12754. ++ # := preinc(#1)
  12755. @end example
  12756. @noindent
  12757. To complete the job, we would use corresponding composition functions
  12758. and @kbd{Z C} to cause these functions to display in their respective
  12759. Maple and C notations. (Note that the C example ignores issues of
  12760. operator precedence, which are discussed in the next section.)
  12761. You can enclose any token in quotes to prevent its usual
  12762. interpretation in syntax patterns:
  12763. @example
  12764. # ":=" # := becomes(#1,#2)
  12765. @end example
  12766. Quotes also allow you to include spaces in a token, although once
  12767. again it is generally better to use two tokens than one token with
  12768. an embedded space. To include an actual quotation mark in a quoted
  12769. token, precede it with a backslash. (This also works to include
  12770. backslashes in tokens.)
  12771. @example
  12772. # "bad token" # "/\"\\" # := silly(#1,#2,#3)
  12773. @end example
  12774. @noindent
  12775. This will parse @samp{3 bad token 4 /"\ 5} to @samp{silly(3,4,5)}.
  12776. The token @kbd{#} has a predefined meaning in Calc's formula parser;
  12777. it is not legal to use @samp{"#"} in a syntax rule. However, longer
  12778. tokens that include the @samp{#} character are allowed. Also, while
  12779. @samp{"$"} and @samp{"\""} are allowed as tokens, their presence in
  12780. the syntax table will prevent those characters from working in their
  12781. usual ways (referring to stack entries and quoting strings,
  12782. respectively).
  12783. Finally, the notation @samp{%%} anywhere in a syntax table causes
  12784. the rest of the line to be ignored as a comment.
  12785. @node Precedence in Syntax Tables, Advanced Syntax Patterns, Syntax Table Basics, Syntax Tables
  12786. @subsubsection Precedence
  12787. @noindent
  12788. Different operators are generally assigned different @dfn{precedences}.
  12789. By default, an operator defined by a rule like
  12790. @example
  12791. # foo # := foo(#1,#2)
  12792. @end example
  12793. @noindent
  12794. will have an extremely low precedence, so that @samp{2*3+4 foo 5 == 6}
  12795. will be parsed as @samp{(2*3+4) foo (5 == 6)}. To change the
  12796. precedence of an operator, use the notation @samp{#/@var{p}} in
  12797. place of @samp{#}, where @var{p} is an integer precedence level.
  12798. For example, 185 lies between the precedences for @samp{+} and
  12799. @samp{*}, so if we change this rule to
  12800. @example
  12801. #/185 foo #/186 := foo(#1,#2)
  12802. @end example
  12803. @noindent
  12804. then @samp{2+3 foo 4*5} will be parsed as @samp{2+(3 foo (4*5))}.
  12805. Also, because we've given the righthand expression slightly higher
  12806. precedence, our new operator will be left-associative:
  12807. @samp{1 foo 2 foo 3} will be parsed as @samp{(1 foo 2) foo 3}.
  12808. By raising the precedence of the lefthand expression instead, we
  12809. can create a right-associative operator.
  12810. @xref{Composition Basics}, for a table of precedences of the
  12811. standard Calc operators. For the precedences of operators in other
  12812. language modes, look in the Calc source file @file{calc-lang.el}.
  12813. @node Advanced Syntax Patterns, Conditional Syntax Rules, Precedence in Syntax Tables, Syntax Tables
  12814. @subsubsection Advanced Syntax Patterns
  12815. @noindent
  12816. To match a function with a variable number of arguments, you could
  12817. write
  12818. @example
  12819. foo ( # ) := myfunc(#1)
  12820. foo ( # , # ) := myfunc(#1,#2)
  12821. foo ( # , # , # ) := myfunc(#1,#2,#3)
  12822. @end example
  12823. @noindent
  12824. but this isn't very elegant. To match variable numbers of items,
  12825. Calc uses some notations inspired regular expressions and the
  12826. ``extended BNF'' style used by some language designers.
  12827. @example
  12828. foo ( @{ # @}*, ) := apply(myfunc,#1)
  12829. @end example
  12830. The token @samp{@{} introduces a repeated or optional portion.
  12831. One of the three tokens @samp{@}*}, @samp{@}+}, or @samp{@}?}
  12832. ends the portion. These will match zero or more, one or more,
  12833. or zero or one copies of the enclosed pattern, respectively.
  12834. In addition, @samp{@}*} and @samp{@}+} can be followed by a
  12835. separator token (with no space in between, as shown above).
  12836. Thus @samp{@{ # @}*,} matches nothing, or one expression, or
  12837. several expressions separated by commas.
  12838. A complete @samp{@{ ... @}} item matches as a vector of the
  12839. items that matched inside it. For example, the above rule will
  12840. match @samp{foo(1,2,3)} to get @samp{apply(myfunc,[1,2,3])}.
  12841. The Calc @code{apply} function takes a function name and a vector
  12842. of arguments and builds a call to the function with those
  12843. arguments, so the net result is the formula @samp{myfunc(1,2,3)}.
  12844. If the body of a @samp{@{ ... @}} contains several @samp{#}s
  12845. (or nested @samp{@{ ... @}} constructs), then the items will be
  12846. strung together into the resulting vector. If the body
  12847. does not contain anything but literal tokens, the result will
  12848. always be an empty vector.
  12849. @example
  12850. foo ( @{ # , # @}+, ) := bar(#1)
  12851. foo ( @{ @{ # @}*, @}*; ) := matrix(#1)
  12852. @end example
  12853. @noindent
  12854. will parse @samp{foo(1, 2, 3, 4)} as @samp{bar([1, 2, 3, 4])}, and
  12855. @samp{foo(1, 2; 3, 4)} as @samp{matrix([[1, 2], [3, 4]])}. Also, after
  12856. some thought it's easy to see how this pair of rules will parse
  12857. @samp{foo(1, 2, 3)} as @samp{matrix([[1, 2, 3]])}, since the first
  12858. rule will only match an even number of arguments. The rule
  12859. @example
  12860. foo ( # @{ , # , # @}? ) := bar(#1,#2)
  12861. @end example
  12862. @noindent
  12863. will parse @samp{foo(2,3,4)} as @samp{bar(2,[3,4])}, and
  12864. @samp{foo(2)} as @samp{bar(2,[])}.
  12865. The notation @samp{@{ ... @}?.} (note the trailing period) works
  12866. just the same as regular @samp{@{ ... @}?}, except that it does not
  12867. count as an argument; the following two rules are equivalent:
  12868. @example
  12869. foo ( # , @{ also @}? # ) := bar(#1,#3)
  12870. foo ( # , @{ also @}?. # ) := bar(#1,#2)
  12871. @end example
  12872. @noindent
  12873. Note that in the first case the optional text counts as @samp{#2},
  12874. which will always be an empty vector, but in the second case no
  12875. empty vector is produced.
  12876. Another variant is @samp{@{ ... @}?$}, which means the body is
  12877. optional only at the end of the input formula. All built-in syntax
  12878. rules in Calc use this for closing delimiters, so that during
  12879. algebraic entry you can type @kbd{[sqrt(2), sqrt(3 @key{RET}}, omitting
  12880. the closing parenthesis and bracket. Calc does this automatically
  12881. for trailing @samp{)}, @samp{]}, and @samp{>} tokens in syntax
  12882. rules, but you can use @samp{@{ ... @}?$} explicitly to get
  12883. this effect with any token (such as @samp{"@}"} or @samp{end}).
  12884. Like @samp{@{ ... @}?.}, this notation does not count as an
  12885. argument. Conversely, you can use quotes, as in @samp{")"}, to
  12886. prevent a closing-delimiter token from being automatically treated
  12887. as optional.
  12888. Calc's parser does not have full backtracking, which means some
  12889. patterns will not work as you might expect:
  12890. @example
  12891. foo ( @{ # , @}? # , # ) := bar(#1,#2,#3)
  12892. @end example
  12893. @noindent
  12894. Here we are trying to make the first argument optional, so that
  12895. @samp{foo(2,3)} parses as @samp{bar([],2,3)}. Unfortunately, Calc
  12896. first tries to match @samp{2,} against the optional part of the
  12897. pattern, finds a match, and so goes ahead to match the rest of the
  12898. pattern. Later on it will fail to match the second comma, but it
  12899. doesn't know how to go back and try the other alternative at that
  12900. point. One way to get around this would be to use two rules:
  12901. @example
  12902. foo ( # , # , # ) := bar([#1],#2,#3)
  12903. foo ( # , # ) := bar([],#1,#2)
  12904. @end example
  12905. More precisely, when Calc wants to match an optional or repeated
  12906. part of a pattern, it scans forward attempting to match that part.
  12907. If it reaches the end of the optional part without failing, it
  12908. ``finalizes'' its choice and proceeds. If it fails, though, it
  12909. backs up and tries the other alternative. Thus Calc has ``partial''
  12910. backtracking. A fully backtracking parser would go on to make sure
  12911. the rest of the pattern matched before finalizing the choice.
  12912. @node Conditional Syntax Rules, , Advanced Syntax Patterns, Syntax Tables
  12913. @subsubsection Conditional Syntax Rules
  12914. @noindent
  12915. It is possible to attach a @dfn{condition} to a syntax rule. For
  12916. example, the rules
  12917. @example
  12918. foo ( # ) := ifoo(#1) :: integer(#1)
  12919. foo ( # ) := gfoo(#1)
  12920. @end example
  12921. @noindent
  12922. will parse @samp{foo(3)} as @samp{ifoo(3)}, but will parse
  12923. @samp{foo(3.5)} and @samp{foo(x)} as calls to @code{gfoo}. Any
  12924. number of conditions may be attached; all must be true for the
  12925. rule to succeed. A condition is ``true'' if it evaluates to a
  12926. nonzero number. @xref{Logical Operations}, for a list of Calc
  12927. functions like @code{integer} that perform logical tests.
  12928. The exact sequence of events is as follows: When Calc tries a
  12929. rule, it first matches the pattern as usual. It then substitutes
  12930. @samp{#1}, @samp{#2}, etc., in the conditions, if any. Next, the
  12931. conditions are simplified and evaluated in order from left to right,
  12932. as if by the @w{@kbd{a s}} algebra command (@pxref{Simplifying Formulas}).
  12933. Each result is true if it is a nonzero number, or an expression
  12934. that can be proven to be nonzero (@pxref{Declarations}). If the
  12935. results of all conditions are true, the expression (such as
  12936. @samp{ifoo(#1)}) has its @samp{#}s substituted, and that is the
  12937. result of the parse. If the result of any condition is false, Calc
  12938. goes on to try the next rule in the syntax table.
  12939. Syntax rules also support @code{let} conditions, which operate in
  12940. exactly the same way as they do in algebraic rewrite rules.
  12941. @xref{Other Features of Rewrite Rules}, for details. A @code{let}
  12942. condition is always true, but as a side effect it defines a
  12943. variable which can be used in later conditions, and also in the
  12944. expression after the @samp{:=} sign:
  12945. @example
  12946. foo ( # ) := hifoo(x) :: let(x := #1 + 0.5) :: dnumint(x)
  12947. @end example
  12948. @noindent
  12949. The @code{dnumint} function tests if a value is numerically an
  12950. integer, i.e., either a true integer or an integer-valued float.
  12951. This rule will parse @code{foo} with a half-integer argument,
  12952. like @samp{foo(3.5)}, to a call like @samp{hifoo(4.)}.
  12953. The lefthand side of a syntax rule @code{let} must be a simple
  12954. variable, not the arbitrary pattern that is allowed in rewrite
  12955. rules.
  12956. The @code{matches} function is also treated specially in syntax
  12957. rule conditions (again, in the same way as in rewrite rules).
  12958. @xref{Matching Commands}. If the matching pattern contains
  12959. meta-variables, then those meta-variables may be used in later
  12960. conditions and in the result expression. The arguments to
  12961. @code{matches} are not evaluated in this situation.
  12962. @example
  12963. sum ( # , # ) := sum(#1,a,b,c) :: matches(#2, a=[b..c])
  12964. @end example
  12965. @noindent
  12966. This is another way to implement the Maple mode @code{sum} notation.
  12967. In this approach, we allow @samp{#2} to equal the whole expression
  12968. @samp{i=1..10}. Then, we use @code{matches} to break it apart into
  12969. its components. If the expression turns out not to match the pattern,
  12970. the syntax rule will fail. Note that @kbd{Z S} always uses Calc's
  12971. normal language mode for editing expressions in syntax rules, so we
  12972. must use regular Calc notation for the interval @samp{[b..c]} that
  12973. will correspond to the Maple mode interval @samp{1..10}.
  12974. @node Modes Variable, Calc Mode Line, Language Modes, Mode Settings
  12975. @section The @code{Modes} Variable
  12976. @noindent
  12977. @kindex m g
  12978. @pindex calc-get-modes
  12979. The @kbd{m g} (@code{calc-get-modes}) command pushes onto the stack
  12980. a vector of numbers that describes the various mode settings that
  12981. are in effect. With a numeric prefix argument, it pushes only the
  12982. @var{n}th mode, i.e., the @var{n}th element of this vector. Keyboard
  12983. macros can use the @kbd{m g} command to modify their behavior based
  12984. on the current mode settings.
  12985. @cindex @code{Modes} variable
  12986. @vindex Modes
  12987. The modes vector is also available in the special variable
  12988. @code{Modes}. In other words, @kbd{m g} is like @kbd{s r Modes @key{RET}}.
  12989. It will not work to store into this variable; in fact, if you do,
  12990. @code{Modes} will cease to track the current modes. (The @kbd{m g}
  12991. command will continue to work, however.)
  12992. In general, each number in this vector is suitable as a numeric
  12993. prefix argument to the associated mode-setting command. (Recall
  12994. that the @kbd{~} key takes a number from the stack and gives it as
  12995. a numeric prefix to the next command.)
  12996. The elements of the modes vector are as follows:
  12997. @enumerate
  12998. @item
  12999. Current precision. Default is 12; associated command is @kbd{p}.
  13000. @item
  13001. Binary word size. Default is 32; associated command is @kbd{b w}.
  13002. @item
  13003. Stack size (not counting the value about to be pushed by @kbd{m g}).
  13004. This is zero if @kbd{m g} is executed with an empty stack.
  13005. @item
  13006. Number radix. Default is 10; command is @kbd{d r}.
  13007. @item
  13008. Floating-point format. This is the number of digits, plus the
  13009. constant 0 for normal notation, 10000 for scientific notation,
  13010. 20000 for engineering notation, or 30000 for fixed-point notation.
  13011. These codes are acceptable as prefix arguments to the @kbd{d n}
  13012. command, but note that this may lose information: For example,
  13013. @kbd{d s} and @kbd{C-u 12 d s} have similar (but not quite
  13014. identical) effects if the current precision is 12, but they both
  13015. produce a code of 10012, which will be treated by @kbd{d n} as
  13016. @kbd{C-u 12 d s}. If the precision then changes, the float format
  13017. will still be frozen at 12 significant figures.
  13018. @item
  13019. Angular mode. Default is 1 (degrees). Other values are 2 (radians)
  13020. and 3 (HMS). The @kbd{m d} command accepts these prefixes.
  13021. @item
  13022. Symbolic mode. Value is 0 or 1; default is 0. Command is @kbd{m s}.
  13023. @item
  13024. Fraction mode. Value is 0 or 1; default is 0. Command is @kbd{m f}.
  13025. @item
  13026. Polar mode. Value is 0 (rectangular) or 1 (polar); default is 0.
  13027. Command is @kbd{m p}.
  13028. @item
  13029. Matrix/scalar mode. Default value is @i{-1}. Value is 0 for scalar
  13030. mode, @i{-2} for matrix mode, or @var{N} for @c{$N\times N$}
  13031. @var{N}x@var{N} matrix mode. Command is @kbd{m v}.
  13032. @item
  13033. Simplification mode. Default is 1. Value is @i{-1} for off (@kbd{m O}),
  13034. 0 for @kbd{m N}, 2 for @kbd{m B}, 3 for @kbd{m A}, 4 for @kbd{m E},
  13035. or 5 for @w{@kbd{m U}}. The @kbd{m D} command accepts these prefixes.
  13036. @item
  13037. Infinite mode. Default is @i{-1} (off). Value is 1 if the mode is on,
  13038. or 0 if the mode is on with positive zeros. Command is @kbd{m i}.
  13039. @end enumerate
  13040. For example, the sequence @kbd{M-1 m g @key{RET} 2 + ~ p} increases the
  13041. precision by two, leaving a copy of the old precision on the stack.
  13042. Later, @kbd{~ p} will restore the original precision using that
  13043. stack value. (This sequence might be especially useful inside a
  13044. keyboard macro.)
  13045. As another example, @kbd{M-3 m g 1 - ~ @key{DEL}} deletes all but the
  13046. oldest (bottommost) stack entry.
  13047. Yet another example: The HP-48 ``round'' command rounds a number
  13048. to the current displayed precision. You could roughly emulate this
  13049. in Calc with the sequence @kbd{M-5 m g 10000 % ~ c c}. (This
  13050. would not work for fixed-point mode, but it wouldn't be hard to
  13051. do a full emulation with the help of the @kbd{Z [} and @kbd{Z ]}
  13052. programming commands. @xref{Conditionals in Macros}.)
  13053. @node Calc Mode Line, , Modes Variable, Mode Settings
  13054. @section The Calc Mode Line
  13055. @noindent
  13056. @cindex Mode line indicators
  13057. This section is a summary of all symbols that can appear on the
  13058. Calc mode line, the highlighted bar that appears under the Calc
  13059. stack window (or under an editing window in Embedded Mode).
  13060. The basic mode line format is:
  13061. @example
  13062. --%%-Calc: 12 Deg @var{other modes} (Calculator)
  13063. @end example
  13064. The @samp{%%} is the Emacs symbol for ``read-only''; it shows that
  13065. regular Emacs commands are not allowed to edit the stack buffer
  13066. as if it were text.
  13067. The word @samp{Calc:} changes to @samp{CalcEmbed:} if Embedded Mode
  13068. is enabled. The words after this describe the various Calc modes
  13069. that are in effect.
  13070. The first mode is always the current precision, an integer.
  13071. The second mode is always the angular mode, either @code{Deg},
  13072. @code{Rad}, or @code{Hms}.
  13073. Here is a complete list of the remaining symbols that can appear
  13074. on the mode line:
  13075. @table @code
  13076. @item Alg
  13077. Algebraic mode (@kbd{m a}; @pxref{Algebraic Entry}).
  13078. @item Alg[(
  13079. Incomplete algebraic mode (@kbd{C-u m a}).
  13080. @item Alg*
  13081. Total algebraic mode (@kbd{m t}).
  13082. @item Symb
  13083. Symbolic mode (@kbd{m s}; @pxref{Symbolic Mode}).
  13084. @item Matrix
  13085. Matrix mode (@kbd{m v}; @pxref{Matrix Mode}).
  13086. @item Matrix@var{n}
  13087. Dimensioned matrix mode (@kbd{C-u @var{n} m v}).
  13088. @item Scalar
  13089. Scalar mode (@kbd{m v}; @pxref{Matrix Mode}).
  13090. @item Polar
  13091. Polar complex mode (@kbd{m p}; @pxref{Polar Mode}).
  13092. @item Frac
  13093. Fraction mode (@kbd{m f}; @pxref{Fraction Mode}).
  13094. @item Inf
  13095. Infinite mode (@kbd{m i}; @pxref{Infinite Mode}).
  13096. @item +Inf
  13097. Positive infinite mode (@kbd{C-u 0 m i}).
  13098. @item NoSimp
  13099. Default simplifications off (@kbd{m O}; @pxref{Simplification Modes}).
  13100. @item NumSimp
  13101. Default simplifications for numeric arguments only (@kbd{m N}).
  13102. @item BinSimp@var{w}
  13103. Binary-integer simplification mode; word size @var{w} (@kbd{m B}, @kbd{b w}).
  13104. @item AlgSimp
  13105. Algebraic simplification mode (@kbd{m A}).
  13106. @item ExtSimp
  13107. Extended algebraic simplification mode (@kbd{m E}).
  13108. @item UnitSimp
  13109. Units simplification mode (@kbd{m U}).
  13110. @item Bin
  13111. Current radix is 2 (@kbd{d 2}; @pxref{Radix Modes}).
  13112. @item Oct
  13113. Current radix is 8 (@kbd{d 8}).
  13114. @item Hex
  13115. Current radix is 16 (@kbd{d 6}).
  13116. @item Radix@var{n}
  13117. Current radix is @var{n} (@kbd{d r}).
  13118. @item Zero
  13119. Leading zeros (@kbd{d z}; @pxref{Radix Modes}).
  13120. @item Big
  13121. Big language mode (@kbd{d B}; @pxref{Normal Language Modes}).
  13122. @item Flat
  13123. One-line normal language mode (@kbd{d O}).
  13124. @item Unform
  13125. Unformatted language mode (@kbd{d U}).
  13126. @item C
  13127. C language mode (@kbd{d C}; @pxref{C FORTRAN Pascal}).
  13128. @item Pascal
  13129. Pascal language mode (@kbd{d P}).
  13130. @item Fortran
  13131. FORTRAN language mode (@kbd{d F}).
  13132. @item TeX
  13133. @TeX{} language mode (@kbd{d T}; @pxref{TeX Language Mode}).
  13134. @item Eqn
  13135. @dfn{Eqn} language mode (@kbd{d E}; @pxref{Eqn Language Mode}).
  13136. @item Math
  13137. Mathematica language mode (@kbd{d M}; @pxref{Mathematica Language Mode}).
  13138. @item Maple
  13139. Maple language mode (@kbd{d W}; @pxref{Maple Language Mode}).
  13140. @item Norm@var{n}
  13141. Normal float mode with @var{n} digits (@kbd{d n}; @pxref{Float Formats}).
  13142. @item Fix@var{n}
  13143. Fixed point mode with @var{n} digits after the point (@kbd{d f}).
  13144. @item Sci
  13145. Scientific notation mode (@kbd{d s}).
  13146. @item Sci@var{n}
  13147. Scientific notation with @var{n} digits (@kbd{d s}).
  13148. @item Eng
  13149. Engineering notation mode (@kbd{d e}).
  13150. @item Eng@var{n}
  13151. Engineering notation with @var{n} digits (@kbd{d e}).
  13152. @item Left@var{n}
  13153. Left-justified display indented by @var{n} (@kbd{d <}; @pxref{Justification}).
  13154. @item Right
  13155. Right-justified display (@kbd{d >}).
  13156. @item Right@var{n}
  13157. Right-justified display with width @var{n} (@kbd{d >}).
  13158. @item Center
  13159. Centered display (@kbd{d =}).
  13160. @item Center@var{n}
  13161. Centered display with center column @var{n} (@kbd{d =}).
  13162. @item Wid@var{n}
  13163. Line breaking with width @var{n} (@kbd{d b}; @pxref{Normal Language Modes}).
  13164. @item Wide
  13165. No line breaking (@kbd{d b}).
  13166. @item Break
  13167. Selections show deep structure (@kbd{j b}; @pxref{Making Selections}).
  13168. @item Save
  13169. Record modes in @file{~/.emacs} (@kbd{m R}; @pxref{General Mode Commands}).
  13170. @item Local
  13171. Record modes in Embedded buffer (@kbd{m R}).
  13172. @item LocEdit
  13173. Record modes as editing-only in Embedded buffer (@kbd{m R}).
  13174. @item LocPerm
  13175. Record modes as permanent-only in Embedded buffer (@kbd{m R}).
  13176. @item Global
  13177. Record modes as global in Embedded buffer (@kbd{m R}).
  13178. @item Manual
  13179. Automatic recomputation turned off (@kbd{m C}; @pxref{Automatic
  13180. Recomputation}).
  13181. @item Graph
  13182. GNUPLOT process is alive in background (@pxref{Graphics}).
  13183. @item Sel
  13184. Top-of-stack has a selection (Embedded only; @pxref{Making Selections}).
  13185. @item Dirty
  13186. The stack display may not be up-to-date (@pxref{Display Modes}).
  13187. @item Inv
  13188. ``Inverse'' prefix was pressed (@kbd{I}; @pxref{Inverse and Hyperbolic}).
  13189. @item Hyp
  13190. ``Hyperbolic'' prefix was pressed (@kbd{H}).
  13191. @item Keep
  13192. ``Keep-arguments'' prefix was pressed (@kbd{K}).
  13193. @item Narrow
  13194. Stack is truncated (@kbd{d t}; @pxref{Truncating the Stack}).
  13195. @end table
  13196. In addition, the symbols @code{Active} and @code{~Active} can appear
  13197. as minor modes on an Embedded buffer's mode line. @xref{Embedded Mode}.
  13198. @node Arithmetic, Scientific Functions, Mode Settings, Top
  13199. @chapter Arithmetic Functions
  13200. @noindent
  13201. This chapter describes the Calc commands for doing simple calculations
  13202. on numbers, such as addition, absolute value, and square roots. These
  13203. commands work by removing the top one or two values from the stack,
  13204. performing the desired operation, and pushing the result back onto the
  13205. stack. If the operation cannot be performed, the result pushed is a
  13206. formula instead of a number, such as @samp{2/0} (because division by zero
  13207. is illegal) or @samp{sqrt(x)} (because the argument @samp{x} is a formula).
  13208. Most of the commands described here can be invoked by a single keystroke.
  13209. Some of the more obscure ones are two-letter sequences beginning with
  13210. the @kbd{f} (``functions'') prefix key.
  13211. @xref{Prefix Arguments}, for a discussion of the effect of numeric
  13212. prefix arguments on commands in this chapter which do not otherwise
  13213. interpret a prefix argument.
  13214. @menu
  13215. * Basic Arithmetic::
  13216. * Integer Truncation::
  13217. * Complex Number Functions::
  13218. * Conversions::
  13219. * Date Arithmetic::
  13220. * Financial Functions::
  13221. * Binary Functions::
  13222. @end menu
  13223. @node Basic Arithmetic, Integer Truncation, Arithmetic, Arithmetic
  13224. @section Basic Arithmetic
  13225. @noindent
  13226. @kindex +
  13227. @pindex calc-plus
  13228. @ignore
  13229. @mindex @null
  13230. @end ignore
  13231. @tindex +
  13232. The @kbd{+} (@code{calc-plus}) command adds two numbers. The numbers may
  13233. be any of the standard Calc data types. The resulting sum is pushed back
  13234. onto the stack.
  13235. If both arguments of @kbd{+} are vectors or matrices (of matching dimensions),
  13236. the result is a vector or matrix sum. If one argument is a vector and the
  13237. other a scalar (i.e., a non-vector), the scalar is added to each of the
  13238. elements of the vector to form a new vector. If the scalar is not a
  13239. number, the operation is left in symbolic form: Suppose you added @samp{x}
  13240. to the vector @samp{[1,2]}. You may want the result @samp{[1+x,2+x]}, or
  13241. you may plan to substitute a 2-vector for @samp{x} in the future. Since
  13242. the Calculator can't tell which interpretation you want, it makes the
  13243. safest assumption. @xref{Reducing and Mapping}, for a way to add @samp{x}
  13244. to every element of a vector.
  13245. If either argument of @kbd{+} is a complex number, the result will in general
  13246. be complex. If one argument is in rectangular form and the other polar,
  13247. the current Polar Mode determines the form of the result. If Symbolic
  13248. Mode is enabled, the sum may be left as a formula if the necessary
  13249. conversions for polar addition are non-trivial.
  13250. If both arguments of @kbd{+} are HMS forms, the forms are added according to
  13251. the usual conventions of hours-minutes-seconds notation. If one argument
  13252. is an HMS form and the other is a number, that number is converted from
  13253. degrees or radians (depending on the current Angular Mode) to HMS format
  13254. and then the two HMS forms are added.
  13255. If one argument of @kbd{+} is a date form, the other can be either a
  13256. real number, which advances the date by a certain number of days, or
  13257. an HMS form, which advances the date by a certain amount of time.
  13258. Subtracting two date forms yields the number of days between them.
  13259. Adding two date forms is meaningless, but Calc interprets it as the
  13260. subtraction of one date form and the negative of the other. (The
  13261. negative of a date form can be understood by remembering that dates
  13262. are stored as the number of days before or after Jan 1, 1 AD.)
  13263. If both arguments of @kbd{+} are error forms, the result is an error form
  13264. with an appropriately computed standard deviation. If one argument is an
  13265. error form and the other is a number, the number is taken to have zero error.
  13266. Error forms may have symbolic formulas as their mean and/or error parts;
  13267. adding these will produce a symbolic error form result. However, adding an
  13268. error form to a plain symbolic formula (as in @samp{(a +/- b) + c}) will not
  13269. work, for the same reasons just mentioned for vectors. Instead you must
  13270. write @samp{(a +/- b) + (c +/- 0)}.
  13271. If both arguments of @kbd{+} are modulo forms with equal values of @cite{M},
  13272. or if one argument is a modulo form and the other a plain number, the
  13273. result is a modulo form which represents the sum, modulo @cite{M}, of
  13274. the two values.
  13275. If both arguments of @kbd{+} are intervals, the result is an interval
  13276. which describes all possible sums of the possible input values. If
  13277. one argument is a plain number, it is treated as the interval
  13278. @w{@samp{[x ..@: x]}}.
  13279. If one argument of @kbd{+} is an infinity and the other is not, the
  13280. result is that same infinity. If both arguments are infinite and in
  13281. the same direction, the result is the same infinity, but if they are
  13282. infinite in different directions the result is @code{nan}.
  13283. @kindex -
  13284. @pindex calc-minus
  13285. @ignore
  13286. @mindex @null
  13287. @end ignore
  13288. @tindex -
  13289. The @kbd{-} (@code{calc-minus}) command subtracts two values. The top
  13290. number on the stack is subtracted from the one behind it, so that the
  13291. computation @kbd{5 @key{RET} 2 -} produces 3, not @i{-3}. All options
  13292. available for @kbd{+} are available for @kbd{-} as well.
  13293. @kindex *
  13294. @pindex calc-times
  13295. @ignore
  13296. @mindex @null
  13297. @end ignore
  13298. @tindex *
  13299. The @kbd{*} (@code{calc-times}) command multiplies two numbers. If one
  13300. argument is a vector and the other a scalar, the scalar is multiplied by
  13301. the elements of the vector to produce a new vector. If both arguments
  13302. are vectors, the interpretation depends on the dimensions of the
  13303. vectors: If both arguments are matrices, a matrix multiplication is
  13304. done. If one argument is a matrix and the other a plain vector, the
  13305. vector is interpreted as a row vector or column vector, whichever is
  13306. dimensionally correct. If both arguments are plain vectors, the result
  13307. is a single scalar number which is the dot product of the two vectors.
  13308. If one argument of @kbd{*} is an HMS form and the other a number, the
  13309. HMS form is multiplied by that amount. It is an error to multiply two
  13310. HMS forms together, or to attempt any multiplication involving date
  13311. forms. Error forms, modulo forms, and intervals can be multiplied;
  13312. see the comments for addition of those forms. When two error forms
  13313. or intervals are multiplied they are considered to be statistically
  13314. independent; thus, @samp{[-2 ..@: 3] * [-2 ..@: 3]} is @samp{[-6 ..@: 9]},
  13315. whereas @w{@samp{[-2 ..@: 3] ^ 2}} is @samp{[0 ..@: 9]}.
  13316. @kindex /
  13317. @pindex calc-divide
  13318. @ignore
  13319. @mindex @null
  13320. @end ignore
  13321. @tindex /
  13322. The @kbd{/} (@code{calc-divide}) command divides two numbers. When
  13323. dividing a scalar @cite{B} by a square matrix @cite{A}, the computation
  13324. performed is @cite{B} times the inverse of @cite{A}. This also occurs
  13325. if @cite{B} is itself a vector or matrix, in which case the effect is
  13326. to solve the set of linear equations represented by @cite{B}. If @cite{B}
  13327. is a matrix with the same number of rows as @cite{A}, or a plain vector
  13328. (which is interpreted here as a column vector), then the equation
  13329. @cite{A X = B} is solved for the vector or matrix @cite{X}. Otherwise,
  13330. if @cite{B} is a non-square matrix with the same number of @emph{columns}
  13331. as @cite{A}, the equation @cite{X A = B} is solved. If you wish a vector
  13332. @cite{B} to be interpreted as a row vector to be solved as @cite{X A = B},
  13333. make it into a one-row matrix with @kbd{C-u 1 v p} first. To force a
  13334. left-handed solution with a square matrix @cite{B}, transpose @cite{A} and
  13335. @cite{B} before dividing, then transpose the result.
  13336. HMS forms can be divided by real numbers or by other HMS forms. Error
  13337. forms can be divided in any combination of ways. Modulo forms where both
  13338. values and the modulo are integers can be divided to get an integer modulo
  13339. form result. Intervals can be divided; dividing by an interval that
  13340. encompasses zero or has zero as a limit will result in an infinite
  13341. interval.
  13342. @kindex ^
  13343. @pindex calc-power
  13344. @ignore
  13345. @mindex @null
  13346. @end ignore
  13347. @tindex ^
  13348. The @kbd{^} (@code{calc-power}) command raises a number to a power. If
  13349. the power is an integer, an exact result is computed using repeated
  13350. multiplications. For non-integer powers, Calc uses Newton's method or
  13351. logarithms and exponentials. Square matrices can be raised to integer
  13352. powers. If either argument is an error (or interval or modulo) form,
  13353. the result is also an error (or interval or modulo) form.
  13354. @kindex I ^
  13355. @tindex nroot
  13356. If you press the @kbd{I} (inverse) key first, the @kbd{I ^} command
  13357. computes an Nth root: @kbd{125 @key{RET} 3 I ^} computes the number 5.
  13358. (This is entirely equivalent to @kbd{125 @key{RET} 1:3 ^}.)
  13359. @kindex \
  13360. @pindex calc-idiv
  13361. @tindex idiv
  13362. @ignore
  13363. @mindex @null
  13364. @end ignore
  13365. @tindex \
  13366. The @kbd{\} (@code{calc-idiv}) command divides two numbers on the stack
  13367. to produce an integer result. It is equivalent to dividing with
  13368. @key{/}, then rounding down with @kbd{F} (@code{calc-floor}), only a bit
  13369. more convenient and efficient. Also, since it is an all-integer
  13370. operation when the arguments are integers, it avoids problems that
  13371. @kbd{/ F} would have with floating-point roundoff.
  13372. @kindex %
  13373. @pindex calc-mod
  13374. @ignore
  13375. @mindex @null
  13376. @end ignore
  13377. @tindex %
  13378. The @kbd{%} (@code{calc-mod}) command performs a ``modulo'' (or ``remainder'')
  13379. operation. Mathematically, @samp{a%b = a - (a\b)*b}, and is defined
  13380. for all real numbers @cite{a} and @cite{b} (except @cite{b=0}). For
  13381. positive @cite{b}, the result will always be between 0 (inclusive) and
  13382. @cite{b} (exclusive). Modulo does not work for HMS forms and error forms.
  13383. If @cite{a} is a modulo form, its modulo is changed to @cite{b}, which
  13384. must be positive real number.
  13385. @kindex :
  13386. @pindex calc-fdiv
  13387. @tindex fdiv
  13388. The @kbd{:} (@code{calc-fdiv}) command [@code{fdiv} function in a formula]
  13389. divides the two integers on the top of the stack to produce a fractional
  13390. result. This is a convenient shorthand for enabling Fraction Mode (with
  13391. @kbd{m f}) temporarily and using @samp{/}. Note that during numeric entry
  13392. the @kbd{:} key is interpreted as a fraction separator, so to divide 8 by 6
  13393. you would have to type @kbd{8 @key{RET} 6 @key{RET} :}. (Of course, in
  13394. this case, it would be much easier simply to enter the fraction directly
  13395. as @kbd{8:6 @key{RET}}!)
  13396. @kindex n
  13397. @pindex calc-change-sign
  13398. The @kbd{n} (@code{calc-change-sign}) command negates the number on the top
  13399. of the stack. It works on numbers, vectors and matrices, HMS forms, date
  13400. forms, error forms, intervals, and modulo forms.
  13401. @kindex A
  13402. @pindex calc-abs
  13403. @tindex abs
  13404. The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the absolute
  13405. value of a number. The result of @code{abs} is always a nonnegative
  13406. real number: With a complex argument, it computes the complex magnitude.
  13407. With a vector or matrix argument, it computes the Frobenius norm, i.e.,
  13408. the square root of the sum of the squares of the absolute values of the
  13409. elements. The absolute value of an error form is defined by replacing
  13410. the mean part with its absolute value and leaving the error part the same.
  13411. The absolute value of a modulo form is undefined. The absolute value of
  13412. an interval is defined in the obvious way.
  13413. @kindex f A
  13414. @pindex calc-abssqr
  13415. @tindex abssqr
  13416. The @kbd{f A} (@code{calc-abssqr}) [@code{abssqr}] command computes the
  13417. absolute value squared of a number, vector or matrix, or error form.
  13418. @kindex f s
  13419. @pindex calc-sign
  13420. @tindex sign
  13421. The @kbd{f s} (@code{calc-sign}) [@code{sign}] command returns 1 if its
  13422. argument is positive, @i{-1} if its argument is negative, or 0 if its
  13423. argument is zero. In algebraic form, you can also write @samp{sign(a,x)}
  13424. which evaluates to @samp{x * sign(a)}, i.e., either @samp{x}, @samp{-x}, or
  13425. zero depending on the sign of @samp{a}.
  13426. @kindex &
  13427. @pindex calc-inv
  13428. @tindex inv
  13429. @cindex Reciprocal
  13430. The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
  13431. reciprocal of a number, i.e., @cite{1 / x}. Operating on a square
  13432. matrix, it computes the inverse of that matrix.
  13433. @kindex Q
  13434. @pindex calc-sqrt
  13435. @tindex sqrt
  13436. The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] command computes the square
  13437. root of a number. For a negative real argument, the result will be a
  13438. complex number whose form is determined by the current Polar Mode.
  13439. @kindex f h
  13440. @pindex calc-hypot
  13441. @tindex hypot
  13442. The @kbd{f h} (@code{calc-hypot}) [@code{hypot}] command computes the square
  13443. root of the sum of the squares of two numbers. That is, @samp{hypot(a,b)}
  13444. is the length of the hypotenuse of a right triangle with sides @cite{a}
  13445. and @cite{b}. If the arguments are complex numbers, their squared
  13446. magnitudes are used.
  13447. @kindex f Q
  13448. @pindex calc-isqrt
  13449. @tindex isqrt
  13450. The @kbd{f Q} (@code{calc-isqrt}) [@code{isqrt}] command computes the
  13451. integer square root of an integer. This is the true square root of the
  13452. number, rounded down to an integer. For example, @samp{isqrt(10)}
  13453. produces 3. Note that, like @kbd{\} [@code{idiv}], this uses exact
  13454. integer arithmetic throughout to avoid roundoff problems. If the input
  13455. is a floating-point number or other non-integer value, this is exactly
  13456. the same as @samp{floor(sqrt(x))}.
  13457. @kindex f n
  13458. @kindex f x
  13459. @pindex calc-min
  13460. @tindex min
  13461. @pindex calc-max
  13462. @tindex max
  13463. The @kbd{f n} (@code{calc-min}) [@code{min}] and @kbd{f x} (@code{calc-max})
  13464. [@code{max}] commands take the minimum or maximum of two real numbers,
  13465. respectively. These commands also work on HMS forms, date forms,
  13466. intervals, and infinities. (In algebraic expressions, these functions
  13467. take any number of arguments and return the maximum or minimum among
  13468. all the arguments.)@refill
  13469. @kindex f M
  13470. @kindex f X
  13471. @pindex calc-mant-part
  13472. @tindex mant
  13473. @pindex calc-xpon-part
  13474. @tindex xpon
  13475. The @kbd{f M} (@code{calc-mant-part}) [@code{mant}] function extracts
  13476. the ``mantissa'' part @cite{m} of its floating-point argument; @kbd{f X}
  13477. (@code{calc-xpon-part}) [@code{xpon}] extracts the ``exponent'' part
  13478. @cite{e}. The original number is equal to @c{$m \times 10^e$}
  13479. @cite{m * 10^e},
  13480. where @cite{m} is in the interval @samp{[1.0 ..@: 10.0)} except that
  13481. @cite{m=e=0} if the original number is zero. For integers
  13482. and fractions, @code{mant} returns the number unchanged and @code{xpon}
  13483. returns zero. The @kbd{v u} (@code{calc-unpack}) command can also be
  13484. used to ``unpack'' a floating-point number; this produces an integer
  13485. mantissa and exponent, with the constraint that the mantissa is not
  13486. a multiple of ten (again except for the @cite{m=e=0} case).@refill
  13487. @kindex f S
  13488. @pindex calc-scale-float
  13489. @tindex scf
  13490. The @kbd{f S} (@code{calc-scale-float}) [@code{scf}] function scales a number
  13491. by a given power of ten. Thus, @samp{scf(mant(x), xpon(x)) = x} for any
  13492. real @samp{x}. The second argument must be an integer, but the first
  13493. may actually be any numeric value. For example, @samp{scf(5,-2) = 0.05}
  13494. or @samp{1:20} depending on the current Fraction Mode.@refill
  13495. @kindex f [
  13496. @kindex f ]
  13497. @pindex calc-decrement
  13498. @pindex calc-increment
  13499. @tindex decr
  13500. @tindex incr
  13501. The @kbd{f [} (@code{calc-decrement}) [@code{decr}] and @kbd{f ]}
  13502. (@code{calc-increment}) [@code{incr}] functions decrease or increase
  13503. a number by one unit. For integers, the effect is obvious. For
  13504. floating-point numbers, the change is by one unit in the last place.
  13505. For example, incrementing @samp{12.3456} when the current precision
  13506. is 6 digits yields @samp{12.3457}. If the current precision had been
  13507. 8 digits, the result would have been @samp{12.345601}. Incrementing
  13508. @samp{0.0} produces @c{$10^{-p}$}
  13509. @cite{10^-p}, where @cite{p} is the current
  13510. precision. These operations are defined only on integers and floats.
  13511. With numeric prefix arguments, they change the number by @cite{n} units.
  13512. Note that incrementing followed by decrementing, or vice-versa, will
  13513. almost but not quite always cancel out. Suppose the precision is
  13514. 6 digits and the number @samp{9.99999} is on the stack. Incrementing
  13515. will produce @samp{10.0000}; decrementing will produce @samp{9.9999}.
  13516. One digit has been dropped. This is an unavoidable consequence of the
  13517. way floating-point numbers work.
  13518. Incrementing a date/time form adjusts it by a certain number of seconds.
  13519. Incrementing a pure date form adjusts it by a certain number of days.
  13520. @node Integer Truncation, Complex Number Functions, Basic Arithmetic, Arithmetic
  13521. @section Integer Truncation
  13522. @noindent
  13523. There are four commands for truncating a real number to an integer,
  13524. differing mainly in their treatment of negative numbers. All of these
  13525. commands have the property that if the argument is an integer, the result
  13526. is the same integer. An integer-valued floating-point argument is converted
  13527. to integer form.
  13528. If you press @kbd{H} (@code{calc-hyperbolic}) first, the result will be
  13529. expressed as an integer-valued floating-point number.
  13530. @cindex Integer part of a number
  13531. @kindex F
  13532. @pindex calc-floor
  13533. @tindex floor
  13534. @tindex ffloor
  13535. @ignore
  13536. @mindex @null
  13537. @end ignore
  13538. @kindex H F
  13539. The @kbd{F} (@code{calc-floor}) [@code{floor} or @code{ffloor}] command
  13540. truncates a real number to the next lower integer, i.e., toward minus
  13541. infinity. Thus @kbd{3.6 F} produces 3, but @kbd{_3.6 F} produces
  13542. @i{-4}.@refill
  13543. @kindex I F
  13544. @pindex calc-ceiling
  13545. @tindex ceil
  13546. @tindex fceil
  13547. @ignore
  13548. @mindex @null
  13549. @end ignore
  13550. @kindex H I F
  13551. The @kbd{I F} (@code{calc-ceiling}) [@code{ceil} or @code{fceil}]
  13552. command truncates toward positive infinity. Thus @kbd{3.6 I F} produces
  13553. 4, and @kbd{_3.6 I F} produces @i{-3}.@refill
  13554. @kindex R
  13555. @pindex calc-round
  13556. @tindex round
  13557. @tindex fround
  13558. @ignore
  13559. @mindex @null
  13560. @end ignore
  13561. @kindex H R
  13562. The @kbd{R} (@code{calc-round}) [@code{round} or @code{fround}] command
  13563. rounds to the nearest integer. When the fractional part is .5 exactly,
  13564. this command rounds away from zero. (All other rounding in the
  13565. Calculator uses this convention as well.) Thus @kbd{3.5 R} produces 4
  13566. but @kbd{3.4 R} produces 3; @kbd{_3.5 R} produces @i{-4}.@refill
  13567. @kindex I R
  13568. @pindex calc-trunc
  13569. @tindex trunc
  13570. @tindex ftrunc
  13571. @ignore
  13572. @mindex @null
  13573. @end ignore
  13574. @kindex H I R
  13575. The @kbd{I R} (@code{calc-trunc}) [@code{trunc} or @code{ftrunc}]
  13576. command truncates toward zero. In other words, it ``chops off''
  13577. everything after the decimal point. Thus @kbd{3.6 I R} produces 3 and
  13578. @kbd{_3.6 I R} produces @i{-3}.@refill
  13579. These functions may not be applied meaningfully to error forms, but they
  13580. do work for intervals. As a convenience, applying @code{floor} to a
  13581. modulo form floors the value part of the form. Applied to a vector,
  13582. these functions operate on all elements of the vector one by one.
  13583. Applied to a date form, they operate on the internal numerical
  13584. representation of dates, converting a date/time form into a pure date.
  13585. @ignore
  13586. @starindex
  13587. @end ignore
  13588. @tindex rounde
  13589. @ignore
  13590. @starindex
  13591. @end ignore
  13592. @tindex roundu
  13593. @ignore
  13594. @starindex
  13595. @end ignore
  13596. @tindex frounde
  13597. @ignore
  13598. @starindex
  13599. @end ignore
  13600. @tindex froundu
  13601. There are two more rounding functions which can only be entered in
  13602. algebraic notation. The @code{roundu} function is like @code{round}
  13603. except that it rounds up, toward plus infinity, when the fractional
  13604. part is .5. This distinction matters only for negative arguments.
  13605. Also, @code{rounde} rounds to an even number in the case of a tie,
  13606. rounding up or down as necessary. For example, @samp{rounde(3.5)} and
  13607. @samp{rounde(4.5)} both return 4, but @samp{rounde(5.5)} returns 6.
  13608. The advantage of round-to-even is that the net error due to rounding
  13609. after a long calculation tends to cancel out to zero. An important
  13610. subtle point here is that the number being fed to @code{rounde} will
  13611. already have been rounded to the current precision before @code{rounde}
  13612. begins. For example, @samp{rounde(2.500001)} with a current precision
  13613. of 6 will incorrectly, or at least surprisingly, yield 2 because the
  13614. argument will first have been rounded down to @cite{2.5} (which
  13615. @code{rounde} sees as an exact tie between 2 and 3).
  13616. Each of these functions, when written in algebraic formulas, allows
  13617. a second argument which specifies the number of digits after the
  13618. decimal point to keep. For example, @samp{round(123.4567, 2)} will
  13619. produce the answer 123.46, and @samp{round(123.4567, -1)} will
  13620. produce 120 (i.e., the cutoff is one digit to the @emph{left} of
  13621. the decimal point). A second argument of zero is equivalent to
  13622. no second argument at all.
  13623. @cindex Fractional part of a number
  13624. To compute the fractional part of a number (i.e., the amount which, when
  13625. added to `@t{floor(}@var{n}@t{)}', will produce @var{n}) just take @var{n}
  13626. modulo 1 using the @code{%} command.@refill
  13627. Note also the @kbd{\} (integer quotient), @kbd{f I} (integer logarithm),
  13628. and @kbd{f Q} (integer square root) commands, which are analogous to
  13629. @kbd{/}, @kbd{B}, and @kbd{Q}, respectively, except that they take integer
  13630. arguments and return the result rounded down to an integer.
  13631. @node Complex Number Functions, Conversions, Integer Truncation, Arithmetic
  13632. @section Complex Number Functions
  13633. @noindent
  13634. @kindex J
  13635. @pindex calc-conj
  13636. @tindex conj
  13637. The @kbd{J} (@code{calc-conj}) [@code{conj}] command computes the
  13638. complex conjugate of a number. For complex number @cite{a+bi}, the
  13639. complex conjugate is @cite{a-bi}. If the argument is a real number,
  13640. this command leaves it the same. If the argument is a vector or matrix,
  13641. this command replaces each element by its complex conjugate.
  13642. @kindex G
  13643. @pindex calc-argument
  13644. @tindex arg
  13645. The @kbd{G} (@code{calc-argument}) [@code{arg}] command computes the
  13646. ``argument'' or polar angle of a complex number. For a number in polar
  13647. notation, this is simply the second component of the pair
  13648. `@t{(}@var{r}@t{;}@c{$\theta$}
  13649. @var{theta}@t{)}'.
  13650. The result is expressed according to the current angular mode and will
  13651. be in the range @i{-180} degrees (exclusive) to @i{+180} degrees
  13652. (inclusive), or the equivalent range in radians.@refill
  13653. @pindex calc-imaginary
  13654. The @code{calc-imaginary} command multiplies the number on the
  13655. top of the stack by the imaginary number @cite{i = (0,1)}. This
  13656. command is not normally bound to a key in Calc, but it is available
  13657. on the @key{IMAG} button in Keypad Mode.
  13658. @kindex f r
  13659. @pindex calc-re
  13660. @tindex re
  13661. The @kbd{f r} (@code{calc-re}) [@code{re}] command replaces a complex number
  13662. by its real part. This command has no effect on real numbers. (As an
  13663. added convenience, @code{re} applied to a modulo form extracts
  13664. the value part.)@refill
  13665. @kindex f i
  13666. @pindex calc-im
  13667. @tindex im
  13668. The @kbd{f i} (@code{calc-im}) [@code{im}] command replaces a complex number
  13669. by its imaginary part; real numbers are converted to zero. With a vector
  13670. or matrix argument, these functions operate element-wise.@refill
  13671. @ignore
  13672. @mindex v p
  13673. @end ignore
  13674. @kindex v p (complex)
  13675. @pindex calc-pack
  13676. The @kbd{v p} (@code{calc-pack}) command can pack the top two numbers on
  13677. the stack into a composite object such as a complex number. With
  13678. a prefix argument of @i{-1}, it produces a rectangular complex number;
  13679. with an argument of @i{-2}, it produces a polar complex number.
  13680. (Also, @pxref{Building Vectors}.)
  13681. @ignore
  13682. @mindex v u
  13683. @end ignore
  13684. @kindex v u (complex)
  13685. @pindex calc-unpack
  13686. The @kbd{v u} (@code{calc-unpack}) command takes the complex number
  13687. (or other composite object) on the top of the stack and unpacks it
  13688. into its separate components.
  13689. @node Conversions, Date Arithmetic, Complex Number Functions, Arithmetic
  13690. @section Conversions
  13691. @noindent
  13692. The commands described in this section convert numbers from one form
  13693. to another; they are two-key sequences beginning with the letter @kbd{c}.
  13694. @kindex c f
  13695. @pindex calc-float
  13696. @tindex pfloat
  13697. The @kbd{c f} (@code{calc-float}) [@code{pfloat}] command converts the
  13698. number on the top of the stack to floating-point form. For example,
  13699. @cite{23} is converted to @cite{23.0}, @cite{3:2} is converted to
  13700. @cite{1.5}, and @cite{2.3} is left the same. If the value is a composite
  13701. object such as a complex number or vector, each of the components is
  13702. converted to floating-point. If the value is a formula, all numbers
  13703. in the formula are converted to floating-point. Note that depending
  13704. on the current floating-point precision, conversion to floating-point
  13705. format may lose information.@refill
  13706. As a special exception, integers which appear as powers or subscripts
  13707. are not floated by @kbd{c f}. If you really want to float a power,
  13708. you can use a @kbd{j s} command to select the power followed by @kbd{c f}.
  13709. Because @kbd{c f} cannot examine the formula outside of the selection,
  13710. it does not notice that the thing being floated is a power.
  13711. @xref{Selecting Subformulas}.
  13712. The normal @kbd{c f} command is ``pervasive'' in the sense that it
  13713. applies to all numbers throughout the formula. The @code{pfloat}
  13714. algebraic function never stays around in a formula; @samp{pfloat(a + 1)}
  13715. changes to @samp{a + 1.0} as soon as it is evaluated.
  13716. @kindex H c f
  13717. @tindex float
  13718. With the Hyperbolic flag, @kbd{H c f} [@code{float}] operates
  13719. only on the number or vector of numbers at the top level of its
  13720. argument. Thus, @samp{float(1)} is 1.0, but @samp{float(a + 1)}
  13721. is left unevaluated because its argument is not a number.
  13722. You should use @kbd{H c f} if you wish to guarantee that the final
  13723. value, once all the variables have been assigned, is a float; you
  13724. would use @kbd{c f} if you wish to do the conversion on the numbers
  13725. that appear right now.
  13726. @kindex c F
  13727. @pindex calc-fraction
  13728. @tindex pfrac
  13729. The @kbd{c F} (@code{calc-fraction}) [@code{pfrac}] command converts a
  13730. floating-point number into a fractional approximation. By default, it
  13731. produces a fraction whose decimal representation is the same as the
  13732. input number, to within the current precision. You can also give a
  13733. numeric prefix argument to specify a tolerance, either directly, or,
  13734. if the prefix argument is zero, by using the number on top of the stack
  13735. as the tolerance. If the tolerance is a positive integer, the fraction
  13736. is correct to within that many significant figures. If the tolerance is
  13737. a non-positive integer, it specifies how many digits fewer than the current
  13738. precision to use. If the tolerance is a floating-point number, the
  13739. fraction is correct to within that absolute amount.
  13740. @kindex H c F
  13741. @tindex frac
  13742. The @code{pfrac} function is pervasive, like @code{pfloat}.
  13743. There is also a non-pervasive version, @kbd{H c F} [@code{frac}],
  13744. which is analogous to @kbd{H c f} discussed above.
  13745. @kindex c d
  13746. @pindex calc-to-degrees
  13747. @tindex deg
  13748. The @kbd{c d} (@code{calc-to-degrees}) [@code{deg}] command converts a
  13749. number into degrees form. The value on the top of the stack may be an
  13750. HMS form (interpreted as degrees-minutes-seconds), or a real number which
  13751. will be interpreted in radians regardless of the current angular mode.@refill
  13752. @kindex c r
  13753. @pindex calc-to-radians
  13754. @tindex rad
  13755. The @kbd{c r} (@code{calc-to-radians}) [@code{rad}] command converts an
  13756. HMS form or angle in degrees into an angle in radians.
  13757. @kindex c h
  13758. @pindex calc-to-hms
  13759. @tindex hms
  13760. The @kbd{c h} (@code{calc-to-hms}) [@code{hms}] command converts a real
  13761. number, interpreted according to the current angular mode, to an HMS
  13762. form describing the same angle. In algebraic notation, the @code{hms}
  13763. function also accepts three arguments: @samp{hms(@var{h}, @var{m}, @var{s})}.
  13764. (The three-argument version is independent of the current angular mode.)
  13765. @pindex calc-from-hms
  13766. The @code{calc-from-hms} command converts the HMS form on the top of the
  13767. stack into a real number according to the current angular mode.
  13768. @kindex c p
  13769. @kindex I c p
  13770. @pindex calc-polar
  13771. @tindex polar
  13772. @tindex rect
  13773. The @kbd{c p} (@code{calc-polar}) command converts the complex number on
  13774. the top of the stack from polar to rectangular form, or from rectangular
  13775. to polar form, whichever is appropriate. Real numbers are left the same.
  13776. This command is equivalent to the @code{rect} or @code{polar}
  13777. functions in algebraic formulas, depending on the direction of
  13778. conversion. (It uses @code{polar}, except that if the argument is
  13779. already a polar complex number, it uses @code{rect} instead. The
  13780. @kbd{I c p} command always uses @code{rect}.)@refill
  13781. @kindex c c
  13782. @pindex calc-clean
  13783. @tindex pclean
  13784. The @kbd{c c} (@code{calc-clean}) [@code{pclean}] command ``cleans'' the
  13785. number on the top of the stack. Floating point numbers are re-rounded
  13786. according to the current precision. Polar numbers whose angular
  13787. components have strayed from the @i{-180} to @i{+180} degree range
  13788. are normalized. (Note that results will be undesirable if the current
  13789. angular mode is different from the one under which the number was
  13790. produced!) Integers and fractions are generally unaffected by this
  13791. operation. Vectors and formulas are cleaned by cleaning each component
  13792. number (i.e., pervasively).@refill
  13793. If the simplification mode is set below the default level, it is raised
  13794. to the default level for the purposes of this command. Thus, @kbd{c c}
  13795. applies the default simplifications even if their automatic application
  13796. is disabled. @xref{Simplification Modes}.
  13797. @cindex Roundoff errors, correcting
  13798. A numeric prefix argument to @kbd{c c} sets the floating-point precision
  13799. to that value for the duration of the command. A positive prefix (of at
  13800. least 3) sets the precision to the specified value; a negative or zero
  13801. prefix decreases the precision by the specified amount.
  13802. @kindex c 0-9
  13803. @pindex calc-clean-num
  13804. The keystroke sequences @kbd{c 0} through @kbd{c 9} are equivalent
  13805. to @kbd{c c} with the corresponding negative prefix argument. If roundoff
  13806. errors have changed 2.0 into 1.999999, typing @kbd{c 1} to clip off one
  13807. decimal place often conveniently does the trick.
  13808. The @kbd{c c} command with a numeric prefix argument, and the @kbd{c 0}
  13809. through @kbd{c 9} commands, also ``clip'' very small floating-point
  13810. numbers to zero. If the exponent is less than or equal to the negative
  13811. of the specified precision, the number is changed to 0.0. For example,
  13812. if the current precision is 12, then @kbd{c 2} changes the vector
  13813. @samp{[1e-8, 1e-9, 1e-10, 1e-11]} to @samp{[1e-8, 1e-9, 0, 0]}.
  13814. Numbers this small generally arise from roundoff noise.
  13815. If the numbers you are using really are legitimately this small,
  13816. you should avoid using the @kbd{c 0} through @kbd{c 9} commands.
  13817. (The plain @kbd{c c} command rounds to the current precision but
  13818. does not clip small numbers.)
  13819. One more property of @kbd{c 0} through @kbd{c 9}, and of @kbd{c c} with
  13820. a prefix argument, is that integer-valued floats are converted to
  13821. plain integers, so that @kbd{c 1} on @samp{[1., 1.5, 2., 2.5, 3.]}
  13822. produces @samp{[1, 1.5, 2, 2.5, 3]}. This is not done for huge
  13823. numbers (@samp{1e100} is technically an integer-valued float, but
  13824. you wouldn't want it automatically converted to a 100-digit integer).
  13825. @kindex H c 0-9
  13826. @kindex H c c
  13827. @tindex clean
  13828. With the Hyperbolic flag, @kbd{H c c} and @kbd{H c 0} through @kbd{H c 9}
  13829. operate non-pervasively [@code{clean}].
  13830. @node Date Arithmetic, Financial Functions, Conversions, Arithmetic
  13831. @section Date Arithmetic
  13832. @noindent
  13833. @cindex Date arithmetic, additional functions
  13834. The commands described in this section perform various conversions
  13835. and calculations involving date forms (@pxref{Date Forms}). They
  13836. use the @kbd{t} (for time/date) prefix key followed by shifted
  13837. letters.
  13838. The simplest date arithmetic is done using the regular @kbd{+} and @kbd{-}
  13839. commands. In particular, adding a number to a date form advances the
  13840. date form by a certain number of days; adding an HMS form to a date
  13841. form advances the date by a certain amount of time; and subtracting two
  13842. date forms produces a difference measured in days. The commands
  13843. described here provide additional, more specialized operations on dates.
  13844. Many of these commands accept a numeric prefix argument; if you give
  13845. plain @kbd{C-u} as the prefix, these commands will instead take the
  13846. additional argument from the top of the stack.
  13847. @menu
  13848. * Date Conversions::
  13849. * Date Functions::
  13850. * Time Zones::
  13851. * Business Days::
  13852. @end menu
  13853. @node Date Conversions, Date Functions, Date Arithmetic, Date Arithmetic
  13854. @subsection Date Conversions
  13855. @noindent
  13856. @kindex t D
  13857. @pindex calc-date
  13858. @tindex date
  13859. The @kbd{t D} (@code{calc-date}) [@code{date}] command converts a
  13860. date form into a number, measured in days since Jan 1, 1 AD. The
  13861. result will be an integer if @var{date} is a pure date form, or a
  13862. fraction or float if @var{date} is a date/time form. Or, if its
  13863. argument is a number, it converts this number into a date form.
  13864. With a numeric prefix argument, @kbd{t D} takes that many objects
  13865. (up to six) from the top of the stack and interprets them in one
  13866. of the following ways:
  13867. The @samp{date(@var{year}, @var{month}, @var{day})} function
  13868. builds a pure date form out of the specified year, month, and
  13869. day, which must all be integers. @var{Year} is a year number,
  13870. such as 1991 (@emph{not} the same as 91!). @var{Month} must be
  13871. an integer in the range 1 to 12; @var{day} must be in the range
  13872. 1 to 31. If the specified month has fewer than 31 days and
  13873. @var{day} is too large, the equivalent day in the following
  13874. month will be used.
  13875. The @samp{date(@var{month}, @var{day})} function builds a
  13876. pure date form using the current year, as determined by the
  13877. real-time clock.
  13878. The @samp{date(@var{year}, @var{month}, @var{day}, @var{hms})}
  13879. function builds a date/time form using an @var{hms} form.
  13880. The @samp{date(@var{year}, @var{month}, @var{day}, @var{hour},
  13881. @var{minute}, @var{second})} function builds a date/time form.
  13882. @var{hour} should be an integer in the range 0 to 23;
  13883. @var{minute} should be an integer in the range 0 to 59;
  13884. @var{second} should be any real number in the range @samp{[0 .. 60)}.
  13885. The last two arguments default to zero if omitted.
  13886. @kindex t J
  13887. @pindex calc-julian
  13888. @tindex julian
  13889. @cindex Julian day counts, conversions
  13890. The @kbd{t J} (@code{calc-julian}) [@code{julian}] command converts
  13891. a date form into a Julian day count, which is the number of days
  13892. since noon on Jan 1, 4713 BC. A pure date is converted to an integer
  13893. Julian count representing noon of that day. A date/time form is
  13894. converted to an exact floating-point Julian count, adjusted to
  13895. interpret the date form in the current time zone but the Julian
  13896. day count in Greenwich Mean Time. A numeric prefix argument allows
  13897. you to specify the time zone; @pxref{Time Zones}. Use a prefix of
  13898. zero to suppress the time zone adjustment. Note that pure date forms
  13899. are never time-zone adjusted.
  13900. This command can also do the opposite conversion, from a Julian day
  13901. count (either an integer day, or a floating-point day and time in
  13902. the GMT zone), into a pure date form or a date/time form in the
  13903. current or specified time zone.
  13904. @kindex t U
  13905. @pindex calc-unix-time
  13906. @tindex unixtime
  13907. @cindex Unix time format, conversions
  13908. The @kbd{t U} (@code{calc-unix-time}) [@code{unixtime}] command
  13909. converts a date form into a Unix time value, which is the number of
  13910. seconds since midnight on Jan 1, 1970, or vice-versa. The numeric result
  13911. will be an integer if the current precision is 12 or less; for higher
  13912. precisions, the result may be a float with (@var{precision}@minus{}12)
  13913. digits after the decimal. Just as for @kbd{t J}, the numeric time
  13914. is interpreted in the GMT time zone and the date form is interpreted
  13915. in the current or specified zone. Some systems use Unix-like
  13916. numbering but with the local time zone; give a prefix of zero to
  13917. suppress the adjustment if so.
  13918. @kindex t C
  13919. @pindex calc-convert-time-zones
  13920. @tindex tzconv
  13921. @cindex Time Zones, converting between
  13922. The @kbd{t C} (@code{calc-convert-time-zones}) [@code{tzconv}]
  13923. command converts a date form from one time zone to another. You
  13924. are prompted for each time zone name in turn; you can answer with
  13925. any suitable Calc time zone expression (@pxref{Time Zones}).
  13926. If you answer either prompt with a blank line, the local time
  13927. zone is used for that prompt. You can also answer the first
  13928. prompt with @kbd{$} to take the two time zone names from the
  13929. stack (and the date to be converted from the third stack level).
  13930. @node Date Functions, Business Days, Date Conversions, Date Arithmetic
  13931. @subsection Date Functions
  13932. @noindent
  13933. @kindex t N
  13934. @pindex calc-now
  13935. @tindex now
  13936. The @kbd{t N} (@code{calc-now}) [@code{now}] command pushes the
  13937. current date and time on the stack as a date form. The time is
  13938. reported in terms of the specified time zone; with no numeric prefix
  13939. argument, @kbd{t N} reports for the current time zone.
  13940. @kindex t P
  13941. @pindex calc-date-part
  13942. The @kbd{t P} (@code{calc-date-part}) command extracts one part
  13943. of a date form. The prefix argument specifies the part; with no
  13944. argument, this command prompts for a part code from 1 to 9.
  13945. The various part codes are described in the following paragraphs.
  13946. @tindex year
  13947. The @kbd{M-1 t P} [@code{year}] function extracts the year number
  13948. from a date form as an integer, e.g., 1991. This and the
  13949. following functions will also accept a real number for an
  13950. argument, which is interpreted as a standard Calc day number.
  13951. Note that this function will never return zero, since the year
  13952. 1 BC immediately precedes the year 1 AD.
  13953. @tindex month
  13954. The @kbd{M-2 t P} [@code{month}] function extracts the month number
  13955. from a date form as an integer in the range 1 to 12.
  13956. @tindex day
  13957. The @kbd{M-3 t P} [@code{day}] function extracts the day number
  13958. from a date form as an integer in the range 1 to 31.
  13959. @tindex hour
  13960. The @kbd{M-4 t P} [@code{hour}] function extracts the hour from
  13961. a date form as an integer in the range 0 (midnight) to 23. Note
  13962. that 24-hour time is always used. This returns zero for a pure
  13963. date form. This function (and the following two) also accept
  13964. HMS forms as input.
  13965. @tindex minute
  13966. The @kbd{M-5 t P} [@code{minute}] function extracts the minute
  13967. from a date form as an integer in the range 0 to 59.
  13968. @tindex second
  13969. The @kbd{M-6 t P} [@code{second}] function extracts the second
  13970. from a date form. If the current precision is 12 or less,
  13971. the result is an integer in the range 0 to 59. For higher
  13972. precisions, the result may instead be a floating-point number.
  13973. @tindex weekday
  13974. The @kbd{M-7 t P} [@code{weekday}] function extracts the weekday
  13975. number from a date form as an integer in the range 0 (Sunday)
  13976. to 6 (Saturday).
  13977. @tindex yearday
  13978. The @kbd{M-8 t P} [@code{yearday}] function extracts the day-of-year
  13979. number from a date form as an integer in the range 1 (January 1)
  13980. to 366 (December 31 of a leap year).
  13981. @tindex time
  13982. The @kbd{M-9 t P} [@code{time}] function extracts the time portion
  13983. of a date form as an HMS form. This returns @samp{0@@ 0' 0"}
  13984. for a pure date form.
  13985. @kindex t M
  13986. @pindex calc-new-month
  13987. @tindex newmonth
  13988. The @kbd{t M} (@code{calc-new-month}) [@code{newmonth}] command
  13989. computes a new date form that represents the first day of the month
  13990. specified by the input date. The result is always a pure date
  13991. form; only the year and month numbers of the input are retained.
  13992. With a numeric prefix argument @var{n} in the range from 1 to 31,
  13993. @kbd{t M} computes the @var{n}th day of the month. (If @var{n}
  13994. is greater than the actual number of days in the month, or if
  13995. @var{n} is zero, the last day of the month is used.)
  13996. @kindex t Y
  13997. @pindex calc-new-year
  13998. @tindex newyear
  13999. The @kbd{t Y} (@code{calc-new-year}) [@code{newyear}] command
  14000. computes a new pure date form that represents the first day of
  14001. the year specified by the input. The month, day, and time
  14002. of the input date form are lost. With a numeric prefix argument
  14003. @var{n} in the range from 1 to 366, @kbd{t Y} computes the
  14004. @var{n}th day of the year (366 is treated as 365 in non-leap
  14005. years). A prefix argument of 0 computes the last day of the
  14006. year (December 31). A negative prefix argument from @i{-1} to
  14007. @i{-12} computes the first day of the @var{n}th month of the year.
  14008. @kindex t W
  14009. @pindex calc-new-week
  14010. @tindex newweek
  14011. The @kbd{t W} (@code{calc-new-week}) [@code{newweek}] command
  14012. computes a new pure date form that represents the Sunday on or before
  14013. the input date. With a numeric prefix argument, it can be made to
  14014. use any day of the week as the starting day; the argument must be in
  14015. the range from 0 (Sunday) to 6 (Saturday). This function always
  14016. subtracts between 0 and 6 days from the input date.
  14017. Here's an example use of @code{newweek}: Find the date of the next
  14018. Wednesday after a given date. Using @kbd{M-3 t W} or @samp{newweek(d, 3)}
  14019. will give you the @emph{preceding} Wednesday, so @samp{newweek(d+7, 3)}
  14020. will give you the following Wednesday. A further look at the definition
  14021. of @code{newweek} shows that if the input date is itself a Wednesday,
  14022. this formula will return the Wednesday one week in the future. An
  14023. exercise for the reader is to modify this formula to yield the same day
  14024. if the input is already a Wednesday. Another interesting exercise is
  14025. to preserve the time-of-day portion of the input (@code{newweek} resets
  14026. the time to midnight; hint:@: how can @code{newweek} be defined in terms
  14027. of the @code{weekday} function?).
  14028. @ignore
  14029. @starindex
  14030. @end ignore
  14031. @tindex pwday
  14032. The @samp{pwday(@var{date})} function (not on any key) computes the
  14033. day-of-month number of the Sunday on or before @var{date}. With
  14034. two arguments, @samp{pwday(@var{date}, @var{day})} computes the day
  14035. number of the Sunday on or before day number @var{day} of the month
  14036. specified by @var{date}. The @var{day} must be in the range from
  14037. 7 to 31; if the day number is greater than the actual number of days
  14038. in the month, the true number of days is used instead. Thus
  14039. @samp{pwday(@var{date}, 7)} finds the first Sunday of the month, and
  14040. @samp{pwday(@var{date}, 31)} finds the last Sunday of the month.
  14041. With a third @var{weekday} argument, @code{pwday} can be made to look
  14042. for any day of the week instead of Sunday.
  14043. @kindex t I
  14044. @pindex calc-inc-month
  14045. @tindex incmonth
  14046. The @kbd{t I} (@code{calc-inc-month}) [@code{incmonth}] command
  14047. increases a date form by one month, or by an arbitrary number of
  14048. months specified by a numeric prefix argument. The time portion,
  14049. if any, of the date form stays the same. The day also stays the
  14050. same, except that if the new month has fewer days the day
  14051. number may be reduced to lie in the valid range. For example,
  14052. @samp{incmonth(<Jan 31, 1991>)} produces @samp{<Feb 28, 1991>}.
  14053. Because of this, @kbd{t I t I} and @kbd{M-2 t I} do not always give
  14054. the same results (@samp{<Mar 28, 1991>} versus @samp{<Mar 31, 1991>}
  14055. in this case).
  14056. @ignore
  14057. @starindex
  14058. @end ignore
  14059. @tindex incyear
  14060. The @samp{incyear(@var{date}, @var{step})} function increases
  14061. a date form by the specified number of years, which may be
  14062. any positive or negative integer. Note that @samp{incyear(d, n)}
  14063. is equivalent to @w{@samp{incmonth(d, 12*n)}}, but these do not have
  14064. simple equivalents in terms of day arithmetic because
  14065. months and years have varying lengths. If the @var{step}
  14066. argument is omitted, 1 year is assumed. There is no keyboard
  14067. command for this function; use @kbd{C-u 12 t I} instead.
  14068. There is no @code{newday} function at all because @kbd{F} [@code{floor}]
  14069. serves this purpose. Similarly, instead of @code{incday} and
  14070. @code{incweek} simply use @cite{d + n} or @cite{d + 7 n}.
  14071. @xref{Basic Arithmetic}, for the @kbd{f ]} [@code{incr}] command
  14072. which can adjust a date/time form by a certain number of seconds.
  14073. @node Business Days, Time Zones, Date Functions, Date Arithmetic
  14074. @subsection Business Days
  14075. @noindent
  14076. Often time is measured in ``business days'' or ``working days,''
  14077. where weekends and holidays are skipped. Calc's normal date
  14078. arithmetic functions use calendar days, so that subtracting two
  14079. consecutive Mondays will yield a difference of 7 days. By contrast,
  14080. subtracting two consecutive Mondays would yield 5 business days
  14081. (assuming two-day weekends and the absence of holidays).
  14082. @kindex t +
  14083. @kindex t -
  14084. @tindex badd
  14085. @tindex bsub
  14086. @pindex calc-business-days-plus
  14087. @pindex calc-business-days-minus
  14088. The @kbd{t +} (@code{calc-business-days-plus}) [@code{badd}]
  14089. and @kbd{t -} (@code{calc-business-days-minus}) [@code{bsub}]
  14090. commands perform arithmetic using business days. For @kbd{t +},
  14091. one argument must be a date form and the other must be a real
  14092. number (positive or negative). If the number is not an integer,
  14093. then a certain amount of time is added as well as a number of
  14094. days; for example, adding 0.5 business days to a time in Friday
  14095. evening will produce a time in Monday morning. It is also
  14096. possible to add an HMS form; adding @samp{12@@ 0' 0"} also adds
  14097. half a business day. For @kbd{t -}, the arguments are either a
  14098. date form and a number or HMS form, or two date forms, in which
  14099. case the result is the number of business days between the two
  14100. dates.
  14101. @cindex @code{Holidays} variable
  14102. @vindex Holidays
  14103. By default, Calc considers any day that is not a Saturday or
  14104. Sunday to be a business day. You can define any number of
  14105. additional holidays by editing the variable @code{Holidays}.
  14106. (There is an @w{@kbd{s H}} convenience command for editing this
  14107. variable.) Initially, @code{Holidays} contains the vector
  14108. @samp{[sat, sun]}. Entries in the @code{Holidays} vector may
  14109. be any of the following kinds of objects:
  14110. @itemize @bullet
  14111. @item
  14112. Date forms (pure dates, not date/time forms). These specify
  14113. particular days which are to be treated as holidays.
  14114. @item
  14115. Intervals of date forms. These specify a range of days, all of
  14116. which are holidays (e.g., Christmas week). @xref{Interval Forms}.
  14117. @item
  14118. Nested vectors of date forms. Each date form in the vector is
  14119. considered to be a holiday.
  14120. @item
  14121. Any Calc formula which evaluates to one of the above three things.
  14122. If the formula involves the variable @cite{y}, it stands for a
  14123. yearly repeating holiday; @cite{y} will take on various year
  14124. numbers like 1992. For example, @samp{date(y, 12, 25)} specifies
  14125. Christmas day, and @samp{newweek(date(y, 11, 7), 4) + 21} specifies
  14126. Thanksgiving (which is held on the fourth Thursday of November).
  14127. If the formula involves the variable @cite{m}, that variable
  14128. takes on month numbers from 1 to 12: @samp{date(y, m, 15)} is
  14129. a holiday that takes place on the 15th of every month.
  14130. @item
  14131. A weekday name, such as @code{sat} or @code{sun}. This is really
  14132. a variable whose name is a three-letter, lower-case day name.
  14133. @item
  14134. An interval of year numbers (integers). This specifies the span of
  14135. years over which this holiday list is to be considered valid. Any
  14136. business-day arithmetic that goes outside this range will result
  14137. in an error message. Use this if you are including an explicit
  14138. list of holidays, rather than a formula to generate them, and you
  14139. want to make sure you don't accidentally go beyond the last point
  14140. where the holidays you entered are complete. If there is no
  14141. limiting interval in the @code{Holidays} vector, the default
  14142. @samp{[1 .. 2737]} is used. (This is the absolute range of years
  14143. for which Calc's business-day algorithms will operate.)
  14144. @item
  14145. An interval of HMS forms. This specifies the span of hours that
  14146. are to be considered one business day. For example, if this
  14147. range is @samp{[9@@ 0' 0" .. 17@@ 0' 0"]} (i.e., 9am to 5pm), then
  14148. the business day is only eight hours long, so that @kbd{1.5 t +}
  14149. on @samp{<4:00pm Fri Dec 13, 1991>} will add one business day and
  14150. four business hours to produce @samp{<12:00pm Tue Dec 17, 1991>}.
  14151. Likewise, @kbd{t -} will now express differences in time as
  14152. fractions of an eight-hour day. Times before 9am will be treated
  14153. as 9am by business date arithmetic, and times at or after 5pm will
  14154. be treated as 4:59:59pm. If there is no HMS interval in @code{Holidays},
  14155. the full 24-hour day @samp{[0@ 0' 0" .. 24@ 0' 0"]} is assumed.
  14156. (Regardless of the type of bounds you specify, the interval is
  14157. treated as inclusive on the low end and exclusive on the high end,
  14158. so that the work day goes from 9am up to, but not including, 5pm.)
  14159. @end itemize
  14160. If the @code{Holidays} vector is empty, then @kbd{t +} and
  14161. @kbd{t -} will act just like @kbd{+} and @kbd{-} because there will
  14162. then be no difference between business days and calendar days.
  14163. Calc expands the intervals and formulas you give into a complete
  14164. list of holidays for internal use. This is done mainly to make
  14165. sure it can detect multiple holidays. (For example,
  14166. @samp{<Jan 1, 1989>} is both New Year's Day and a Sunday, but
  14167. Calc's algorithms take care to count it only once when figuring
  14168. the number of holidays between two dates.)
  14169. Since the complete list of holidays for all the years from 1 to
  14170. 2737 would be huge, Calc actually computes only the part of the
  14171. list between the smallest and largest years that have been involved
  14172. in business-day calculations so far. Normally, you won't have to
  14173. worry about this. Keep in mind, however, that if you do one
  14174. calculation for 1992, and another for 1792, even if both involve
  14175. only a small range of years, Calc will still work out all the
  14176. holidays that fall in that 200-year span.
  14177. If you add a (positive) number of days to a date form that falls on a
  14178. weekend or holiday, the date form is treated as if it were the most
  14179. recent business day. (Thus adding one business day to a Friday,
  14180. Saturday, or Sunday will all yield the following Monday.) If you
  14181. subtract a number of days from a weekend or holiday, the date is
  14182. effectively on the following business day. (So subtracting one business
  14183. day from Saturday, Sunday, or Monday yields the preceding Friday.) The
  14184. difference between two dates one or both of which fall on holidays
  14185. equals the number of actual business days between them. These
  14186. conventions are consistent in the sense that, if you add @var{n}
  14187. business days to any date, the difference between the result and the
  14188. original date will come out to @var{n} business days. (It can't be
  14189. completely consistent though; a subtraction followed by an addition
  14190. might come out a bit differently, since @kbd{t +} is incapable of
  14191. producing a date that falls on a weekend or holiday.)
  14192. @ignore
  14193. @starindex
  14194. @end ignore
  14195. @tindex holiday
  14196. There is a @code{holiday} function, not on any keys, that takes
  14197. any date form and returns 1 if that date falls on a weekend or
  14198. holiday, as defined in @code{Holidays}, or 0 if the date is a
  14199. business day.
  14200. @node Time Zones, , Business Days, Date Arithmetic
  14201. @subsection Time Zones
  14202. @noindent
  14203. @cindex Time zones
  14204. @cindex Daylight savings time
  14205. Time zones and daylight savings time are a complicated business.
  14206. The conversions to and from Julian and Unix-style dates automatically
  14207. compute the correct time zone and daylight savings adjustment to use,
  14208. provided they can figure out this information. This section describes
  14209. Calc's time zone adjustment algorithm in detail, in case you want to
  14210. do conversions in different time zones or in case Calc's algorithms
  14211. can't determine the right correction to use.
  14212. Adjustments for time zones and daylight savings time are done by
  14213. @kbd{t U}, @kbd{t J}, @kbd{t N}, and @kbd{t C}, but not by any other
  14214. commands. In particular, @samp{<may 1 1991> - <apr 1 1991>} evaluates
  14215. to exactly 30 days even though there is a daylight-savings
  14216. transition in between. This is also true for Julian pure dates:
  14217. @samp{julian(<may 1 1991>) - julian(<apr 1 1991>)}. But Julian
  14218. and Unix date/times will adjust for daylight savings time:
  14219. @samp{julian(<12am may 1 1991>) - julian(<12am apr 1 1991>)}
  14220. evaluates to @samp{29.95834} (that's 29 days and 23 hours)
  14221. because one hour was lost when daylight savings commenced on
  14222. April 7, 1991.
  14223. In brief, the idiom @samp{julian(@var{date1}) - julian(@var{date2})}
  14224. computes the actual number of 24-hour periods between two dates, whereas
  14225. @samp{@var{date1} - @var{date2}} computes the number of calendar
  14226. days between two dates without taking daylight savings into account.
  14227. @pindex calc-time-zone
  14228. @ignore
  14229. @starindex
  14230. @end ignore
  14231. @tindex tzone
  14232. The @code{calc-time-zone} [@code{tzone}] command converts the time
  14233. zone specified by its numeric prefix argument into a number of
  14234. seconds difference from Greenwich mean time (GMT). If the argument
  14235. is a number, the result is simply that value multiplied by 3600.
  14236. Typical arguments for North America are 5 (Eastern) or 8 (Pacific). If
  14237. Daylight Savings time is in effect, one hour should be subtracted from
  14238. the normal difference.
  14239. If you give a prefix of plain @kbd{C-u}, @code{calc-time-zone} (like other
  14240. date arithmetic commands that include a time zone argument) takes the
  14241. zone argument from the top of the stack. (In the case of @kbd{t J}
  14242. and @kbd{t U}, the normal argument is then taken from the second-to-top
  14243. stack position.) This allows you to give a non-integer time zone
  14244. adjustment. The time-zone argument can also be an HMS form, or
  14245. it can be a variable which is a time zone name in upper- or lower-case.
  14246. For example @samp{tzone(PST) = tzone(8)} and @samp{tzone(pdt) = tzone(7)}
  14247. (for Pacific standard and daylight savings times, respectively).
  14248. North American and European time zone names are defined as follows;
  14249. note that for each time zone there is one name for standard time,
  14250. another for daylight savings time, and a third for ``generalized'' time
  14251. in which the daylight savings adjustment is computed from context.
  14252. @smallexample
  14253. @group
  14254. YST PST MST CST EST AST NST GMT WET MET MEZ
  14255. 9 8 7 6 5 4 3.5 0 -1 -2 -2
  14256. YDT PDT MDT CDT EDT ADT NDT BST WETDST METDST MESZ
  14257. 8 7 6 5 4 3 2.5 -1 -2 -3 -3
  14258. YGT PGT MGT CGT EGT AGT NGT BGT WEGT MEGT MEGZ
  14259. 9/8 8/7 7/6 6/5 5/4 4/3 3.5/2.5 0/-1 -1/-2 -2/-3 -2/-3
  14260. @end group
  14261. @end smallexample
  14262. @vindex math-tzone-names
  14263. To define time zone names that do not appear in the above table,
  14264. you must modify the Lisp variable @code{math-tzone-names}. This
  14265. is a list of lists describing the different time zone names; its
  14266. structure is best explained by an example. The three entries for
  14267. Pacific Time look like this:
  14268. @smallexample
  14269. @group
  14270. ( ( "PST" 8 0 ) ; Name as an upper-case string, then standard
  14271. ( "PDT" 8 -1 ) ; adjustment, then daylight savings adjustment.
  14272. ( "PGT" 8 "PST" "PDT" ) ) ; Generalized time zone.
  14273. @end group
  14274. @end smallexample
  14275. @cindex @code{TimeZone} variable
  14276. @vindex TimeZone
  14277. With no arguments, @code{calc-time-zone} or @samp{tzone()} obtains an
  14278. argument from the Calc variable @code{TimeZone} if a value has been
  14279. stored for that variable. If not, Calc runs the Unix @samp{date}
  14280. command and looks for one of the above time zone names in the output;
  14281. if this does not succeed, @samp{tzone()} leaves itself unevaluated.
  14282. The time zone name in the @samp{date} output may be followed by a signed
  14283. adjustment, e.g., @samp{GMT+5} or @samp{GMT+0500} which specifies a
  14284. number of hours and minutes to be added to the base time zone.
  14285. Calc stores the time zone it finds into @code{TimeZone} to speed
  14286. later calls to @samp{tzone()}.
  14287. The special time zone name @code{local} is equivalent to no argument,
  14288. i.e., it uses the local time zone as obtained from the @code{date}
  14289. command.
  14290. If the time zone name found is one of the standard or daylight
  14291. savings zone names from the above table, and Calc's internal
  14292. daylight savings algorithm says that time and zone are consistent
  14293. (e.g., @code{PDT} accompanies a date that Calc's algorithm would also
  14294. consider to be daylight savings, or @code{PST} accompanies a date
  14295. that Calc would consider to be standard time), then Calc substitutes
  14296. the corresponding generalized time zone (like @code{PGT}).
  14297. If your system does not have a suitable @samp{date} command, you
  14298. may wish to put a @samp{(setq var-TimeZone ...)} in your Emacs
  14299. initialization file to set the time zone. The easiest way to do
  14300. this is to edit the @code{TimeZone} variable using Calc's @kbd{s T}
  14301. command, then use the @kbd{s p} (@code{calc-permanent-variable})
  14302. command to save the value of @code{TimeZone} permanently.
  14303. The @kbd{t J} and @code{t U} commands with no numeric prefix
  14304. arguments do the same thing as @samp{tzone()}. If the current
  14305. time zone is a generalized time zone, e.g., @code{EGT}, Calc
  14306. examines the date being converted to tell whether to use standard
  14307. or daylight savings time. But if the current time zone is explicit,
  14308. e.g., @code{EST} or @code{EDT}, then that adjustment is used exactly
  14309. and Calc's daylight savings algorithm is not consulted.
  14310. Some places don't follow the usual rules for daylight savings time.
  14311. The state of Arizona, for example, does not observe daylight savings
  14312. time. If you run Calc during the winter season in Arizona, the
  14313. Unix @code{date} command will report @code{MST} time zone, which
  14314. Calc will change to @code{MGT}. If you then convert a time that
  14315. lies in the summer months, Calc will apply an incorrect daylight
  14316. savings time adjustment. To avoid this, set your @code{TimeZone}
  14317. variable explicitly to @code{MST} to force the use of standard,
  14318. non-daylight-savings time.
  14319. @vindex math-daylight-savings-hook
  14320. @findex math-std-daylight-savings
  14321. By default Calc always considers daylight savings time to begin at
  14322. 2 a.m.@: on the first Sunday of April, and to end at 2 a.m.@: on the
  14323. last Sunday of October. This is the rule that has been in effect
  14324. in North America since 1987. If you are in a country that uses
  14325. different rules for computing daylight savings time, you have two
  14326. choices: Write your own daylight savings hook, or control time
  14327. zones explicitly by setting the @code{TimeZone} variable and/or
  14328. always giving a time-zone argument for the conversion functions.
  14329. The Lisp variable @code{math-daylight-savings-hook} holds the
  14330. name of a function that is used to compute the daylight savings
  14331. adjustment for a given date. The default is
  14332. @code{math-std-daylight-savings}, which computes an adjustment
  14333. (either 0 or @i{-1}) using the North American rules given above.
  14334. The daylight savings hook function is called with four arguments:
  14335. The date, as a floating-point number in standard Calc format;
  14336. a six-element list of the date decomposed into year, month, day,
  14337. hour, minute, and second, respectively; a string which contains
  14338. the generalized time zone name in upper-case, e.g., @code{"WEGT"};
  14339. and a special adjustment to be applied to the hour value when
  14340. converting into a generalized time zone (see below).
  14341. @findex math-prev-weekday-in-month
  14342. The Lisp function @code{math-prev-weekday-in-month} is useful for
  14343. daylight savings computations. This is an internal version of
  14344. the user-level @code{pwday} function described in the previous
  14345. section. It takes four arguments: The floating-point date value,
  14346. the corresponding six-element date list, the day-of-month number,
  14347. and the weekday number (0-6).
  14348. The default daylight savings hook ignores the time zone name, but a
  14349. more sophisticated hook could use different algorithms for different
  14350. time zones. It would also be possible to use different algorithms
  14351. depending on the year number, but the default hook always uses the
  14352. algorithm for 1987 and later. Here is a listing of the default
  14353. daylight savings hook:
  14354. @smallexample
  14355. (defun math-std-daylight-savings (date dt zone bump)
  14356. (cond ((< (nth 1 dt) 4) 0)
  14357. ((= (nth 1 dt) 4)
  14358. (let ((sunday (math-prev-weekday-in-month date dt 7 0)))
  14359. (cond ((< (nth 2 dt) sunday) 0)
  14360. ((= (nth 2 dt) sunday)
  14361. (if (>= (nth 3 dt) (+ 3 bump)) -1 0))
  14362. (t -1))))
  14363. ((< (nth 1 dt) 10) -1)
  14364. ((= (nth 1 dt) 10)
  14365. (let ((sunday (math-prev-weekday-in-month date dt 31 0)))
  14366. (cond ((< (nth 2 dt) sunday) -1)
  14367. ((= (nth 2 dt) sunday)
  14368. (if (>= (nth 3 dt) (+ 2 bump)) 0 -1))
  14369. (t 0))))
  14370. (t 0))
  14371. )
  14372. @end smallexample
  14373. @noindent
  14374. The @code{bump} parameter is equal to zero when Calc is converting
  14375. from a date form in a generalized time zone into a GMT date value.
  14376. It is @i{-1} when Calc is converting in the other direction. The
  14377. adjustments shown above ensure that the conversion behaves correctly
  14378. and reasonably around the 2 a.m.@: transition in each direction.
  14379. There is a ``missing'' hour between 2 a.m.@: and 3 a.m.@: at the
  14380. beginning of daylight savings time; converting a date/time form that
  14381. falls in this hour results in a time value for the following hour,
  14382. from 3 a.m.@: to 4 a.m. At the end of daylight savings time, the
  14383. hour from 1 a.m.@: to 2 a.m.@: repeats itself; converting a date/time
  14384. form that falls in in this hour results in a time value for the first
  14385. manifestion of that time (@emph{not} the one that occurs one hour later).
  14386. If @code{math-daylight-savings-hook} is @code{nil}, then the
  14387. daylight savings adjustment is always taken to be zero.
  14388. In algebraic formulas, @samp{tzone(@var{zone}, @var{date})}
  14389. computes the time zone adjustment for a given zone name at a
  14390. given date. The @var{date} is ignored unless @var{zone} is a
  14391. generalized time zone. If @var{date} is a date form, the
  14392. daylight savings computation is applied to it as it appears.
  14393. If @var{date} is a numeric date value, it is adjusted for the
  14394. daylight-savings version of @var{zone} before being given to
  14395. the daylight savings hook. This odd-sounding rule ensures
  14396. that the daylight-savings computation is always done in
  14397. local time, not in the GMT time that a numeric @var{date}
  14398. is typically represented in.
  14399. @ignore
  14400. @starindex
  14401. @end ignore
  14402. @tindex dsadj
  14403. The @samp{dsadj(@var{date}, @var{zone})} function computes the
  14404. daylight savings adjustment that is appropriate for @var{date} in
  14405. time zone @var{zone}. If @var{zone} is explicitly in or not in
  14406. daylight savings time (e.g., @code{PDT} or @code{PST}) the
  14407. @var{date} is ignored. If @var{zone} is a generalized time zone,
  14408. the algorithms described above are used. If @var{zone} is omitted,
  14409. the computation is done for the current time zone.
  14410. @xref{Reporting Bugs}, for the address of Calc's author, if you
  14411. should wish to contribute your improved versions of
  14412. @code{math-tzone-names} and @code{math-daylight-savings-hook}
  14413. to the Calc distribution.
  14414. @node Financial Functions, Binary Functions, Date Arithmetic, Arithmetic
  14415. @section Financial Functions
  14416. @noindent
  14417. Calc's financial or business functions use the @kbd{b} prefix
  14418. key followed by a shifted letter. (The @kbd{b} prefix followed by
  14419. a lower-case letter is used for operations on binary numbers.)
  14420. Note that the rate and the number of intervals given to these
  14421. functions must be on the same time scale, e.g., both months or
  14422. both years. Mixing an annual interest rate with a time expressed
  14423. in months will give you very wrong answers!
  14424. It is wise to compute these functions to a higher precision than
  14425. you really need, just to make sure your answer is correct to the
  14426. last penny; also, you may wish to check the definitions at the end
  14427. of this section to make sure the functions have the meaning you expect.
  14428. @menu
  14429. * Percentages::
  14430. * Future Value::
  14431. * Present Value::
  14432. * Related Financial Functions::
  14433. * Depreciation Functions::
  14434. * Definitions of Financial Functions::
  14435. @end menu
  14436. @node Percentages, Future Value, Financial Functions, Financial Functions
  14437. @subsection Percentages
  14438. @kindex M-%
  14439. @pindex calc-percent
  14440. @tindex %
  14441. @tindex percent
  14442. The @kbd{M-%} (@code{calc-percent}) command takes a percentage value,
  14443. say 5.4, and converts it to an equivalent actual number. For example,
  14444. @kbd{5.4 M-%} enters 0.054 on the stack. (That's the @key{META} or
  14445. @key{ESC} key combined with @kbd{%}.)
  14446. Actually, @kbd{M-%} creates a formula of the form @samp{5.4%}.
  14447. You can enter @samp{5.4%} yourself during algebraic entry. The
  14448. @samp{%} operator simply means, ``the preceding value divided by
  14449. 100.'' The @samp{%} operator has very high precedence, so that
  14450. @samp{1+8%} is interpreted as @samp{1+(8%)}, not as @samp{(1+8)%}.
  14451. (The @samp{%} operator is just a postfix notation for the
  14452. @code{percent} function, just like @samp{20!} is the notation for
  14453. @samp{fact(20)}, or twenty-factorial.)
  14454. The formula @samp{5.4%} would normally evaluate immediately to
  14455. 0.054, but the @kbd{M-%} command suppresses evaluation as it puts
  14456. the formula onto the stack. However, the next Calc command that
  14457. uses the formula @samp{5.4%} will evaluate it as its first step.
  14458. The net effect is that you get to look at @samp{5.4%} on the stack,
  14459. but Calc commands see it as @samp{0.054}, which is what they expect.
  14460. In particular, @samp{5.4%} and @samp{0.054} are suitable values
  14461. for the @var{rate} arguments of the various financial functions,
  14462. but the number @samp{5.4} is probably @emph{not} suitable---it
  14463. represents a rate of 540 percent!
  14464. The key sequence @kbd{M-% *} effectively means ``percent-of.''
  14465. For example, @kbd{68 @key{RET} 25 M-% *} computes 17, which is 25% of
  14466. 68 (and also 68% of 25, which comes out to the same thing).
  14467. @kindex c %
  14468. @pindex calc-convert-percent
  14469. The @kbd{c %} (@code{calc-convert-percent}) command converts the
  14470. value on the top of the stack from numeric to percentage form.
  14471. For example, if 0.08 is on the stack, @kbd{c %} converts it to
  14472. @samp{8%}. The quantity is the same, it's just represented
  14473. differently. (Contrast this with @kbd{M-%}, which would convert
  14474. this number to @samp{0.08%}.) The @kbd{=} key is a convenient way
  14475. to convert a formula like @samp{8%} back to numeric form, 0.08.
  14476. To compute what percentage one quantity is of another quantity,
  14477. use @kbd{/ c %}. For example, @w{@kbd{17 @key{RET} 68 / c %}} displays
  14478. @samp{25%}.
  14479. @kindex b %
  14480. @pindex calc-percent-change
  14481. @tindex relch
  14482. The @kbd{b %} (@code{calc-percent-change}) [@code{relch}] command
  14483. calculates the percentage change from one number to another.
  14484. For example, @kbd{40 @key{RET} 50 b %} produces the answer @samp{25%},
  14485. since 50 is 25% larger than 40. A negative result represents a
  14486. decrease: @kbd{50 @key{RET} 40 b %} produces @samp{-20%}, since 40 is
  14487. 20% smaller than 50. (The answers are different in magnitude
  14488. because, in the first case, we're increasing by 25% of 40, but
  14489. in the second case, we're decreasing by 20% of 50.) The effect
  14490. of @kbd{40 @key{RET} 50 b %} is to compute @cite{(50-40)/40}, converting
  14491. the answer to percentage form as if by @kbd{c %}.
  14492. @node Future Value, Present Value, Percentages, Financial Functions
  14493. @subsection Future Value
  14494. @noindent
  14495. @kindex b F
  14496. @pindex calc-fin-fv
  14497. @tindex fv
  14498. The @kbd{b F} (@code{calc-fin-fv}) [@code{fv}] command computes
  14499. the future value of an investment. It takes three arguments
  14500. from the stack: @samp{fv(@var{rate}, @var{n}, @var{payment})}.
  14501. If you give payments of @var{payment} every year for @var{n}
  14502. years, and the money you have paid earns interest at @var{rate} per
  14503. year, then this function tells you what your investment would be
  14504. worth at the end of the period. (The actual interval doesn't
  14505. have to be years, as long as @var{n} and @var{rate} are expressed
  14506. in terms of the same intervals.) This function assumes payments
  14507. occur at the @emph{end} of each interval.
  14508. @kindex I b F
  14509. @tindex fvb
  14510. The @kbd{I b F} [@code{fvb}] command does the same computation,
  14511. but assuming your payments are at the beginning of each interval.
  14512. Suppose you plan to deposit $1000 per year in a savings account
  14513. earning 5.4% interest, starting right now. How much will be
  14514. in the account after five years? @code{fvb(5.4%, 5, 1000) = 5870.73}.
  14515. Thus you will have earned $870 worth of interest over the years.
  14516. Using the stack, this calculation would have been
  14517. @kbd{5.4 M-% 5 @key{RET} 1000 I b F}. Note that the rate is expressed
  14518. as a number between 0 and 1, @emph{not} as a percentage.
  14519. @kindex H b F
  14520. @tindex fvl
  14521. The @kbd{H b F} [@code{fvl}] command computes the future value
  14522. of an initial lump sum investment. Suppose you could deposit
  14523. those five thousand dollars in the bank right now; how much would
  14524. they be worth in five years? @code{fvl(5.4%, 5, 5000) = 6503.89}.
  14525. The algebraic functions @code{fv} and @code{fvb} accept an optional
  14526. fourth argument, which is used as an initial lump sum in the sense
  14527. of @code{fvl}. In other words, @code{fv(@var{rate}, @var{n},
  14528. @var{payment}, @var{initial}) = fv(@var{rate}, @var{n}, @var{payment})
  14529. + fvl(@var{rate}, @var{n}, @var{initial})}.@refill
  14530. To illustrate the relationships between these functions, we could
  14531. do the @code{fvb} calculation ``by hand'' using @code{fvl}. The
  14532. final balance will be the sum of the contributions of our five
  14533. deposits at various times. The first deposit earns interest for
  14534. five years: @code{fvl(5.4%, 5, 1000) = 1300.78}. The second
  14535. deposit only earns interest for four years: @code{fvl(5.4%, 4, 1000) =
  14536. 1234.13}. And so on down to the last deposit, which earns one
  14537. year's interest: @code{fvl(5.4%, 1, 1000) = 1054.00}. The sum of
  14538. these five values is, sure enough, $5870.73, just as was computed
  14539. by @code{fvb} directly.
  14540. What does @code{fv(5.4%, 5, 1000) = 5569.96} mean? The payments
  14541. are now at the ends of the periods. The end of one year is the same
  14542. as the beginning of the next, so what this really means is that we've
  14543. lost the payment at year zero (which contributed $1300.78), but we're
  14544. now counting the payment at year five (which, since it didn't have
  14545. a chance to earn interest, counts as $1000). Indeed, @cite{5569.96 =
  14546. 5870.73 - 1300.78 + 1000} (give or take a bit of roundoff error).
  14547. @node Present Value, Related Financial Functions, Future Value, Financial Functions
  14548. @subsection Present Value
  14549. @noindent
  14550. @kindex b P
  14551. @pindex calc-fin-pv
  14552. @tindex pv
  14553. The @kbd{b P} (@code{calc-fin-pv}) [@code{pv}] command computes
  14554. the present value of an investment. Like @code{fv}, it takes
  14555. three arguments: @code{pv(@var{rate}, @var{n}, @var{payment})}.
  14556. It computes the present value of a series of regular payments.
  14557. Suppose you have the chance to make an investment that will
  14558. pay $2000 per year over the next four years; as you receive
  14559. these payments you can put them in the bank at 9% interest.
  14560. You want to know whether it is better to make the investment, or
  14561. to keep the money in the bank where it earns 9% interest right
  14562. from the start. The calculation @code{pv(9%, 4, 2000)} gives the
  14563. result 6479.44. If your initial investment must be less than this,
  14564. say, $6000, then the investment is worthwhile. But if you had to
  14565. put up $7000, then it would be better just to leave it in the bank.
  14566. Here is the interpretation of the result of @code{pv}: You are
  14567. trying to compare the return from the investment you are
  14568. considering, which is @code{fv(9%, 4, 2000) = 9146.26}, with
  14569. the return from leaving the money in the bank, which is
  14570. @code{fvl(9%, 4, @var{x})} where @var{x} is the amount of money
  14571. you would have to put up in advance. The @code{pv} function
  14572. finds the break-even point, @cite{x = 6479.44}, at which
  14573. @code{fvl(9%, 4, 6479.44)} is also equal to 9146.26. This is
  14574. the largest amount you should be willing to invest.
  14575. @kindex I b P
  14576. @tindex pvb
  14577. The @kbd{I b P} [@code{pvb}] command solves the same problem,
  14578. but with payments occurring at the beginning of each interval.
  14579. It has the same relationship to @code{fvb} as @code{pv} has
  14580. to @code{fv}. For example @code{pvb(9%, 4, 2000) = 7062.59},
  14581. a larger number than @code{pv} produced because we get to start
  14582. earning interest on the return from our investment sooner.
  14583. @kindex H b P
  14584. @tindex pvl
  14585. The @kbd{H b P} [@code{pvl}] command computes the present value of
  14586. an investment that will pay off in one lump sum at the end of the
  14587. period. For example, if we get our $8000 all at the end of the
  14588. four years, @code{pvl(9%, 4, 8000) = 5667.40}. This is much
  14589. less than @code{pv} reported, because we don't earn any interest
  14590. on the return from this investment. Note that @code{pvl} and
  14591. @code{fvl} are simple inverses: @code{fvl(9%, 4, 5667.40) = 8000}.
  14592. You can give an optional fourth lump-sum argument to @code{pv}
  14593. and @code{pvb}; this is handled in exactly the same way as the
  14594. fourth argument for @code{fv} and @code{fvb}.
  14595. @kindex b N
  14596. @pindex calc-fin-npv
  14597. @tindex npv
  14598. The @kbd{b N} (@code{calc-fin-npv}) [@code{npv}] command computes
  14599. the net present value of a series of irregular investments.
  14600. The first argument is the interest rate. The second argument is
  14601. a vector which represents the expected return from the investment
  14602. at the end of each interval. For example, if the rate represents
  14603. a yearly interest rate, then the vector elements are the return
  14604. from the first year, second year, and so on.
  14605. Thus, @code{npv(9%, [2000,2000,2000,2000]) = pv(9%, 4, 2000) = 6479.44}.
  14606. Obviously this function is more interesting when the payments are
  14607. not all the same!
  14608. The @code{npv} function can actually have two or more arguments.
  14609. Multiple arguments are interpreted in the same way as for the
  14610. vector statistical functions like @code{vsum}.
  14611. @xref{Single-Variable Statistics}. Basically, if there are several
  14612. payment arguments, each either a vector or a plain number, all these
  14613. values are collected left-to-right into the complete list of payments.
  14614. A numeric prefix argument on the @kbd{b N} command says how many
  14615. payment values or vectors to take from the stack.@refill
  14616. @kindex I b N
  14617. @tindex npvb
  14618. The @kbd{I b N} [@code{npvb}] command computes the net present
  14619. value where payments occur at the beginning of each interval
  14620. rather than at the end.
  14621. @node Related Financial Functions, Depreciation Functions, Present Value, Financial Functions
  14622. @subsection Related Financial Functions
  14623. @noindent
  14624. The functions in this section are basically inverses of the
  14625. present value functions with respect to the various arguments.
  14626. @kindex b M
  14627. @pindex calc-fin-pmt
  14628. @tindex pmt
  14629. The @kbd{b M} (@code{calc-fin-pmt}) [@code{pmt}] command computes
  14630. the amount of periodic payment necessary to amortize a loan.
  14631. Thus @code{pmt(@var{rate}, @var{n}, @var{amount})} equals the
  14632. value of @var{payment} such that @code{pv(@var{rate}, @var{n},
  14633. @var{payment}) = @var{amount}}.@refill
  14634. @kindex I b M
  14635. @tindex pmtb
  14636. The @kbd{I b M} [@code{pmtb}] command does the same computation
  14637. but using @code{pvb} instead of @code{pv}. Like @code{pv} and
  14638. @code{pvb}, these functions can also take a fourth argument which
  14639. represents an initial lump-sum investment.
  14640. @kindex H b M
  14641. The @kbd{H b M} key just invokes the @code{fvl} function, which is
  14642. the inverse of @code{pvl}. There is no explicit @code{pmtl} function.
  14643. @kindex b #
  14644. @pindex calc-fin-nper
  14645. @tindex nper
  14646. The @kbd{b #} (@code{calc-fin-nper}) [@code{nper}] command computes
  14647. the number of regular payments necessary to amortize a loan.
  14648. Thus @code{nper(@var{rate}, @var{payment}, @var{amount})} equals
  14649. the value of @var{n} such that @code{pv(@var{rate}, @var{n},
  14650. @var{payment}) = @var{amount}}. If @var{payment} is too small
  14651. ever to amortize a loan for @var{amount} at interest rate @var{rate},
  14652. the @code{nper} function is left in symbolic form.@refill
  14653. @kindex I b #
  14654. @tindex nperb
  14655. The @kbd{I b #} [@code{nperb}] command does the same computation
  14656. but using @code{pvb} instead of @code{pv}. You can give a fourth
  14657. lump-sum argument to these functions, but the computation will be
  14658. rather slow in the four-argument case.@refill
  14659. @kindex H b #
  14660. @tindex nperl
  14661. The @kbd{H b #} [@code{nperl}] command does the same computation
  14662. using @code{pvl}. By exchanging @var{payment} and @var{amount} you
  14663. can also get the solution for @code{fvl}. For example,
  14664. @code{nperl(8%, 2000, 1000) = 9.006}, so if you place $1000 in a
  14665. bank account earning 8%, it will take nine years to grow to $2000.@refill
  14666. @kindex b T
  14667. @pindex calc-fin-rate
  14668. @tindex rate
  14669. The @kbd{b T} (@code{calc-fin-rate}) [@code{rate}] command computes
  14670. the rate of return on an investment. This is also an inverse of @code{pv}:
  14671. @code{rate(@var{n}, @var{payment}, @var{amount})} computes the value of
  14672. @var{rate} such that @code{pv(@var{rate}, @var{n}, @var{payment}) =
  14673. @var{amount}}. The result is expressed as a formula like @samp{6.3%}.@refill
  14674. @kindex I b T
  14675. @kindex H b T
  14676. @tindex rateb
  14677. @tindex ratel
  14678. The @kbd{I b T} [@code{rateb}] and @kbd{H b T} [@code{ratel}]
  14679. commands solve the analogous equations with @code{pvb} or @code{pvl}
  14680. in place of @code{pv}. Also, @code{rate} and @code{rateb} can
  14681. accept an optional fourth argument just like @code{pv} and @code{pvb}.
  14682. To redo the above example from a different perspective,
  14683. @code{ratel(9, 2000, 1000) = 8.00597%}, which says you will need an
  14684. interest rate of 8% in order to double your account in nine years.@refill
  14685. @kindex b I
  14686. @pindex calc-fin-irr
  14687. @tindex irr
  14688. The @kbd{b I} (@code{calc-fin-irr}) [@code{irr}] command is the
  14689. analogous function to @code{rate} but for net present value.
  14690. Its argument is a vector of payments. Thus @code{irr(@var{payments})}
  14691. computes the @var{rate} such that @code{npv(@var{rate}, @var{payments}) = 0};
  14692. this rate is known as the @dfn{internal rate of return}.
  14693. @kindex I b I
  14694. @tindex irrb
  14695. The @kbd{I b I} [@code{irrb}] command computes the internal rate of
  14696. return assuming payments occur at the beginning of each period.
  14697. @node Depreciation Functions, Definitions of Financial Functions, Related Financial Functions, Financial Functions
  14698. @subsection Depreciation Functions
  14699. @noindent
  14700. The functions in this section calculate @dfn{depreciation}, which is
  14701. the amount of value that a possession loses over time. These functions
  14702. are characterized by three parameters: @var{cost}, the original cost
  14703. of the asset; @var{salvage}, the value the asset will have at the end
  14704. of its expected ``useful life''; and @var{life}, the number of years
  14705. (or other periods) of the expected useful life.
  14706. There are several methods for calculating depreciation that differ in
  14707. the way they spread the depreciation over the lifetime of the asset.
  14708. @kindex b S
  14709. @pindex calc-fin-sln
  14710. @tindex sln
  14711. The @kbd{b S} (@code{calc-fin-sln}) [@code{sln}] command computes the
  14712. ``straight-line'' depreciation. In this method, the asset depreciates
  14713. by the same amount every year (or period). For example,
  14714. @samp{sln(12000, 2000, 5)} returns 2000. The asset costs $12000
  14715. initially and will be worth $2000 after five years; it loses $2000
  14716. per year.
  14717. @kindex b Y
  14718. @pindex calc-fin-syd
  14719. @tindex syd
  14720. The @kbd{b Y} (@code{calc-fin-syd}) [@code{syd}] command computes the
  14721. accelerated ``sum-of-years'-digits'' depreciation. Here the depreciation
  14722. is higher during the early years of the asset's life. Since the
  14723. depreciation is different each year, @kbd{b Y} takes a fourth @var{period}
  14724. parameter which specifies which year is requested, from 1 to @var{life}.
  14725. If @var{period} is outside this range, the @code{syd} function will
  14726. return zero.
  14727. @kindex b D
  14728. @pindex calc-fin-ddb
  14729. @tindex ddb
  14730. The @kbd{b D} (@code{calc-fin-ddb}) [@code{ddb}] command computes an
  14731. accelerated depreciation using the double-declining balance method.
  14732. It also takes a fourth @var{period} parameter.
  14733. For symmetry, the @code{sln} function will accept a @var{period}
  14734. parameter as well, although it will ignore its value except that the
  14735. return value will as usual be zero if @var{period} is out of range.
  14736. For example, pushing the vector @cite{[1,2,3,4,5]} (perhaps with @kbd{v x 5})
  14737. and then mapping @kbd{V M ' [sln(12000,2000,5,$), syd(12000,2000,5,$),
  14738. ddb(12000,2000,5,$)] @key{RET}} produces a matrix that allows us to compare
  14739. the three depreciation methods:
  14740. @example
  14741. @group
  14742. [ [ 2000, 3333, 4800 ]
  14743. [ 2000, 2667, 2880 ]
  14744. [ 2000, 2000, 1728 ]
  14745. [ 2000, 1333, 592 ]
  14746. [ 2000, 667, 0 ] ]
  14747. @end group
  14748. @end example
  14749. @noindent
  14750. (Values have been rounded to nearest integers in this figure.)
  14751. We see that @code{sln} depreciates by the same amount each year,
  14752. @kbd{syd} depreciates more at the beginning and less at the end,
  14753. and @kbd{ddb} weights the depreciation even more toward the beginning.
  14754. Summing columns with @kbd{V R : +} yields @cite{[10000, 10000, 10000]};
  14755. the total depreciation in any method is (by definition) the
  14756. difference between the cost and the salvage value.
  14757. @node Definitions of Financial Functions, , Depreciation Functions, Financial Functions
  14758. @subsection Definitions
  14759. @noindent
  14760. For your reference, here are the actual formulas used to compute
  14761. Calc's financial functions.
  14762. Calc will not evaluate a financial function unless the @var{rate} or
  14763. @var{n} argument is known. However, @var{payment} or @var{amount} can
  14764. be a variable. Calc expands these functions according to the
  14765. formulas below for symbolic arguments only when you use the @kbd{a "}
  14766. (@code{calc-expand-formula}) command, or when taking derivatives or
  14767. integrals or solving equations involving the functions.
  14768. @ifinfo
  14769. These formulas are shown using the conventions of ``Big'' display
  14770. mode (@kbd{d B}); for example, the formula for @code{fv} written
  14771. linearly is @samp{pmt * ((1 + rate)^n) - 1) / rate}.
  14772. @example
  14773. n
  14774. (1 + rate) - 1
  14775. fv(rate, n, pmt) = pmt * ---------------
  14776. rate
  14777. n
  14778. ((1 + rate) - 1) (1 + rate)
  14779. fvb(rate, n, pmt) = pmt * ----------------------------
  14780. rate
  14781. n
  14782. fvl(rate, n, pmt) = pmt * (1 + rate)
  14783. -n
  14784. 1 - (1 + rate)
  14785. pv(rate, n, pmt) = pmt * ----------------
  14786. rate
  14787. -n
  14788. (1 - (1 + rate) ) (1 + rate)
  14789. pvb(rate, n, pmt) = pmt * -----------------------------
  14790. rate
  14791. -n
  14792. pvl(rate, n, pmt) = pmt * (1 + rate)
  14793. -1 -2 -3
  14794. npv(rate, [a, b, c]) = a*(1 + rate) + b*(1 + rate) + c*(1 + rate)
  14795. -1 -2
  14796. npvb(rate, [a, b, c]) = a + b*(1 + rate) + c*(1 + rate)
  14797. -n
  14798. (amt - x * (1 + rate) ) * rate
  14799. pmt(rate, n, amt, x) = -------------------------------
  14800. -n
  14801. 1 - (1 + rate)
  14802. -n
  14803. (amt - x * (1 + rate) ) * rate
  14804. pmtb(rate, n, amt, x) = -------------------------------
  14805. -n
  14806. (1 - (1 + rate) ) (1 + rate)
  14807. amt * rate
  14808. nper(rate, pmt, amt) = - log(1 - ------------, 1 + rate)
  14809. pmt
  14810. amt * rate
  14811. nperb(rate, pmt, amt) = - log(1 - ---------------, 1 + rate)
  14812. pmt * (1 + rate)
  14813. amt
  14814. nperl(rate, pmt, amt) = - log(---, 1 + rate)
  14815. pmt
  14816. 1/n
  14817. pmt
  14818. ratel(n, pmt, amt) = ------ - 1
  14819. 1/n
  14820. amt
  14821. cost - salv
  14822. sln(cost, salv, life) = -----------
  14823. life
  14824. (cost - salv) * (life - per + 1)
  14825. syd(cost, salv, life, per) = --------------------------------
  14826. life * (life + 1) / 2
  14827. book * 2
  14828. ddb(cost, salv, life, per) = --------, book = cost - depreciation so far
  14829. life
  14830. @end example
  14831. @end ifinfo
  14832. @tex
  14833. \turnoffactive
  14834. $$ \code{fv}(r, n, p) = p { (1 + r)^n - 1 \over r } $$
  14835. $$ \code{fvb}(r, n, p) = p { ((1 + r)^n - 1) (1 + r) \over r } $$
  14836. $$ \code{fvl}(r, n, p) = p (1 + r)^n $$
  14837. $$ \code{pv}(r, n, p) = p { 1 - (1 + r)^{-n} \over r } $$
  14838. $$ \code{pvb}(r, n, p) = p { (1 - (1 + r)^{-n}) (1 + r) \over r } $$
  14839. $$ \code{pvl}(r, n, p) = p (1 + r)^{-n} $$
  14840. $$ \code{npv}(r, [a,b,c]) = a (1 + r)^{-1} + b (1 + r)^{-2} + c (1 + r)^{-3} $$
  14841. $$ \code{npvb}(r, [a,b,c]) = a + b (1 + r)^{-1} + c (1 + r)^{-2} $$
  14842. $$ \code{pmt}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over 1 - (1 + r)^{-n} }$$
  14843. $$ \code{pmtb}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over
  14844. (1 - (1 + r)^{-n}) (1 + r) } $$
  14845. $$ \code{nper}(r, p, a) = -\code{log}(1 - { a r \over p }, 1 + r) $$
  14846. $$ \code{nperb}(r, p, a) = -\code{log}(1 - { a r \over p (1 + r) }, 1 + r) $$
  14847. $$ \code{nperl}(r, p, a) = -\code{log}({a \over p}, 1 + r) $$
  14848. $$ \code{ratel}(n, p, a) = { p^{1/n} \over a^{1/n} } - 1 $$
  14849. $$ \code{sln}(c, s, l) = { c - s \over l } $$
  14850. $$ \code{syd}(c, s, l, p) = { (c - s) (l - p + 1) \over l (l+1) / 2 } $$
  14851. $$ \code{ddb}(c, s, l, p) = { 2 (c - \hbox{depreciation so far}) \over l } $$
  14852. @end tex
  14853. @noindent
  14854. In @code{pmt} and @code{pmtb}, @cite{x=0} if omitted.
  14855. These functions accept any numeric objects, including error forms,
  14856. intervals, and even (though not very usefully) complex numbers. The
  14857. above formulas specify exactly the behavior of these functions with
  14858. all sorts of inputs.
  14859. Note that if the first argument to the @code{log} in @code{nper} is
  14860. negative, @code{nper} leaves itself in symbolic form rather than
  14861. returning a (financially meaningless) complex number.
  14862. @samp{rate(num, pmt, amt)} solves the equation
  14863. @samp{pv(rate, num, pmt) = amt} for @samp{rate} using @kbd{H a R}
  14864. (@code{calc-find-root}), with the interval @samp{[.01% .. 100%]}
  14865. for an initial guess. The @code{rateb} function is the same except
  14866. that it uses @code{pvb}. Note that @code{ratel} can be solved
  14867. directly; its formula is shown in the above list.
  14868. Similarly, @samp{irr(pmts)} solves the equation @samp{npv(rate, pmts) = 0}
  14869. for @samp{rate}.
  14870. If you give a fourth argument to @code{nper} or @code{nperb}, Calc
  14871. will also use @kbd{H a R} to solve the equation using an initial
  14872. guess interval of @samp{[0 .. 100]}.
  14873. A fourth argument to @code{fv} simply sums the two components
  14874. calculated from the above formulas for @code{fv} and @code{fvl}.
  14875. The same is true of @code{fvb}, @code{pv}, and @code{pvb}.
  14876. The @kbd{ddb} function is computed iteratively; the ``book'' value
  14877. starts out equal to @var{cost}, and decreases according to the above
  14878. formula for the specified number of periods. If the book value
  14879. would decrease below @var{salvage}, it only decreases to @var{salvage}
  14880. and the depreciation is zero for all subsequent periods. The @code{ddb}
  14881. function returns the amount the book value decreased in the specified
  14882. period.
  14883. The Calc financial function names were borrowed mostly from Microsoft
  14884. Excel and Borland's Quattro. The @code{ratel} function corresponds to
  14885. @samp{@@CGR} in Borland's Reflex. The @code{nper} and @code{nperl}
  14886. functions correspond to @samp{@@TERM} and @samp{@@CTERM} in Quattro,
  14887. respectively. Beware that the Calc functions may take their arguments
  14888. in a different order than the corresponding functions in your favorite
  14889. spreadsheet.
  14890. @node Binary Functions, , Financial Functions, Arithmetic
  14891. @section Binary Number Functions
  14892. @noindent
  14893. The commands in this chapter all use two-letter sequences beginning with
  14894. the @kbd{b} prefix.
  14895. @cindex Binary numbers
  14896. The ``binary'' operations actually work regardless of the currently
  14897. displayed radix, although their results make the most sense in a radix
  14898. like 2, 8, or 16 (as obtained by the @kbd{d 2}, @kbd{d 8}, or @w{@kbd{d 6}}
  14899. commands, respectively). You may also wish to enable display of leading
  14900. zeros with @kbd{d z}. @xref{Radix Modes}.
  14901. @cindex Word size for binary operations
  14902. The Calculator maintains a current @dfn{word size} @cite{w}, an
  14903. arbitrary positive or negative integer. For a positive word size, all
  14904. of the binary operations described here operate modulo @cite{2^w}. In
  14905. particular, negative arguments are converted to positive integers modulo
  14906. @cite{2^w} by all binary functions.@refill
  14907. If the word size is negative, binary operations produce 2's complement
  14908. integers from @c{$-2^{-w-1}$}
  14909. @cite{-(2^(-w-1))} to @c{$2^{-w-1}-1$}
  14910. @cite{2^(-w-1)-1} inclusive. Either
  14911. mode accepts inputs in any range; the sign of @cite{w} affects only
  14912. the results produced.
  14913. @kindex b c
  14914. @pindex calc-clip
  14915. @tindex clip
  14916. The @kbd{b c} (@code{calc-clip})
  14917. [@code{clip}] command can be used to clip a number by reducing it modulo
  14918. @cite{2^w}. The commands described in this chapter automatically clip
  14919. their results to the current word size. Note that other operations like
  14920. addition do not use the current word size, since integer addition
  14921. generally is not ``binary.'' (However, @pxref{Simplification Modes},
  14922. @code{calc-bin-simplify-mode}.) For example, with a word size of 8
  14923. bits @kbd{b c} converts a number to the range 0 to 255; with a word
  14924. size of @i{-8} @kbd{b c} converts to the range @i{-128} to 127.@refill
  14925. @kindex b w
  14926. @pindex calc-word-size
  14927. The default word size is 32 bits. All operations except the shifts and
  14928. rotates allow you to specify a different word size for that one
  14929. operation by giving a numeric prefix argument: @kbd{C-u 8 b c} clips the
  14930. top of stack to the range 0 to 255 regardless of the current word size.
  14931. To set the word size permanently, use @kbd{b w} (@code{calc-word-size}).
  14932. This command displays a prompt with the current word size; press @key{RET}
  14933. immediately to keep this word size, or type a new word size at the prompt.
  14934. When the binary operations are written in symbolic form, they take an
  14935. optional second (or third) word-size parameter. When a formula like
  14936. @samp{and(a,b)} is finally evaluated, the word size current at that time
  14937. will be used, but when @samp{and(a,b,-8)} is evaluated, a word size of
  14938. @i{-8} will always be used. A symbolic binary function will be left
  14939. in symbolic form unless the all of its argument(s) are integers or
  14940. integer-valued floats.
  14941. If either or both arguments are modulo forms for which @cite{M} is a
  14942. power of two, that power of two is taken as the word size unless a
  14943. numeric prefix argument overrides it. The current word size is never
  14944. consulted when modulo-power-of-two forms are involved.
  14945. @kindex b a
  14946. @pindex calc-and
  14947. @tindex and
  14948. The @kbd{b a} (@code{calc-and}) [@code{and}] command computes the bitwise
  14949. AND of the two numbers on the top of the stack. In other words, for each
  14950. of the @cite{w} binary digits of the two numbers (pairwise), the corresponding
  14951. bit of the result is 1 if and only if both input bits are 1:
  14952. @samp{and(2#1100, 2#1010) = 2#1000}.
  14953. @kindex b o
  14954. @pindex calc-or
  14955. @tindex or
  14956. The @kbd{b o} (@code{calc-or}) [@code{or}] command computes the bitwise
  14957. inclusive OR of two numbers. A bit is 1 if either of the input bits, or
  14958. both, are 1: @samp{or(2#1100, 2#1010) = 2#1110}.
  14959. @kindex b x
  14960. @pindex calc-xor
  14961. @tindex xor
  14962. The @kbd{b x} (@code{calc-xor}) [@code{xor}] command computes the bitwise
  14963. exclusive OR of two numbers. A bit is 1 if exactly one of the input bits
  14964. is 1: @samp{xor(2#1100, 2#1010) = 2#0110}.
  14965. @kindex b d
  14966. @pindex calc-diff
  14967. @tindex diff
  14968. The @kbd{b d} (@code{calc-diff}) [@code{diff}] command computes the bitwise
  14969. difference of two numbers; this is defined by @samp{diff(a,b) = and(a,not(b))},
  14970. so that @samp{diff(2#1100, 2#1010) = 2#0100}.
  14971. @kindex b n
  14972. @pindex calc-not
  14973. @tindex not
  14974. The @kbd{b n} (@code{calc-not}) [@code{not}] command computes the bitwise
  14975. NOT of a number. A bit is 1 if the input bit is 0 and vice-versa.
  14976. @kindex b l
  14977. @pindex calc-lshift-binary
  14978. @tindex lsh
  14979. The @kbd{b l} (@code{calc-lshift-binary}) [@code{lsh}] command shifts a
  14980. number left by one bit, or by the number of bits specified in the numeric
  14981. prefix argument. A negative prefix argument performs a logical right shift,
  14982. in which zeros are shifted in on the left. In symbolic form, @samp{lsh(a)}
  14983. is short for @samp{lsh(a,1)}, which in turn is short for @samp{lsh(a,n,w)}.
  14984. Bits shifted ``off the end,'' according to the current word size, are lost.
  14985. @kindex H b l
  14986. @kindex H b r
  14987. @ignore
  14988. @mindex @idots
  14989. @end ignore
  14990. @kindex H b L
  14991. @ignore
  14992. @mindex @null
  14993. @end ignore
  14994. @kindex H b R
  14995. @ignore
  14996. @mindex @null
  14997. @end ignore
  14998. @kindex H b t
  14999. The @kbd{H b l} command also does a left shift, but it takes two arguments
  15000. from the stack (the value to shift, and, at top-of-stack, the number of
  15001. bits to shift). This version interprets the prefix argument just like
  15002. the regular binary operations, i.e., as a word size. The Hyperbolic flag
  15003. has a similar effect on the rest of the binary shift and rotate commands.
  15004. @kindex b r
  15005. @pindex calc-rshift-binary
  15006. @tindex rsh
  15007. The @kbd{b r} (@code{calc-rshift-binary}) [@code{rsh}] command shifts a
  15008. number right by one bit, or by the number of bits specified in the numeric
  15009. prefix argument: @samp{rsh(a,n) = lsh(a,-n)}.
  15010. @kindex b L
  15011. @pindex calc-lshift-arith
  15012. @tindex ash
  15013. The @kbd{b L} (@code{calc-lshift-arith}) [@code{ash}] command shifts a
  15014. number left. It is analogous to @code{lsh}, except that if the shift
  15015. is rightward (the prefix argument is negative), an arithmetic shift
  15016. is performed as described below.
  15017. @kindex b R
  15018. @pindex calc-rshift-arith
  15019. @tindex rash
  15020. The @kbd{b R} (@code{calc-rshift-arith}) [@code{rash}] command performs
  15021. an ``arithmetic'' shift to the right, in which the leftmost bit (according
  15022. to the current word size) is duplicated rather than shifting in zeros.
  15023. This corresponds to dividing by a power of two where the input is interpreted
  15024. as a signed, twos-complement number. (The distinction between the @samp{rsh}
  15025. and @samp{rash} operations is totally independent from whether the word
  15026. size is positive or negative.) With a negative prefix argument, this
  15027. performs a standard left shift.
  15028. @kindex b t
  15029. @pindex calc-rotate-binary
  15030. @tindex rot
  15031. The @kbd{b t} (@code{calc-rotate-binary}) [@code{rot}] command rotates a
  15032. number one bit to the left. The leftmost bit (according to the current
  15033. word size) is dropped off the left and shifted in on the right. With a
  15034. numeric prefix argument, the number is rotated that many bits to the left
  15035. or right.
  15036. @xref{Set Operations}, for the @kbd{b p} and @kbd{b u} commands that
  15037. pack and unpack binary integers into sets. (For example, @kbd{b u}
  15038. unpacks the number @samp{2#11001} to the set of bit-numbers
  15039. @samp{[0, 3, 4]}.) Type @kbd{b u V #} to count the number of ``1''
  15040. bits in a binary integer.
  15041. Another interesting use of the set representation of binary integers
  15042. is to reverse the bits in, say, a 32-bit integer. Type @kbd{b u} to
  15043. unpack; type @kbd{31 @key{TAB} -} to replace each bit-number in the set
  15044. with 31 minus that bit-number; type @kbd{b p} to pack the set back
  15045. into a binary integer.
  15046. @node Scientific Functions, Matrix Functions, Arithmetic, Top
  15047. @chapter Scientific Functions
  15048. @noindent
  15049. The functions described here perform trigonometric and other transcendental
  15050. calculations. They generally produce floating-point answers correct to the
  15051. full current precision. The @kbd{H} (Hyperbolic) and @kbd{I} (Inverse)
  15052. flag keys must be used to get some of these functions from the keyboard.
  15053. @kindex P
  15054. @pindex calc-pi
  15055. @cindex @code{pi} variable
  15056. @vindex pi
  15057. @kindex H P
  15058. @cindex @code{e} variable
  15059. @vindex e
  15060. @kindex I P
  15061. @cindex @code{gamma} variable
  15062. @vindex gamma
  15063. @cindex Gamma constant, Euler's
  15064. @cindex Euler's gamma constant
  15065. @kindex H I P
  15066. @cindex @code{phi} variable
  15067. @cindex Phi, golden ratio
  15068. @cindex Golden ratio
  15069. One miscellanous command is shift-@kbd{P} (@code{calc-pi}), which pushes
  15070. the value of @c{$\pi$}
  15071. @cite{pi} (at the current precision) onto the stack. With the
  15072. Hyperbolic flag, it pushes the value @cite{e}, the base of natural logarithms.
  15073. With the Inverse flag, it pushes Euler's constant @c{$\gamma$}
  15074. @cite{gamma} (about 0.5772). With both Inverse and Hyperbolic, it
  15075. pushes the ``golden ratio'' @c{$\phi$}
  15076. @cite{phi} (about 1.618). (At present, Euler's constant is not available
  15077. to unlimited precision; Calc knows only the first 100 digits.)
  15078. In Symbolic mode, these commands push the
  15079. actual variables @samp{pi}, @samp{e}, @samp{gamma}, and @samp{phi},
  15080. respectively, instead of their values; @pxref{Symbolic Mode}.@refill
  15081. @ignore
  15082. @mindex Q
  15083. @end ignore
  15084. @ignore
  15085. @mindex I Q
  15086. @end ignore
  15087. @kindex I Q
  15088. @tindex sqr
  15089. The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] function is described elsewhere;
  15090. @pxref{Basic Arithmetic}. With the Inverse flag [@code{sqr}], this command
  15091. computes the square of the argument.
  15092. @xref{Prefix Arguments}, for a discussion of the effect of numeric
  15093. prefix arguments on commands in this chapter which do not otherwise
  15094. interpret a prefix argument.
  15095. @menu
  15096. * Logarithmic Functions::
  15097. * Trigonometric and Hyperbolic Functions::
  15098. * Advanced Math Functions::
  15099. * Branch Cuts::
  15100. * Random Numbers::
  15101. * Combinatorial Functions::
  15102. * Probability Distribution Functions::
  15103. @end menu
  15104. @node Logarithmic Functions, Trigonometric and Hyperbolic Functions, Scientific Functions, Scientific Functions
  15105. @section Logarithmic Functions
  15106. @noindent
  15107. @kindex L
  15108. @pindex calc-ln
  15109. @tindex ln
  15110. @ignore
  15111. @mindex @null
  15112. @end ignore
  15113. @kindex I E
  15114. The shift-@kbd{L} (@code{calc-ln}) [@code{ln}] command computes the natural
  15115. logarithm of the real or complex number on the top of the stack. With
  15116. the Inverse flag it computes the exponential function instead, although
  15117. this is redundant with the @kbd{E} command.
  15118. @kindex E
  15119. @pindex calc-exp
  15120. @tindex exp
  15121. @ignore
  15122. @mindex @null
  15123. @end ignore
  15124. @kindex I L
  15125. The shift-@kbd{E} (@code{calc-exp}) [@code{exp}] command computes the
  15126. exponential, i.e., @cite{e} raised to the power of the number on the stack.
  15127. The meanings of the Inverse and Hyperbolic flags follow from those for
  15128. the @code{calc-ln} command.
  15129. @kindex H L
  15130. @kindex H E
  15131. @pindex calc-log10
  15132. @tindex log10
  15133. @tindex exp10
  15134. @ignore
  15135. @mindex @null
  15136. @end ignore
  15137. @kindex H I L
  15138. @ignore
  15139. @mindex @null
  15140. @end ignore
  15141. @kindex H I E
  15142. The @kbd{H L} (@code{calc-log10}) [@code{log10}] command computes the common
  15143. (base-10) logarithm of a number. (With the Inverse flag [@code{exp10}],
  15144. it raises ten to a given power.) Note that the common logarithm of a
  15145. complex number is computed by taking the natural logarithm and dividing
  15146. by @c{$\ln10$}
  15147. @cite{ln(10)}.
  15148. @kindex B
  15149. @kindex I B
  15150. @pindex calc-log
  15151. @tindex log
  15152. @tindex alog
  15153. The @kbd{B} (@code{calc-log}) [@code{log}] command computes a logarithm
  15154. to any base. For example, @kbd{1024 @key{RET} 2 B} produces 10, since
  15155. @c{$2^{10} = 1024$}
  15156. @cite{2^10 = 1024}. In certain cases like @samp{log(3,9)}, the result
  15157. will be either @cite{1:2} or @cite{0.5} depending on the current Fraction
  15158. Mode setting. With the Inverse flag [@code{alog}], this command is
  15159. similar to @kbd{^} except that the order of the arguments is reversed.
  15160. @kindex f I
  15161. @pindex calc-ilog
  15162. @tindex ilog
  15163. The @kbd{f I} (@code{calc-ilog}) [@code{ilog}] command computes the
  15164. integer logarithm of a number to any base. The number and the base must
  15165. themselves be positive integers. This is the true logarithm, rounded
  15166. down to an integer. Thus @kbd{ilog(x,10)} is 3 for all @cite{x} in the
  15167. range from 1000 to 9999. If both arguments are positive integers, exact
  15168. integer arithmetic is used; otherwise, this is equivalent to
  15169. @samp{floor(log(x,b))}.
  15170. @kindex f E
  15171. @pindex calc-expm1
  15172. @tindex expm1
  15173. The @kbd{f E} (@code{calc-expm1}) [@code{expm1}] command computes
  15174. @c{$e^x - 1$}
  15175. @cite{exp(x)-1}, but using an algorithm that produces a more accurate
  15176. answer when the result is close to zero, i.e., when @c{$e^x$}
  15177. @cite{exp(x)} is close
  15178. to one.
  15179. @kindex f L
  15180. @pindex calc-lnp1
  15181. @tindex lnp1
  15182. The @kbd{f L} (@code{calc-lnp1}) [@code{lnp1}] command computes
  15183. @c{$\ln(x+1)$}
  15184. @cite{ln(x+1)}, producing a more accurate answer when @cite{x} is close
  15185. to zero.
  15186. @node Trigonometric and Hyperbolic Functions, Advanced Math Functions, Logarithmic Functions, Scientific Functions
  15187. @section Trigonometric/Hyperbolic Functions
  15188. @noindent
  15189. @kindex S
  15190. @pindex calc-sin
  15191. @tindex sin
  15192. The shift-@kbd{S} (@code{calc-sin}) [@code{sin}] command computes the sine
  15193. of an angle or complex number. If the input is an HMS form, it is interpreted
  15194. as degrees-minutes-seconds; otherwise, the input is interpreted according
  15195. to the current angular mode. It is best to use Radians mode when operating
  15196. on complex numbers.@refill
  15197. Calc's ``units'' mechanism includes angular units like @code{deg},
  15198. @code{rad}, and @code{grad}. While @samp{sin(45 deg)} is not evaluated
  15199. all the time, the @kbd{u s} (@code{calc-simplify-units}) command will
  15200. simplify @samp{sin(45 deg)} by taking the sine of 45 degrees, regardless
  15201. of the current angular mode. @xref{Basic Operations on Units}.
  15202. Also, the symbolic variable @code{pi} is not ordinarily recognized in
  15203. arguments to trigonometric functions, as in @samp{sin(3 pi / 4)}, but
  15204. the @kbd{a s} (@code{calc-simplify}) command recognizes many such
  15205. formulas when the current angular mode is radians @emph{and} symbolic
  15206. mode is enabled; this example would be replaced by @samp{sqrt(2) / 2}.
  15207. @xref{Symbolic Mode}. Beware, this simplification occurs even if you
  15208. have stored a different value in the variable @samp{pi}; this is one
  15209. reason why changing built-in variables is a bad idea. Arguments of
  15210. the form @cite{x} plus a multiple of @c{$\pi/2$}
  15211. @cite{pi/2} are also simplified.
  15212. Calc includes similar formulas for @code{cos} and @code{tan}.@refill
  15213. The @kbd{a s} command knows all angles which are integer multiples of
  15214. @c{$\pi/12$}
  15215. @cite{pi/12}, @c{$\pi/10$}
  15216. @cite{pi/10}, or @c{$\pi/8$}
  15217. @cite{pi/8} radians. In degrees mode,
  15218. analogous simplifications occur for integer multiples of 15 or 18
  15219. degrees, and for arguments plus multiples of 90 degrees.
  15220. @kindex I S
  15221. @pindex calc-arcsin
  15222. @tindex arcsin
  15223. With the Inverse flag, @code{calc-sin} computes an arcsine. This is also
  15224. available as the @code{calc-arcsin} command or @code{arcsin} algebraic
  15225. function. The returned argument is converted to degrees, radians, or HMS
  15226. notation depending on the current angular mode.
  15227. @kindex H S
  15228. @pindex calc-sinh
  15229. @tindex sinh
  15230. @kindex H I S
  15231. @pindex calc-arcsinh
  15232. @tindex arcsinh
  15233. With the Hyperbolic flag, @code{calc-sin} computes the hyperbolic
  15234. sine, also available as @code{calc-sinh} [@code{sinh}]. With the
  15235. Hyperbolic and Inverse flags, it computes the hyperbolic arcsine
  15236. (@code{calc-arcsinh}) [@code{arcsinh}].
  15237. @kindex C
  15238. @pindex calc-cos
  15239. @tindex cos
  15240. @ignore
  15241. @mindex @idots
  15242. @end ignore
  15243. @kindex I C
  15244. @pindex calc-arccos
  15245. @ignore
  15246. @mindex @null
  15247. @end ignore
  15248. @tindex arccos
  15249. @ignore
  15250. @mindex @null
  15251. @end ignore
  15252. @kindex H C
  15253. @pindex calc-cosh
  15254. @ignore
  15255. @mindex @null
  15256. @end ignore
  15257. @tindex cosh
  15258. @ignore
  15259. @mindex @null
  15260. @end ignore
  15261. @kindex H I C
  15262. @pindex calc-arccosh
  15263. @ignore
  15264. @mindex @null
  15265. @end ignore
  15266. @tindex arccosh
  15267. @ignore
  15268. @mindex @null
  15269. @end ignore
  15270. @kindex T
  15271. @pindex calc-tan
  15272. @ignore
  15273. @mindex @null
  15274. @end ignore
  15275. @tindex tan
  15276. @ignore
  15277. @mindex @null
  15278. @end ignore
  15279. @kindex I T
  15280. @pindex calc-arctan
  15281. @ignore
  15282. @mindex @null
  15283. @end ignore
  15284. @tindex arctan
  15285. @ignore
  15286. @mindex @null
  15287. @end ignore
  15288. @kindex H T
  15289. @pindex calc-tanh
  15290. @ignore
  15291. @mindex @null
  15292. @end ignore
  15293. @tindex tanh
  15294. @ignore
  15295. @mindex @null
  15296. @end ignore
  15297. @kindex H I T
  15298. @pindex calc-arctanh
  15299. @ignore
  15300. @mindex @null
  15301. @end ignore
  15302. @tindex arctanh
  15303. The shift-@kbd{C} (@code{calc-cos}) [@code{cos}] command computes the cosine
  15304. of an angle or complex number, and shift-@kbd{T} (@code{calc-tan}) [@code{tan}]
  15305. computes the tangent, along with all the various inverse and hyperbolic
  15306. variants of these functions.
  15307. @kindex f T
  15308. @pindex calc-arctan2
  15309. @tindex arctan2
  15310. The @kbd{f T} (@code{calc-arctan2}) [@code{arctan2}] command takes two
  15311. numbers from the stack and computes the arc tangent of their ratio. The
  15312. result is in the full range from @i{-180} (exclusive) to @i{+180}
  15313. (inclusive) degrees, or the analogous range in radians. A similar
  15314. result would be obtained with @kbd{/} followed by @kbd{I T}, but the
  15315. value would only be in the range from @i{-90} to @i{+90} degrees
  15316. since the division loses information about the signs of the two
  15317. components, and an error might result from an explicit division by zero
  15318. which @code{arctan2} would avoid. By (arbitrary) definition,
  15319. @samp{arctan2(0,0)=0}.
  15320. @pindex calc-sincos
  15321. @ignore
  15322. @starindex
  15323. @end ignore
  15324. @tindex sincos
  15325. @ignore
  15326. @starindex
  15327. @end ignore
  15328. @ignore
  15329. @mindex arc@idots
  15330. @end ignore
  15331. @tindex arcsincos
  15332. The @code{calc-sincos} [@code{sincos}] command computes the sine and
  15333. cosine of a number, returning them as a vector of the form
  15334. @samp{[@var{cos}, @var{sin}]}.
  15335. With the Inverse flag [@code{arcsincos}], this command takes a two-element
  15336. vector as an argument and computes @code{arctan2} of the elements.
  15337. (This command does not accept the Hyperbolic flag.)@refill
  15338. @node Advanced Math Functions, Branch Cuts, Trigonometric and Hyperbolic Functions, Scientific Functions
  15339. @section Advanced Mathematical Functions
  15340. @noindent
  15341. Calc can compute a variety of less common functions that arise in
  15342. various branches of mathematics. All of the functions described in
  15343. this section allow arbitrary complex arguments and, except as noted,
  15344. will work to arbitrarily large precisions. They can not at present
  15345. handle error forms or intervals as arguments.
  15346. NOTE: These functions are still experimental. In particular, their
  15347. accuracy is not guaranteed in all domains. It is advisable to set the
  15348. current precision comfortably higher than you actually need when
  15349. using these functions. Also, these functions may be impractically
  15350. slow for some values of the arguments.
  15351. @kindex f g
  15352. @pindex calc-gamma
  15353. @tindex gamma
  15354. The @kbd{f g} (@code{calc-gamma}) [@code{gamma}] command computes the Euler
  15355. gamma function. For positive integer arguments, this is related to the
  15356. factorial function: @samp{gamma(n+1) = fact(n)}. For general complex
  15357. arguments the gamma function can be defined by the following definite
  15358. integral: @c{$\Gamma(a) = \int_0^\infty t^{a-1} e^t dt$}
  15359. @cite{gamma(a) = integ(t^(a-1) exp(t), t, 0, inf)}.
  15360. (The actual implementation uses far more efficient computational methods.)
  15361. @kindex f G
  15362. @tindex gammaP
  15363. @ignore
  15364. @mindex @idots
  15365. @end ignore
  15366. @kindex I f G
  15367. @ignore
  15368. @mindex @null
  15369. @end ignore
  15370. @kindex H f G
  15371. @ignore
  15372. @mindex @null
  15373. @end ignore
  15374. @kindex H I f G
  15375. @pindex calc-inc-gamma
  15376. @ignore
  15377. @mindex @null
  15378. @end ignore
  15379. @tindex gammaQ
  15380. @ignore
  15381. @mindex @null
  15382. @end ignore
  15383. @tindex gammag
  15384. @ignore
  15385. @mindex @null
  15386. @end ignore
  15387. @tindex gammaG
  15388. The @kbd{f G} (@code{calc-inc-gamma}) [@code{gammaP}] command computes
  15389. the incomplete gamma function, denoted @samp{P(a,x)}. This is defined by
  15390. the integral, @c{$P(a,x) = \left( \int_0^x t^{a-1} e^t dt \right) / \Gamma(a)$}
  15391. @cite{gammaP(a,x) = integ(t^(a-1) exp(t), t, 0, x) / gamma(a)}.
  15392. This implies that @samp{gammaP(a,inf) = 1} for any @cite{a} (see the
  15393. definition of the normal gamma function).
  15394. Several other varieties of incomplete gamma function are defined.
  15395. The complement of @cite{P(a,x)}, called @cite{Q(a,x) = 1-P(a,x)} by
  15396. some authors, is computed by the @kbd{I f G} [@code{gammaQ}] command.
  15397. You can think of this as taking the other half of the integral, from
  15398. @cite{x} to infinity.
  15399. @ifinfo
  15400. The functions corresponding to the integrals that define @cite{P(a,x)}
  15401. and @cite{Q(a,x)} but without the normalizing @cite{1/gamma(a)}
  15402. factor are called @cite{g(a,x)} and @cite{G(a,x)}, respectively
  15403. (where @cite{g} and @cite{G} represent the lower- and upper-case Greek
  15404. letter gamma). You can obtain these using the @kbd{H f G} [@code{gammag}]
  15405. and @kbd{H I f G} [@code{gammaG}] commands.
  15406. @end ifinfo
  15407. @tex
  15408. \turnoffactive
  15409. The functions corresponding to the integrals that define $P(a,x)$
  15410. and $Q(a,x)$ but without the normalizing $1/\Gamma(a)$
  15411. factor are called $\gamma(a,x)$ and $\Gamma(a,x)$, respectively.
  15412. You can obtain these using the \kbd{H f G} [\code{gammag}] and
  15413. \kbd{I H f G} [\code{gammaG}] commands.
  15414. @end tex
  15415. @kindex f b
  15416. @pindex calc-beta
  15417. @tindex beta
  15418. The @kbd{f b} (@code{calc-beta}) [@code{beta}] command computes the
  15419. Euler beta function, which is defined in terms of the gamma function as
  15420. @c{$B(a,b) = \Gamma(a) \Gamma(b) / \Gamma(a+b)$}
  15421. @cite{beta(a,b) = gamma(a) gamma(b) / gamma(a+b)}, or by
  15422. @c{$B(a,b) = \int_0^1 t^{a-1} (1-t)^{b-1} dt$}
  15423. @cite{beta(a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, 1)}.
  15424. @kindex f B
  15425. @kindex H f B
  15426. @pindex calc-inc-beta
  15427. @tindex betaI
  15428. @tindex betaB
  15429. The @kbd{f B} (@code{calc-inc-beta}) [@code{betaI}] command computes
  15430. the incomplete beta function @cite{I(x,a,b)}. It is defined by
  15431. @c{$I(x,a,b) = \left( \int_0^x t^{a-1} (1-t)^{b-1} dt \right) / B(a,b)$}
  15432. @cite{betaI(x,a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, x) / beta(a,b)}.
  15433. Once again, the @kbd{H} (hyperbolic) prefix gives the corresponding
  15434. un-normalized version [@code{betaB}].
  15435. @kindex f e
  15436. @kindex I f e
  15437. @pindex calc-erf
  15438. @tindex erf
  15439. @tindex erfc
  15440. The @kbd{f e} (@code{calc-erf}) [@code{erf}] command computes the
  15441. error function @c{$\hbox{erf}(x) = {2 \over \sqrt{\pi}} \int_0^x e^{-t^2} dt$}
  15442. @cite{erf(x) = 2 integ(exp(-(t^2)), t, 0, x) / sqrt(pi)}.
  15443. The complementary error function @kbd{I f e} (@code{calc-erfc}) [@code{erfc}]
  15444. is the corresponding integral from @samp{x} to infinity; the sum
  15445. @c{$\hbox{erf}(x) + \hbox{erfc}(x) = 1$}
  15446. @cite{erf(x) + erfc(x) = 1}.
  15447. @kindex f j
  15448. @kindex f y
  15449. @pindex calc-bessel-J
  15450. @pindex calc-bessel-Y
  15451. @tindex besJ
  15452. @tindex besY
  15453. The @kbd{f j} (@code{calc-bessel-J}) [@code{besJ}] and @kbd{f y}
  15454. (@code{calc-bessel-Y}) [@code{besY}] commands compute the Bessel
  15455. functions of the first and second kinds, respectively.
  15456. In @samp{besJ(n,x)} and @samp{besY(n,x)} the ``order'' parameter
  15457. @cite{n} is often an integer, but is not required to be one.
  15458. Calc's implementation of the Bessel functions currently limits the
  15459. precision to 8 digits, and may not be exact even to that precision.
  15460. Use with care!@refill
  15461. @node Branch Cuts, Random Numbers, Advanced Math Functions, Scientific Functions
  15462. @section Branch Cuts and Principal Values
  15463. @noindent
  15464. @cindex Branch cuts
  15465. @cindex Principal values
  15466. All of the logarithmic, trigonometric, and other scientific functions are
  15467. defined for complex numbers as well as for reals.
  15468. This section describes the values
  15469. returned in cases where the general result is a family of possible values.
  15470. Calc follows section 12.5.3 of Steele's @dfn{Common Lisp, the Language},
  15471. second edition, in these matters. This section will describe each
  15472. function briefly; for a more detailed discussion (including some nifty
  15473. diagrams), consult Steele's book.
  15474. Note that the branch cuts for @code{arctan} and @code{arctanh} were
  15475. changed between the first and second editions of Steele. Versions of
  15476. Calc starting with 2.00 follow the second edition.
  15477. The new branch cuts exactly match those of the HP-28/48 calculators.
  15478. They also match those of Mathematica 1.2, except that Mathematica's
  15479. @code{arctan} cut is always in the right half of the complex plane,
  15480. and its @code{arctanh} cut is always in the top half of the plane.
  15481. Calc's cuts are continuous with quadrants I and III for @code{arctan},
  15482. or II and IV for @code{arctanh}.
  15483. Note: The current implementations of these functions with complex arguments
  15484. are designed with proper behavior around the branch cuts in mind, @emph{not}
  15485. efficiency or accuracy. You may need to increase the floating precision
  15486. and wait a while to get suitable answers from them.
  15487. For @samp{sqrt(a+bi)}: When @cite{a<0} and @cite{b} is small but positive
  15488. or zero, the result is close to the @cite{+i} axis. For @cite{b} small and
  15489. negative, the result is close to the @cite{-i} axis. The result always lies
  15490. in the right half of the complex plane.
  15491. For @samp{ln(a+bi)}: The real part is defined as @samp{ln(abs(a+bi))}.
  15492. The imaginary part is defined as @samp{arg(a+bi) = arctan2(b,a)}.
  15493. Thus the branch cuts for @code{sqrt} and @code{ln} both lie on the
  15494. negative real axis.
  15495. The following table describes these branch cuts in another way.
  15496. If the real and imaginary parts of @cite{z} are as shown, then
  15497. the real and imaginary parts of @cite{f(z)} will be as shown.
  15498. Here @code{eps} stands for a small positive value; each
  15499. occurrence of @code{eps} may stand for a different small value.
  15500. @smallexample
  15501. z sqrt(z) ln(z)
  15502. ----------------------------------------
  15503. +, 0 +, 0 any, 0
  15504. -, 0 0, + any, pi
  15505. -, +eps +eps, + +eps, +
  15506. -, -eps +eps, - +eps, -
  15507. @end smallexample
  15508. For @samp{z1^z2}: This is defined by @samp{exp(ln(z1)*z2)}.
  15509. One interesting consequence of this is that @samp{(-8)^1:3} does
  15510. not evaluate to @i{-2} as you might expect, but to the complex
  15511. number @cite{(1., 1.732)}. Both of these are valid cube roots
  15512. of @i{-8} (as is @cite{(1., -1.732)}); Calc chooses a perhaps
  15513. less-obvious root for the sake of mathematical consistency.
  15514. For @samp{arcsin(z)}: This is defined by @samp{-i*ln(i*z + sqrt(1-z^2))}.
  15515. The branch cuts are on the real axis, less than @i{-1} and greater than 1.
  15516. For @samp{arccos(z)}: This is defined by @samp{-i*ln(z + i*sqrt(1-z^2))},
  15517. or equivalently by @samp{pi/2 - arcsin(z)}. The branch cuts are on
  15518. the real axis, less than @i{-1} and greater than 1.
  15519. For @samp{arctan(z)}: This is defined by
  15520. @samp{(ln(1+i*z) - ln(1-i*z)) / (2*i)}. The branch cuts are on the
  15521. imaginary axis, below @cite{-i} and above @cite{i}.
  15522. For @samp{arcsinh(z)}: This is defined by @samp{ln(z + sqrt(1+z^2))}.
  15523. The branch cuts are on the imaginary axis, below @cite{-i} and
  15524. above @cite{i}.
  15525. For @samp{arccosh(z)}: This is defined by
  15526. @samp{ln(z + (z+1)*sqrt((z-1)/(z+1)))}. The branch cut is on the
  15527. real axis less than 1.
  15528. For @samp{arctanh(z)}: This is defined by @samp{(ln(1+z) - ln(1-z)) / 2}.
  15529. The branch cuts are on the real axis, less than @i{-1} and greater than 1.
  15530. The following tables for @code{arcsin}, @code{arccos}, and
  15531. @code{arctan} assume the current angular mode is radians. The
  15532. hyperbolic functions operate independently of the angular mode.
  15533. @smallexample
  15534. z arcsin(z) arccos(z)
  15535. -------------------------------------------------------
  15536. (-1..1), 0 (-pi/2..pi/2), 0 (0..pi), 0
  15537. (-1..1), +eps (-pi/2..pi/2), +eps (0..pi), -eps
  15538. (-1..1), -eps (-pi/2..pi/2), -eps (0..pi), +eps
  15539. <-1, 0 -pi/2, + pi, -
  15540. <-1, +eps -pi/2 + eps, + pi - eps, -
  15541. <-1, -eps -pi/2 + eps, - pi - eps, +
  15542. >1, 0 pi/2, - 0, +
  15543. >1, +eps pi/2 - eps, + +eps, -
  15544. >1, -eps pi/2 - eps, - +eps, +
  15545. @end smallexample
  15546. @smallexample
  15547. z arccosh(z) arctanh(z)
  15548. -----------------------------------------------------
  15549. (-1..1), 0 0, (0..pi) any, 0
  15550. (-1..1), +eps +eps, (0..pi) any, +eps
  15551. (-1..1), -eps +eps, (-pi..0) any, -eps
  15552. <-1, 0 +, pi -, pi/2
  15553. <-1, +eps +, pi - eps -, pi/2 - eps
  15554. <-1, -eps +, -pi + eps -, -pi/2 + eps
  15555. >1, 0 +, 0 +, -pi/2
  15556. >1, +eps +, +eps +, pi/2 - eps
  15557. >1, -eps +, -eps +, -pi/2 + eps
  15558. @end smallexample
  15559. @smallexample
  15560. z arcsinh(z) arctan(z)
  15561. -----------------------------------------------------
  15562. 0, (-1..1) 0, (-pi/2..pi/2) 0, any
  15563. 0, <-1 -, -pi/2 -pi/2, -
  15564. +eps, <-1 +, -pi/2 + eps pi/2 - eps, -
  15565. -eps, <-1 -, -pi/2 + eps -pi/2 + eps, -
  15566. 0, >1 +, pi/2 pi/2, +
  15567. +eps, >1 +, pi/2 - eps pi/2 - eps, +
  15568. -eps, >1 -, pi/2 - eps -pi/2 + eps, +
  15569. @end smallexample
  15570. Finally, the following identities help to illustrate the relationship
  15571. between the complex trigonometric and hyperbolic functions. They
  15572. are valid everywhere, including on the branch cuts.
  15573. @smallexample
  15574. sin(i*z) = i*sinh(z) arcsin(i*z) = i*arcsinh(z)
  15575. cos(i*z) = cosh(z) arcsinh(i*z) = i*arcsin(z)
  15576. tan(i*z) = i*tanh(z) arctan(i*z) = i*arctanh(z)
  15577. sinh(i*z) = i*sin(z) cosh(i*z) = cos(z)
  15578. @end smallexample
  15579. The ``advanced math'' functions (gamma, Bessel, etc.@:) are also defined
  15580. for general complex arguments, but their branch cuts and principal values
  15581. are not rigorously specified at present.
  15582. @node Random Numbers, Combinatorial Functions, Branch Cuts, Scientific Functions
  15583. @section Random Numbers
  15584. @noindent
  15585. @kindex k r
  15586. @pindex calc-random
  15587. @tindex random
  15588. The @kbd{k r} (@code{calc-random}) [@code{random}] command produces
  15589. random numbers of various sorts.
  15590. Given a positive numeric prefix argument @cite{M}, it produces a random
  15591. integer @cite{N} in the range @c{$0 \le N < M$}
  15592. @cite{0 <= N < M}. Each of the @cite{M}
  15593. values appears with equal probability.@refill
  15594. With no numeric prefix argument, the @kbd{k r} command takes its argument
  15595. from the stack instead. Once again, if this is a positive integer @cite{M}
  15596. the result is a random integer less than @cite{M}. However, note that
  15597. while numeric prefix arguments are limited to six digits or so, an @cite{M}
  15598. taken from the stack can be arbitrarily large. If @cite{M} is negative,
  15599. the result is a random integer in the range @c{$M < N \le 0$}
  15600. @cite{M < N <= 0}.
  15601. If the value on the stack is a floating-point number @cite{M}, the result
  15602. is a random floating-point number @cite{N} in the range @c{$0 \le N < M$}
  15603. @cite{0 <= N < M}
  15604. or @c{$M < N \le 0$}
  15605. @cite{M < N <= 0}, according to the sign of @cite{M}.
  15606. If @cite{M} is zero, the result is a Gaussian-distributed random real
  15607. number; the distribution has a mean of zero and a standard deviation
  15608. of one. The algorithm used generates random numbers in pairs; thus,
  15609. every other call to this function will be especially fast.
  15610. If @cite{M} is an error form @c{$m$ @code{+/-} $\sigma$}
  15611. @samp{m +/- s} where @var{m}
  15612. and @c{$\sigma$}
  15613. @var{s} are both real numbers, the result uses a Gaussian
  15614. distribution with mean @var{m} and standard deviation @c{$\sigma$}
  15615. @var{s}.
  15616. If @cite{M} is an interval form, the lower and upper bounds specify the
  15617. acceptable limits of the random numbers. If both bounds are integers,
  15618. the result is a random integer in the specified range. If either bound
  15619. is floating-point, the result is a random real number in the specified
  15620. range. If the interval is open at either end, the result will be sure
  15621. not to equal that end value. (This makes a big difference for integer
  15622. intervals, but for floating-point intervals it's relatively minor:
  15623. with a precision of 6, @samp{random([1.0..2.0))} will return any of one
  15624. million numbers from 1.00000 to 1.99999; @samp{random([1.0..2.0])} may
  15625. additionally return 2.00000, but the probability of this happening is
  15626. extremely small.)
  15627. If @cite{M} is a vector, the result is one element taken at random from
  15628. the vector. All elements of the vector are given equal probabilities.
  15629. @vindex RandSeed
  15630. The sequence of numbers produced by @kbd{k r} is completely random by
  15631. default, i.e., the sequence is seeded each time you start Calc using
  15632. the current time and other information. You can get a reproducible
  15633. sequence by storing a particular ``seed value'' in the Calc variable
  15634. @code{RandSeed}. Any integer will do for a seed; integers of from 1
  15635. to 12 digits are good. If you later store a different integer into
  15636. @code{RandSeed}, Calc will switch to a different pseudo-random
  15637. sequence. If you ``unstore'' @code{RandSeed}, Calc will re-seed itself
  15638. from the current time. If you store the same integer that you used
  15639. before back into @code{RandSeed}, you will get the exact same sequence
  15640. of random numbers as before.
  15641. @pindex calc-rrandom
  15642. The @code{calc-rrandom} command (not on any key) produces a random real
  15643. number between zero and one. It is equivalent to @samp{random(1.0)}.
  15644. @kindex k a
  15645. @pindex calc-random-again
  15646. The @kbd{k a} (@code{calc-random-again}) command produces another random
  15647. number, re-using the most recent value of @cite{M}. With a numeric
  15648. prefix argument @var{n}, it produces @var{n} more random numbers using
  15649. that value of @cite{M}.
  15650. @kindex k h
  15651. @pindex calc-shuffle
  15652. @tindex shuffle
  15653. The @kbd{k h} (@code{calc-shuffle}) command produces a vector of several
  15654. random values with no duplicates. The value on the top of the stack
  15655. specifies the set from which the random values are drawn, and may be any
  15656. of the @cite{M} formats described above. The numeric prefix argument
  15657. gives the length of the desired list. (If you do not provide a numeric
  15658. prefix argument, the length of the list is taken from the top of the
  15659. stack, and @cite{M} from second-to-top.)
  15660. If @cite{M} is a floating-point number, zero, or an error form (so
  15661. that the random values are being drawn from the set of real numbers)
  15662. there is little practical difference between using @kbd{k h} and using
  15663. @kbd{k r} several times. But if the set of possible values consists
  15664. of just a few integers, or the elements of a vector, then there is
  15665. a very real chance that multiple @kbd{k r}'s will produce the same
  15666. number more than once. The @kbd{k h} command produces a vector whose
  15667. elements are always distinct. (Actually, there is a slight exception:
  15668. If @cite{M} is a vector, no given vector element will be drawn more
  15669. than once, but if several elements of @cite{M} are equal, they may
  15670. each make it into the result vector.)
  15671. One use of @kbd{k h} is to rearrange a list at random. This happens
  15672. if the prefix argument is equal to the number of values in the list:
  15673. @kbd{[1, 1.5, 2, 2.5, 3] 5 k h} might produce the permuted list
  15674. @samp{[2.5, 1, 1.5, 3, 2]}. As a convenient feature, if the argument
  15675. @var{n} is negative it is replaced by the size of the set represented
  15676. by @cite{M}. Naturally, this is allowed only when @cite{M} specifies
  15677. a small discrete set of possibilities.
  15678. To do the equivalent of @kbd{k h} but with duplications allowed,
  15679. given @cite{M} on the stack and with @var{n} just entered as a numeric
  15680. prefix, use @kbd{v b} to build a vector of copies of @cite{M}, then use
  15681. @kbd{V M k r} to ``map'' the normal @kbd{k r} function over the
  15682. elements of this vector. @xref{Matrix Functions}.
  15683. @menu
  15684. * Random Number Generator:: (Complete description of Calc's algorithm)
  15685. @end menu
  15686. @node Random Number Generator, , Random Numbers, Random Numbers
  15687. @subsection Random Number Generator
  15688. Calc's random number generator uses several methods to ensure that
  15689. the numbers it produces are highly random. Knuth's @emph{Art of
  15690. Computer Programming}, Volume II, contains a thorough description
  15691. of the theory of random number generators and their measurement and
  15692. characterization.
  15693. If @code{RandSeed} has no stored value, Calc calls Emacs' built-in
  15694. @code{random} function to get a stream of random numbers, which it
  15695. then treats in various ways to avoid problems inherent in the simple
  15696. random number generators that many systems use to implement @code{random}.
  15697. When Calc's random number generator is first invoked, it ``seeds''
  15698. the low-level random sequence using the time of day, so that the
  15699. random number sequence will be different every time you use Calc.
  15700. Since Emacs Lisp doesn't specify the range of values that will be
  15701. returned by its @code{random} function, Calc exercises the function
  15702. several times to estimate the range. When Calc subsequently uses
  15703. the @code{random} function, it takes only 10 bits of the result
  15704. near the most-significant end. (It avoids at least the bottom
  15705. four bits, preferably more, and also tries to avoid the top two
  15706. bits.) This strategy works well with the linear congruential
  15707. generators that are typically used to implement @code{random}.
  15708. If @code{RandSeed} contains an integer, Calc uses this integer to
  15709. seed an ``additive congruential'' method (Knuth's algorithm 3.2.2A,
  15710. computing @c{$X_{n-55} - X_{n-24}$}
  15711. @cite{X_n-55 - X_n-24}). This method expands the seed
  15712. value into a large table which is maintained internally; the variable
  15713. @code{RandSeed} is changed from, e.g., 42 to the vector @cite{[42]}
  15714. to indicate that the seed has been absorbed into this table. When
  15715. @code{RandSeed} contains a vector, @kbd{k r} and related commands
  15716. continue to use the same internal table as last time. There is no
  15717. way to extract the complete state of the random number generator
  15718. so that you can restart it from any point; you can only restart it
  15719. from the same initial seed value. A simple way to restart from the
  15720. same seed is to type @kbd{s r RandSeed} to get the seed vector,
  15721. @kbd{v u} to unpack it back into a number, then @kbd{s t RandSeed}
  15722. to reseed the generator with that number.
  15723. Calc uses a ``shuffling'' method as described in algorithm 3.2.2B
  15724. of Knuth. It fills a table with 13 random 10-bit numbers. Then,
  15725. to generate a new random number, it uses the previous number to
  15726. index into the table, picks the value it finds there as the new
  15727. random number, then replaces that table entry with a new value
  15728. obtained from a call to the base random number generator (either
  15729. the additive congruential generator or the @code{random} function
  15730. supplied by the system). If there are any flaws in the base
  15731. generator, shuffling will tend to even them out. But if the system
  15732. provides an excellent @code{random} function, shuffling will not
  15733. damage its randomness.
  15734. To create a random integer of a certain number of digits, Calc
  15735. builds the integer three decimal digits at a time. For each group
  15736. of three digits, Calc calls its 10-bit shuffling random number generator
  15737. (which returns a value from 0 to 1023); if the random value is 1000
  15738. or more, Calc throws it out and tries again until it gets a suitable
  15739. value.
  15740. To create a random floating-point number with precision @var{p}, Calc
  15741. simply creates a random @var{p}-digit integer and multiplies by
  15742. @c{$10^{-p}$}
  15743. @cite{10^-p}. The resulting random numbers should be very clean, but note
  15744. that relatively small numbers will have few significant random digits.
  15745. In other words, with a precision of 12, you will occasionally get
  15746. numbers on the order of @c{$10^{-9}$}
  15747. @cite{10^-9} or @c{$10^{-10}$}
  15748. @cite{10^-10}, but those numbers
  15749. will only have two or three random digits since they correspond to small
  15750. integers times @c{$10^{-12}$}
  15751. @cite{10^-12}.
  15752. To create a random integer in the interval @samp{[0 .. @var{m})}, Calc
  15753. counts the digits in @var{m}, creates a random integer with three
  15754. additional digits, then reduces modulo @var{m}. Unless @var{m} is a
  15755. power of ten the resulting values will be very slightly biased toward
  15756. the lower numbers, but this bias will be less than 0.1%. (For example,
  15757. if @var{m} is 42, Calc will reduce a random integer less than 100000
  15758. modulo 42 to get a result less than 42. It is easy to show that the
  15759. numbers 40 and 41 will be only 2380/2381 as likely to result from this
  15760. modulo operation as numbers 39 and below.) If @var{m} is a power of
  15761. ten, however, the numbers should be completely unbiased.
  15762. The Gaussian random numbers generated by @samp{random(0.0)} use the
  15763. ``polar'' method described in Knuth section 3.4.1C. This method
  15764. generates a pair of Gaussian random numbers at a time, so only every
  15765. other call to @samp{random(0.0)} will require significant calculations.
  15766. @node Combinatorial Functions, Probability Distribution Functions, Random Numbers, Scientific Functions
  15767. @section Combinatorial Functions
  15768. @noindent
  15769. Commands relating to combinatorics and number theory begin with the
  15770. @kbd{k} key prefix.
  15771. @kindex k g
  15772. @pindex calc-gcd
  15773. @tindex gcd
  15774. The @kbd{k g} (@code{calc-gcd}) [@code{gcd}] command computes the
  15775. Greatest Common Divisor of two integers. It also accepts fractions;
  15776. the GCD of two fractions is defined by taking the GCD of the
  15777. numerators, and the LCM of the denominators. This definition is
  15778. consistent with the idea that @samp{a / gcd(a,x)} should yield an
  15779. integer for any @samp{a} and @samp{x}. For other types of arguments,
  15780. the operation is left in symbolic form.@refill
  15781. @kindex k l
  15782. @pindex calc-lcm
  15783. @tindex lcm
  15784. The @kbd{k l} (@code{calc-lcm}) [@code{lcm}] command computes the
  15785. Least Common Multiple of two integers or fractions. The product of
  15786. the LCM and GCD of two numbers is equal to the product of the
  15787. numbers.@refill
  15788. @kindex k E
  15789. @pindex calc-extended-gcd
  15790. @tindex egcd
  15791. The @kbd{k E} (@code{calc-extended-gcd}) [@code{egcd}] command computes
  15792. the GCD of two integers @cite{x} and @cite{y} and returns a vector
  15793. @cite{[g, a, b]} where @c{$g = \gcd(x,y) = a x + b y$}
  15794. @cite{g = gcd(x,y) = a x + b y}.
  15795. @kindex !
  15796. @pindex calc-factorial
  15797. @tindex fact
  15798. @ignore
  15799. @mindex @null
  15800. @end ignore
  15801. @tindex !
  15802. The @kbd{!} (@code{calc-factorial}) [@code{fact}] command computes the
  15803. factorial of the number at the top of the stack. If the number is an
  15804. integer, the result is an exact integer. If the number is an
  15805. integer-valued float, the result is a floating-point approximation. If
  15806. the number is a non-integral real number, the generalized factorial is used,
  15807. as defined by the Euler Gamma function. Please note that computation of
  15808. large factorials can be slow; using floating-point format will help
  15809. since fewer digits must be maintained. The same is true of many of
  15810. the commands in this section.@refill
  15811. @kindex k d
  15812. @pindex calc-double-factorial
  15813. @tindex dfact
  15814. @ignore
  15815. @mindex @null
  15816. @end ignore
  15817. @tindex !!
  15818. The @kbd{k d} (@code{calc-double-factorial}) [@code{dfact}] command
  15819. computes the ``double factorial'' of an integer. For an even integer,
  15820. this is the product of even integers from 2 to @cite{N}. For an odd
  15821. integer, this is the product of odd integers from 3 to @cite{N}. If
  15822. the argument is an integer-valued float, the result is a floating-point
  15823. approximation. This function is undefined for negative even integers.
  15824. The notation @cite{N!!} is also recognized for double factorials.@refill
  15825. @kindex k c
  15826. @pindex calc-choose
  15827. @tindex choose
  15828. The @kbd{k c} (@code{calc-choose}) [@code{choose}] command computes the
  15829. binomial coefficient @cite{N}-choose-@cite{M}, where @cite{M} is the number
  15830. on the top of the stack and @cite{N} is second-to-top. If both arguments
  15831. are integers, the result is an exact integer. Otherwise, the result is a
  15832. floating-point approximation. The binomial coefficient is defined for all
  15833. real numbers by @c{$N! \over M! (N-M)!\,$}
  15834. @cite{N! / M! (N-M)!}.
  15835. @kindex H k c
  15836. @pindex calc-perm
  15837. @tindex perm
  15838. @ifinfo
  15839. The @kbd{H k c} (@code{calc-perm}) [@code{perm}] command computes the
  15840. number-of-permutations function @cite{N! / (N-M)!}.
  15841. @end ifinfo
  15842. @tex
  15843. The \kbd{H k c} (\code{calc-perm}) [\code{perm}] command computes the
  15844. number-of-perm\-utations function $N! \over (N-M)!\,$.
  15845. @end tex
  15846. @kindex k b
  15847. @kindex H k b
  15848. @pindex calc-bernoulli-number
  15849. @tindex bern
  15850. The @kbd{k b} (@code{calc-bernoulli-number}) [@code{bern}] command
  15851. computes a given Bernoulli number. The value at the top of the stack
  15852. is a nonnegative integer @cite{n} that specifies which Bernoulli number
  15853. is desired. The @kbd{H k b} command computes a Bernoulli polynomial,
  15854. taking @cite{n} from the second-to-top position and @cite{x} from the
  15855. top of the stack. If @cite{x} is a variable or formula the result is
  15856. a polynomial in @cite{x}; if @cite{x} is a number the result is a number.
  15857. @kindex k e
  15858. @kindex H k e
  15859. @pindex calc-euler-number
  15860. @tindex euler
  15861. The @kbd{k e} (@code{calc-euler-number}) [@code{euler}] command similarly
  15862. computes an Euler number, and @w{@kbd{H k e}} computes an Euler polynomial.
  15863. Bernoulli and Euler numbers occur in the Taylor expansions of several
  15864. functions.
  15865. @kindex k s
  15866. @kindex H k s
  15867. @pindex calc-stirling-number
  15868. @tindex stir1
  15869. @tindex stir2
  15870. The @kbd{k s} (@code{calc-stirling-number}) [@code{stir1}] command
  15871. computes a Stirling number of the first kind@c{ $n \brack m$}
  15872. @asis{}, given two integers
  15873. @cite{n} and @cite{m} on the stack. The @kbd{H k s} [@code{stir2}]
  15874. command computes a Stirling number of the second kind@c{ $n \brace m$}
  15875. @asis{}. These are
  15876. the number of @cite{m}-cycle permutations of @cite{n} objects, and
  15877. the number of ways to partition @cite{n} objects into @cite{m}
  15878. non-empty sets, respectively.
  15879. @kindex k p
  15880. @pindex calc-prime-test
  15881. @cindex Primes
  15882. The @kbd{k p} (@code{calc-prime-test}) command checks if the integer on
  15883. the top of the stack is prime. For integers less than eight million, the
  15884. answer is always exact and reasonably fast. For larger integers, a
  15885. probabilistic method is used (see Knuth vol. II, section 4.5.4, algorithm P).
  15886. The number is first checked against small prime factors (up to 13). Then,
  15887. any number of iterations of the algorithm are performed. Each step either
  15888. discovers that the number is non-prime, or substantially increases the
  15889. certainty that the number is prime. After a few steps, the chance that
  15890. a number was mistakenly described as prime will be less than one percent.
  15891. (Indeed, this is a worst-case estimate of the probability; in practice
  15892. even a single iteration is quite reliable.) After the @kbd{k p} command,
  15893. the number will be reported as definitely prime or non-prime if possible,
  15894. or otherwise ``probably'' prime with a certain probability of error.
  15895. @ignore
  15896. @starindex
  15897. @end ignore
  15898. @tindex prime
  15899. The normal @kbd{k p} command performs one iteration of the primality
  15900. test. Pressing @kbd{k p} repeatedly for the same integer will perform
  15901. additional iterations. Also, @kbd{k p} with a numeric prefix performs
  15902. the specified number of iterations. There is also an algebraic function
  15903. @samp{prime(n)} or @samp{prime(n,iters)} which returns 1 if @cite{n}
  15904. is (probably) prime and 0 if not.
  15905. @kindex k f
  15906. @pindex calc-prime-factors
  15907. @tindex prfac
  15908. The @kbd{k f} (@code{calc-prime-factors}) [@code{prfac}] command
  15909. attempts to decompose an integer into its prime factors. For numbers up
  15910. to 25 million, the answer is exact although it may take some time. The
  15911. result is a vector of the prime factors in increasing order. For larger
  15912. inputs, prime factors above 5000 may not be found, in which case the
  15913. last number in the vector will be an unfactored integer greater than 25
  15914. million (with a warning message). For negative integers, the first
  15915. element of the list will be @i{-1}. For inputs @i{-1}, @i{0}, and
  15916. @i{1}, the result is a list of the same number.
  15917. @kindex k n
  15918. @pindex calc-next-prime
  15919. @ignore
  15920. @mindex nextpr@idots
  15921. @end ignore
  15922. @tindex nextprime
  15923. The @kbd{k n} (@code{calc-next-prime}) [@code{nextprime}] command finds
  15924. the next prime above a given number. Essentially, it searches by calling
  15925. @code{calc-prime-test} on successive integers until it finds one that
  15926. passes the test. This is quite fast for integers less than eight million,
  15927. but once the probabilistic test comes into play the search may be rather
  15928. slow. Ordinarily this command stops for any prime that passes one iteration
  15929. of the primality test. With a numeric prefix argument, a number must pass
  15930. the specified number of iterations before the search stops. (This only
  15931. matters when searching above eight million.) You can always use additional
  15932. @kbd{k p} commands to increase your certainty that the number is indeed
  15933. prime.
  15934. @kindex I k n
  15935. @pindex calc-prev-prime
  15936. @ignore
  15937. @mindex prevpr@idots
  15938. @end ignore
  15939. @tindex prevprime
  15940. The @kbd{I k n} (@code{calc-prev-prime}) [@code{prevprime}] command
  15941. analogously finds the next prime less than a given number.
  15942. @kindex k t
  15943. @pindex calc-totient
  15944. @tindex totient
  15945. The @kbd{k t} (@code{calc-totient}) [@code{totient}] command computes the
  15946. Euler ``totient'' function@c{ $\phi(n)$}
  15947. @asis{}, the number of integers less than @cite{n} which
  15948. are relatively prime to @cite{n}.
  15949. @kindex k m
  15950. @pindex calc-moebius
  15951. @tindex moebius
  15952. The @kbd{k m} (@code{calc-moebius}) [@code{moebius}] command computes the
  15953. @c{M\"obius $\mu$}
  15954. @asis{Moebius ``mu''} function. If the input number is a product of @cite{k}
  15955. distinct factors, this is @cite{(-1)^k}. If the input number has any
  15956. duplicate factors (i.e., can be divided by the same prime more than once),
  15957. the result is zero.
  15958. @node Probability Distribution Functions, , Combinatorial Functions, Scientific Functions
  15959. @section Probability Distribution Functions
  15960. @noindent
  15961. The functions in this section compute various probability distributions.
  15962. For continuous distributions, this is the integral of the probability
  15963. density function from @cite{x} to infinity. (These are the ``upper
  15964. tail'' distribution functions; there are also corresponding ``lower
  15965. tail'' functions which integrate from minus infinity to @cite{x}.)
  15966. For discrete distributions, the upper tail function gives the sum
  15967. from @cite{x} to infinity; the lower tail function gives the sum
  15968. from minus infinity up to, but not including,@w{ }@cite{x}.
  15969. To integrate from @cite{x} to @cite{y}, just use the distribution
  15970. function twice and subtract. For example, the probability that a
  15971. Gaussian random variable with mean 2 and standard deviation 1 will
  15972. lie in the range from 2.5 to 2.8 is @samp{utpn(2.5,2,1) - utpn(2.8,2,1)}
  15973. (``the probability that it is greater than 2.5, but not greater than 2.8''),
  15974. or equivalently @samp{ltpn(2.8,2,1) - ltpn(2.5,2,1)}.
  15975. @kindex k B
  15976. @kindex I k B
  15977. @pindex calc-utpb
  15978. @tindex utpb
  15979. @tindex ltpb
  15980. The @kbd{k B} (@code{calc-utpb}) [@code{utpb}] function uses the
  15981. binomial distribution. Push the parameters @var{n}, @var{p}, and
  15982. then @var{x} onto the stack; the result (@samp{utpb(x,n,p)}) is the
  15983. probability that an event will occur @var{x} or more times out
  15984. of @var{n} trials, if its probability of occurring in any given
  15985. trial is @var{p}. The @kbd{I k B} [@code{ltpb}] function is
  15986. the probability that the event will occur fewer than @var{x} times.
  15987. The other probability distribution functions similarly take the
  15988. form @kbd{k @var{X}} (@code{calc-utp@var{x}}) [@code{utp@var{x}}]
  15989. and @kbd{I k @var{X}} [@code{ltp@var{x}}], for various letters
  15990. @var{x}. The arguments to the algebraic functions are the value of
  15991. the random variable first, then whatever other parameters define the
  15992. distribution. Note these are among the few Calc functions where the
  15993. order of the arguments in algebraic form differs from the order of
  15994. arguments as found on the stack. (The random variable comes last on
  15995. the stack, so that you can type, e.g., @kbd{2 @key{RET} 1 @key{RET} 2.5
  15996. k N M-@key{RET} @key{DEL} 2.8 k N -}, using @kbd{M-@key{RET} @key{DEL}} to
  15997. recover the original arguments but substitute a new value for @cite{x}.)
  15998. @kindex k C
  15999. @pindex calc-utpc
  16000. @tindex utpc
  16001. @ignore
  16002. @mindex @idots
  16003. @end ignore
  16004. @kindex I k C
  16005. @ignore
  16006. @mindex @null
  16007. @end ignore
  16008. @tindex ltpc
  16009. The @samp{utpc(x,v)} function uses the chi-square distribution with
  16010. @c{$\nu$}
  16011. @cite{v} degrees of freedom. It is the probability that a model is
  16012. correct if its chi-square statistic is @cite{x}.
  16013. @kindex k F
  16014. @pindex calc-utpf
  16015. @tindex utpf
  16016. @ignore
  16017. @mindex @idots
  16018. @end ignore
  16019. @kindex I k F
  16020. @ignore
  16021. @mindex @null
  16022. @end ignore
  16023. @tindex ltpf
  16024. The @samp{utpf(F,v1,v2)} function uses the F distribution, used in
  16025. various statistical tests. The parameters @c{$\nu_1$}
  16026. @cite{v1} and @c{$\nu_2$}
  16027. @cite{v2}
  16028. are the degrees of freedom in the numerator and denominator,
  16029. respectively, used in computing the statistic @cite{F}.
  16030. @kindex k N
  16031. @pindex calc-utpn
  16032. @tindex utpn
  16033. @ignore
  16034. @mindex @idots
  16035. @end ignore
  16036. @kindex I k N
  16037. @ignore
  16038. @mindex @null
  16039. @end ignore
  16040. @tindex ltpn
  16041. The @samp{utpn(x,m,s)} function uses a normal (Gaussian) distribution
  16042. with mean @cite{m} and standard deviation @c{$\sigma$}
  16043. @cite{s}. It is the
  16044. probability that such a normal-distributed random variable would
  16045. exceed @cite{x}.
  16046. @kindex k P
  16047. @pindex calc-utpp
  16048. @tindex utpp
  16049. @ignore
  16050. @mindex @idots
  16051. @end ignore
  16052. @kindex I k P
  16053. @ignore
  16054. @mindex @null
  16055. @end ignore
  16056. @tindex ltpp
  16057. The @samp{utpp(n,x)} function uses a Poisson distribution with
  16058. mean @cite{x}. It is the probability that @cite{n} or more such
  16059. Poisson random events will occur.
  16060. @kindex k T
  16061. @pindex calc-ltpt
  16062. @tindex utpt
  16063. @ignore
  16064. @mindex @idots
  16065. @end ignore
  16066. @kindex I k T
  16067. @ignore
  16068. @mindex @null
  16069. @end ignore
  16070. @tindex ltpt
  16071. The @samp{utpt(t,v)} function uses the Student's ``t'' distribution
  16072. with @c{$\nu$}
  16073. @cite{v} degrees of freedom. It is the probability that a
  16074. t-distributed random variable will be greater than @cite{t}.
  16075. (Note: This computes the distribution function @c{$A(t|\nu)$}
  16076. @cite{A(t|v)}
  16077. where @c{$A(0|\nu) = 1$}
  16078. @cite{A(0|v) = 1} and @c{$A(\infty|\nu) \to 0$}
  16079. @cite{A(inf|v) -> 0}. The
  16080. @code{UTPT} operation on the HP-48 uses a different definition
  16081. which returns half of Calc's value: @samp{UTPT(t,v) = .5*utpt(t,v)}.)
  16082. While Calc does not provide inverses of the probability distribution
  16083. functions, the @kbd{a R} command can be used to solve for the inverse.
  16084. Since the distribution functions are monotonic, @kbd{a R} is guaranteed
  16085. to be able to find a solution given any initial guess.
  16086. @xref{Numerical Solutions}.
  16087. @node Matrix Functions, Algebra, Scientific Functions, Top
  16088. @chapter Vector/Matrix Functions
  16089. @noindent
  16090. Many of the commands described here begin with the @kbd{v} prefix.
  16091. (For convenience, the shift-@kbd{V} prefix is equivalent to @kbd{v}.)
  16092. The commands usually apply to both plain vectors and matrices; some
  16093. apply only to matrices or only to square matrices. If the argument
  16094. has the wrong dimensions the operation is left in symbolic form.
  16095. Vectors are entered and displayed using @samp{[a,b,c]} notation.
  16096. Matrices are vectors of which all elements are vectors of equal length.
  16097. (Though none of the standard Calc commands use this concept, a
  16098. three-dimensional matrix or rank-3 tensor could be defined as a
  16099. vector of matrices, and so on.)
  16100. @menu
  16101. * Packing and Unpacking::
  16102. * Building Vectors::
  16103. * Extracting Elements::
  16104. * Manipulating Vectors::
  16105. * Vector and Matrix Arithmetic::
  16106. * Set Operations::
  16107. * Statistical Operations::
  16108. * Reducing and Mapping::
  16109. * Vector and Matrix Formats::
  16110. @end menu
  16111. @node Packing and Unpacking, Building Vectors, Matrix Functions, Matrix Functions
  16112. @section Packing and Unpacking
  16113. @noindent
  16114. Calc's ``pack'' and ``unpack'' commands collect stack entries to build
  16115. composite objects such as vectors and complex numbers. They are
  16116. described in this chapter because they are most often used to build
  16117. vectors.
  16118. @kindex v p
  16119. @pindex calc-pack
  16120. The @kbd{v p} (@code{calc-pack}) [@code{pack}] command collects several
  16121. elements from the stack into a matrix, complex number, HMS form, error
  16122. form, etc. It uses a numeric prefix argument to specify the kind of
  16123. object to be built; this argument is referred to as the ``packing mode.''
  16124. If the packing mode is a nonnegative integer, a vector of that
  16125. length is created. For example, @kbd{C-u 5 v p} will pop the top
  16126. five stack elements and push back a single vector of those five
  16127. elements. (@kbd{C-u 0 v p} simply creates an empty vector.)
  16128. The same effect can be had by pressing @kbd{[} to push an incomplete
  16129. vector on the stack, using @key{TAB} (@code{calc-roll-down}) to sneak
  16130. the incomplete object up past a certain number of elements, and
  16131. then pressing @kbd{]} to complete the vector.
  16132. Negative packing modes create other kinds of composite objects:
  16133. @table @cite
  16134. @item -1
  16135. Two values are collected to build a complex number. For example,
  16136. @kbd{5 @key{RET} 7 C-u -1 v p} creates the complex number
  16137. @cite{(5, 7)}. The result is always a rectangular complex
  16138. number. The two input values must both be real numbers,
  16139. i.e., integers, fractions, or floats. If they are not, Calc
  16140. will instead build a formula like @samp{a + (0, 1) b}. (The
  16141. other packing modes also create a symbolic answer if the
  16142. components are not suitable.)
  16143. @item -2
  16144. Two values are collected to build a polar complex number.
  16145. The first is the magnitude; the second is the phase expressed
  16146. in either degrees or radians according to the current angular
  16147. mode.
  16148. @item -3
  16149. Three values are collected into an HMS form. The first
  16150. two values (hours and minutes) must be integers or
  16151. integer-valued floats. The third value may be any real
  16152. number.
  16153. @item -4
  16154. Two values are collected into an error form. The inputs
  16155. may be real numbers or formulas.
  16156. @item -5
  16157. Two values are collected into a modulo form. The inputs
  16158. must be real numbers.
  16159. @item -6
  16160. Two values are collected into the interval @samp{[a .. b]}.
  16161. The inputs may be real numbers, HMS or date forms, or formulas.
  16162. @item -7
  16163. Two values are collected into the interval @samp{[a .. b)}.
  16164. @item -8
  16165. Two values are collected into the interval @samp{(a .. b]}.
  16166. @item -9
  16167. Two values are collected into the interval @samp{(a .. b)}.
  16168. @item -10
  16169. Two integer values are collected into a fraction.
  16170. @item -11
  16171. Two values are collected into a floating-point number.
  16172. The first is the mantissa; the second, which must be an
  16173. integer, is the exponent. The result is the mantissa
  16174. times ten to the power of the exponent.
  16175. @item -12
  16176. This is treated the same as @i{-11} by the @kbd{v p} command.
  16177. When unpacking, @i{-12} specifies that a floating-point mantissa
  16178. is desired.
  16179. @item -13
  16180. A real number is converted into a date form.
  16181. @item -14
  16182. Three numbers (year, month, day) are packed into a pure date form.
  16183. @item -15
  16184. Six numbers are packed into a date/time form.
  16185. @end table
  16186. With any of the two-input negative packing modes, either or both
  16187. of the inputs may be vectors. If both are vectors of the same
  16188. length, the result is another vector made by packing corresponding
  16189. elements of the input vectors. If one input is a vector and the
  16190. other is a plain number, the number is packed along with each vector
  16191. element to produce a new vector. For example, @kbd{C-u -4 v p}
  16192. could be used to convert a vector of numbers and a vector of errors
  16193. into a single vector of error forms; @kbd{C-u -5 v p} could convert
  16194. a vector of numbers and a single number @var{M} into a vector of
  16195. numbers modulo @var{M}.
  16196. If you don't give a prefix argument to @kbd{v p}, it takes
  16197. the packing mode from the top of the stack. The elements to
  16198. be packed then begin at stack level 2. Thus
  16199. @kbd{1 @key{RET} 2 @key{RET} 4 n v p} is another way to
  16200. enter the error form @samp{1 +/- 2}.
  16201. If the packing mode taken from the stack is a vector, the result is a
  16202. matrix with the dimensions specified by the elements of the vector,
  16203. which must each be integers. For example, if the packing mode is
  16204. @samp{[2, 3]}, then six numbers will be taken from the stack and
  16205. returned in the form @samp{[@w{[a, b, c]}, [d, e, f]]}.
  16206. If any elements of the vector are negative, other kinds of
  16207. packing are done at that level as described above. For
  16208. example, @samp{[2, 3, -4]} takes 12 objects and creates a
  16209. @c{$2\times3$}
  16210. @asis{2x3} matrix of error forms: @samp{[[a +/- b, c +/- d ... ]]}.
  16211. Also, @samp{[-4, -10]} will convert four integers into an
  16212. error form consisting of two fractions: @samp{a:b +/- c:d}.
  16213. @ignore
  16214. @starindex
  16215. @end ignore
  16216. @tindex pack
  16217. There is an equivalent algebraic function,
  16218. @samp{pack(@var{mode}, @var{items})} where @var{mode} is a
  16219. packing mode (an integer or a vector of integers) and @var{items}
  16220. is a vector of objects to be packed (re-packed, really) according
  16221. to that mode. For example, @samp{pack([3, -4], [a,b,c,d,e,f])}
  16222. yields @samp{[a +/- b, @w{c +/- d}, e +/- f]}. The function is
  16223. left in symbolic form if the packing mode is illegal, or if the
  16224. number of data items does not match the number of items required
  16225. by the mode.
  16226. @kindex v u
  16227. @pindex calc-unpack
  16228. The @kbd{v u} (@code{calc-unpack}) command takes the vector, complex
  16229. number, HMS form, or other composite object on the top of the stack and
  16230. ``unpacks'' it, pushing each of its elements onto the stack as separate
  16231. objects. Thus, it is the ``inverse'' of @kbd{v p}. If the value
  16232. at the top of the stack is a formula, @kbd{v u} unpacks it by pushing
  16233. each of the arguments of the top-level operator onto the stack.
  16234. You can optionally give a numeric prefix argument to @kbd{v u}
  16235. to specify an explicit (un)packing mode. If the packing mode is
  16236. negative and the input is actually a vector or matrix, the result
  16237. will be two or more similar vectors or matrices of the elements.
  16238. For example, given the vector @samp{[@w{a +/- b}, c^2, d +/- 7]},
  16239. the result of @kbd{C-u -4 v u} will be the two vectors
  16240. @samp{[a, c^2, d]} and @w{@samp{[b, 0, 7]}}.
  16241. Note that the prefix argument can have an effect even when the input is
  16242. not a vector. For example, if the input is the number @i{-5}, then
  16243. @kbd{c-u -1 v u} yields @i{-5} and 0 (the components of @i{-5}
  16244. when viewed as a rectangular complex number); @kbd{C-u -2 v u} yields 5
  16245. and 180 (assuming degrees mode); and @kbd{C-u -10 v u} yields @i{-5}
  16246. and 1 (the numerator and denominator of @i{-5}, viewed as a rational
  16247. number). Plain @kbd{v u} with this input would complain that the input
  16248. is not a composite object.
  16249. Unpacking mode @i{-11} converts a float into an integer mantissa and
  16250. an integer exponent, where the mantissa is not divisible by 10
  16251. (except that 0.0 is represented by a mantissa and exponent of 0).
  16252. Unpacking mode @i{-12} converts a float into a floating-point mantissa
  16253. and integer exponent, where the mantissa (for non-zero numbers)
  16254. is guaranteed to lie in the range [1 .. 10). In both cases,
  16255. the mantissa is shifted left or right (and the exponent adjusted
  16256. to compensate) in order to satisfy these constraints.
  16257. Positive unpacking modes are treated differently than for @kbd{v p}.
  16258. A mode of 1 is much like plain @kbd{v u} with no prefix argument,
  16259. except that in addition to the components of the input object,
  16260. a suitable packing mode to re-pack the object is also pushed.
  16261. Thus, @kbd{C-u 1 v u} followed by @kbd{v p} will re-build the
  16262. original object.
  16263. A mode of 2 unpacks two levels of the object; the resulting
  16264. re-packing mode will be a vector of length 2. This might be used
  16265. to unpack a matrix, say, or a vector of error forms. Higher
  16266. unpacking modes unpack the input even more deeply.
  16267. @ignore
  16268. @starindex
  16269. @end ignore
  16270. @tindex unpack
  16271. There are two algebraic functions analogous to @kbd{v u}.
  16272. The @samp{unpack(@var{mode}, @var{item})} function unpacks the
  16273. @var{item} using the given @var{mode}, returning the result as
  16274. a vector of components. Here the @var{mode} must be an
  16275. integer, not a vector. For example, @samp{unpack(-4, a +/- b)}
  16276. returns @samp{[a, b]}, as does @samp{unpack(1, a +/- b)}.
  16277. @ignore
  16278. @starindex
  16279. @end ignore
  16280. @tindex unpackt
  16281. The @code{unpackt} function is like @code{unpack} but instead
  16282. of returning a simple vector of items, it returns a vector of
  16283. two things: The mode, and the vector of items. For example,
  16284. @samp{unpackt(1, 2:3 +/- 1:4)} returns @samp{[-4, [2:3, 1:4]]},
  16285. and @samp{unpackt(2, 2:3 +/- 1:4)} returns @samp{[[-4, -10], [2, 3, 1, 4]]}.
  16286. The identity for re-building the original object is
  16287. @samp{apply(pack, unpackt(@var{n}, @var{x})) = @var{x}}. (The
  16288. @code{apply} function builds a function call given the function
  16289. name and a vector of arguments.)
  16290. @cindex Numerator of a fraction, extracting
  16291. Subscript notation is a useful way to extract a particular part
  16292. of an object. For example, to get the numerator of a rational
  16293. number, you can use @samp{unpack(-10, @var{x})_1}.
  16294. @node Building Vectors, Extracting Elements, Packing and Unpacking, Matrix Functions
  16295. @section Building Vectors
  16296. @noindent
  16297. Vectors and matrices can be added,
  16298. subtracted, multiplied, and divided; @pxref{Basic Arithmetic}.@refill
  16299. @kindex |
  16300. @pindex calc-concat
  16301. @ignore
  16302. @mindex @null
  16303. @end ignore
  16304. @tindex |
  16305. The @kbd{|} (@code{calc-concat}) command ``concatenates'' two vectors
  16306. into one. For example, after @kbd{@w{[ 1 , 2 ]} [ 3 , 4 ] |}, the stack
  16307. will contain the single vector @samp{[1, 2, 3, 4]}. If the arguments
  16308. are matrices, the rows of the first matrix are concatenated with the
  16309. rows of the second. (In other words, two matrices are just two vectors
  16310. of row-vectors as far as @kbd{|} is concerned.)
  16311. If either argument to @kbd{|} is a scalar (a non-vector), it is treated
  16312. like a one-element vector for purposes of concatenation: @kbd{1 [ 2 , 3 ] |}
  16313. produces the vector @samp{[1, 2, 3]}. Likewise, if one argument is a
  16314. matrix and the other is a plain vector, the vector is treated as a
  16315. one-row matrix.
  16316. @kindex H |
  16317. @tindex append
  16318. The @kbd{H |} (@code{calc-append}) [@code{append}] command concatenates
  16319. two vectors without any special cases. Both inputs must be vectors.
  16320. Whether or not they are matrices is not taken into account. If either
  16321. argument is a scalar, the @code{append} function is left in symbolic form.
  16322. See also @code{cons} and @code{rcons} below.
  16323. @kindex I |
  16324. @kindex H I |
  16325. The @kbd{I |} and @kbd{H I |} commands are similar, but they use their
  16326. two stack arguments in the opposite order. Thus @kbd{I |} is equivalent
  16327. to @kbd{@key{TAB} |}, but possibly more convenient and also a bit faster.
  16328. @kindex v d
  16329. @pindex calc-diag
  16330. @tindex diag
  16331. The @kbd{v d} (@code{calc-diag}) [@code{diag}] function builds a diagonal
  16332. square matrix. The optional numeric prefix gives the number of rows
  16333. and columns in the matrix. If the value at the top of the stack is a
  16334. vector, the elements of the vector are used as the diagonal elements; the
  16335. prefix, if specified, must match the size of the vector. If the value on
  16336. the stack is a scalar, it is used for each element on the diagonal, and
  16337. the prefix argument is required.
  16338. To build a constant square matrix, e.g., a @c{$3\times3$}
  16339. @asis{3x3} matrix filled with ones,
  16340. use @kbd{0 M-3 v d 1 +}, i.e., build a zero matrix first and then add a
  16341. constant value to that matrix. (Another alternative would be to use
  16342. @kbd{v b} and @kbd{v a}; see below.)
  16343. @kindex v i
  16344. @pindex calc-ident
  16345. @tindex idn
  16346. The @kbd{v i} (@code{calc-ident}) [@code{idn}] function builds an identity
  16347. matrix of the specified size. It is a convenient form of @kbd{v d}
  16348. where the diagonal element is always one. If no prefix argument is given,
  16349. this command prompts for one.
  16350. In algebraic notation, @samp{idn(a,n)} acts much like @samp{diag(a,n)},
  16351. except that @cite{a} is required to be a scalar (non-vector) quantity.
  16352. If @cite{n} is omitted, @samp{idn(a)} represents @cite{a} times an
  16353. identity matrix of unknown size. Calc can operate algebraically on
  16354. such generic identity matrices, and if one is combined with a matrix
  16355. whose size is known, it is converted automatically to an identity
  16356. matrix of a suitable matching size. The @kbd{v i} command with an
  16357. argument of zero creates a generic identity matrix, @samp{idn(1)}.
  16358. Note that in dimensioned matrix mode (@pxref{Matrix Mode}), generic
  16359. identity matrices are immediately expanded to the current default
  16360. dimensions.
  16361. @kindex v x
  16362. @pindex calc-index
  16363. @tindex index
  16364. The @kbd{v x} (@code{calc-index}) [@code{index}] function builds a vector
  16365. of consecutive integers from 1 to @var{n}, where @var{n} is the numeric
  16366. prefix argument. If you do not provide a prefix argument, you will be
  16367. prompted to enter a suitable number. If @var{n} is negative, the result
  16368. is a vector of negative integers from @var{n} to @i{-1}.
  16369. With a prefix argument of just @kbd{C-u}, the @kbd{v x} command takes
  16370. three values from the stack: @var{n}, @var{start}, and @var{incr} (with
  16371. @var{incr} at top-of-stack). Counting starts at @var{start} and increases
  16372. by @var{incr} for successive vector elements. If @var{start} or @var{n}
  16373. is in floating-point format, the resulting vector elements will also be
  16374. floats. Note that @var{start} and @var{incr} may in fact be any kind
  16375. of numbers or formulas.
  16376. When @var{start} and @var{incr} are specified, a negative @var{n} has a
  16377. different interpretation: It causes a geometric instead of arithmetic
  16378. sequence to be generated. For example, @samp{index(-3, a, b)} produces
  16379. @samp{[a, a b, a b^2]}. If you omit @var{incr} in the algebraic form,
  16380. @samp{index(@var{n}, @var{start})}, the default value for @var{incr}
  16381. is one for positive @var{n} or two for negative @var{n}.
  16382. @kindex v b
  16383. @pindex calc-build-vector
  16384. @tindex cvec
  16385. The @kbd{v b} (@code{calc-build-vector}) [@code{cvec}] function builds a
  16386. vector of @var{n} copies of the value on the top of the stack, where @var{n}
  16387. is the numeric prefix argument. In algebraic formulas, @samp{cvec(x,n,m)}
  16388. can also be used to build an @var{n}-by-@var{m} matrix of copies of @var{x}.
  16389. (Interactively, just use @kbd{v b} twice: once to build a row, then again
  16390. to build a matrix of copies of that row.)
  16391. @kindex v h
  16392. @kindex I v h
  16393. @pindex calc-head
  16394. @pindex calc-tail
  16395. @tindex head
  16396. @tindex tail
  16397. The @kbd{v h} (@code{calc-head}) [@code{head}] function returns the first
  16398. element of a vector. The @kbd{I v h} (@code{calc-tail}) [@code{tail}]
  16399. function returns the vector with its first element removed. In both
  16400. cases, the argument must be a non-empty vector.
  16401. @kindex v k
  16402. @pindex calc-cons
  16403. @tindex cons
  16404. The @kbd{v k} (@code{calc-cons}) [@code{cons}] function takes a value @var{h}
  16405. and a vector @var{t} from the stack, and produces the vector whose head is
  16406. @var{h} and whose tail is @var{t}. This is similar to @kbd{|}, except
  16407. if @var{h} is itself a vector, @kbd{|} will concatenate the two vectors
  16408. whereas @code{cons} will insert @var{h} at the front of the vector @var{t}.
  16409. @kindex H v h
  16410. @tindex rhead
  16411. @ignore
  16412. @mindex @idots
  16413. @end ignore
  16414. @kindex H I v h
  16415. @ignore
  16416. @mindex @null
  16417. @end ignore
  16418. @kindex H v k
  16419. @ignore
  16420. @mindex @null
  16421. @end ignore
  16422. @tindex rtail
  16423. @ignore
  16424. @mindex @null
  16425. @end ignore
  16426. @tindex rcons
  16427. Each of these three functions also accepts the Hyperbolic flag [@code{rhead},
  16428. @code{rtail}, @code{rcons}] in which case @var{t} instead represents
  16429. the @emph{last} single element of the vector, with @var{h}
  16430. representing the remainder of the vector. Thus the vector
  16431. @samp{[a, b, c, d] = cons(a, [b, c, d]) = rcons([a, b, c], d)}.
  16432. Also, @samp{head([a, b, c, d]) = a}, @samp{tail([a, b, c, d]) = [b, c, d]},
  16433. @samp{rhead([a, b, c, d]) = [a, b, c]}, and @samp{rtail([a, b, c, d]) = d}.
  16434. @node Extracting Elements, Manipulating Vectors, Building Vectors, Matrix Functions
  16435. @section Extracting Vector Elements
  16436. @noindent
  16437. @kindex v r
  16438. @pindex calc-mrow
  16439. @tindex mrow
  16440. The @kbd{v r} (@code{calc-mrow}) [@code{mrow}] command extracts one row of
  16441. the matrix on the top of the stack, or one element of the plain vector on
  16442. the top of the stack. The row or element is specified by the numeric
  16443. prefix argument; the default is to prompt for the row or element number.
  16444. The matrix or vector is replaced by the specified row or element in the
  16445. form of a vector or scalar, respectively.
  16446. @cindex Permutations, applying
  16447. With a prefix argument of @kbd{C-u} only, @kbd{v r} takes the index of
  16448. the element or row from the top of the stack, and the vector or matrix
  16449. from the second-to-top position. If the index is itself a vector of
  16450. integers, the result is a vector of the corresponding elements of the
  16451. input vector, or a matrix of the corresponding rows of the input matrix.
  16452. This command can be used to obtain any permutation of a vector.
  16453. With @kbd{C-u}, if the index is an interval form with integer components,
  16454. it is interpreted as a range of indices and the corresponding subvector or
  16455. submatrix is returned.
  16456. @cindex Subscript notation
  16457. @kindex a _
  16458. @pindex calc-subscript
  16459. @tindex subscr
  16460. @tindex _
  16461. Subscript notation in algebraic formulas (@samp{a_b}) stands for the
  16462. Calc function @code{subscr}, which is synonymous with @code{mrow}.
  16463. Thus, @samp{[x, y, z]_k} produces @cite{x}, @cite{y}, or @cite{z} if
  16464. @cite{k} is one, two, or three, respectively. A double subscript
  16465. (@samp{M_i_j}, equivalent to @samp{subscr(subscr(M, i), j)}) will
  16466. access the element at row @cite{i}, column @cite{j} of a matrix.
  16467. The @kbd{a _} (@code{calc-subscript}) command creates a subscript
  16468. formula @samp{a_b} out of two stack entries. (It is on the @kbd{a}
  16469. ``algebra'' prefix because subscripted variables are often used
  16470. purely as an algebraic notation.)
  16471. @tindex mrrow
  16472. Given a negative prefix argument, @kbd{v r} instead deletes one row or
  16473. element from the matrix or vector on the top of the stack. Thus
  16474. @kbd{C-u 2 v r} replaces a matrix with its second row, but @kbd{C-u -2 v r}
  16475. replaces the matrix with the same matrix with its second row removed.
  16476. In algebraic form this function is called @code{mrrow}.
  16477. @tindex getdiag
  16478. Given a prefix argument of zero, @kbd{v r} extracts the diagonal elements
  16479. of a square matrix in the form of a vector. In algebraic form this
  16480. function is called @code{getdiag}.
  16481. @kindex v c
  16482. @pindex calc-mcol
  16483. @tindex mcol
  16484. @tindex mrcol
  16485. The @kbd{v c} (@code{calc-mcol}) [@code{mcol} or @code{mrcol}] command is
  16486. the analogous operation on columns of a matrix. Given a plain vector
  16487. it extracts (or removes) one element, just like @kbd{v r}. If the
  16488. index in @kbd{C-u v c} is an interval or vector and the argument is a
  16489. matrix, the result is a submatrix with only the specified columns
  16490. retained (and possibly permuted in the case of a vector index).@refill
  16491. To extract a matrix element at a given row and column, use @kbd{v r} to
  16492. extract the row as a vector, then @kbd{v c} to extract the column element
  16493. from that vector. In algebraic formulas, it is often more convenient to
  16494. use subscript notation: @samp{m_i_j} gives row @cite{i}, column @cite{j}
  16495. of matrix @cite{m}.
  16496. @kindex v s
  16497. @pindex calc-subvector
  16498. @tindex subvec
  16499. The @kbd{v s} (@code{calc-subvector}) [@code{subvec}] command extracts
  16500. a subvector of a vector. The arguments are the vector, the starting
  16501. index, and the ending index, with the ending index in the top-of-stack
  16502. position. The starting index indicates the first element of the vector
  16503. to take. The ending index indicates the first element @emph{past} the
  16504. range to be taken. Thus, @samp{subvec([a, b, c, d, e], 2, 4)} produces
  16505. the subvector @samp{[b, c]}. You could get the same result using
  16506. @samp{mrow([a, b, c, d, e], @w{[2 .. 4)})}.
  16507. If either the start or the end index is zero or negative, it is
  16508. interpreted as relative to the end of the vector. Thus
  16509. @samp{subvec([a, b, c, d, e], 2, -2)} also produces @samp{[b, c]}. In
  16510. the algebraic form, the end index can be omitted in which case it
  16511. is taken as zero, i.e., elements from the starting element to the
  16512. end of the vector are used. The infinity symbol, @code{inf}, also
  16513. has this effect when used as the ending index.
  16514. @kindex I v s
  16515. @tindex rsubvec
  16516. With the Inverse flag, @kbd{I v s} [@code{rsubvec}] removes a subvector
  16517. from a vector. The arguments are interpreted the same as for the
  16518. normal @kbd{v s} command. Thus, @samp{rsubvec([a, b, c, d, e], 2, 4)}
  16519. produces @samp{[a, d, e]}. It is always true that @code{subvec} and
  16520. @code{rsubvec} return complementary parts of the input vector.
  16521. @xref{Selecting Subformulas}, for an alternative way to operate on
  16522. vectors one element at a time.
  16523. @node Manipulating Vectors, Vector and Matrix Arithmetic, Extracting Elements, Matrix Functions
  16524. @section Manipulating Vectors
  16525. @noindent
  16526. @kindex v l
  16527. @pindex calc-vlength
  16528. @tindex vlen
  16529. The @kbd{v l} (@code{calc-vlength}) [@code{vlen}] command computes the
  16530. length of a vector. The length of a non-vector is considered to be zero.
  16531. Note that matrices are just vectors of vectors for the purposes of this
  16532. command.@refill
  16533. @kindex H v l
  16534. @tindex mdims
  16535. With the Hyperbolic flag, @kbd{H v l} [@code{mdims}] computes a vector
  16536. of the dimensions of a vector, matrix, or higher-order object. For
  16537. example, @samp{mdims([[a,b,c],[d,e,f]])} returns @samp{[2, 3]} since
  16538. its argument is a @c{$2\times3$}
  16539. @asis{2x3} matrix.
  16540. @kindex v f
  16541. @pindex calc-vector-find
  16542. @tindex find
  16543. The @kbd{v f} (@code{calc-vector-find}) [@code{find}] command searches
  16544. along a vector for the first element equal to a given target. The target
  16545. is on the top of the stack; the vector is in the second-to-top position.
  16546. If a match is found, the result is the index of the matching element.
  16547. Otherwise, the result is zero. The numeric prefix argument, if given,
  16548. allows you to select any starting index for the search.
  16549. @kindex v a
  16550. @pindex calc-arrange-vector
  16551. @tindex arrange
  16552. @cindex Arranging a matrix
  16553. @cindex Reshaping a matrix
  16554. @cindex Flattening a matrix
  16555. The @kbd{v a} (@code{calc-arrange-vector}) [@code{arrange}] command
  16556. rearranges a vector to have a certain number of columns and rows. The
  16557. numeric prefix argument specifies the number of columns; if you do not
  16558. provide an argument, you will be prompted for the number of columns.
  16559. The vector or matrix on the top of the stack is @dfn{flattened} into a
  16560. plain vector. If the number of columns is nonzero, this vector is
  16561. then formed into a matrix by taking successive groups of @var{n} elements.
  16562. If the number of columns does not evenly divide the number of elements
  16563. in the vector, the last row will be short and the result will not be
  16564. suitable for use as a matrix. For example, with the matrix
  16565. @samp{[[1, 2], @w{[3, 4]}]} on the stack, @kbd{v a 4} produces
  16566. @samp{[[1, 2, 3, 4]]} (a @c{$1\times4$}
  16567. @asis{1x4} matrix), @kbd{v a 1} produces
  16568. @samp{[[1], [2], [3], [4]]} (a @c{$4\times1$}
  16569. @asis{4x1} matrix), @kbd{v a 2} produces
  16570. @samp{[[1, 2], [3, 4]]} (the original @c{$2\times2$}
  16571. @asis{2x2} matrix), @w{@kbd{v a 3}} produces
  16572. @samp{[[1, 2, 3], [4]]} (not a matrix), and @kbd{v a 0} produces
  16573. the flattened list @samp{[1, 2, @w{3, 4}]}.
  16574. @cindex Sorting data
  16575. @kindex V S
  16576. @kindex I V S
  16577. @pindex calc-sort
  16578. @tindex sort
  16579. @tindex rsort
  16580. The @kbd{V S} (@code{calc-sort}) [@code{sort}] command sorts the elements of
  16581. a vector into increasing order. Real numbers, real infinities, and
  16582. constant interval forms come first in this ordering; next come other
  16583. kinds of numbers, then variables (in alphabetical order), then finally
  16584. come formulas and other kinds of objects; these are sorted according
  16585. to a kind of lexicographic ordering with the useful property that
  16586. one vector is less or greater than another if the first corresponding
  16587. unequal elements are less or greater, respectively. Since quoted strings
  16588. are stored by Calc internally as vectors of ASCII character codes
  16589. (@pxref{Strings}), this means vectors of strings are also sorted into
  16590. alphabetical order by this command.
  16591. The @kbd{I V S} [@code{rsort}] command sorts a vector into decreasing order.
  16592. @cindex Permutation, inverse of
  16593. @cindex Inverse of permutation
  16594. @cindex Index tables
  16595. @cindex Rank tables
  16596. @kindex V G
  16597. @kindex I V G
  16598. @pindex calc-grade
  16599. @tindex grade
  16600. @tindex rgrade
  16601. The @kbd{V G} (@code{calc-grade}) [@code{grade}, @code{rgrade}] command
  16602. produces an index table or permutation vector which, if applied to the
  16603. input vector (as the index of @kbd{C-u v r}, say), would sort the vector.
  16604. A permutation vector is just a vector of integers from 1 to @var{n}, where
  16605. each integer occurs exactly once. One application of this is to sort a
  16606. matrix of data rows using one column as the sort key; extract that column,
  16607. grade it with @kbd{V G}, then use the result to reorder the original matrix
  16608. with @kbd{C-u v r}. Another interesting property of the @code{V G} command
  16609. is that, if the input is itself a permutation vector, the result will
  16610. be the inverse of the permutation. The inverse of an index table is
  16611. a rank table, whose @var{k}th element says where the @var{k}th original
  16612. vector element will rest when the vector is sorted. To get a rank
  16613. table, just use @kbd{V G V G}.
  16614. With the Inverse flag, @kbd{I V G} produces an index table that would
  16615. sort the input into decreasing order. Note that @kbd{V S} and @kbd{V G}
  16616. use a ``stable'' sorting algorithm, i.e., any two elements which are equal
  16617. will not be moved out of their original order. Generally there is no way
  16618. to tell with @kbd{V S}, since two elements which are equal look the same,
  16619. but with @kbd{V G} this can be an important issue. In the matrix-of-rows
  16620. example, suppose you have names and telephone numbers as two columns and
  16621. you wish to sort by phone number primarily, and by name when the numbers
  16622. are equal. You can sort the data matrix by names first, and then again
  16623. by phone numbers. Because the sort is stable, any two rows with equal
  16624. phone numbers will remain sorted by name even after the second sort.
  16625. @cindex Histograms
  16626. @kindex V H
  16627. @pindex calc-histogram
  16628. @ignore
  16629. @mindex histo@idots
  16630. @end ignore
  16631. @tindex histogram
  16632. The @kbd{V H} (@code{calc-histogram}) [@code{histogram}] command builds a
  16633. histogram of a vector of numbers. Vector elements are assumed to be
  16634. integers or real numbers in the range [0..@var{n}) for some ``number of
  16635. bins'' @var{n}, which is the numeric prefix argument given to the
  16636. command. The result is a vector of @var{n} counts of how many times
  16637. each value appeared in the original vector. Non-integers in the input
  16638. are rounded down to integers. Any vector elements outside the specified
  16639. range are ignored. (You can tell if elements have been ignored by noting
  16640. that the counts in the result vector don't add up to the length of the
  16641. input vector.)
  16642. @kindex H V H
  16643. With the Hyperbolic flag, @kbd{H V H} pulls two vectors from the stack.
  16644. The second-to-top vector is the list of numbers as before. The top
  16645. vector is an equal-sized list of ``weights'' to attach to the elements
  16646. of the data vector. For example, if the first data element is 4.2 and
  16647. the first weight is 10, then 10 will be added to bin 4 of the result
  16648. vector. Without the hyperbolic flag, every element has a weight of one.
  16649. @kindex v t
  16650. @pindex calc-transpose
  16651. @tindex trn
  16652. The @kbd{v t} (@code{calc-transpose}) [@code{trn}] command computes
  16653. the transpose of the matrix at the top of the stack. If the argument
  16654. is a plain vector, it is treated as a row vector and transposed into
  16655. a one-column matrix.
  16656. @kindex v v
  16657. @pindex calc-reverse-vector
  16658. @tindex rev
  16659. The @kbd{v v} (@code{calc-reverse-vector}) [@code{vec}] command reverses
  16660. a vector end-for-end. Given a matrix, it reverses the order of the rows.
  16661. (To reverse the columns instead, just use @kbd{v t v v v t}. The same
  16662. principle can be used to apply other vector commands to the columns of
  16663. a matrix.)
  16664. @kindex v m
  16665. @pindex calc-mask-vector
  16666. @tindex vmask
  16667. The @kbd{v m} (@code{calc-mask-vector}) [@code{vmask}] command uses
  16668. one vector as a mask to extract elements of another vector. The mask
  16669. is in the second-to-top position; the target vector is on the top of
  16670. the stack. These vectors must have the same length. The result is
  16671. the same as the target vector, but with all elements which correspond
  16672. to zeros in the mask vector deleted. Thus, for example,
  16673. @samp{vmask([1, 0, 1, 0, 1], [a, b, c, d, e])} produces @samp{[a, c, e]}.
  16674. @xref{Logical Operations}.
  16675. @kindex v e
  16676. @pindex calc-expand-vector
  16677. @tindex vexp
  16678. The @kbd{v e} (@code{calc-expand-vector}) [@code{vexp}] command
  16679. expands a vector according to another mask vector. The result is a
  16680. vector the same length as the mask, but with nonzero elements replaced
  16681. by successive elements from the target vector. The length of the target
  16682. vector is normally the number of nonzero elements in the mask. If the
  16683. target vector is longer, its last few elements are lost. If the target
  16684. vector is shorter, the last few nonzero mask elements are left
  16685. unreplaced in the result. Thus @samp{vexp([2, 0, 3, 0, 7], [a, b])}
  16686. produces @samp{[a, 0, b, 0, 7]}.
  16687. @kindex H v e
  16688. With the Hyperbolic flag, @kbd{H v e} takes a filler value from the
  16689. top of the stack; the mask and target vectors come from the third and
  16690. second elements of the stack. This filler is used where the mask is
  16691. zero: @samp{vexp([2, 0, 3, 0, 7], [a, b], z)} produces
  16692. @samp{[a, z, c, z, 7]}. If the filler value is itself a vector,
  16693. then successive values are taken from it, so that the effect is to
  16694. interleave two vectors according to the mask:
  16695. @samp{vexp([2, 0, 3, 7, 0, 0], [a, b], [x, y])} produces
  16696. @samp{[a, x, b, 7, y, 0]}.
  16697. Another variation on the masking idea is to combine @samp{[a, b, c, d, e]}
  16698. with the mask @samp{[1, 0, 1, 0, 1]} to produce @samp{[a, 0, c, 0, e]}.
  16699. You can accomplish this with @kbd{V M a &}, mapping the logical ``and''
  16700. operation across the two vectors. @xref{Logical Operations}. Note that
  16701. the @code{? :} operation also discussed there allows other types of
  16702. masking using vectors.
  16703. @node Vector and Matrix Arithmetic, Set Operations, Manipulating Vectors, Matrix Functions
  16704. @section Vector and Matrix Arithmetic
  16705. @noindent
  16706. Basic arithmetic operations like addition and multiplication are defined
  16707. for vectors and matrices as well as for numbers. Division of matrices, in
  16708. the sense of multiplying by the inverse, is supported. (Division by a
  16709. matrix actually uses LU-decomposition for greater accuracy and speed.)
  16710. @xref{Basic Arithmetic}.
  16711. The following functions are applied element-wise if their arguments are
  16712. vectors or matrices: @code{change-sign}, @code{conj}, @code{arg},
  16713. @code{re}, @code{im}, @code{polar}, @code{rect}, @code{clean},
  16714. @code{float}, @code{frac}. @xref{Function Index}.@refill
  16715. @kindex V J
  16716. @pindex calc-conj-transpose
  16717. @tindex ctrn
  16718. The @kbd{V J} (@code{calc-conj-transpose}) [@code{ctrn}] command computes
  16719. the conjugate transpose of its argument, i.e., @samp{conj(trn(x))}.
  16720. @ignore
  16721. @mindex A
  16722. @end ignore
  16723. @kindex A (vectors)
  16724. @pindex calc-abs (vectors)
  16725. @ignore
  16726. @mindex abs
  16727. @end ignore
  16728. @tindex abs (vectors)
  16729. The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the
  16730. Frobenius norm of a vector or matrix argument. This is the square
  16731. root of the sum of the squares of the absolute values of the
  16732. elements of the vector or matrix. If the vector is interpreted as
  16733. a point in two- or three-dimensional space, this is the distance
  16734. from that point to the origin.@refill
  16735. @kindex v n
  16736. @pindex calc-rnorm
  16737. @tindex rnorm
  16738. The @kbd{v n} (@code{calc-rnorm}) [@code{rnorm}] command computes
  16739. the row norm, or infinity-norm, of a vector or matrix. For a plain
  16740. vector, this is the maximum of the absolute values of the elements.
  16741. For a matrix, this is the maximum of the row-absolute-value-sums,
  16742. i.e., of the sums of the absolute values of the elements along the
  16743. various rows.
  16744. @kindex V N
  16745. @pindex calc-cnorm
  16746. @tindex cnorm
  16747. The @kbd{V N} (@code{calc-cnorm}) [@code{cnorm}] command computes
  16748. the column norm, or one-norm, of a vector or matrix. For a plain
  16749. vector, this is the sum of the absolute values of the elements.
  16750. For a matrix, this is the maximum of the column-absolute-value-sums.
  16751. General @cite{k}-norms for @cite{k} other than one or infinity are
  16752. not provided.
  16753. @kindex V C
  16754. @pindex calc-cross
  16755. @tindex cross
  16756. The @kbd{V C} (@code{calc-cross}) [@code{cross}] command computes the
  16757. right-handed cross product of two vectors, each of which must have
  16758. exactly three elements.
  16759. @ignore
  16760. @mindex &
  16761. @end ignore
  16762. @kindex & (matrices)
  16763. @pindex calc-inv (matrices)
  16764. @ignore
  16765. @mindex inv
  16766. @end ignore
  16767. @tindex inv (matrices)
  16768. The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
  16769. inverse of a square matrix. If the matrix is singular, the inverse
  16770. operation is left in symbolic form. Matrix inverses are recorded so
  16771. that once an inverse (or determinant) of a particular matrix has been
  16772. computed, the inverse and determinant of the matrix can be recomputed
  16773. quickly in the future.
  16774. If the argument to @kbd{&} is a plain number @cite{x}, this
  16775. command simply computes @cite{1/x}. This is okay, because the
  16776. @samp{/} operator also does a matrix inversion when dividing one
  16777. by a matrix.
  16778. @kindex V D
  16779. @pindex calc-mdet
  16780. @tindex det
  16781. The @kbd{V D} (@code{calc-mdet}) [@code{det}] command computes the
  16782. determinant of a square matrix.
  16783. @kindex V L
  16784. @pindex calc-mlud
  16785. @tindex lud
  16786. The @kbd{V L} (@code{calc-mlud}) [@code{lud}] command computes the
  16787. LU decomposition of a matrix. The result is a list of three matrices
  16788. which, when multiplied together left-to-right, form the original matrix.
  16789. The first is a permutation matrix that arises from pivoting in the
  16790. algorithm, the second is lower-triangular with ones on the diagonal,
  16791. and the third is upper-triangular.
  16792. @kindex V T
  16793. @pindex calc-mtrace
  16794. @tindex tr
  16795. The @kbd{V T} (@code{calc-mtrace}) [@code{tr}] command computes the
  16796. trace of a square matrix. This is defined as the sum of the diagonal
  16797. elements of the matrix.
  16798. @node Set Operations, Statistical Operations, Vector and Matrix Arithmetic, Matrix Functions
  16799. @section Set Operations using Vectors
  16800. @noindent
  16801. @cindex Sets, as vectors
  16802. Calc includes several commands which interpret vectors as @dfn{sets} of
  16803. objects. A set is a collection of objects; any given object can appear
  16804. only once in the set. Calc stores sets as vectors of objects in
  16805. sorted order. Objects in a Calc set can be any of the usual things,
  16806. such as numbers, variables, or formulas. Two set elements are considered
  16807. equal if they are identical, except that numerically equal numbers like
  16808. the integer 4 and the float 4.0 are considered equal even though they
  16809. are not ``identical.'' Variables are treated like plain symbols without
  16810. attached values by the set operations; subtracting the set @samp{[b]}
  16811. from @samp{[a, b]} always yields the set @samp{[a]} even though if
  16812. the variables @samp{a} and @samp{b} both equalled 17, you might
  16813. expect the answer @samp{[]}.
  16814. If a set contains interval forms, then it is assumed to be a set of
  16815. real numbers. In this case, all set operations require the elements
  16816. of the set to be only things that are allowed in intervals: Real
  16817. numbers, plus and minus infinity, HMS forms, and date forms. If
  16818. there are variables or other non-real objects present in a real set,
  16819. all set operations on it will be left in unevaluated form.
  16820. If the input to a set operation is a plain number or interval form
  16821. @var{a}, it is treated like the one-element vector @samp{[@var{a}]}.
  16822. The result is always a vector, except that if the set consists of a
  16823. single interval, the interval itself is returned instead.
  16824. @xref{Logical Operations}, for the @code{in} function which tests if
  16825. a certain value is a member of a given set. To test if the set @cite{A}
  16826. is a subset of the set @cite{B}, use @samp{vdiff(A, B) = []}.
  16827. @kindex V +
  16828. @pindex calc-remove-duplicates
  16829. @tindex rdup
  16830. The @kbd{V +} (@code{calc-remove-duplicates}) [@code{rdup}] command
  16831. converts an arbitrary vector into set notation. It works by sorting
  16832. the vector as if by @kbd{V S}, then removing duplicates. (For example,
  16833. @kbd{[a, 5, 4, a, 4.0]} is sorted to @samp{[4, 4.0, 5, a, a]} and then
  16834. reduced to @samp{[4, 5, a]}). Overlapping intervals are merged as
  16835. necessary. You rarely need to use @kbd{V +} explicitly, since all the
  16836. other set-based commands apply @kbd{V +} to their inputs before using
  16837. them.
  16838. @kindex V V
  16839. @pindex calc-set-union
  16840. @tindex vunion
  16841. The @kbd{V V} (@code{calc-set-union}) [@code{vunion}] command computes
  16842. the union of two sets. An object is in the union of two sets if and
  16843. only if it is in either (or both) of the input sets. (You could
  16844. accomplish the same thing by concatenating the sets with @kbd{|},
  16845. then using @kbd{V +}.)
  16846. @kindex V ^
  16847. @pindex calc-set-intersect
  16848. @tindex vint
  16849. The @kbd{V ^} (@code{calc-set-intersect}) [@code{vint}] command computes
  16850. the intersection of two sets. An object is in the intersection if
  16851. and only if it is in both of the input sets. Thus if the input
  16852. sets are disjoint, i.e., if they share no common elements, the result
  16853. will be the empty vector @samp{[]}. Note that the characters @kbd{V}
  16854. and @kbd{^} were chosen to be close to the conventional mathematical
  16855. notation for set union@c{ ($A \cup B$)}
  16856. @asis{} and intersection@c{ ($A \cap B$)}
  16857. @asis{}.
  16858. @kindex V -
  16859. @pindex calc-set-difference
  16860. @tindex vdiff
  16861. The @kbd{V -} (@code{calc-set-difference}) [@code{vdiff}] command computes
  16862. the difference between two sets. An object is in the difference
  16863. @cite{A - B} if and only if it is in @cite{A} but not in @cite{B}.
  16864. Thus subtracting @samp{[y,z]} from a set will remove the elements
  16865. @samp{y} and @samp{z} if they are present. You can also think of this
  16866. as a general @dfn{set complement} operator; if @cite{A} is the set of
  16867. all possible values, then @cite{A - B} is the ``complement'' of @cite{B}.
  16868. Obviously this is only practical if the set of all possible values in
  16869. your problem is small enough to list in a Calc vector (or simple
  16870. enough to express in a few intervals).
  16871. @kindex V X
  16872. @pindex calc-set-xor
  16873. @tindex vxor
  16874. The @kbd{V X} (@code{calc-set-xor}) [@code{vxor}] command computes
  16875. the ``exclusive-or,'' or ``symmetric difference'' of two sets.
  16876. An object is in the symmetric difference of two sets if and only
  16877. if it is in one, but @emph{not} both, of the sets. Objects that
  16878. occur in both sets ``cancel out.''
  16879. @kindex V ~
  16880. @pindex calc-set-complement
  16881. @tindex vcompl
  16882. The @kbd{V ~} (@code{calc-set-complement}) [@code{vcompl}] command
  16883. computes the complement of a set with respect to the real numbers.
  16884. Thus @samp{vcompl(x)} is equivalent to @samp{vdiff([-inf .. inf], x)}.
  16885. For example, @samp{vcompl([2, (3 .. 4]])} evaluates to
  16886. @samp{[[-inf .. 2), (2 .. 3], (4 .. inf]]}.
  16887. @kindex V F
  16888. @pindex calc-set-floor
  16889. @tindex vfloor
  16890. The @kbd{V F} (@code{calc-set-floor}) [@code{vfloor}] command
  16891. reinterprets a set as a set of integers. Any non-integer values,
  16892. and intervals that do not enclose any integers, are removed. Open
  16893. intervals are converted to equivalent closed intervals. Successive
  16894. integers are converted into intervals of integers. For example, the
  16895. complement of the set @samp{[2, 6, 7, 8]} is messy, but if you wanted
  16896. the complement with respect to the set of integers you could type
  16897. @kbd{V ~ V F} to get @samp{[[-inf .. 1], [3 .. 5], [9 .. inf]]}.
  16898. @kindex V E
  16899. @pindex calc-set-enumerate
  16900. @tindex venum
  16901. The @kbd{V E} (@code{calc-set-enumerate}) [@code{venum}] command
  16902. converts a set of integers into an explicit vector. Intervals in
  16903. the set are expanded out to lists of all integers encompassed by
  16904. the intervals. This only works for finite sets (i.e., sets which
  16905. do not involve @samp{-inf} or @samp{inf}).
  16906. @kindex V :
  16907. @pindex calc-set-span
  16908. @tindex vspan
  16909. The @kbd{V :} (@code{calc-set-span}) [@code{vspan}] command converts any
  16910. set of reals into an interval form that encompasses all its elements.
  16911. The lower limit will be the smallest element in the set; the upper
  16912. limit will be the largest element. For an empty set, @samp{vspan([])}
  16913. returns the empty interval @w{@samp{[0 .. 0)}}.
  16914. @kindex V #
  16915. @pindex calc-set-cardinality
  16916. @tindex vcard
  16917. The @kbd{V #} (@code{calc-set-cardinality}) [@code{vcard}] command counts
  16918. the number of integers in a set. The result is the length of the vector
  16919. that would be produced by @kbd{V E}, although the computation is much
  16920. more efficient than actually producing that vector.
  16921. @cindex Sets, as binary numbers
  16922. Another representation for sets that may be more appropriate in some
  16923. cases is binary numbers. If you are dealing with sets of integers
  16924. in the range 0 to 49, you can use a 50-bit binary number where a
  16925. particular bit is 1 if the corresponding element is in the set.
  16926. @xref{Binary Functions}, for a list of commands that operate on
  16927. binary numbers. Note that many of the above set operations have
  16928. direct equivalents in binary arithmetic: @kbd{b o} (@code{calc-or}),
  16929. @kbd{b a} (@code{calc-and}), @kbd{b d} (@code{calc-diff}),
  16930. @kbd{b x} (@code{calc-xor}), and @kbd{b n} (@code{calc-not}),
  16931. respectively. You can use whatever representation for sets is most
  16932. convenient to you.
  16933. @kindex b p
  16934. @kindex b u
  16935. @pindex calc-pack-bits
  16936. @pindex calc-unpack-bits
  16937. @tindex vpack
  16938. @tindex vunpack
  16939. The @kbd{b u} (@code{calc-unpack-bits}) [@code{vunpack}] command
  16940. converts an integer that represents a set in binary into a set
  16941. in vector/interval notation. For example, @samp{vunpack(67)}
  16942. returns @samp{[[0 .. 1], 6]}. If the input is negative, the set
  16943. it represents is semi-infinite: @samp{vunpack(-4) = [2 .. inf)}.
  16944. Use @kbd{V E} afterwards to expand intervals to individual
  16945. values if you wish. Note that this command uses the @kbd{b}
  16946. (binary) prefix key.
  16947. The @kbd{b p} (@code{calc-pack-bits}) [@code{vpack}] command
  16948. converts the other way, from a vector or interval representing
  16949. a set of nonnegative integers into a binary integer describing
  16950. the same set. The set may include positive infinity, but must
  16951. not include any negative numbers. The input is interpreted as a
  16952. set of integers in the sense of @kbd{V F} (@code{vfloor}). Beware
  16953. that a simple input like @samp{[100]} can result in a huge integer
  16954. representation (@c{$2^{100}$}
  16955. @cite{2^100}, a 31-digit integer, in this case).
  16956. @node Statistical Operations, Reducing and Mapping, Set Operations, Matrix Functions
  16957. @section Statistical Operations on Vectors
  16958. @noindent
  16959. @cindex Statistical functions
  16960. The commands in this section take vectors as arguments and compute
  16961. various statistical measures on the data stored in the vectors. The
  16962. references used in the definitions of these functions are Bevington's
  16963. @emph{Data Reduction and Error Analysis for the Physical Sciences},
  16964. and @emph{Numerical Recipes} by Press, Flannery, Teukolsky and
  16965. Vetterling.
  16966. The statistical commands use the @kbd{u} prefix key followed by
  16967. a shifted letter or other character.
  16968. @xref{Manipulating Vectors}, for a description of @kbd{V H}
  16969. (@code{calc-histogram}).
  16970. @xref{Curve Fitting}, for the @kbd{a F} command for doing
  16971. least-squares fits to statistical data.
  16972. @xref{Probability Distribution Functions}, for several common
  16973. probability distribution functions.
  16974. @menu
  16975. * Single-Variable Statistics::
  16976. * Paired-Sample Statistics::
  16977. @end menu
  16978. @node Single-Variable Statistics, Paired-Sample Statistics, Statistical Operations, Statistical Operations
  16979. @subsection Single-Variable Statistics
  16980. @noindent
  16981. These functions do various statistical computations on single
  16982. vectors. Given a numeric prefix argument, they actually pop
  16983. @var{n} objects from the stack and combine them into a data
  16984. vector. Each object may be either a number or a vector; if a
  16985. vector, any sub-vectors inside it are ``flattened'' as if by
  16986. @kbd{v a 0}; @pxref{Manipulating Vectors}. By default one object
  16987. is popped, which (in order to be useful) is usually a vector.
  16988. If an argument is a variable name, and the value stored in that
  16989. variable is a vector, then the stored vector is used. This method
  16990. has the advantage that if your data vector is large, you can avoid
  16991. the slow process of manipulating it directly on the stack.
  16992. These functions are left in symbolic form if any of their arguments
  16993. are not numbers or vectors, e.g., if an argument is a formula, or
  16994. a non-vector variable. However, formulas embedded within vector
  16995. arguments are accepted; the result is a symbolic representation
  16996. of the computation, based on the assumption that the formula does
  16997. not itself represent a vector. All varieties of numbers such as
  16998. error forms and interval forms are acceptable.
  16999. Some of the functions in this section also accept a single error form
  17000. or interval as an argument. They then describe a property of the
  17001. normal or uniform (respectively) statistical distribution described
  17002. by the argument. The arguments are interpreted in the same way as
  17003. the @var{M} argument of the random number function @kbd{k r}. In
  17004. particular, an interval with integer limits is considered an integer
  17005. distribution, so that @samp{[2 .. 6)} is the same as @samp{[2 .. 5]}.
  17006. An interval with at least one floating-point limit is a continuous
  17007. distribution: @samp{[2.0 .. 6.0)} is @emph{not} the same as
  17008. @samp{[2.0 .. 5.0]}!
  17009. @kindex u #
  17010. @pindex calc-vector-count
  17011. @tindex vcount
  17012. The @kbd{u #} (@code{calc-vector-count}) [@code{vcount}] command
  17013. computes the number of data values represented by the inputs.
  17014. For example, @samp{vcount(1, [2, 3], [[4, 5], [], x, y])} returns 7.
  17015. If the argument is a single vector with no sub-vectors, this
  17016. simply computes the length of the vector.
  17017. @kindex u +
  17018. @kindex u *
  17019. @pindex calc-vector-sum
  17020. @pindex calc-vector-prod
  17021. @tindex vsum
  17022. @tindex vprod
  17023. @cindex Summations (statistical)
  17024. The @kbd{u +} (@code{calc-vector-sum}) [@code{vsum}] command
  17025. computes the sum of the data values. The @kbd{u *}
  17026. (@code{calc-vector-prod}) [@code{vprod}] command computes the
  17027. product of the data values. If the input is a single flat vector,
  17028. these are the same as @kbd{V R +} and @kbd{V R *}
  17029. (@pxref{Reducing and Mapping}).@refill
  17030. @kindex u X
  17031. @kindex u N
  17032. @pindex calc-vector-max
  17033. @pindex calc-vector-min
  17034. @tindex vmax
  17035. @tindex vmin
  17036. The @kbd{u X} (@code{calc-vector-max}) [@code{vmax}] command
  17037. computes the maximum of the data values, and the @kbd{u N}
  17038. (@code{calc-vector-min}) [@code{vmin}] command computes the minimum.
  17039. If the argument is an interval, this finds the minimum or maximum
  17040. value in the interval. (Note that @samp{vmax([2..6)) = 5} as
  17041. described above.) If the argument is an error form, this returns
  17042. plus or minus infinity.
  17043. @kindex u M
  17044. @pindex calc-vector-mean
  17045. @tindex vmean
  17046. @cindex Mean of data values
  17047. The @kbd{u M} (@code{calc-vector-mean}) [@code{vmean}] command
  17048. computes the average (arithmetic mean) of the data values.
  17049. If the inputs are error forms @c{$x$ @code{+/-} $\sigma$}
  17050. @samp{x +/- s}, this is the weighted
  17051. mean of the @cite{x} values with weights @c{$1 / \sigma^2$}
  17052. @cite{1 / s^2}.
  17053. @tex
  17054. \turnoffactive
  17055. $$ \mu = { \displaystyle \sum { x_i \over \sigma_i^2 } \over
  17056. \displaystyle \sum { 1 \over \sigma_i^2 } } $$
  17057. @end tex
  17058. If the inputs are not error forms, this is simply the sum of the
  17059. values divided by the count of the values.@refill
  17060. Note that a plain number can be considered an error form with
  17061. error @c{$\sigma = 0$}
  17062. @cite{s = 0}. If the input to @kbd{u M} is a mixture of
  17063. plain numbers and error forms, the result is the mean of the
  17064. plain numbers, ignoring all values with non-zero errors. (By the
  17065. above definitions it's clear that a plain number effectively
  17066. has an infinite weight, next to which an error form with a finite
  17067. weight is completely negligible.)
  17068. This function also works for distributions (error forms or
  17069. intervals). The mean of an error form `@var{a} @t{+/-} @var{b}' is simply
  17070. @cite{a}. The mean of an interval is the mean of the minimum
  17071. and maximum values of the interval.
  17072. @kindex I u M
  17073. @pindex calc-vector-mean-error
  17074. @tindex vmeane
  17075. The @kbd{I u M} (@code{calc-vector-mean-error}) [@code{vmeane}]
  17076. command computes the mean of the data points expressed as an
  17077. error form. This includes the estimated error associated with
  17078. the mean. If the inputs are error forms, the error is the square
  17079. root of the reciprocal of the sum of the reciprocals of the squares
  17080. of the input errors. (I.e., the variance is the reciprocal of the
  17081. sum of the reciprocals of the variances.)
  17082. @tex
  17083. \turnoffactive
  17084. $$ \sigma_\mu^2 = {1 \over \displaystyle \sum {1 \over \sigma_i^2}} $$
  17085. @end tex
  17086. If the inputs are plain
  17087. numbers, the error is equal to the standard deviation of the values
  17088. divided by the square root of the number of values. (This works
  17089. out to be equivalent to calculating the standard deviation and
  17090. then assuming each value's error is equal to this standard
  17091. deviation.)@refill
  17092. @tex
  17093. \turnoffactive
  17094. $$ \sigma_\mu^2 = {\sigma^2 \over N} $$
  17095. @end tex
  17096. @kindex H u M
  17097. @pindex calc-vector-median
  17098. @tindex vmedian
  17099. @cindex Median of data values
  17100. The @kbd{H u M} (@code{calc-vector-median}) [@code{vmedian}]
  17101. command computes the median of the data values. The values are
  17102. first sorted into numerical order; the median is the middle
  17103. value after sorting. (If the number of data values is even,
  17104. the median is taken to be the average of the two middle values.)
  17105. The median function is different from the other functions in
  17106. this section in that the arguments must all be real numbers;
  17107. variables are not accepted even when nested inside vectors.
  17108. (Otherwise it is not possible to sort the data values.) If
  17109. any of the input values are error forms, their error parts are
  17110. ignored.
  17111. The median function also accepts distributions. For both normal
  17112. (error form) and uniform (interval) distributions, the median is
  17113. the same as the mean.
  17114. @kindex H I u M
  17115. @pindex calc-vector-harmonic-mean
  17116. @tindex vhmean
  17117. @cindex Harmonic mean
  17118. The @kbd{H I u M} (@code{calc-vector-harmonic-mean}) [@code{vhmean}]
  17119. command computes the harmonic mean of the data values. This is
  17120. defined as the reciprocal of the arithmetic mean of the reciprocals
  17121. of the values.
  17122. @tex
  17123. \turnoffactive
  17124. $$ { N \over \displaystyle \sum {1 \over x_i} } $$
  17125. @end tex
  17126. @kindex u G
  17127. @pindex calc-vector-geometric-mean
  17128. @tindex vgmean
  17129. @cindex Geometric mean
  17130. The @kbd{u G} (@code{calc-vector-geometric-mean}) [@code{vgmean}]
  17131. command computes the geometric mean of the data values. This
  17132. is the @var{n}th root of the product of the values. This is also
  17133. equal to the @code{exp} of the arithmetic mean of the logarithms
  17134. of the data values.
  17135. @tex
  17136. \turnoffactive
  17137. $$ \exp \left ( \sum { \ln x_i } \right ) =
  17138. \left ( \prod { x_i } \right)^{1 / N} $$
  17139. @end tex
  17140. @kindex H u G
  17141. @tindex agmean
  17142. The @kbd{H u G} [@code{agmean}] command computes the ``arithmetic-geometric
  17143. mean'' of two numbers taken from the stack. This is computed by
  17144. replacing the two numbers with their arithmetic mean and geometric
  17145. mean, then repeating until the two values converge.
  17146. @tex
  17147. \turnoffactive
  17148. $$ a_{i+1} = { a_i + b_i \over 2 } , \qquad b_{i+1} = \sqrt{a_i b_i} $$
  17149. @end tex
  17150. @cindex Root-mean-square
  17151. Another commonly used mean, the RMS (root-mean-square), can be computed
  17152. for a vector of numbers simply by using the @kbd{A} command.
  17153. @kindex u S
  17154. @pindex calc-vector-sdev
  17155. @tindex vsdev
  17156. @cindex Standard deviation
  17157. @cindex Sample statistics
  17158. The @kbd{u S} (@code{calc-vector-sdev}) [@code{vsdev}] command
  17159. computes the standard deviation@c{ $\sigma$}
  17160. @asis{} of the data values. If the
  17161. values are error forms, the errors are used as weights just
  17162. as for @kbd{u M}. This is the @emph{sample} standard deviation,
  17163. whose value is the square root of the sum of the squares of the
  17164. differences between the values and the mean of the @cite{N} values,
  17165. divided by @cite{N-1}.
  17166. @tex
  17167. \turnoffactive
  17168. $$ \sigma^2 = {1 \over N - 1} \sum (x_i - \mu)^2 $$
  17169. @end tex
  17170. This function also applies to distributions. The standard deviation
  17171. of a single error form is simply the error part. The standard deviation
  17172. of a continuous interval happens to equal the difference between the
  17173. limits, divided by @c{$\sqrt{12}$}
  17174. @cite{sqrt(12)}. The standard deviation of an
  17175. integer interval is the same as the standard deviation of a vector
  17176. of those integers.
  17177. @kindex I u S
  17178. @pindex calc-vector-pop-sdev
  17179. @tindex vpsdev
  17180. @cindex Population statistics
  17181. The @kbd{I u S} (@code{calc-vector-pop-sdev}) [@code{vpsdev}]
  17182. command computes the @emph{population} standard deviation.
  17183. It is defined by the same formula as above but dividing
  17184. by @cite{N} instead of by @cite{N-1}. The population standard
  17185. deviation is used when the input represents the entire set of
  17186. data values in the distribution; the sample standard deviation
  17187. is used when the input represents a sample of the set of all
  17188. data values, so that the mean computed from the input is itself
  17189. only an estimate of the true mean.
  17190. @tex
  17191. \turnoffactive
  17192. $$ \sigma^2 = {1 \over N} \sum (x_i - \mu)^2 $$
  17193. @end tex
  17194. For error forms and continuous intervals, @code{vpsdev} works
  17195. exactly like @code{vsdev}. For integer intervals, it computes the
  17196. population standard deviation of the equivalent vector of integers.
  17197. @kindex H u S
  17198. @kindex H I u S
  17199. @pindex calc-vector-variance
  17200. @pindex calc-vector-pop-variance
  17201. @tindex vvar
  17202. @tindex vpvar
  17203. @cindex Variance of data values
  17204. The @kbd{H u S} (@code{calc-vector-variance}) [@code{vvar}] and
  17205. @kbd{H I u S} (@code{calc-vector-pop-variance}) [@code{vpvar}]
  17206. commands compute the variance of the data values. The variance
  17207. is the square@c{ $\sigma^2$}
  17208. @asis{} of the standard deviation, i.e., the sum of the
  17209. squares of the deviations of the data values from the mean.
  17210. (This definition also applies when the argument is a distribution.)
  17211. @ignore
  17212. @starindex
  17213. @end ignore
  17214. @tindex vflat
  17215. The @code{vflat} algebraic function returns a vector of its
  17216. arguments, interpreted in the same way as the other functions
  17217. in this section. For example, @samp{vflat(1, [2, [3, 4]], 5)}
  17218. returns @samp{[1, 2, 3, 4, 5]}.
  17219. @node Paired-Sample Statistics, , Single-Variable Statistics, Statistical Operations
  17220. @subsection Paired-Sample Statistics
  17221. @noindent
  17222. The functions in this section take two arguments, which must be
  17223. vectors of equal size. The vectors are each flattened in the same
  17224. way as by the single-variable statistical functions. Given a numeric
  17225. prefix argument of 1, these functions instead take one object from
  17226. the stack, which must be an @c{$N\times2$}
  17227. @asis{Nx2} matrix of data values. Once
  17228. again, variable names can be used in place of actual vectors and
  17229. matrices.
  17230. @kindex u C
  17231. @pindex calc-vector-covariance
  17232. @tindex vcov
  17233. @cindex Covariance
  17234. The @kbd{u C} (@code{calc-vector-covariance}) [@code{vcov}] command
  17235. computes the sample covariance of two vectors. The covariance
  17236. of vectors @var{x} and @var{y} is the sum of the products of the
  17237. differences between the elements of @var{x} and the mean of @var{x}
  17238. times the differences between the corresponding elements of @var{y}
  17239. and the mean of @var{y}, all divided by @cite{N-1}. Note that
  17240. the variance of a vector is just the covariance of the vector
  17241. with itself. Once again, if the inputs are error forms the
  17242. errors are used as weight factors. If both @var{x} and @var{y}
  17243. are composed of error forms, the error for a given data point
  17244. is taken as the square root of the sum of the squares of the two
  17245. input errors.
  17246. @tex
  17247. \turnoffactive
  17248. $$ \sigma_{x\!y}^2 = {1 \over N-1} \sum (x_i - \mu_x) (y_i - \mu_y) $$
  17249. $$ \sigma_{x\!y}^2 =
  17250. {\displaystyle {1 \over N-1}
  17251. \sum {(x_i - \mu_x) (y_i - \mu_y) \over \sigma_i^2}
  17252. \over \displaystyle {1 \over N} \sum {1 \over \sigma_i^2}}
  17253. $$
  17254. @end tex
  17255. @kindex I u C
  17256. @pindex calc-vector-pop-covariance
  17257. @tindex vpcov
  17258. The @kbd{I u C} (@code{calc-vector-pop-covariance}) [@code{vpcov}]
  17259. command computes the population covariance, which is the same as the
  17260. sample covariance computed by @kbd{u C} except dividing by @cite{N}
  17261. instead of @cite{N-1}.
  17262. @kindex H u C
  17263. @pindex calc-vector-correlation
  17264. @tindex vcorr
  17265. @cindex Correlation coefficient
  17266. @cindex Linear correlation
  17267. The @kbd{H u C} (@code{calc-vector-correlation}) [@code{vcorr}]
  17268. command computes the linear correlation coefficient of two vectors.
  17269. This is defined by the covariance of the vectors divided by the
  17270. product of their standard deviations. (There is no difference
  17271. between sample or population statistics here.)
  17272. @tex
  17273. \turnoffactive
  17274. $$ r_{x\!y} = { \sigma_{x\!y}^2 \over \sigma_x^2 \sigma_y^2 } $$
  17275. @end tex
  17276. @node Reducing and Mapping, Vector and Matrix Formats, Statistical Operations, Matrix Functions
  17277. @section Reducing and Mapping Vectors
  17278. @noindent
  17279. The commands in this section allow for more general operations on the
  17280. elements of vectors.
  17281. @kindex V A
  17282. @pindex calc-apply
  17283. @tindex apply
  17284. The simplest of these operations is @kbd{V A} (@code{calc-apply})
  17285. [@code{apply}], which applies a given operator to the elements of a vector.
  17286. For example, applying the hypothetical function @code{f} to the vector
  17287. @w{@samp{[1, 2, 3]}} would produce the function call @samp{f(1, 2, 3)}.
  17288. Applying the @code{+} function to the vector @samp{[a, b]} gives
  17289. @samp{a + b}. Applying @code{+} to the vector @samp{[a, b, c]} is an
  17290. error, since the @code{+} function expects exactly two arguments.
  17291. While @kbd{V A} is useful in some cases, you will usually find that either
  17292. @kbd{V R} or @kbd{V M}, described below, is closer to what you want.
  17293. @menu
  17294. * Specifying Operators::
  17295. * Mapping::
  17296. * Reducing::
  17297. * Nesting and Fixed Points::
  17298. * Generalized Products::
  17299. @end menu
  17300. @node Specifying Operators, Mapping, Reducing and Mapping, Reducing and Mapping
  17301. @subsection Specifying Operators
  17302. @noindent
  17303. Commands in this section (like @kbd{V A}) prompt you to press the key
  17304. corresponding to the desired operator. Press @kbd{?} for a partial
  17305. list of the available operators. Generally, an operator is any key or
  17306. sequence of keys that would normally take one or more arguments from
  17307. the stack and replace them with a result. For example, @kbd{V A H C}
  17308. uses the hyperbolic cosine operator, @code{cosh}. (Since @code{cosh}
  17309. expects one argument, @kbd{V A H C} requires a vector with a single
  17310. element as its argument.)
  17311. You can press @kbd{x} at the operator prompt to select any algebraic
  17312. function by name to use as the operator. This includes functions you
  17313. have defined yourself using the @kbd{Z F} command. (@xref{Algebraic
  17314. Definitions}.) If you give a name for which no function has been
  17315. defined, the result is left in symbolic form, as in @samp{f(1, 2, 3)}.
  17316. Calc will prompt for the number of arguments the function takes if it
  17317. can't figure it out on its own (say, because you named a function that
  17318. is currently undefined). It is also possible to type a digit key before
  17319. the function name to specify the number of arguments, e.g.,
  17320. @kbd{V M 3 x f @key{RET}} calls @code{f} with three arguments even if it
  17321. looks like it ought to have only two. This technique may be necessary
  17322. if the function allows a variable number of arguments. For example,
  17323. the @kbd{v e} [@code{vexp}] function accepts two or three arguments;
  17324. if you want to map with the three-argument version, you will have to
  17325. type @kbd{V M 3 v e}.
  17326. It is also possible to apply any formula to a vector by treating that
  17327. formula as a function. When prompted for the operator to use, press
  17328. @kbd{'} (the apostrophe) and type your formula as an algebraic entry.
  17329. You will then be prompted for the argument list, which defaults to a
  17330. list of all variables that appear in the formula, sorted into alphabetic
  17331. order. For example, suppose you enter the formula @w{@samp{x + 2y^x}}.
  17332. The default argument list would be @samp{(x y)}, which means that if
  17333. this function is applied to the arguments @samp{[3, 10]} the result will
  17334. be @samp{3 + 2*10^3}. (If you plan to use a certain formula in this
  17335. way often, you might consider defining it as a function with @kbd{Z F}.)
  17336. Another way to specify the arguments to the formula you enter is with
  17337. @kbd{$}, @kbd{$$}, and so on. For example, @kbd{V A ' $$ + 2$^$$}
  17338. has the same effect as the previous example. The argument list is
  17339. automatically taken to be @samp{($$ $)}. (The order of the arguments
  17340. may seem backwards, but it is analogous to the way normal algebraic
  17341. entry interacts with the stack.)
  17342. If you press @kbd{$} at the operator prompt, the effect is similar to
  17343. the apostrophe except that the relevant formula is taken from top-of-stack
  17344. instead. The actual vector arguments of the @kbd{V A $} or related command
  17345. then start at the second-to-top stack position. You will still be
  17346. prompted for an argument list.
  17347. @cindex Nameless functions
  17348. @cindex Generic functions
  17349. A function can be written without a name using the notation @samp{<#1 - #2>},
  17350. which means ``a function of two arguments that computes the first
  17351. argument minus the second argument.'' The symbols @samp{#1} and @samp{#2}
  17352. are placeholders for the arguments. You can use any names for these
  17353. placeholders if you wish, by including an argument list followed by a
  17354. colon: @samp{<x, y : x - y>}. When you type @kbd{V A ' $$ + 2$^$$ @key{RET}},
  17355. Calc builds the nameless function @samp{<#1 + 2 #2^#1>} as the function
  17356. to map across the vectors. When you type @kbd{V A ' x + 2y^x @key{RET} @key{RET}},
  17357. Calc builds the nameless function @w{@samp{<x, y : x + 2 y^x>}}. In both
  17358. cases, Calc also writes the nameless function to the Trail so that you
  17359. can get it back later if you wish.
  17360. If there is only one argument, you can write @samp{#} in place of @samp{#1}.
  17361. (Note that @samp{< >} notation is also used for date forms. Calc tells
  17362. that @samp{<@var{stuff}>} is a nameless function by the presence of
  17363. @samp{#} signs inside @var{stuff}, or by the fact that @var{stuff}
  17364. begins with a list of variables followed by a colon.)
  17365. You can type a nameless function directly to @kbd{V A '}, or put one on
  17366. the stack and use it with @w{@kbd{V A $}}. Calc will not prompt for an
  17367. argument list in this case, since the nameless function specifies the
  17368. argument list as well as the function itself. In @kbd{V A '}, you can
  17369. omit the @samp{< >} marks if you use @samp{#} notation for the arguments,
  17370. so that @kbd{V A ' #1+#2 @key{RET}} is the same as @kbd{V A ' <#1+#2> @key{RET}},
  17371. which in turn is the same as @kbd{V A ' $$+$ @key{RET}}.
  17372. @cindex Lambda expressions
  17373. @ignore
  17374. @starindex
  17375. @end ignore
  17376. @tindex lambda
  17377. The internal format for @samp{<x, y : x + y>} is @samp{lambda(x, y, x + y)}.
  17378. (The word @code{lambda} derives from Lisp notation and the theory of
  17379. functions.) The internal format for @samp{<#1 + #2>} is @samp{lambda(ArgA,
  17380. ArgB, ArgA + ArgB)}. Note that there is no actual Calc function called
  17381. @code{lambda}; the whole point is that the @code{lambda} expression is
  17382. used in its symbolic form, not evaluated for an answer until it is applied
  17383. to specific arguments by a command like @kbd{V A} or @kbd{V M}.
  17384. (Actually, @code{lambda} does have one special property: Its arguments
  17385. are never evaluated; for example, putting @samp{<(2/3) #>} on the stack
  17386. will not simplify the @samp{2/3} until the nameless function is actually
  17387. called.)
  17388. @tindex add
  17389. @tindex sub
  17390. @ignore
  17391. @mindex @idots
  17392. @end ignore
  17393. @tindex mul
  17394. @ignore
  17395. @mindex @null
  17396. @end ignore
  17397. @tindex div
  17398. @ignore
  17399. @mindex @null
  17400. @end ignore
  17401. @tindex pow
  17402. @ignore
  17403. @mindex @null
  17404. @end ignore
  17405. @tindex neg
  17406. @ignore
  17407. @mindex @null
  17408. @end ignore
  17409. @tindex mod
  17410. @ignore
  17411. @mindex @null
  17412. @end ignore
  17413. @tindex vconcat
  17414. As usual, commands like @kbd{V A} have algebraic function name equivalents.
  17415. For example, @kbd{V A k g} with an argument of @samp{v} is equivalent to
  17416. @samp{apply(gcd, v)}. The first argument specifies the operator name,
  17417. and is either a variable whose name is the same as the function name,
  17418. or a nameless function like @samp{<#^3+1>}. Operators that are normally
  17419. written as algebraic symbols have the names @code{add}, @code{sub},
  17420. @code{mul}, @code{div}, @code{pow}, @code{neg}, @code{mod}, and
  17421. @code{vconcat}.@refill
  17422. @ignore
  17423. @starindex
  17424. @end ignore
  17425. @tindex call
  17426. The @code{call} function builds a function call out of several arguments:
  17427. @samp{call(gcd, x, y)} is the same as @samp{apply(gcd, [x, y])}, which
  17428. in turn is the same as @samp{gcd(x, y)}. The first argument of @code{call},
  17429. like the other functions described here, may be either a variable naming a
  17430. function, or a nameless function (@samp{call(<#1+2#2>, x, y)} is the same
  17431. as @samp{x + 2y}).
  17432. (Experts will notice that it's not quite proper to use a variable to name
  17433. a function, since the name @code{gcd} corresponds to the Lisp variable
  17434. @code{var-gcd} but to the Lisp function @code{calcFunc-gcd}. Calc
  17435. automatically makes this translation, so you don't have to worry
  17436. about it.)
  17437. @node Mapping, Reducing, Specifying Operators, Reducing and Mapping
  17438. @subsection Mapping
  17439. @noindent
  17440. @kindex V M
  17441. @pindex calc-map
  17442. @tindex map
  17443. The @kbd{V M} (@code{calc-map}) [@code{map}] command applies a given
  17444. operator elementwise to one or more vectors. For example, mapping
  17445. @code{A} [@code{abs}] produces a vector of the absolute values of the
  17446. elements in the input vector. Mapping @code{+} pops two vectors from
  17447. the stack, which must be of equal length, and produces a vector of the
  17448. pairwise sums of the elements. If either argument is a non-vector, it
  17449. is duplicated for each element of the other vector. For example,
  17450. @kbd{[1,2,3] 2 V M ^} squares the elements of the specified vector.
  17451. With the 2 listed first, it would have computed a vector of powers of
  17452. two. Mapping a user-defined function pops as many arguments from the
  17453. stack as the function requires. If you give an undefined name, you will
  17454. be prompted for the number of arguments to use.@refill
  17455. If any argument to @kbd{V M} is a matrix, the operator is normally mapped
  17456. across all elements of the matrix. For example, given the matrix
  17457. @cite{[[1, -2, 3], [-4, 5, -6]]}, @kbd{V M A} takes six absolute values to
  17458. produce another @c{$3\times2$}
  17459. @asis{3x2} matrix, @cite{[[1, 2, 3], [4, 5, 6]]}.
  17460. @tindex mapr
  17461. The command @kbd{V M _} [@code{mapr}] (i.e., type an underscore at the
  17462. operator prompt) maps by rows instead. For example, @kbd{V M _ A} views
  17463. the above matrix as a vector of two 3-element row vectors. It produces
  17464. a new vector which contains the absolute values of those row vectors,
  17465. namely @cite{[3.74, 8.77]}. (Recall, the absolute value of a vector is
  17466. defined as the square root of the sum of the squares of the elements.)
  17467. Some operators accept vectors and return new vectors; for example,
  17468. @kbd{v v} reverses a vector, so @kbd{V M _ v v} would reverse each row
  17469. of the matrix to get a new matrix, @cite{[[3, -2, 1], [-6, 5, -4]]}.
  17470. Sometimes a vector of vectors (representing, say, strings, sets, or lists)
  17471. happens to look like a matrix. If so, remember to use @kbd{V M _} if you
  17472. want to map a function across the whole strings or sets rather than across
  17473. their individual elements.
  17474. @tindex mapc
  17475. The command @kbd{V M :} [@code{mapc}] maps by columns. Basically, it
  17476. transposes the input matrix, maps by rows, and then, if the result is a
  17477. matrix, transposes again. For example, @kbd{V M : A} takes the absolute
  17478. values of the three columns of the matrix, treating each as a 2-vector,
  17479. and @kbd{V M : v v} reverses the columns to get the matrix
  17480. @cite{[[-4, 5, -6], [1, -2, 3]]}.
  17481. (The symbols @kbd{_} and @kbd{:} were chosen because they had row-like
  17482. and column-like appearances, and were not already taken by useful
  17483. operators. Also, they appear shifted on most keyboards so they are easy
  17484. to type after @kbd{V M}.)
  17485. The @kbd{_} and @kbd{:} modifiers have no effect on arguments that are
  17486. not matrices (so if none of the arguments are matrices, they have no
  17487. effect at all). If some of the arguments are matrices and others are
  17488. plain numbers, the plain numbers are held constant for all rows of the
  17489. matrix (so that @kbd{2 V M _ ^} squares every row of a matrix; squaring
  17490. a vector takes a dot product of the vector with itself).
  17491. If some of the arguments are vectors with the same lengths as the
  17492. rows (for @kbd{V M _}) or columns (for @kbd{V M :}) of the matrix
  17493. arguments, those vectors are also held constant for every row or
  17494. column.
  17495. Sometimes it is useful to specify another mapping command as the operator
  17496. to use with @kbd{V M}. For example, @kbd{V M _ V A +} applies @kbd{V A +}
  17497. to each row of the input matrix, which in turn adds the two values on that
  17498. row. If you give another vector-operator command as the operator for
  17499. @kbd{V M}, it automatically uses map-by-rows mode if you don't specify
  17500. otherwise; thus @kbd{V M V A +} is equivalent to @kbd{V M _ V A +}. (If
  17501. you really want to map-by-elements another mapping command, you can use
  17502. a triple-nested mapping command: @kbd{V M V M V A +} means to map
  17503. @kbd{V M V A +} over the rows of the matrix; in turn, @kbd{V A +} is
  17504. mapped over the elements of each row.)
  17505. @tindex mapa
  17506. @tindex mapd
  17507. Previous versions of Calc had ``map across'' and ``map down'' modes
  17508. that are now considered obsolete; the old ``map across'' is now simply
  17509. @kbd{V M V A}, and ``map down'' is now @kbd{V M : V A}. The algebraic
  17510. functions @code{mapa} and @code{mapd} are still supported, though.
  17511. Note also that, while the old mapping modes were persistent (once you
  17512. set the mode, it would apply to later mapping commands until you reset
  17513. it), the new @kbd{:} and @kbd{_} modifiers apply only to the current
  17514. mapping command. The default @kbd{V M} always means map-by-elements.
  17515. @xref{Algebraic Manipulation}, for the @kbd{a M} command, which is like
  17516. @kbd{V M} but for equations and inequalities instead of vectors.
  17517. @xref{Storing Variables}, for the @kbd{s m} command which modifies a
  17518. variable's stored value using a @kbd{V M}-like operator.
  17519. @node Reducing, Nesting and Fixed Points, Mapping, Reducing and Mapping
  17520. @subsection Reducing
  17521. @noindent
  17522. @kindex V R
  17523. @pindex calc-reduce
  17524. @tindex reduce
  17525. The @kbd{V R} (@code{calc-reduce}) [@code{reduce}] command applies a given
  17526. binary operator across all the elements of a vector. A binary operator is
  17527. a function such as @code{+} or @code{max} which takes two arguments. For
  17528. example, reducing @code{+} over a vector computes the sum of the elements
  17529. of the vector. Reducing @code{-} computes the first element minus each of
  17530. the remaining elements. Reducing @code{max} computes the maximum element
  17531. and so on. In general, reducing @code{f} over the vector @samp{[a, b, c, d]}
  17532. produces @samp{f(f(f(a, b), c), d)}.
  17533. @kindex I V R
  17534. @tindex rreduce
  17535. The @kbd{I V R} [@code{rreduce}] command is similar to @kbd{V R} except
  17536. that works from right to left through the vector. For example, plain
  17537. @kbd{V R -} on the vector @samp{[a, b, c, d]} produces @samp{a - b - c - d}
  17538. but @kbd{I V R -} on the same vector produces @samp{a - (b - (c - d))},
  17539. or @samp{a - b + c - d}. This ``alternating sum'' occurs frequently
  17540. in power series expansions.
  17541. @kindex V U
  17542. @tindex accum
  17543. The @kbd{V U} (@code{calc-accumulate}) [@code{accum}] command does an
  17544. accumulation operation. Here Calc does the corresponding reduction
  17545. operation, but instead of producing only the final result, it produces
  17546. a vector of all the intermediate results. Accumulating @code{+} over
  17547. the vector @samp{[a, b, c, d]} produces the vector
  17548. @samp{[a, a + b, a + b + c, a + b + c + d]}.
  17549. @kindex I V U
  17550. @tindex raccum
  17551. The @kbd{I V U} [@code{raccum}] command does a right-to-left accumulation.
  17552. For example, @kbd{I V U -} on the vector @samp{[a, b, c, d]} produces the
  17553. vector @samp{[a - b + c - d, b - c + d, c - d, d]}.
  17554. @tindex reducea
  17555. @tindex rreducea
  17556. @tindex reduced
  17557. @tindex rreduced
  17558. As for @kbd{V M}, @kbd{V R} normally reduces a matrix elementwise. For
  17559. example, given the matrix @cite{[[a, b, c], [d, e, f]]}, @kbd{V R +} will
  17560. compute @cite{a + b + c + d + e + f}. You can type @kbd{V R _} or
  17561. @kbd{V R :} to modify this behavior. The @kbd{V R _} [@code{reducea}]
  17562. command reduces ``across'' the matrix; it reduces each row of the matrix
  17563. as a vector, then collects the results. Thus @kbd{V R _ +} of this
  17564. matrix would produce @cite{[a + b + c, d + e + f]}. Similarly, @kbd{V R :}
  17565. [@code{reduced}] reduces down; @kbd{V R : +} would produce @cite{[a + d,
  17566. b + e, c + f]}.
  17567. @tindex reducer
  17568. @tindex rreducer
  17569. There is a third ``by rows'' mode for reduction that is occasionally
  17570. useful; @kbd{V R =} [@code{reducer}] simply reduces the operator over
  17571. the rows of the matrix themselves. Thus @kbd{V R = +} on the above
  17572. matrix would get the same result as @kbd{V R : +}, since adding two
  17573. row vectors is equivalent to adding their elements. But @kbd{V R = *}
  17574. would multiply the two rows (to get a single number, their dot product),
  17575. while @kbd{V R : *} would produce a vector of the products of the columns.
  17576. These three matrix reduction modes work with @kbd{V R} and @kbd{I V R},
  17577. but they are not currently supported with @kbd{V U} or @kbd{I V U}.
  17578. @tindex reducec
  17579. @tindex rreducec
  17580. The obsolete reduce-by-columns function, @code{reducec}, is still
  17581. supported but there is no way to get it through the @kbd{V R} command.
  17582. The commands @kbd{M-# :} and @kbd{M-# _} are equivalent to typing
  17583. @kbd{M-# r} to grab a rectangle of data into Calc, and then typing
  17584. @kbd{V R : +} or @kbd{V R _ +}, respectively, to sum the columns or
  17585. rows of the matrix. @xref{Grabbing From Buffers}.
  17586. @node Nesting and Fixed Points, Generalized Products, Reducing, Reducing and Mapping
  17587. @subsection Nesting and Fixed Points
  17588. @noindent
  17589. @kindex H V R
  17590. @tindex nest
  17591. The @kbd{H V R} [@code{nest}] command applies a function to a given
  17592. argument repeatedly. It takes two values, @samp{a} and @samp{n}, from
  17593. the stack, where @samp{n} must be an integer. It then applies the
  17594. function nested @samp{n} times; if the function is @samp{f} and @samp{n}
  17595. is 3, the result is @samp{f(f(f(a)))}. The number @samp{n} may be
  17596. negative if Calc knows an inverse for the function @samp{f}; for
  17597. example, @samp{nest(sin, a, -2)} returns @samp{arcsin(arcsin(a))}.
  17598. @kindex H V U
  17599. @tindex anest
  17600. The @kbd{H V U} [@code{anest}] command is an accumulating version of
  17601. @code{nest}: It returns a vector of @samp{n+1} values, e.g.,
  17602. @samp{[a, f(a), f(f(a)), f(f(f(a)))]}. If @samp{n} is negative and
  17603. @samp{F} is the inverse of @samp{f}, then the result is of the
  17604. form @samp{[a, F(a), F(F(a)), F(F(F(a)))]}.
  17605. @kindex H I V R
  17606. @tindex fixp
  17607. @cindex Fixed points
  17608. The @kbd{H I V R} [@code{fixp}] command is like @kbd{H V R}, except
  17609. that it takes only an @samp{a} value from the stack; the function is
  17610. applied until it reaches a ``fixed point,'' i.e., until the result
  17611. no longer changes.
  17612. @kindex H I V U
  17613. @tindex afixp
  17614. The @kbd{H I V U} [@code{afixp}] command is an accumulating @code{fixp}.
  17615. The first element of the return vector will be the initial value @samp{a};
  17616. the last element will be the final result that would have been returned
  17617. by @code{fixp}.
  17618. For example, 0.739085 is a fixed point of the cosine function (in radians):
  17619. @samp{cos(0.739085) = 0.739085}. You can find this value by putting, say,
  17620. 1.0 on the stack and typing @kbd{H I V U C}. (We use the accumulating
  17621. version so we can see the intermediate results: @samp{[1, 0.540302, 0.857553,
  17622. 0.65329, ...]}. With a precision of six, this command will take 36 steps
  17623. to converge to 0.739085.)
  17624. Newton's method for finding roots is a classic example of iteration
  17625. to a fixed point. To find the square root of five starting with an
  17626. initial guess, Newton's method would look for a fixed point of the
  17627. function @samp{(x + 5/x) / 2}. Putting a guess of 1 on the stack
  17628. and typing @kbd{H I V R ' ($ + 5/$)/2 @key{RET}} quickly yields the result
  17629. 2.23607. This is equivalent to using the @kbd{a R} (@code{calc-find-root})
  17630. command to find a root of the equation @samp{x^2 = 5}.
  17631. These examples used numbers for @samp{a} values. Calc keeps applying
  17632. the function until two successive results are equal to within the
  17633. current precision. For complex numbers, both the real parts and the
  17634. imaginary parts must be equal to within the current precision. If
  17635. @samp{a} is a formula (say, a variable name), then the function is
  17636. applied until two successive results are exactly the same formula.
  17637. It is up to you to ensure that the function will eventually converge;
  17638. if it doesn't, you may have to press @kbd{C-g} to stop the Calculator.
  17639. The algebraic @code{fixp} function takes two optional arguments, @samp{n}
  17640. and @samp{tol}. The first is the maximum number of steps to be allowed,
  17641. and must be either an integer or the symbol @samp{inf} (infinity, the
  17642. default). The second is a convergence tolerance. If a tolerance is
  17643. specified, all results during the calculation must be numbers, not
  17644. formulas, and the iteration stops when the magnitude of the difference
  17645. between two successive results is less than or equal to the tolerance.
  17646. (This implies that a tolerance of zero iterates until the results are
  17647. exactly equal.)
  17648. Putting it all together, @samp{fixp(<(# + A/#)/2>, B, 20, 1e-10)}
  17649. computes the square root of @samp{A} given the initial guess @samp{B},
  17650. stopping when the result is correct within the specified tolerance, or
  17651. when 20 steps have been taken, whichever is sooner.
  17652. @node Generalized Products, , Nesting and Fixed Points, Reducing and Mapping
  17653. @subsection Generalized Products
  17654. @kindex V O
  17655. @pindex calc-outer-product
  17656. @tindex outer
  17657. The @kbd{V O} (@code{calc-outer-product}) [@code{outer}] command applies
  17658. a given binary operator to all possible pairs of elements from two
  17659. vectors, to produce a matrix. For example, @kbd{V O *} with @samp{[a, b]}
  17660. and @samp{[x, y, z]} on the stack produces a multiplication table:
  17661. @samp{[[a x, a y, a z], [b x, b y, b z]]}. Element @var{r},@var{c} of
  17662. the result matrix is obtained by applying the operator to element @var{r}
  17663. of the lefthand vector and element @var{c} of the righthand vector.
  17664. @kindex V I
  17665. @pindex calc-inner-product
  17666. @tindex inner
  17667. The @kbd{V I} (@code{calc-inner-product}) [@code{inner}] command computes
  17668. the generalized inner product of two vectors or matrices, given a
  17669. ``multiplicative'' operator and an ``additive'' operator. These can each
  17670. actually be any binary operators; if they are @samp{*} and @samp{+},
  17671. respectively, the result is a standard matrix multiplication. Element
  17672. @var{r},@var{c} of the result matrix is obtained by mapping the
  17673. multiplicative operator across row @var{r} of the lefthand matrix and
  17674. column @var{c} of the righthand matrix, and then reducing with the additive
  17675. operator. Just as for the standard @kbd{*} command, this can also do a
  17676. vector-matrix or matrix-vector inner product, or a vector-vector
  17677. generalized dot product.
  17678. Since @kbd{V I} requires two operators, it prompts twice. In each case,
  17679. you can use any of the usual methods for entering the operator. If you
  17680. use @kbd{$} twice to take both operator formulas from the stack, the
  17681. first (multiplicative) operator is taken from the top of the stack
  17682. and the second (additive) operator is taken from second-to-top.
  17683. @node Vector and Matrix Formats, , Reducing and Mapping, Matrix Functions
  17684. @section Vector and Matrix Display Formats
  17685. @noindent
  17686. Commands for controlling vector and matrix display use the @kbd{v} prefix
  17687. instead of the usual @kbd{d} prefix. But they are display modes; in
  17688. particular, they are influenced by the @kbd{I} and @kbd{H} prefix keys
  17689. in the same way (@pxref{Display Modes}). Matrix display is also
  17690. influenced by the @kbd{d O} (@code{calc-flat-language}) mode;
  17691. @pxref{Normal Language Modes}.
  17692. @kindex V <
  17693. @pindex calc-matrix-left-justify
  17694. @kindex V =
  17695. @pindex calc-matrix-center-justify
  17696. @kindex V >
  17697. @pindex calc-matrix-right-justify
  17698. The commands @kbd{v <} (@code{calc-matrix-left-justify}), @kbd{v >}
  17699. (@code{calc-matrix-right-justify}), and @w{@kbd{v =}}
  17700. (@code{calc-matrix-center-justify}) control whether matrix elements
  17701. are justified to the left, right, or center of their columns.@refill
  17702. @kindex V [
  17703. @pindex calc-vector-brackets
  17704. @kindex V @{
  17705. @pindex calc-vector-braces
  17706. @kindex V (
  17707. @pindex calc-vector-parens
  17708. The @kbd{v [} (@code{calc-vector-brackets}) command turns the square
  17709. brackets that surround vectors and matrices displayed in the stack on
  17710. and off. The @kbd{v @{} (@code{calc-vector-braces}) and @kbd{v (}
  17711. (@code{calc-vector-parens}) commands use curly braces or parentheses,
  17712. respectively, instead of square brackets. For example, @kbd{v @{} might
  17713. be used in preparation for yanking a matrix into a buffer running
  17714. Mathematica. (In fact, the Mathematica language mode uses this mode;
  17715. @pxref{Mathematica Language Mode}.) Note that, regardless of the
  17716. display mode, either brackets or braces may be used to enter vectors,
  17717. and parentheses may never be used for this purpose.@refill
  17718. @kindex V ]
  17719. @pindex calc-matrix-brackets
  17720. The @kbd{v ]} (@code{calc-matrix-brackets}) command controls the
  17721. ``big'' style display of matrices. It prompts for a string of code
  17722. letters; currently implemented letters are @code{R}, which enables
  17723. brackets on each row of the matrix; @code{O}, which enables outer
  17724. brackets in opposite corners of the matrix; and @code{C}, which
  17725. enables commas or semicolons at the ends of all rows but the last.
  17726. The default format is @samp{RO}. (Before Calc 2.00, the format
  17727. was fixed at @samp{ROC}.) Here are some example matrices:
  17728. @example
  17729. @group
  17730. [ [ 123, 0, 0 ] [ [ 123, 0, 0 ],
  17731. [ 0, 123, 0 ] [ 0, 123, 0 ],
  17732. [ 0, 0, 123 ] ] [ 0, 0, 123 ] ]
  17733. RO ROC
  17734. @end group
  17735. @end example
  17736. @noindent
  17737. @example
  17738. @group
  17739. [ 123, 0, 0 [ 123, 0, 0 ;
  17740. 0, 123, 0 0, 123, 0 ;
  17741. 0, 0, 123 ] 0, 0, 123 ]
  17742. O OC
  17743. @end group
  17744. @end example
  17745. @noindent
  17746. @example
  17747. @group
  17748. [ 123, 0, 0 ] 123, 0, 0
  17749. [ 0, 123, 0 ] 0, 123, 0
  17750. [ 0, 0, 123 ] 0, 0, 123
  17751. R @r{blank}
  17752. @end group
  17753. @end example
  17754. @noindent
  17755. Note that of the formats shown here, @samp{RO}, @samp{ROC}, and
  17756. @samp{OC} are all recognized as matrices during reading, while
  17757. the others are useful for display only.
  17758. @kindex V ,
  17759. @pindex calc-vector-commas
  17760. The @kbd{v ,} (@code{calc-vector-commas}) command turns commas on and
  17761. off in vector and matrix display.@refill
  17762. In vectors of length one, and in all vectors when commas have been
  17763. turned off, Calc adds extra parentheses around formulas that might
  17764. otherwise be ambiguous. For example, @samp{[a b]} could be a vector
  17765. of the one formula @samp{a b}, or it could be a vector of two
  17766. variables with commas turned off. Calc will display the former
  17767. case as @samp{[(a b)]}. You can disable these extra parentheses
  17768. (to make the output less cluttered at the expense of allowing some
  17769. ambiguity) by adding the letter @code{P} to the control string you
  17770. give to @kbd{v ]} (as described above).
  17771. @kindex V .
  17772. @pindex calc-full-vectors
  17773. The @kbd{v .} (@code{calc-full-vectors}) command turns abbreviated
  17774. display of long vectors on and off. In this mode, vectors of six
  17775. or more elements, or matrices of six or more rows or columns, will
  17776. be displayed in an abbreviated form that displays only the first
  17777. three elements and the last element: @samp{[a, b, c, ..., z]}.
  17778. When very large vectors are involved this will substantially
  17779. improve Calc's display speed.
  17780. @kindex t .
  17781. @pindex calc-full-trail-vectors
  17782. The @kbd{t .} (@code{calc-full-trail-vectors}) command controls a
  17783. similar mode for recording vectors in the Trail. If you turn on
  17784. this mode, vectors of six or more elements and matrices of six or
  17785. more rows or columns will be abbreviated when they are put in the
  17786. Trail. The @kbd{t y} (@code{calc-trail-yank}) command will be
  17787. unable to recover those vectors. If you are working with very
  17788. large vectors, this mode will improve the speed of all operations
  17789. that involve the trail.
  17790. @kindex V /
  17791. @pindex calc-break-vectors
  17792. The @kbd{v /} (@code{calc-break-vectors}) command turns multi-line
  17793. vector display on and off. Normally, matrices are displayed with one
  17794. row per line but all other types of vectors are displayed in a single
  17795. line. This mode causes all vectors, whether matrices or not, to be
  17796. displayed with a single element per line. Sub-vectors within the
  17797. vectors will still use the normal linear form.
  17798. @node Algebra, Units, Matrix Functions, Top
  17799. @chapter Algebra
  17800. @noindent
  17801. This section covers the Calc features that help you work with
  17802. algebraic formulas. First, the general sub-formula selection
  17803. mechanism is described; this works in conjunction with any Calc
  17804. commands. Then, commands for specific algebraic operations are
  17805. described. Finally, the flexible @dfn{rewrite rule} mechanism
  17806. is discussed.
  17807. The algebraic commands use the @kbd{a} key prefix; selection
  17808. commands use the @kbd{j} (for ``just a letter that wasn't used
  17809. for anything else'') prefix.
  17810. @xref{Editing Stack Entries}, to see how to manipulate formulas
  17811. using regular Emacs editing commands.@refill
  17812. When doing algebraic work, you may find several of the Calculator's
  17813. modes to be helpful, including algebraic-simplification mode (@kbd{m A})
  17814. or no-simplification mode (@kbd{m O}),
  17815. algebraic-entry mode (@kbd{m a}), fraction mode (@kbd{m f}), and
  17816. symbolic mode (@kbd{m s}). @xref{Mode Settings}, for discussions
  17817. of these modes. You may also wish to select ``big'' display mode (@kbd{d B}).
  17818. @xref{Normal Language Modes}.@refill
  17819. @menu
  17820. * Selecting Subformulas::
  17821. * Algebraic Manipulation::
  17822. * Simplifying Formulas::
  17823. * Polynomials::
  17824. * Calculus::
  17825. * Solving Equations::
  17826. * Numerical Solutions::
  17827. * Curve Fitting::
  17828. * Summations::
  17829. * Logical Operations::
  17830. * Rewrite Rules::
  17831. @end menu
  17832. @node Selecting Subformulas, Algebraic Manipulation, Algebra, Algebra
  17833. @section Selecting Sub-Formulas
  17834. @noindent
  17835. @cindex Selections
  17836. @cindex Sub-formulas
  17837. @cindex Parts of formulas
  17838. When working with an algebraic formula it is often necessary to
  17839. manipulate a portion of the formula rather than the formula as a
  17840. whole. Calc allows you to ``select'' a portion of any formula on
  17841. the stack. Commands which would normally operate on that stack
  17842. entry will now operate only on the sub-formula, leaving the
  17843. surrounding part of the stack entry alone.
  17844. One common non-algebraic use for selection involves vectors. To work
  17845. on one element of a vector in-place, simply select that element as a
  17846. ``sub-formula'' of the vector.
  17847. @menu
  17848. * Making Selections::
  17849. * Changing Selections::
  17850. * Displaying Selections::
  17851. * Operating on Selections::
  17852. * Rearranging with Selections::
  17853. @end menu
  17854. @node Making Selections, Changing Selections, Selecting Subformulas, Selecting Subformulas
  17855. @subsection Making Selections
  17856. @noindent
  17857. @kindex j s
  17858. @pindex calc-select-here
  17859. To select a sub-formula, move the Emacs cursor to any character in that
  17860. sub-formula, and press @w{@kbd{j s}} (@code{calc-select-here}). Calc will
  17861. highlight the smallest portion of the formula that contains that
  17862. character. By default the sub-formula is highlighted by blanking out
  17863. all of the rest of the formula with dots. Selection works in any
  17864. display mode but is perhaps easiest in ``big'' (@kbd{d B}) mode.
  17865. Suppose you enter the following formula:
  17866. @smallexample
  17867. @group
  17868. 3 ___
  17869. (a + b) + V c
  17870. 1: ---------------
  17871. 2 x + 1
  17872. @end group
  17873. @end smallexample
  17874. @noindent
  17875. (by typing @kbd{' ((a+b)^3 + sqrt(c)) / (2x+1)}). If you move the
  17876. cursor to the letter @samp{b} and press @w{@kbd{j s}}, the display changes
  17877. to
  17878. @smallexample
  17879. @group
  17880. . ...
  17881. .. . b. . . .
  17882. 1* ...............
  17883. . . . .
  17884. @end group
  17885. @end smallexample
  17886. @noindent
  17887. Every character not part of the sub-formula @samp{b} has been changed
  17888. to a dot. The @samp{*} next to the line number is to remind you that
  17889. the formula has a portion of it selected. (In this case, it's very
  17890. obvious, but it might not always be. If Embedded Mode is enabled,
  17891. the word @samp{Sel} also appears in the mode line because the stack
  17892. may not be visible. @pxref{Embedded Mode}.)
  17893. If you had instead placed the cursor on the parenthesis immediately to
  17894. the right of the @samp{b}, the selection would have been:
  17895. @smallexample
  17896. @group
  17897. . ...
  17898. (a + b) . . .
  17899. 1* ...............
  17900. . . . .
  17901. @end group
  17902. @end smallexample
  17903. @noindent
  17904. The portion selected is always large enough to be considered a complete
  17905. formula all by itself, so selecting the parenthesis selects the whole
  17906. formula that it encloses. Putting the cursor on the @samp{+} sign
  17907. would have had the same effect.
  17908. (Strictly speaking, the Emacs cursor is really the manifestation of
  17909. the Emacs ``point,'' which is a position @emph{between} two characters
  17910. in the buffer. So purists would say that Calc selects the smallest
  17911. sub-formula which contains the character to the right of ``point.'')
  17912. If you supply a numeric prefix argument @var{n}, the selection is
  17913. expanded to the @var{n}th enclosing sub-formula. Thus, positioning
  17914. the cursor on the @samp{b} and typing @kbd{C-u 1 j s} will select
  17915. @samp{a + b}; typing @kbd{C-u 2 j s} will select @samp{(a + b)^3},
  17916. and so on.
  17917. If the cursor is not on any part of the formula, or if you give a
  17918. numeric prefix that is too large, the entire formula is selected.
  17919. If the cursor is on the @samp{.} line that marks the top of the stack
  17920. (i.e., its normal ``rest position''), this command selects the entire
  17921. formula at stack level 1. Most selection commands similarly operate
  17922. on the formula at the top of the stack if you haven't positioned the
  17923. cursor on any stack entry.
  17924. @kindex j a
  17925. @pindex calc-select-additional
  17926. The @kbd{j a} (@code{calc-select-additional}) command enlarges the
  17927. current selection to encompass the cursor. To select the smallest
  17928. sub-formula defined by two different points, move to the first and
  17929. press @kbd{j s}, then move to the other and press @kbd{j a}. This
  17930. is roughly analogous to using @kbd{C-@@} (@code{set-mark-command}) to
  17931. select the two ends of a region of text during normal Emacs editing.
  17932. @kindex j o
  17933. @pindex calc-select-once
  17934. The @kbd{j o} (@code{calc-select-once}) command selects a formula in
  17935. exactly the same way as @kbd{j s}, except that the selection will
  17936. last only as long as the next command that uses it. For example,
  17937. @kbd{j o 1 +} is a handy way to add one to the sub-formula indicated
  17938. by the cursor.
  17939. (A somewhat more precise definition: The @kbd{j o} command sets a flag
  17940. such that the next command involving selected stack entries will clear
  17941. the selections on those stack entries afterwards. All other selection
  17942. commands except @kbd{j a} and @kbd{j O} clear this flag.)
  17943. @kindex j S
  17944. @kindex j O
  17945. @pindex calc-select-here-maybe
  17946. @pindex calc-select-once-maybe
  17947. The @kbd{j S} (@code{calc-select-here-maybe}) and @kbd{j O}
  17948. (@code{calc-select-once-maybe}) commands are equivalent to @kbd{j s}
  17949. and @kbd{j o}, respectively, except that if the formula already
  17950. has a selection they have no effect. This is analogous to the
  17951. behavior of some commands such as @kbd{j r} (@code{calc-rewrite-selection};
  17952. @pxref{Selections with Rewrite Rules}) and is mainly intended to be
  17953. used in keyboard macros that implement your own selection-oriented
  17954. commands.@refill
  17955. Selection of sub-formulas normally treats associative terms like
  17956. @samp{a + b - c + d} and @samp{x * y * z} as single levels of the formula.
  17957. If you place the cursor anywhere inside @samp{a + b - c + d} except
  17958. on one of the variable names and use @kbd{j s}, you will select the
  17959. entire four-term sum.
  17960. @kindex j b
  17961. @pindex calc-break-selections
  17962. The @kbd{j b} (@code{calc-break-selections}) command controls a mode
  17963. in which the ``deep structure'' of these associative formulas shows
  17964. through. Calc actually stores the above formulas as @samp{((a + b) - c) + d}
  17965. and @samp{x * (y * z)}. (Note that for certain obscure reasons, Calc
  17966. treats multiplication as right-associative.) Once you have enabled
  17967. @kbd{j b} mode, selecting with the cursor on the @samp{-} sign would
  17968. only select the @samp{a + b - c} portion, which makes sense when the
  17969. deep structure of the sum is considered. There is no way to select
  17970. the @samp{b - c + d} portion; although this might initially look
  17971. like just as legitimate a sub-formula as @samp{a + b - c}, the deep
  17972. structure shows that it isn't. The @kbd{d U} command can be used
  17973. to view the deep structure of any formula (@pxref{Normal Language Modes}).
  17974. When @kbd{j b} mode has not been enabled, the deep structure is
  17975. generally hidden by the selection commands---what you see is what
  17976. you get.
  17977. @kindex j u
  17978. @pindex calc-unselect
  17979. The @kbd{j u} (@code{calc-unselect}) command unselects the formula
  17980. that the cursor is on. If there was no selection in the formula,
  17981. this command has no effect. With a numeric prefix argument, it
  17982. unselects the @var{n}th stack element rather than using the cursor
  17983. position.
  17984. @kindex j c
  17985. @pindex calc-clear-selections
  17986. The @kbd{j c} (@code{calc-clear-selections}) command unselects all
  17987. stack elements.
  17988. @node Changing Selections, Displaying Selections, Making Selections, Selecting Subformulas
  17989. @subsection Changing Selections
  17990. @noindent
  17991. @kindex j m
  17992. @pindex calc-select-more
  17993. Once you have selected a sub-formula, you can expand it using the
  17994. @w{@kbd{j m}} (@code{calc-select-more}) command. If @samp{a + b} is
  17995. selected, pressing @w{@kbd{j m}} repeatedly works as follows:
  17996. @smallexample
  17997. @group
  17998. 3 ... 3 ___ 3 ___
  17999. (a + b) . . . (a + b) + V c (a + b) + V c
  18000. 1* ............... 1* ............... 1* ---------------
  18001. . . . . . . . . 2 x + 1
  18002. @end group
  18003. @end smallexample
  18004. @noindent
  18005. In the last example, the entire formula is selected. This is roughly
  18006. the same as having no selection at all, but because there are subtle
  18007. differences the @samp{*} character is still there on the line number.
  18008. With a numeric prefix argument @var{n}, @kbd{j m} expands @var{n}
  18009. times (or until the entire formula is selected). Note that @kbd{j s}
  18010. with argument @var{n} is equivalent to plain @kbd{j s} followed by
  18011. @kbd{j m} with argument @var{n}. If @w{@kbd{j m}} is used when there
  18012. is no current selection, it is equivalent to @w{@kbd{j s}}.
  18013. Even though @kbd{j m} does not explicitly use the location of the
  18014. cursor within the formula, it nevertheless uses the cursor to determine
  18015. which stack element to operate on. As usual, @kbd{j m} when the cursor
  18016. is not on any stack element operates on the top stack element.
  18017. @kindex j l
  18018. @pindex calc-select-less
  18019. The @kbd{j l} (@code{calc-select-less}) command reduces the current
  18020. selection around the cursor position. That is, it selects the
  18021. immediate sub-formula of the current selection which contains the
  18022. cursor, the opposite of @kbd{j m}. If the cursor is not inside the
  18023. current selection, the command de-selects the formula.
  18024. @kindex j 1-9
  18025. @pindex calc-select-part
  18026. The @kbd{j 1} through @kbd{j 9} (@code{calc-select-part}) commands
  18027. select the @var{n}th sub-formula of the current selection. They are
  18028. like @kbd{j l} (@code{calc-select-less}) except they use counting
  18029. rather than the cursor position to decide which sub-formula to select.
  18030. For example, if the current selection is @kbd{a + b + c} or
  18031. @kbd{f(a, b, c)} or @kbd{[a, b, c]}, then @kbd{j 1} selects @samp{a},
  18032. @kbd{j 2} selects @samp{b}, and @kbd{j 3} selects @samp{c}; in each of
  18033. these cases, @kbd{j 4} through @kbd{j 9} would be errors.
  18034. If there is no current selection, @kbd{j 1} through @kbd{j 9} select
  18035. the @var{n}th top-level sub-formula. (In other words, they act as if
  18036. the entire stack entry were selected first.) To select the @var{n}th
  18037. sub-formula where @var{n} is greater than nine, you must instead invoke
  18038. @w{@kbd{j 1}} with @var{n} as a numeric prefix argument.@refill
  18039. @kindex j n
  18040. @kindex j p
  18041. @pindex calc-select-next
  18042. @pindex calc-select-previous
  18043. The @kbd{j n} (@code{calc-select-next}) and @kbd{j p}
  18044. (@code{calc-select-previous}) commands change the current selection
  18045. to the next or previous sub-formula at the same level. For example,
  18046. if @samp{b} is selected in @w{@samp{2 + a*b*c + x}}, then @kbd{j n}
  18047. selects @samp{c}. Further @kbd{j n} commands would be in error because,
  18048. even though there is something to the right of @samp{c} (namely, @samp{x}),
  18049. it is not at the same level; in this case, it is not a term of the
  18050. same product as @samp{b} and @samp{c}. However, @kbd{j m} (to select
  18051. the whole product @samp{a*b*c} as a term of the sum) followed by
  18052. @w{@kbd{j n}} would successfully select the @samp{x}.
  18053. Similarly, @kbd{j p} moves the selection from the @samp{b} in this
  18054. sample formula to the @samp{a}. Both commands accept numeric prefix
  18055. arguments to move several steps at a time.
  18056. It is interesting to compare Calc's selection commands with the
  18057. Emacs Info system's commands for navigating through hierarchically
  18058. organized documentation. Calc's @kbd{j n} command is completely
  18059. analogous to Info's @kbd{n} command. Likewise, @kbd{j p} maps to
  18060. @kbd{p}, @kbd{j 2} maps to @kbd{2}, and Info's @kbd{u} is like @kbd{j m}.
  18061. (Note that @kbd{j u} stands for @code{calc-unselect}, not ``up''.)
  18062. The Info @kbd{m} command is somewhat similar to Calc's @kbd{j s} and
  18063. @kbd{j l}; in each case, you can jump directly to a sub-component
  18064. of the hierarchy simply by pointing to it with the cursor.
  18065. @node Displaying Selections, Operating on Selections, Changing Selections, Selecting Subformulas
  18066. @subsection Displaying Selections
  18067. @noindent
  18068. @kindex j d
  18069. @pindex calc-show-selections
  18070. The @kbd{j d} (@code{calc-show-selections}) command controls how
  18071. selected sub-formulas are displayed. One of the alternatives is
  18072. illustrated in the above examples; if we press @kbd{j d} we switch
  18073. to the other style in which the selected portion itself is obscured
  18074. by @samp{#} signs:
  18075. @smallexample
  18076. @group
  18077. 3 ... # ___
  18078. (a + b) . . . ## # ## + V c
  18079. 1* ............... 1* ---------------
  18080. . . . . 2 x + 1
  18081. @end group
  18082. @end smallexample
  18083. @node Operating on Selections, Rearranging with Selections, Displaying Selections, Selecting Subformulas
  18084. @subsection Operating on Selections
  18085. @noindent
  18086. Once a selection is made, all Calc commands that manipulate items
  18087. on the stack will operate on the selected portions of the items
  18088. instead. (Note that several stack elements may have selections
  18089. at once, though there can be only one selection at a time in any
  18090. given stack element.)
  18091. @kindex j e
  18092. @pindex calc-enable-selections
  18093. The @kbd{j e} (@code{calc-enable-selections}) command disables the
  18094. effect that selections have on Calc commands. The current selections
  18095. still exist, but Calc commands operate on whole stack elements anyway.
  18096. This mode can be identified by the fact that the @samp{*} markers on
  18097. the line numbers are gone, even though selections are visible. To
  18098. reactivate the selections, press @kbd{j e} again.
  18099. To extract a sub-formula as a new formula, simply select the
  18100. sub-formula and press @key{RET}. This normally duplicates the top
  18101. stack element; here it duplicates only the selected portion of that
  18102. element.
  18103. To replace a sub-formula with something different, you can enter the
  18104. new value onto the stack and press @key{TAB}. This normally exchanges
  18105. the top two stack elements; here it swaps the value you entered into
  18106. the selected portion of the formula, returning the old selected
  18107. portion to the top of the stack.
  18108. @smallexample
  18109. @group
  18110. 3 ... ... ___
  18111. (a + b) . . . 17 x y . . . 17 x y + V c
  18112. 2* ............... 2* ............. 2: -------------
  18113. . . . . . . . . 2 x + 1
  18114. 3 3
  18115. 1: 17 x y 1: (a + b) 1: (a + b)
  18116. @end group
  18117. @end smallexample
  18118. In this example we select a sub-formula of our original example,
  18119. enter a new formula, @key{TAB} it into place, then deselect to see
  18120. the complete, edited formula.
  18121. If you want to swap whole formulas around even though they contain
  18122. selections, just use @kbd{j e} before and after.
  18123. @kindex j '
  18124. @pindex calc-enter-selection
  18125. The @kbd{j '} (@code{calc-enter-selection}) command is another way
  18126. to replace a selected sub-formula. This command does an algebraic
  18127. entry just like the regular @kbd{'} key. When you press @key{RET},
  18128. the formula you type replaces the original selection. You can use
  18129. the @samp{$} symbol in the formula to refer to the original
  18130. selection. If there is no selection in the formula under the cursor,
  18131. the cursor is used to make a temporary selection for the purposes of
  18132. the command. Thus, to change a term of a formula, all you have to
  18133. do is move the Emacs cursor to that term and press @kbd{j '}.
  18134. @kindex j `
  18135. @pindex calc-edit-selection
  18136. The @kbd{j `} (@code{calc-edit-selection}) command is a similar
  18137. analogue of the @kbd{`} (@code{calc-edit}) command. It edits the
  18138. selected sub-formula in a separate buffer. If there is no
  18139. selection, it edits the sub-formula indicated by the cursor.
  18140. To delete a sub-formula, press @key{DEL}. This generally replaces
  18141. the sub-formula with the constant zero, but in a few suitable contexts
  18142. it uses the constant one instead. The @key{DEL} key automatically
  18143. deselects and re-simplifies the entire formula afterwards. Thus:
  18144. @smallexample
  18145. @group
  18146. ###
  18147. 17 x y + # # 17 x y 17 # y 17 y
  18148. 1* ------------- 1: ------- 1* ------- 1: -------
  18149. 2 x + 1 2 x + 1 2 x + 1 2 x + 1
  18150. @end group
  18151. @end smallexample
  18152. In this example, we first delete the @samp{sqrt(c)} term; Calc
  18153. accomplishes this by replacing @samp{sqrt(c)} with zero and
  18154. resimplifying. We then delete the @kbd{x} in the numerator;
  18155. since this is part of a product, Calc replaces it with @samp{1}
  18156. and resimplifies.
  18157. If you select an element of a vector and press @key{DEL}, that
  18158. element is deleted from the vector. If you delete one side of
  18159. an equation or inequality, only the opposite side remains.
  18160. @kindex j @key{DEL}
  18161. @pindex calc-del-selection
  18162. The @kbd{j @key{DEL}} (@code{calc-del-selection}) command is like
  18163. @key{DEL} but with the auto-selecting behavior of @kbd{j '} and
  18164. @kbd{j `}. It deletes the selected portion of the formula
  18165. indicated by the cursor, or, in the absence of a selection, it
  18166. deletes the sub-formula indicated by the cursor position.
  18167. @kindex j @key{RET}
  18168. @pindex calc-grab-selection
  18169. (There is also an auto-selecting @kbd{j @key{RET}} (@code{calc-copy-selection})
  18170. command.)
  18171. Normal arithmetic operations also apply to sub-formulas. Here we
  18172. select the denominator, press @kbd{5 -} to subtract five from the
  18173. denominator, press @kbd{n} to negate the denominator, then
  18174. press @kbd{Q} to take the square root.
  18175. @smallexample
  18176. @group
  18177. .. . .. . .. . .. .
  18178. 1* ....... 1* ....... 1* ....... 1* ..........
  18179. 2 x + 1 2 x - 4 4 - 2 x _________
  18180. V 4 - 2 x
  18181. @end group
  18182. @end smallexample
  18183. Certain types of operations on selections are not allowed. For
  18184. example, for an arithmetic function like @kbd{-} no more than one of
  18185. the arguments may be a selected sub-formula. (As the above example
  18186. shows, the result of the subtraction is spliced back into the argument
  18187. which had the selection; if there were more than one selection involved,
  18188. this would not be well-defined.) If you try to subtract two selections,
  18189. the command will abort with an error message.
  18190. Operations on sub-formulas sometimes leave the formula as a whole
  18191. in an ``un-natural'' state. Consider negating the @samp{2 x} term
  18192. of our sample formula by selecting it and pressing @kbd{n}
  18193. (@code{calc-change-sign}).@refill
  18194. @smallexample
  18195. @group
  18196. .. . .. .
  18197. 1* .......... 1* ...........
  18198. ......... ..........
  18199. . . . 2 x . . . -2 x
  18200. @end group
  18201. @end smallexample
  18202. Unselecting the sub-formula reveals that the minus sign, which would
  18203. normally have cancelled out with the subtraction automatically, has
  18204. not been able to do so because the subtraction was not part of the
  18205. selected portion. Pressing @kbd{=} (@code{calc-evaluate}) or doing
  18206. any other mathematical operation on the whole formula will cause it
  18207. to be simplified.
  18208. @smallexample
  18209. @group
  18210. 17 y 17 y
  18211. 1: ----------- 1: ----------
  18212. __________ _________
  18213. V 4 - -2 x V 4 + 2 x
  18214. @end group
  18215. @end smallexample
  18216. @node Rearranging with Selections, , Operating on Selections, Selecting Subformulas
  18217. @subsection Rearranging Formulas using Selections
  18218. @noindent
  18219. @kindex j R
  18220. @pindex calc-commute-right
  18221. The @kbd{j R} (@code{calc-commute-right}) command moves the selected
  18222. sub-formula to the right in its surrounding formula. Generally the
  18223. selection is one term of a sum or product; the sum or product is
  18224. rearranged according to the commutative laws of algebra.
  18225. As with @kbd{j '} and @kbd{j @key{DEL}}, the term under the cursor is used
  18226. if there is no selection in the current formula. All commands described
  18227. in this section share this property. In this example, we place the
  18228. cursor on the @samp{a} and type @kbd{j R}, then repeat.
  18229. @smallexample
  18230. 1: a + b - c 1: b + a - c 1: b - c + a
  18231. @end smallexample
  18232. @noindent
  18233. Note that in the final step above, the @samp{a} is switched with
  18234. the @samp{c} but the signs are adjusted accordingly. When moving
  18235. terms of sums and products, @kbd{j R} will never change the
  18236. mathematical meaning of the formula.
  18237. The selected term may also be an element of a vector or an argument
  18238. of a function. The term is exchanged with the one to its right.
  18239. In this case, the ``meaning'' of the vector or function may of
  18240. course be drastically changed.
  18241. @smallexample
  18242. 1: [a, b, c] 1: [b, a, c] 1: [b, c, a]
  18243. 1: f(a, b, c) 1: f(b, a, c) 1: f(b, c, a)
  18244. @end smallexample
  18245. @kindex j L
  18246. @pindex calc-commute-left
  18247. The @kbd{j L} (@code{calc-commute-left}) command is like @kbd{j R}
  18248. except that it swaps the selected term with the one to its left.
  18249. With numeric prefix arguments, these commands move the selected
  18250. term several steps at a time. It is an error to try to move a
  18251. term left or right past the end of its enclosing formula.
  18252. With numeric prefix arguments of zero, these commands move the
  18253. selected term as far as possible in the given direction.
  18254. @kindex j D
  18255. @pindex calc-sel-distribute
  18256. The @kbd{j D} (@code{calc-sel-distribute}) command mixes the selected
  18257. sum or product into the surrounding formula using the distributive
  18258. law. For example, in @samp{a * (b - c)} with the @samp{b - c}
  18259. selected, the result is @samp{a b - a c}. This also distributes
  18260. products or quotients into surrounding powers, and can also do
  18261. transformations like @samp{exp(a + b)} to @samp{exp(a) exp(b)},
  18262. where @samp{a + b} is the selected term, and @samp{ln(a ^ b)}
  18263. to @samp{ln(a) b}, where @samp{a ^ b} is the selected term.
  18264. For multiple-term sums or products, @kbd{j D} takes off one term
  18265. at a time: @samp{a * (b + c - d)} goes to @samp{a * (c - d) + a b}
  18266. with the @samp{c - d} selected so that you can type @kbd{j D}
  18267. repeatedly to expand completely. The @kbd{j D} command allows a
  18268. numeric prefix argument which specifies the maximum number of
  18269. times to expand at once; the default is one time only.
  18270. @vindex DistribRules
  18271. The @kbd{j D} command is implemented using rewrite rules.
  18272. @xref{Selections with Rewrite Rules}. The rules are stored in
  18273. the Calc variable @code{DistribRules}. A convenient way to view
  18274. these rules is to use @kbd{s e} (@code{calc-edit-variable}) which
  18275. displays and edits the stored value of a variable. Press @kbd{M-# M-#}
  18276. to return from editing mode; be careful not to make any actual changes
  18277. or else you will affect the behavior of future @kbd{j D} commands!
  18278. To extend @kbd{j D} to handle new cases, just edit @code{DistribRules}
  18279. as described above. You can then use the @kbd{s p} command to save
  18280. this variable's value permanently for future Calc sessions.
  18281. @xref{Operations on Variables}.
  18282. @kindex j M
  18283. @pindex calc-sel-merge
  18284. @vindex MergeRules
  18285. The @kbd{j M} (@code{calc-sel-merge}) command is the complement
  18286. of @kbd{j D}; given @samp{a b - a c} with either @samp{a b} or
  18287. @samp{a c} selected, the result is @samp{a * (b - c)}. Once
  18288. again, @kbd{j M} can also merge calls to functions like @code{exp}
  18289. and @code{ln}; examine the variable @code{MergeRules} to see all
  18290. the relevant rules.
  18291. @kindex j C
  18292. @pindex calc-sel-commute
  18293. @vindex CommuteRules
  18294. The @kbd{j C} (@code{calc-sel-commute}) command swaps the arguments
  18295. of the selected sum, product, or equation. It always behaves as
  18296. if @kbd{j b} mode were in effect, i.e., the sum @samp{a + b + c} is
  18297. treated as the nested sums @samp{(a + b) + c} by this command.
  18298. If you put the cursor on the first @samp{+}, the result is
  18299. @samp{(b + a) + c}; if you put the cursor on the second @samp{+}, the
  18300. result is @samp{c + (a + b)} (which the default simplifications
  18301. will rearrange to @samp{(c + a) + b}). The relevant rules are stored
  18302. in the variable @code{CommuteRules}.
  18303. You may need to turn default simplifications off (with the @kbd{m O}
  18304. command) in order to get the full benefit of @kbd{j C}. For example,
  18305. commuting @samp{a - b} produces @samp{-b + a}, but the default
  18306. simplifications will ``simplify'' this right back to @samp{a - b} if
  18307. you don't turn them off. The same is true of some of the other
  18308. manipulations described in this section.
  18309. @kindex j N
  18310. @pindex calc-sel-negate
  18311. @vindex NegateRules
  18312. The @kbd{j N} (@code{calc-sel-negate}) command replaces the selected
  18313. term with the negative of that term, then adjusts the surrounding
  18314. formula in order to preserve the meaning. For example, given
  18315. @samp{exp(a - b)} where @samp{a - b} is selected, the result is
  18316. @samp{1 / exp(b - a)}. By contrast, selecting a term and using the
  18317. regular @kbd{n} (@code{calc-change-sign}) command negates the
  18318. term without adjusting the surroundings, thus changing the meaning
  18319. of the formula as a whole. The rules variable is @code{NegateRules}.
  18320. @kindex j &
  18321. @pindex calc-sel-invert
  18322. @vindex InvertRules
  18323. The @kbd{j &} (@code{calc-sel-invert}) command is similar to @kbd{j N}
  18324. except it takes the reciprocal of the selected term. For example,
  18325. given @samp{a - ln(b)} with @samp{b} selected, the result is
  18326. @samp{a + ln(1/b)}. The rules variable is @code{InvertRules}.
  18327. @kindex j E
  18328. @pindex calc-sel-jump-equals
  18329. @vindex JumpRules
  18330. The @kbd{j E} (@code{calc-sel-jump-equals}) command moves the
  18331. selected term from one side of an equation to the other. Given
  18332. @samp{a + b = c + d} with @samp{c} selected, the result is
  18333. @samp{a + b - c = d}. This command also works if the selected
  18334. term is part of a @samp{*}, @samp{/}, or @samp{^} formula. The
  18335. relevant rules variable is @code{JumpRules}.
  18336. @kindex j I
  18337. @kindex H j I
  18338. @pindex calc-sel-isolate
  18339. The @kbd{j I} (@code{calc-sel-isolate}) command isolates the
  18340. selected term on its side of an equation. It uses the @kbd{a S}
  18341. (@code{calc-solve-for}) command to solve the equation, and the
  18342. Hyperbolic flag affects it in the same way. @xref{Solving Equations}.
  18343. When it applies, @kbd{j I} is often easier to use than @kbd{j E}.
  18344. It understands more rules of algebra, and works for inequalities
  18345. as well as equations.
  18346. @kindex j *
  18347. @kindex j /
  18348. @pindex calc-sel-mult-both-sides
  18349. @pindex calc-sel-div-both-sides
  18350. The @kbd{j *} (@code{calc-sel-mult-both-sides}) command prompts for a
  18351. formula using algebraic entry, then multiplies both sides of the
  18352. selected quotient or equation by that formula. It simplifies each
  18353. side with @kbd{a s} (@code{calc-simplify}) before re-forming the
  18354. quotient or equation. You can suppress this simplification by
  18355. providing any numeric prefix argument. There is also a @kbd{j /}
  18356. (@code{calc-sel-div-both-sides}) which is similar to @kbd{j *} but
  18357. dividing instead of multiplying by the factor you enter.
  18358. As a special feature, if the numerator of the quotient is 1, then
  18359. the denominator is expanded at the top level using the distributive
  18360. law (i.e., using the @kbd{C-u -1 a x} command). Suppose the
  18361. formula on the stack is @samp{1 / (sqrt(a) + 1)}, and you wish
  18362. to eliminate the square root in the denominator by multiplying both
  18363. sides by @samp{sqrt(a) - 1}. Calc's default simplifications would
  18364. change the result @samp{(sqrt(a) - 1) / (sqrt(a) - 1) (sqrt(a) + 1)}
  18365. right back to the original form by cancellation; Calc expands the
  18366. denominator to @samp{sqrt(a) (sqrt(a) - 1) + sqrt(a) - 1} to prevent
  18367. this. (You would now want to use an @kbd{a x} command to expand
  18368. the rest of the way, whereupon the denominator would cancel out to
  18369. the desired form, @samp{a - 1}.) When the numerator is not 1, this
  18370. initial expansion is not necessary because Calc's default
  18371. simplifications will not notice the potential cancellation.
  18372. If the selection is an inequality, @kbd{j *} and @kbd{j /} will
  18373. accept any factor, but will warn unless they can prove the factor
  18374. is either positive or negative. (In the latter case the direction
  18375. of the inequality will be switched appropriately.) @xref{Declarations},
  18376. for ways to inform Calc that a given variable is positive or
  18377. negative. If Calc can't tell for sure what the sign of the factor
  18378. will be, it will assume it is positive and display a warning
  18379. message.
  18380. For selections that are not quotients, equations, or inequalities,
  18381. these commands pull out a multiplicative factor: They divide (or
  18382. multiply) by the entered formula, simplify, then multiply (or divide)
  18383. back by the formula.
  18384. @kindex j +
  18385. @kindex j -
  18386. @pindex calc-sel-add-both-sides
  18387. @pindex calc-sel-sub-both-sides
  18388. The @kbd{j +} (@code{calc-sel-add-both-sides}) and @kbd{j -}
  18389. (@code{calc-sel-sub-both-sides}) commands analogously add to or
  18390. subtract from both sides of an equation or inequality. For other
  18391. types of selections, they extract an additive factor. A numeric
  18392. prefix argument suppresses simplification of the intermediate
  18393. results.
  18394. @kindex j U
  18395. @pindex calc-sel-unpack
  18396. The @kbd{j U} (@code{calc-sel-unpack}) command replaces the
  18397. selected function call with its argument. For example, given
  18398. @samp{a + sin(x^2)} with @samp{sin(x^2)} selected, the result
  18399. is @samp{a + x^2}. (The @samp{x^2} will remain selected; if you
  18400. wanted to change the @code{sin} to @code{cos}, just press @kbd{C}
  18401. now to take the cosine of the selected part.)
  18402. @kindex j v
  18403. @pindex calc-sel-evaluate
  18404. The @kbd{j v} (@code{calc-sel-evaluate}) command performs the
  18405. normal default simplifications on the selected sub-formula.
  18406. These are the simplifications that are normally done automatically
  18407. on all results, but which may have been partially inhibited by
  18408. previous selection-related operations, or turned off altogether
  18409. by the @kbd{m O} command. This command is just an auto-selecting
  18410. version of the @w{@kbd{a v}} command (@pxref{Algebraic Manipulation}).
  18411. With a numeric prefix argument of 2, @kbd{C-u 2 j v} applies
  18412. the @kbd{a s} (@code{calc-simplify}) command to the selected
  18413. sub-formula. With a prefix argument of 3 or more, e.g., @kbd{C-u j v}
  18414. applies the @kbd{a e} (@code{calc-simplify-extended}) command.
  18415. @xref{Simplifying Formulas}. With a negative prefix argument
  18416. it simplifies at the top level only, just as with @kbd{a v}.
  18417. Here the ``top'' level refers to the top level of the selected
  18418. sub-formula.
  18419. @kindex j "
  18420. @pindex calc-sel-expand-formula
  18421. The @kbd{j "} (@code{calc-sel-expand-formula}) command is to @kbd{a "}
  18422. (@pxref{Algebraic Manipulation}) what @kbd{j v} is to @kbd{a v}.
  18423. You can use the @kbd{j r} (@code{calc-rewrite-selection}) command
  18424. to define other algebraic operations on sub-formulas. @xref{Rewrite Rules}.
  18425. @node Algebraic Manipulation, Simplifying Formulas, Selecting Subformulas, Algebra
  18426. @section Algebraic Manipulation
  18427. @noindent
  18428. The commands in this section perform general-purpose algebraic
  18429. manipulations. They work on the whole formula at the top of the
  18430. stack (unless, of course, you have made a selection in that
  18431. formula).
  18432. Many algebra commands prompt for a variable name or formula. If you
  18433. answer the prompt with a blank line, the variable or formula is taken
  18434. from top-of-stack, and the normal argument for the command is taken
  18435. from the second-to-top stack level.
  18436. @kindex a v
  18437. @pindex calc-alg-evaluate
  18438. The @kbd{a v} (@code{calc-alg-evaluate}) command performs the normal
  18439. default simplifications on a formula; for example, @samp{a - -b} is
  18440. changed to @samp{a + b}. These simplifications are normally done
  18441. automatically on all Calc results, so this command is useful only if
  18442. you have turned default simplifications off with an @kbd{m O}
  18443. command. @xref{Simplification Modes}.
  18444. It is often more convenient to type @kbd{=}, which is like @kbd{a v}
  18445. but which also substitutes stored values for variables in the formula.
  18446. Use @kbd{a v} if you want the variables to ignore their stored values.
  18447. If you give a numeric prefix argument of 2 to @kbd{a v}, it simplifies
  18448. as if in algebraic simplification mode. This is equivalent to typing
  18449. @kbd{a s}; @pxref{Simplifying Formulas}. If you give a numeric prefix
  18450. of 3 or more, it uses extended simplification mode (@kbd{a e}).
  18451. If you give a negative prefix argument @i{-1}, @i{-2}, or @i{-3},
  18452. it simplifies in the corresponding mode but only works on the top-level
  18453. function call of the formula. For example, @samp{(2 + 3) * (2 + 3)} will
  18454. simplify to @samp{(2 + 3)^2}, without simplifying the sub-formulas
  18455. @samp{2 + 3}. As another example, typing @kbd{V R +} to sum the vector
  18456. @samp{[1, 2, 3, 4]} produces the formula @samp{reduce(add, [1, 2, 3, 4])}
  18457. in no-simplify mode. Using @kbd{a v} will evaluate this all the way to
  18458. 10; using @kbd{C-u - a v} will evaluate it only to @samp{1 + 2 + 3 + 4}.
  18459. (@xref{Reducing and Mapping}.)
  18460. @tindex evalv
  18461. @tindex evalvn
  18462. The @kbd{=} command corresponds to the @code{evalv} function, and
  18463. the related @kbd{N} command, which is like @kbd{=} but temporarily
  18464. disables symbolic (@kbd{m s}) mode during the evaluation, corresponds
  18465. to the @code{evalvn} function. (These commands interpret their prefix
  18466. arguments differently than @kbd{a v}; @kbd{=} treats the prefix as
  18467. the number of stack elements to evaluate at once, and @kbd{N} treats
  18468. it as a temporary different working precision.)
  18469. The @code{evalvn} function can take an alternate working precision
  18470. as an optional second argument. This argument can be either an
  18471. integer, to set the precision absolutely, or a vector containing
  18472. a single integer, to adjust the precision relative to the current
  18473. precision. Note that @code{evalvn} with a larger than current
  18474. precision will do the calculation at this higher precision, but the
  18475. result will as usual be rounded back down to the current precision
  18476. afterward. For example, @samp{evalvn(pi - 3.1415)} at a precision
  18477. of 12 will return @samp{9.265359e-5}; @samp{evalvn(pi - 3.1415, 30)}
  18478. will return @samp{9.26535897932e-5} (computing a 25-digit result which
  18479. is then rounded down to 12); and @samp{evalvn(pi - 3.1415, [-2])}
  18480. will return @samp{9.2654e-5}.
  18481. @kindex a "
  18482. @pindex calc-expand-formula
  18483. The @kbd{a "} (@code{calc-expand-formula}) command expands functions
  18484. into their defining formulas wherever possible. For example,
  18485. @samp{deg(x^2)} is changed to @samp{180 x^2 / pi}. Most functions,
  18486. like @code{sin} and @code{gcd}, are not defined by simple formulas
  18487. and so are unaffected by this command. One important class of
  18488. functions which @emph{can} be expanded is the user-defined functions
  18489. created by the @kbd{Z F} command. @xref{Algebraic Definitions}.
  18490. Other functions which @kbd{a "} can expand include the probability
  18491. distribution functions, most of the financial functions, and the
  18492. hyperbolic and inverse hyperbolic functions. A numeric prefix argument
  18493. affects @kbd{a "} in the same way as it does @kbd{a v}: A positive
  18494. argument expands all functions in the formula and then simplifies in
  18495. various ways; a negative argument expands and simplifies only the
  18496. top-level function call.
  18497. @kindex a M
  18498. @pindex calc-map-equation
  18499. @tindex mapeq
  18500. The @kbd{a M} (@code{calc-map-equation}) [@code{mapeq}] command applies
  18501. a given function or operator to one or more equations. It is analogous
  18502. to @kbd{V M}, which operates on vectors instead of equations.
  18503. @pxref{Reducing and Mapping}. For example, @kbd{a M S} changes
  18504. @samp{x = y+1} to @samp{sin(x) = sin(y+1)}, and @kbd{a M +} with
  18505. @samp{x = y+1} and @cite{6} on the stack produces @samp{x+6 = y+7}.
  18506. With two equations on the stack, @kbd{a M +} would add the lefthand
  18507. sides together and the righthand sides together to get the two
  18508. respective sides of a new equation.
  18509. Mapping also works on inequalities. Mapping two similar inequalities
  18510. produces another inequality of the same type. Mapping an inequality
  18511. with an equation produces an inequality of the same type. Mapping a
  18512. @samp{<=} with a @samp{<} or @samp{!=} (not-equal) produces a @samp{<}.
  18513. If inequalities with opposite direction (e.g., @samp{<} and @samp{>})
  18514. are mapped, the direction of the second inequality is reversed to
  18515. match the first: Using @kbd{a M +} on @samp{a < b} and @samp{a > 2}
  18516. reverses the latter to get @samp{2 < a}, which then allows the
  18517. combination @samp{a + 2 < b + a}, which the @kbd{a s} command can
  18518. then simplify to get @samp{2 < b}.
  18519. Using @kbd{a M *}, @kbd{a M /}, @kbd{a M n}, or @kbd{a M &} to negate
  18520. or invert an inequality will reverse the direction of the inequality.
  18521. Other adjustments to inequalities are @emph{not} done automatically;
  18522. @kbd{a M S} will change @w{@samp{x < y}} to @samp{sin(x) < sin(y)} even
  18523. though this is not true for all values of the variables.
  18524. @kindex H a M
  18525. @tindex mapeqp
  18526. With the Hyperbolic flag, @kbd{H a M} [@code{mapeqp}] does a plain
  18527. mapping operation without reversing the direction of any inequalities.
  18528. Thus, @kbd{H a M &} would change @kbd{x > 2} to @kbd{1/x > 0.5}.
  18529. (This change is mathematically incorrect, but perhaps you were
  18530. fixing an inequality which was already incorrect.)
  18531. @kindex I a M
  18532. @tindex mapeqr
  18533. With the Inverse flag, @kbd{I a M} [@code{mapeqr}] always reverses
  18534. the direction of the inequality. You might use @kbd{I a M C} to
  18535. change @samp{x < y} to @samp{cos(x) > cos(y)} if you know you are
  18536. working with small positive angles.
  18537. @kindex a b
  18538. @pindex calc-substitute
  18539. @tindex subst
  18540. The @kbd{a b} (@code{calc-substitute}) [@code{subst}] command substitutes
  18541. all occurrences
  18542. of some variable or sub-expression of an expression with a new
  18543. sub-expression. For example, substituting @samp{sin(x)} with @samp{cos(y)}
  18544. in @samp{2 sin(x)^2 + x sin(x) + sin(2 x)} produces
  18545. @samp{2 cos(y)^2 + x cos(y) + @w{sin(2 x)}}.
  18546. Note that this is a purely structural substitution; the lone @samp{x} and
  18547. the @samp{sin(2 x)} stayed the same because they did not look like
  18548. @samp{sin(x)}. @xref{Rewrite Rules}, for a more general method for
  18549. doing substitutions.@refill
  18550. The @kbd{a b} command normally prompts for two formulas, the old
  18551. one and the new one. If you enter a blank line for the first
  18552. prompt, all three arguments are taken from the stack (new, then old,
  18553. then target expression). If you type an old formula but then enter a
  18554. blank line for the new one, the new formula is taken from top-of-stack
  18555. and the target from second-to-top. If you answer both prompts, the
  18556. target is taken from top-of-stack as usual.
  18557. Note that @kbd{a b} has no understanding of commutativity or
  18558. associativity. The pattern @samp{x+y} will not match the formula
  18559. @samp{y+x}. Also, @samp{y+z} will not match inside the formula @samp{x+y+z}
  18560. because the @samp{+} operator is left-associative, so the ``deep
  18561. structure'' of that formula is @samp{(x+y) + z}. Use @kbd{d U}
  18562. (@code{calc-unformatted-language}) mode to see the true structure of
  18563. a formula. The rewrite rule mechanism, discussed later, does not have
  18564. these limitations.
  18565. As an algebraic function, @code{subst} takes three arguments:
  18566. Target expression, old, new. Note that @code{subst} is always
  18567. evaluated immediately, even if its arguments are variables, so if
  18568. you wish to put a call to @code{subst} onto the stack you must
  18569. turn the default simplifications off first (with @kbd{m O}).
  18570. @node Simplifying Formulas, Polynomials, Algebraic Manipulation, Algebra
  18571. @section Simplifying Formulas
  18572. @noindent
  18573. @kindex a s
  18574. @pindex calc-simplify
  18575. @tindex simplify
  18576. The @kbd{a s} (@code{calc-simplify}) [@code{simplify}] command applies
  18577. various algebraic rules to simplify a formula. This includes rules which
  18578. are not part of the default simplifications because they may be too slow
  18579. to apply all the time, or may not be desirable all of the time. For
  18580. example, non-adjacent terms of sums are combined, as in @samp{a + b + 2 a}
  18581. to @samp{b + 3 a}, and some formulas like @samp{sin(arcsin(x))} are
  18582. simplified to @samp{x}.
  18583. The sections below describe all the various kinds of algebraic
  18584. simplifications Calc provides in full detail. None of Calc's
  18585. simplification commands are designed to pull rabbits out of hats;
  18586. they simply apply certain specific rules to put formulas into
  18587. less redundant or more pleasing forms. Serious algebra in Calc
  18588. must be done manually, usually with a combination of selections
  18589. and rewrite rules. @xref{Rearranging with Selections}.
  18590. @xref{Rewrite Rules}.
  18591. @xref{Simplification Modes}, for commands to control what level of
  18592. simplification occurs automatically. Normally only the ``default
  18593. simplifications'' occur.
  18594. @menu
  18595. * Default Simplifications::
  18596. * Algebraic Simplifications::
  18597. * Unsafe Simplifications::
  18598. * Simplification of Units::
  18599. @end menu
  18600. @node Default Simplifications, Algebraic Simplifications, Simplifying Formulas, Simplifying Formulas
  18601. @subsection Default Simplifications
  18602. @noindent
  18603. @cindex Default simplifications
  18604. This section describes the ``default simplifications,'' those which are
  18605. normally applied to all results. For example, if you enter the variable
  18606. @cite{x} on the stack twice and push @kbd{+}, Calc's default
  18607. simplifications automatically change @cite{x + x} to @cite{2 x}.
  18608. The @kbd{m O} command turns off the default simplifications, so that
  18609. @cite{x + x} will remain in this form unless you give an explicit
  18610. ``simplify'' command like @kbd{=} or @kbd{a v}. @xref{Algebraic
  18611. Manipulation}. The @kbd{m D} command turns the default simplifications
  18612. back on.
  18613. The most basic default simplification is the evaluation of functions.
  18614. For example, @cite{2 + 3} is evaluated to @cite{5}, and @cite{@t{sqrt}(9)}
  18615. is evaluated to @cite{3}. Evaluation does not occur if the arguments
  18616. to a function are somehow of the wrong type (@cite{@t{tan}([2,3,4])},
  18617. range (@cite{@t{tan}(90)}), or number (@cite{@t{tan}(3,5)}), or if the
  18618. function name is not recognized (@cite{@t{f}(5)}), or if ``symbolic''
  18619. mode (@pxref{Symbolic Mode}) prevents evaluation (@cite{@t{sqrt}(2)}).
  18620. Calc simplifies (evaluates) the arguments to a function before it
  18621. simplifies the function itself. Thus @cite{@t{sqrt}(5+4)} is
  18622. simplified to @cite{@t{sqrt}(9)} before the @code{sqrt} function
  18623. itself is applied. There are very few exceptions to this rule:
  18624. @code{quote}, @code{lambda}, and @code{condition} (the @code{::}
  18625. operator) do not evaluate their arguments, @code{if} (the @code{? :}
  18626. operator) does not evaluate all of its arguments, and @code{evalto}
  18627. does not evaluate its lefthand argument.
  18628. Most commands apply the default simplifications to all arguments they
  18629. take from the stack, perform a particular operation, then simplify
  18630. the result before pushing it back on the stack. In the common special
  18631. case of regular arithmetic commands like @kbd{+} and @kbd{Q} [@code{sqrt}],
  18632. the arguments are simply popped from the stack and collected into a
  18633. suitable function call, which is then simplified (the arguments being
  18634. simplified first as part of the process, as described above).
  18635. The default simplifications are too numerous to describe completely
  18636. here, but this section will describe the ones that apply to the
  18637. major arithmetic operators. This list will be rather technical in
  18638. nature, and will probably be interesting to you only if you are
  18639. a serious user of Calc's algebra facilities.
  18640. @tex
  18641. \bigskip
  18642. @end tex
  18643. As well as the simplifications described here, if you have stored
  18644. any rewrite rules in the variable @code{EvalRules} then these rules
  18645. will also be applied before any built-in default simplifications.
  18646. @xref{Automatic Rewrites}, for details.
  18647. @tex
  18648. \bigskip
  18649. @end tex
  18650. And now, on with the default simplifications:
  18651. Arithmetic operators like @kbd{+} and @kbd{*} always take two
  18652. arguments in Calc's internal form. Sums and products of three or
  18653. more terms are arranged by the associative law of algebra into
  18654. a left-associative form for sums, @cite{((a + b) + c) + d}, and
  18655. a right-associative form for products, @cite{a * (b * (c * d))}.
  18656. Formulas like @cite{(a + b) + (c + d)} are rearranged to
  18657. left-associative form, though this rarely matters since Calc's
  18658. algebra commands are designed to hide the inner structure of
  18659. sums and products as much as possible. Sums and products in
  18660. their proper associative form will be written without parentheses
  18661. in the examples below.
  18662. Sums and products are @emph{not} rearranged according to the
  18663. commutative law (@cite{a + b} to @cite{b + a}) except in a few
  18664. special cases described below. Some algebra programs always
  18665. rearrange terms into a canonical order, which enables them to
  18666. see that @cite{a b + b a} can be simplified to @cite{2 a b}.
  18667. Calc assumes you have put the terms into the order you want
  18668. and generally leaves that order alone, with the consequence
  18669. that formulas like the above will only be simplified if you
  18670. explicitly give the @kbd{a s} command. @xref{Algebraic
  18671. Simplifications}.
  18672. Differences @cite{a - b} are treated like sums @cite{a + (-b)}
  18673. for purposes of simplification; one of the default simplifications
  18674. is to rewrite @cite{a + (-b)} or @cite{(-b) + a}, where @cite{-b}
  18675. represents a ``negative-looking'' term, into @cite{a - b} form.
  18676. ``Negative-looking'' means negative numbers, negated formulas like
  18677. @cite{-x}, and products or quotients in which either term is
  18678. negative-looking.
  18679. Other simplifications involving negation are @cite{-(-x)} to @cite{x};
  18680. @cite{-(a b)} or @cite{-(a/b)} where either @cite{a} or @cite{b} is
  18681. negative-looking, simplified by negating that term, or else where
  18682. @cite{a} or @cite{b} is any number, by negating that number;
  18683. @cite{-(a + b)} to @cite{-a - b}, and @cite{-(b - a)} to @cite{a - b}.
  18684. (This, and rewriting @cite{(-b) + a} to @cite{a - b}, are the only
  18685. cases where the order of terms in a sum is changed by the default
  18686. simplifications.)
  18687. The distributive law is used to simplify sums in some cases:
  18688. @cite{a x + b x} to @cite{(a + b) x}, where @cite{a} represents
  18689. a number or an implicit 1 or @i{-1} (as in @cite{x} or @cite{-x})
  18690. and similarly for @cite{b}. Use the @kbd{a c}, @w{@kbd{a f}}, or
  18691. @kbd{j M} commands to merge sums with non-numeric coefficients
  18692. using the distributive law.
  18693. The distributive law is only used for sums of two terms, or
  18694. for adjacent terms in a larger sum. Thus @cite{a + b + b + c}
  18695. is simplified to @cite{a + 2 b + c}, but @cite{a + b + c + b}
  18696. is not simplified. The reason is that comparing all terms of a
  18697. sum with one another would require time proportional to the
  18698. square of the number of terms; Calc relegates potentially slow
  18699. operations like this to commands that have to be invoked
  18700. explicitly, like @kbd{a s}.
  18701. Finally, @cite{a + 0} and @cite{0 + a} are simplified to @cite{a}.
  18702. A consequence of the above rules is that @cite{0 - a} is simplified
  18703. to @cite{-a}.
  18704. @tex
  18705. \bigskip
  18706. @end tex
  18707. The products @cite{1 a} and @cite{a 1} are simplified to @cite{a};
  18708. @cite{(-1) a} and @cite{a (-1)} are simplified to @cite{-a};
  18709. @cite{0 a} and @cite{a 0} are simplified to @cite{0}, except that
  18710. in matrix mode where @cite{a} is not provably scalar the result
  18711. is the generic zero matrix @samp{idn(0)}, and that if @cite{a} is
  18712. infinite the result is @samp{nan}.
  18713. Also, @cite{(-a) b} and @cite{a (-b)} are simplified to @cite{-(a b)},
  18714. where this occurs for negated formulas but not for regular negative
  18715. numbers.
  18716. Products are commuted only to move numbers to the front:
  18717. @cite{a b 2} is commuted to @cite{2 a b}.
  18718. The product @cite{a (b + c)} is distributed over the sum only if
  18719. @cite{a} and at least one of @cite{b} and @cite{c} are numbers:
  18720. @cite{2 (x + 3)} goes to @cite{2 x + 6}. The formula
  18721. @cite{(-a) (b - c)}, where @cite{-a} is a negative number, is
  18722. rewritten to @cite{a (c - b)}.
  18723. The distributive law of products and powers is used for adjacent
  18724. terms of the product: @cite{x^a x^b} goes to @c{$x^{a+b}$}
  18725. @cite{x^(a+b)}
  18726. where @cite{a} is a number, or an implicit 1 (as in @cite{x}),
  18727. or the implicit one-half of @cite{@t{sqrt}(x)}, and similarly for
  18728. @cite{b}. The result is written using @samp{sqrt} or @samp{1/sqrt}
  18729. if the sum of the powers is @cite{1/2} or @cite{-1/2}, respectively.
  18730. If the sum of the powers is zero, the product is simplified to
  18731. @cite{1} or to @samp{idn(1)} if matrix mode is enabled.
  18732. The product of a negative power times anything but another negative
  18733. power is changed to use division: @c{$x^{-2} y$}
  18734. @cite{x^(-2) y} goes to @cite{y / x^2} unless matrix mode is
  18735. in effect and neither @cite{x} nor @cite{y} are scalar (in which
  18736. case it is considered unsafe to rearrange the order of the terms).
  18737. Finally, @cite{a (b/c)} is rewritten to @cite{(a b)/c}, and also
  18738. @cite{(a/b) c} is changed to @cite{(a c)/b} unless in matrix mode.
  18739. @tex
  18740. \bigskip
  18741. @end tex
  18742. Simplifications for quotients are analogous to those for products.
  18743. The quotient @cite{0 / x} is simplified to @cite{0}, with the same
  18744. exceptions that were noted for @cite{0 x}. Likewise, @cite{x / 1}
  18745. and @cite{x / (-1)} are simplified to @cite{x} and @cite{-x},
  18746. respectively.
  18747. The quotient @cite{x / 0} is left unsimplified or changed to an
  18748. infinite quantity, as directed by the current infinite mode.
  18749. @xref{Infinite Mode}.
  18750. The expression @c{$a / b^{-c}$}
  18751. @cite{a / b^(-c)} is changed to @cite{a b^c},
  18752. where @cite{-c} is any negative-looking power. Also, @cite{1 / b^c}
  18753. is changed to @c{$b^{-c}$}
  18754. @cite{b^(-c)} for any power @cite{c}.
  18755. Also, @cite{(-a) / b} and @cite{a / (-b)} go to @cite{-(a/b)};
  18756. @cite{(a/b) / c} goes to @cite{a / (b c)}; and @cite{a / (b/c)}
  18757. goes to @cite{(a c) / b} unless matrix mode prevents this
  18758. rearrangement. Similarly, @cite{a / (b:c)} is simplified to
  18759. @cite{(c:b) a} for any fraction @cite{b:c}.
  18760. The distributive law is applied to @cite{(a + b) / c} only if
  18761. @cite{c} and at least one of @cite{a} and @cite{b} are numbers.
  18762. Quotients of powers and square roots are distributed just as
  18763. described for multiplication.
  18764. Quotients of products cancel only in the leading terms of the
  18765. numerator and denominator. In other words, @cite{a x b / a y b}
  18766. is cancelled to @cite{x b / y b} but not to @cite{x / y}. Once
  18767. again this is because full cancellation can be slow; use @kbd{a s}
  18768. to cancel all terms of the quotient.
  18769. Quotients of negative-looking values are simplified according
  18770. to @cite{(-a) / (-b)} to @cite{a / b}, @cite{(-a) / (b - c)}
  18771. to @cite{a / (c - b)}, and @cite{(a - b) / (-c)} to @cite{(b - a) / c}.
  18772. @tex
  18773. \bigskip
  18774. @end tex
  18775. The formula @cite{x^0} is simplified to @cite{1}, or to @samp{idn(1)}
  18776. in matrix mode. The formula @cite{0^x} is simplified to @cite{0}
  18777. unless @cite{x} is a negative number or complex number, in which
  18778. case the result is an infinity or an unsimplified formula according
  18779. to the current infinite mode. Note that @cite{0^0} is an
  18780. indeterminate form, as evidenced by the fact that the simplifications
  18781. for @cite{x^0} and @cite{0^x} conflict when @cite{x=0}.
  18782. Powers of products or quotients @cite{(a b)^c}, @cite{(a/b)^c}
  18783. are distributed to @cite{a^c b^c}, @cite{a^c / b^c} only if @cite{c}
  18784. is an integer, or if either @cite{a} or @cite{b} are nonnegative
  18785. real numbers. Powers of powers @cite{(a^b)^c} are simplified to
  18786. @c{$a^{b c}$}
  18787. @cite{a^(b c)} only when @cite{c} is an integer and @cite{b c} also
  18788. evaluates to an integer. Without these restrictions these simplifications
  18789. would not be safe because of problems with principal values.
  18790. (In other words, @c{$((-3)^{1/2})^2$}
  18791. @cite{((-3)^1:2)^2} is safe to simplify, but
  18792. @c{$((-3)^2)^{1/2}$}
  18793. @cite{((-3)^2)^1:2} is not.) @xref{Declarations}, for ways to inform
  18794. Calc that your variables satisfy these requirements.
  18795. As a special case of this rule, @cite{@t{sqrt}(x)^n} is simplified to
  18796. @c{$x^{n/2}$}
  18797. @cite{x^(n/2)} only for even integers @cite{n}.
  18798. If @cite{a} is known to be real, @cite{b} is an even integer, and
  18799. @cite{c} is a half- or quarter-integer, then @cite{(a^b)^c} is
  18800. simplified to @c{$@t{abs}(a^{b c})$}
  18801. @cite{@t{abs}(a^(b c))}.
  18802. Also, @cite{(-a)^b} is simplified to @cite{a^b} if @cite{b} is an
  18803. even integer, or to @cite{-(a^b)} if @cite{b} is an odd integer,
  18804. for any negative-looking expression @cite{-a}.
  18805. Square roots @cite{@t{sqrt}(x)} generally act like one-half powers
  18806. @c{$x^{1:2}$}
  18807. @cite{x^1:2} for the purposes of the above-listed simplifications.
  18808. Also, note that @c{$1 / x^{1:2}$}
  18809. @cite{1 / x^1:2} is changed to @c{$x^{-1:2}$}
  18810. @cite{x^(-1:2)},
  18811. but @cite{1 / @t{sqrt}(x)} is left alone.
  18812. @tex
  18813. \bigskip
  18814. @end tex
  18815. Generic identity matrices (@pxref{Matrix Mode}) are simplified by the
  18816. following rules: @cite{@t{idn}(a) + b} to @cite{a + b} if @cite{b}
  18817. is provably scalar, or expanded out if @cite{b} is a matrix;
  18818. @cite{@t{idn}(a) + @t{idn}(b)} to @cite{@t{idn}(a + b)};
  18819. @cite{-@t{idn}(a)} to @cite{@t{idn}(-a)}; @cite{a @t{idn}(b)} to
  18820. @cite{@t{idn}(a b)} if @cite{a} is provably scalar, or to @cite{a b}
  18821. if @cite{a} is provably non-scalar; @cite{@t{idn}(a) @t{idn}(b)}
  18822. to @cite{@t{idn}(a b)}; analogous simplifications for quotients
  18823. involving @code{idn}; and @cite{@t{idn}(a)^n} to @cite{@t{idn}(a^n)}
  18824. where @cite{n} is an integer.
  18825. @tex
  18826. \bigskip
  18827. @end tex
  18828. The @code{floor} function and other integer truncation functions
  18829. vanish if the argument is provably integer-valued, so that
  18830. @cite{@t{floor}(@t{round}(x))} simplifies to @cite{@t{round}(x)}.
  18831. Also, combinations of @code{float}, @code{floor} and its friends,
  18832. and @code{ffloor} and its friends, are simplified in appropriate
  18833. ways. @xref{Integer Truncation}.
  18834. The expression @cite{@t{abs}(-x)} changes to @cite{@t{abs}(x)}.
  18835. The expression @cite{@t{abs}(@t{abs}(x))} changes to @cite{@t{abs}(x)};
  18836. in fact, @cite{@t{abs}(x)} changes to @cite{x} or @cite{-x} if @cite{x}
  18837. is provably nonnegative or nonpositive (@pxref{Declarations}).
  18838. While most functions do not recognize the variable @code{i} as an
  18839. imaginary number, the @code{arg} function does handle the two cases
  18840. @cite{@t{arg}(@t{i})} and @cite{@t{arg}(-@t{i})} just for convenience.
  18841. The expression @cite{@t{conj}(@t{conj}(x))} simplifies to @cite{x}.
  18842. Various other expressions involving @code{conj}, @code{re}, and
  18843. @code{im} are simplified, especially if some of the arguments are
  18844. provably real or involve the constant @code{i}. For example,
  18845. @cite{@t{conj}(a + b i)} is changed to @cite{@t{conj}(a) - @t{conj}(b) i},
  18846. or to @cite{a - b i} if @cite{a} and @cite{b} are known to be real.
  18847. Functions like @code{sin} and @code{arctan} generally don't have
  18848. any default simplifications beyond simply evaluating the functions
  18849. for suitable numeric arguments and infinity. The @kbd{a s} command
  18850. described in the next section does provide some simplifications for
  18851. these functions, though.
  18852. One important simplification that does occur is that @cite{@t{ln}(@t{e})}
  18853. is simplified to 1, and @cite{@t{ln}(@t{e}^x)} is simplified to @cite{x}
  18854. for any @cite{x}. This occurs even if you have stored a different
  18855. value in the Calc variable @samp{e}; but this would be a bad idea
  18856. in any case if you were also using natural logarithms!
  18857. Among the logical functions, @t{(@var{a} <= @var{b})} changes to
  18858. @t{@var{a} > @var{b}} and so on. Equations and inequalities where both sides
  18859. are either negative-looking or zero are simplified by negating both sides
  18860. and reversing the inequality. While it might seem reasonable to simplify
  18861. @cite{!!x} to @cite{x}, this would not be valid in general because
  18862. @cite{!!2} is 1, not 2.
  18863. Most other Calc functions have few if any default simplifications
  18864. defined, aside of course from evaluation when the arguments are
  18865. suitable numbers.
  18866. @node Algebraic Simplifications, Unsafe Simplifications, Default Simplifications, Simplifying Formulas
  18867. @subsection Algebraic Simplifications
  18868. @noindent
  18869. @cindex Algebraic simplifications
  18870. The @kbd{a s} command makes simplifications that may be too slow to
  18871. do all the time, or that may not be desirable all of the time.
  18872. If you find these simplifications are worthwhile, you can type
  18873. @kbd{m A} to have Calc apply them automatically.
  18874. This section describes all simplifications that are performed by
  18875. the @kbd{a s} command. Note that these occur in addition to the
  18876. default simplifications; even if the default simplifications have
  18877. been turned off by an @kbd{m O} command, @kbd{a s} will turn them
  18878. back on temporarily while it simplifies the formula.
  18879. There is a variable, @code{AlgSimpRules}, in which you can put rewrites
  18880. to be applied by @kbd{a s}. Its use is analogous to @code{EvalRules},
  18881. but without the special restrictions. Basically, the simplifier does
  18882. @samp{@w{a r} AlgSimpRules} with an infinite repeat count on the whole
  18883. expression being simplified, then it traverses the expression applying
  18884. the built-in rules described below. If the result is different from
  18885. the original expression, the process repeats with the default
  18886. simplifications (including @code{EvalRules}), then @code{AlgSimpRules},
  18887. then the built-in simplifications, and so on.
  18888. @tex
  18889. \bigskip
  18890. @end tex
  18891. Sums are simplified in two ways. Constant terms are commuted to the
  18892. end of the sum, so that @cite{a + 2 + b} changes to @cite{a + b + 2}.
  18893. The only exception is that a constant will not be commuted away
  18894. from the first position of a difference, i.e., @cite{2 - x} is not
  18895. commuted to @cite{-x + 2}.
  18896. Also, terms of sums are combined by the distributive law, as in
  18897. @cite{x + y + 2 x} to @cite{y + 3 x}. This always occurs for
  18898. adjacent terms, but @kbd{a s} compares all pairs of terms including
  18899. non-adjacent ones.
  18900. @tex
  18901. \bigskip
  18902. @end tex
  18903. Products are sorted into a canonical order using the commutative
  18904. law. For example, @cite{b c a} is commuted to @cite{a b c}.
  18905. This allows easier comparison of products; for example, the default
  18906. simplifications will not change @cite{x y + y x} to @cite{2 x y},
  18907. but @kbd{a s} will; it first rewrites the sum to @cite{x y + x y},
  18908. and then the default simplifications are able to recognize a sum
  18909. of identical terms.
  18910. The canonical ordering used to sort terms of products has the
  18911. property that real-valued numbers, interval forms and infinities
  18912. come first, and are sorted into increasing order. The @kbd{V S}
  18913. command uses the same ordering when sorting a vector.
  18914. Sorting of terms of products is inhibited when matrix mode is
  18915. turned on; in this case, Calc will never exchange the order of
  18916. two terms unless it knows at least one of the terms is a scalar.
  18917. Products of powers are distributed by comparing all pairs of
  18918. terms, using the same method that the default simplifications
  18919. use for adjacent terms of products.
  18920. Even though sums are not sorted, the commutative law is still
  18921. taken into account when terms of a product are being compared.
  18922. Thus @cite{(x + y) (y + x)} will be simplified to @cite{(x + y)^2}.
  18923. A subtle point is that @cite{(x - y) (y - x)} will @emph{not}
  18924. be simplified to @cite{-(x - y)^2}; Calc does not notice that
  18925. one term can be written as a constant times the other, even if
  18926. that constant is @i{-1}.
  18927. A fraction times any expression, @cite{(a:b) x}, is changed to
  18928. a quotient involving integers: @cite{a x / b}. This is not
  18929. done for floating-point numbers like @cite{0.5}, however. This
  18930. is one reason why you may find it convenient to turn Fraction mode
  18931. on while doing algebra; @pxref{Fraction Mode}.
  18932. @tex
  18933. \bigskip
  18934. @end tex
  18935. Quotients are simplified by comparing all terms in the numerator
  18936. with all terms in the denominator for possible cancellation using
  18937. the distributive law. For example, @cite{a x^2 b / c x^3 d} will
  18938. cancel @cite{x^2} from both sides to get @cite{a b / c x d}.
  18939. (The terms in the denominator will then be rearranged to @cite{c d x}
  18940. as described above.) If there is any common integer or fractional
  18941. factor in the numerator and denominator, it is cancelled out;
  18942. for example, @cite{(4 x + 6) / 8 x} simplifies to @cite{(2 x + 3) / 4 x}.
  18943. Non-constant common factors are not found even by @kbd{a s}. To
  18944. cancel the factor @cite{a} in @cite{(a x + a) / a^2} you could first
  18945. use @kbd{j M} on the product @cite{a x} to Merge the numerator to
  18946. @cite{a (1+x)}, which can then be simplified successfully.
  18947. @tex
  18948. \bigskip
  18949. @end tex
  18950. Integer powers of the variable @code{i} are simplified according
  18951. to the identity @cite{i^2 = -1}. If you store a new value other
  18952. than the complex number @cite{(0,1)} in @code{i}, this simplification
  18953. will no longer occur. This is done by @kbd{a s} instead of by default
  18954. in case someone (unwisely) uses the name @code{i} for a variable
  18955. unrelated to complex numbers; it would be unfortunate if Calc
  18956. quietly and automatically changed this formula for reasons the
  18957. user might not have been thinking of.
  18958. Square roots of integer or rational arguments are simplified in
  18959. several ways. (Note that these will be left unevaluated only in
  18960. Symbolic mode.) First, square integer or rational factors are
  18961. pulled out so that @cite{@t{sqrt}(8)} is rewritten as
  18962. @c{$2\,\t{sqrt}(2)$}
  18963. @cite{2 sqrt(2)}. Conceptually speaking this implies factoring
  18964. the argument into primes and moving pairs of primes out of the
  18965. square root, but for reasons of efficiency Calc only looks for
  18966. primes up to 29.
  18967. Square roots in the denominator of a quotient are moved to the
  18968. numerator: @cite{1 / @t{sqrt}(3)} changes to @cite{@t{sqrt}(3) / 3}.
  18969. The same effect occurs for the square root of a fraction:
  18970. @cite{@t{sqrt}(2:3)} changes to @cite{@t{sqrt}(6) / 3}.
  18971. @tex
  18972. \bigskip
  18973. @end tex
  18974. The @code{%} (modulo) operator is simplified in several ways
  18975. when the modulus @cite{M} is a positive real number. First, if
  18976. the argument is of the form @cite{x + n} for some real number
  18977. @cite{n}, then @cite{n} is itself reduced modulo @cite{M}. For
  18978. example, @samp{(x - 23) % 10} is simplified to @samp{(x + 7) % 10}.
  18979. If the argument is multiplied by a constant, and this constant
  18980. has a common integer divisor with the modulus, then this factor is
  18981. cancelled out. For example, @samp{12 x % 15} is changed to
  18982. @samp{3 (4 x % 5)} by factoring out 3. Also, @samp{(12 x + 1) % 15}
  18983. is changed to @samp{3 ((4 x + 1:3) % 5)}. While these forms may
  18984. not seem ``simpler,'' they allow Calc to discover useful information
  18985. about modulo forms in the presence of declarations.
  18986. If the modulus is 1, then Calc can use @code{int} declarations to
  18987. evaluate the expression. For example, the idiom @samp{x % 2} is
  18988. often used to check whether a number is odd or even. As described
  18989. above, @w{@samp{2 n % 2}} and @samp{(2 n + 1) % 2} are simplified to
  18990. @samp{2 (n % 1)} and @samp{2 ((n + 1:2) % 1)}, respectively; Calc
  18991. can simplify these to 0 and 1 (respectively) if @code{n} has been
  18992. declared to be an integer.
  18993. @tex
  18994. \bigskip
  18995. @end tex
  18996. Trigonometric functions are simplified in several ways. First,
  18997. @cite{@t{sin}(@t{arcsin}(x))} is simplified to @cite{x}, and
  18998. similarly for @code{cos} and @code{tan}. If the argument to
  18999. @code{sin} is negative-looking, it is simplified to @cite{-@t{sin}(x)},
  19000. and similarly for @code{cos} and @code{tan}. Finally, certain
  19001. special values of the argument are recognized;
  19002. @pxref{Trigonometric and Hyperbolic Functions}.
  19003. Trigonometric functions of inverses of different trigonometric
  19004. functions can also be simplified, as in @cite{@t{sin}(@t{arccos}(x))}
  19005. to @cite{@t{sqrt}(1 - x^2)}.
  19006. Hyperbolic functions of their inverses and of negative-looking
  19007. arguments are also handled, as are exponentials of inverse
  19008. hyperbolic functions.
  19009. No simplifications for inverse trigonometric and hyperbolic
  19010. functions are known, except for negative arguments of @code{arcsin},
  19011. @code{arctan}, @code{arcsinh}, and @code{arctanh}. Note that
  19012. @cite{@t{arcsin}(@t{sin}(x))} can @emph{not} safely change to
  19013. @cite{x}, since this only correct within an integer multiple
  19014. of @c{$2 \pi$}
  19015. @cite{2 pi} radians or 360 degrees. However,
  19016. @cite{@t{arcsinh}(@t{sinh}(x))} is simplified to @cite{x} if
  19017. @cite{x} is known to be real.
  19018. Several simplifications that apply to logarithms and exponentials
  19019. are that @cite{@t{exp}(@t{ln}(x))}, @c{$@t{e}^{\ln(x)}$}
  19020. @cite{e^@t{ln}(x)}, and
  19021. @c{$10^{{\rm log10}(x)}$}
  19022. @cite{10^@t{log10}(x)} all reduce to @cite{x}.
  19023. Also, @cite{@t{ln}(@t{exp}(x))}, etc., can reduce to @cite{x} if
  19024. @cite{x} is provably real. The form @cite{@t{exp}(x)^y} is simplified
  19025. to @cite{@t{exp}(x y)}. If @cite{x} is a suitable multiple of @c{$\pi i$}
  19026. @cite{pi i}
  19027. (as described above for the trigonometric functions), then @cite{@t{exp}(x)}
  19028. or @cite{e^x} will be expanded. Finally, @cite{@t{ln}(x)} is simplified
  19029. to a form involving @code{pi} and @code{i} where @cite{x} is provably
  19030. negative, positive imaginary, or negative imaginary.
  19031. The error functions @code{erf} and @code{erfc} are simplified when
  19032. their arguments are negative-looking or are calls to the @code{conj}
  19033. function.
  19034. @tex
  19035. \bigskip
  19036. @end tex
  19037. Equations and inequalities are simplified by cancelling factors
  19038. of products, quotients, or sums on both sides. Inequalities
  19039. change sign if a negative multiplicative factor is cancelled.
  19040. Non-constant multiplicative factors as in @cite{a b = a c} are
  19041. cancelled from equations only if they are provably nonzero (generally
  19042. because they were declared so; @pxref{Declarations}). Factors
  19043. are cancelled from inequalities only if they are nonzero and their
  19044. sign is known.
  19045. Simplification also replaces an equation or inequality with
  19046. 1 or 0 (``true'' or ``false'') if it can through the use of
  19047. declarations. If @cite{x} is declared to be an integer greater
  19048. than 5, then @cite{x < 3}, @cite{x = 3}, and @cite{x = 7.5} are
  19049. all simplified to 0, but @cite{x > 3} is simplified to 1.
  19050. By a similar analysis, @cite{abs(x) >= 0} is simplified to 1,
  19051. as is @cite{x^2 >= 0} if @cite{x} is known to be real.
  19052. @node Unsafe Simplifications, Simplification of Units, Algebraic Simplifications, Simplifying Formulas
  19053. @subsection ``Unsafe'' Simplifications
  19054. @noindent
  19055. @cindex Unsafe simplifications
  19056. @cindex Extended simplification
  19057. @kindex a e
  19058. @pindex calc-simplify-extended
  19059. @ignore
  19060. @mindex esimpl@idots
  19061. @end ignore
  19062. @tindex esimplify
  19063. The @kbd{a e} (@code{calc-simplify-extended}) [@code{esimplify}] command
  19064. is like @kbd{a s}
  19065. except that it applies some additional simplifications which are not
  19066. ``safe'' in all cases. Use this only if you know the values in your
  19067. formula lie in the restricted ranges for which these simplifications
  19068. are valid. The symbolic integrator uses @kbd{a e};
  19069. one effect of this is that the integrator's results must be used with
  19070. caution. Where an integral table will often attach conditions like
  19071. ``for positive @cite{a} only,'' Calc (like most other symbolic
  19072. integration programs) will simply produce an unqualified result.@refill
  19073. Because @kbd{a e}'s simplifications are unsafe, it is sometimes better
  19074. to type @kbd{C-u -3 a v}, which does extended simplification only
  19075. on the top level of the formula without affecting the sub-formulas.
  19076. In fact, @kbd{C-u -3 j v} allows you to target extended simplification
  19077. to any specific part of a formula.
  19078. The variable @code{ExtSimpRules} contains rewrites to be applied by
  19079. the @kbd{a e} command. These are applied in addition to
  19080. @code{EvalRules} and @code{AlgSimpRules}. (The @kbd{a r AlgSimpRules}
  19081. step described above is simply followed by an @kbd{a r ExtSimpRules} step.)
  19082. Following is a complete list of ``unsafe'' simplifications performed
  19083. by @kbd{a e}.
  19084. @tex
  19085. \bigskip
  19086. @end tex
  19087. Inverse trigonometric or hyperbolic functions, called with their
  19088. corresponding non-inverse functions as arguments, are simplified
  19089. by @kbd{a e}. For example, @cite{@t{arcsin}(@t{sin}(x))} changes
  19090. to @cite{x}. Also, @cite{@t{arcsin}(@t{cos}(x))} and
  19091. @cite{@t{arccos}(@t{sin}(x))} both change to @cite{@t{pi}/2 - x}.
  19092. These simplifications are unsafe because they are valid only for
  19093. values of @cite{x} in a certain range; outside that range, values
  19094. are folded down to the 360-degree range that the inverse trigonometric
  19095. functions always produce.
  19096. Powers of powers @cite{(x^a)^b} are simplified to @c{$x^{a b}$}
  19097. @cite{x^(a b)}
  19098. for all @cite{a} and @cite{b}. These results will be valid only
  19099. in a restricted range of @cite{x}; for example, in @c{$(x^2)^{1:2}$}
  19100. @cite{(x^2)^1:2}
  19101. the powers cancel to get @cite{x}, which is valid for positive values
  19102. of @cite{x} but not for negative or complex values.
  19103. Similarly, @cite{@t{sqrt}(x^a)} and @cite{@t{sqrt}(x)^a} are both
  19104. simplified (possibly unsafely) to @c{$x^{a/2}$}
  19105. @cite{x^(a/2)}.
  19106. Forms like @cite{@t{sqrt}(1 - @t{sin}(x)^2)} are simplified to, e.g.,
  19107. @cite{@t{cos}(x)}. Calc has identities of this sort for @code{sin},
  19108. @code{cos}, @code{tan}, @code{sinh}, and @code{cosh}.
  19109. Arguments of square roots are partially factored to look for
  19110. squared terms that can be extracted. For example,
  19111. @cite{@t{sqrt}(a^2 b^3 + a^3 b^2)} simplifies to @cite{a b @t{sqrt}(a+b)}.
  19112. The simplifications of @cite{@t{ln}(@t{exp}(x))}, @cite{@t{ln}(@t{e}^x)},
  19113. and @cite{@t{log10}(10^x)} to @cite{x} are also unsafe because
  19114. of problems with principal values (although these simplifications
  19115. are safe if @cite{x} is known to be real).
  19116. Common factors are cancelled from products on both sides of an
  19117. equation, even if those factors may be zero: @cite{a x / b x}
  19118. to @cite{a / b}. Such factors are never cancelled from
  19119. inequalities: Even @kbd{a e} is not bold enough to reduce
  19120. @cite{a x < b x} to @cite{a < b} (or @cite{a > b}, depending
  19121. on whether you believe @cite{x} is positive or negative).
  19122. The @kbd{a M /} command can be used to divide a factor out of
  19123. both sides of an inequality.
  19124. @node Simplification of Units, , Unsafe Simplifications, Simplifying Formulas
  19125. @subsection Simplification of Units
  19126. @noindent
  19127. The simplifications described in this section are applied by the
  19128. @kbd{u s} (@code{calc-simplify-units}) command. These are in addition
  19129. to the regular @kbd{a s} (but not @kbd{a e}) simplifications described
  19130. earlier. @xref{Basic Operations on Units}.
  19131. The variable @code{UnitSimpRules} contains rewrites to be applied by
  19132. the @kbd{u s} command. These are applied in addition to @code{EvalRules}
  19133. and @code{AlgSimpRules}.
  19134. Scalar mode is automatically put into effect when simplifying units.
  19135. @xref{Matrix Mode}.
  19136. Sums @cite{a + b} involving units are simplified by extracting the
  19137. units of @cite{a} as if by the @kbd{u x} command (call the result
  19138. @cite{u_a}), then simplifying the expression @cite{b / u_a}
  19139. using @kbd{u b} and @kbd{u s}. If the result has units then the sum
  19140. is inconsistent and is left alone. Otherwise, it is rewritten
  19141. in terms of the units @cite{u_a}.
  19142. If units auto-ranging mode is enabled, products or quotients in
  19143. which the first argument is a number which is out of range for the
  19144. leading unit are modified accordingly.
  19145. When cancelling and combining units in products and quotients,
  19146. Calc accounts for unit names that differ only in the prefix letter.
  19147. For example, @samp{2 km m} is simplified to @samp{2000 m^2}.
  19148. However, compatible but different units like @code{ft} and @code{in}
  19149. are not combined in this way.
  19150. Quotients @cite{a / b} are simplified in three additional ways. First,
  19151. if @cite{b} is a number or a product beginning with a number, Calc
  19152. computes the reciprocal of this number and moves it to the numerator.
  19153. Second, for each pair of unit names from the numerator and denominator
  19154. of a quotient, if the units are compatible (e.g., they are both
  19155. units of area) then they are replaced by the ratio between those
  19156. units. For example, in @samp{3 s in N / kg cm} the units
  19157. @samp{in / cm} will be replaced by @cite{2.54}.
  19158. Third, if the units in the quotient exactly cancel out, so that
  19159. a @kbd{u b} command on the quotient would produce a dimensionless
  19160. number for an answer, then the quotient simplifies to that number.
  19161. For powers and square roots, the ``unsafe'' simplifications
  19162. @cite{(a b)^c} to @cite{a^c b^c}, @cite{(a/b)^c} to @cite{a^c / b^c},
  19163. and @cite{(a^b)^c} to @c{$a^{b c}$}
  19164. @cite{a^(b c)} are done if the powers are
  19165. real numbers. (These are safe in the context of units because
  19166. all numbers involved can reasonably be assumed to be real.)
  19167. Also, if a unit name is raised to a fractional power, and the
  19168. base units in that unit name all occur to powers which are a
  19169. multiple of the denominator of the power, then the unit name
  19170. is expanded out into its base units, which can then be simplified
  19171. according to the previous paragraph. For example, @samp{acre^1.5}
  19172. is simplified by noting that @cite{1.5 = 3:2}, that @samp{acre}
  19173. is defined in terms of @samp{m^2}, and that the 2 in the power of
  19174. @code{m} is a multiple of 2 in @cite{3:2}. Thus, @code{acre^1.5} is
  19175. replaced by approximately @c{$(4046 m^2)^{1.5}$}
  19176. @cite{(4046 m^2)^1.5}, which is then
  19177. changed to @c{$4046^{1.5} \, (m^2)^{1.5}$}
  19178. @cite{4046^1.5 (m^2)^1.5}, then to @cite{257440 m^3}.
  19179. The functions @code{float}, @code{frac}, @code{clean}, @code{abs},
  19180. as well as @code{floor} and the other integer truncation functions,
  19181. applied to unit names or products or quotients involving units, are
  19182. simplified. For example, @samp{round(1.6 in)} is changed to
  19183. @samp{round(1.6) round(in)}; the lefthand term evaluates to 2,
  19184. and the righthand term simplifies to @code{in}.
  19185. The functions @code{sin}, @code{cos}, and @code{tan} with arguments
  19186. that have angular units like @code{rad} or @code{arcmin} are
  19187. simplified by converting to base units (radians), then evaluating
  19188. with the angular mode temporarily set to radians.
  19189. @node Polynomials, Calculus, Simplifying Formulas, Algebra
  19190. @section Polynomials
  19191. A @dfn{polynomial} is a sum of terms which are coefficients times
  19192. various powers of a ``base'' variable. For example, @cite{2 x^2 + 3 x - 4}
  19193. is a polynomial in @cite{x}. Some formulas can be considered
  19194. polynomials in several different variables: @cite{1 + 2 x + 3 y + 4 x y^2}
  19195. is a polynomial in both @cite{x} and @cite{y}. Polynomial coefficients
  19196. are often numbers, but they may in general be any formulas not
  19197. involving the base variable.
  19198. @kindex a f
  19199. @pindex calc-factor
  19200. @tindex factor
  19201. The @kbd{a f} (@code{calc-factor}) [@code{factor}] command factors a
  19202. polynomial into a product of terms. For example, the polynomial
  19203. @cite{x^3 + 2 x^2 + x} is factored into @samp{x*(x+1)^2}. As another
  19204. example, @cite{a c + b d + b c + a d} is factored into the product
  19205. @cite{(a + b) (c + d)}.
  19206. Calc currently has three algorithms for factoring. Formulas which are
  19207. linear in several variables, such as the second example above, are
  19208. merged according to the distributive law. Formulas which are
  19209. polynomials in a single variable, with constant integer or fractional
  19210. coefficients, are factored into irreducible linear and/or quadratic
  19211. terms. The first example above factors into three linear terms
  19212. (@cite{x}, @cite{x+1}, and @cite{x+1} again). Finally, formulas
  19213. which do not fit the above criteria are handled by the algebraic
  19214. rewrite mechanism.
  19215. Calc's polynomial factorization algorithm works by using the general
  19216. root-finding command (@w{@kbd{a P}}) to solve for the roots of the
  19217. polynomial. It then looks for roots which are rational numbers
  19218. or complex-conjugate pairs, and converts these into linear and
  19219. quadratic terms, respectively. Because it uses floating-point
  19220. arithmetic, it may be unable to find terms that involve large
  19221. integers (whose number of digits approaches the current precision).
  19222. Also, irreducible factors of degree higher than quadratic are not
  19223. found, and polynomials in more than one variable are not treated.
  19224. (A more robust factorization algorithm may be included in a future
  19225. version of Calc.)
  19226. @vindex FactorRules
  19227. @ignore
  19228. @starindex
  19229. @end ignore
  19230. @tindex thecoefs
  19231. @ignore
  19232. @starindex
  19233. @end ignore
  19234. @ignore
  19235. @mindex @idots
  19236. @end ignore
  19237. @tindex thefactors
  19238. The rewrite-based factorization method uses rules stored in the variable
  19239. @code{FactorRules}. @xref{Rewrite Rules}, for a discussion of the
  19240. operation of rewrite rules. The default @code{FactorRules} are able
  19241. to factor quadratic forms symbolically into two linear terms,
  19242. @cite{(a x + b) (c x + d)}. You can edit these rules to include other
  19243. cases if you wish. To use the rules, Calc builds the formula
  19244. @samp{thecoefs(x, [a, b, c, ...])} where @code{x} is the polynomial
  19245. base variable and @code{a}, @code{b}, etc., are polynomial coefficients
  19246. (which may be numbers or formulas). The constant term is written first,
  19247. i.e., in the @code{a} position. When the rules complete, they should have
  19248. changed the formula into the form @samp{thefactors(x, [f1, f2, f3, ...])}
  19249. where each @code{fi} should be a factored term, e.g., @samp{x - ai}.
  19250. Calc then multiplies these terms together to get the complete
  19251. factored form of the polynomial. If the rules do not change the
  19252. @code{thecoefs} call to a @code{thefactors} call, @kbd{a f} leaves the
  19253. polynomial alone on the assumption that it is unfactorable. (Note that
  19254. the function names @code{thecoefs} and @code{thefactors} are used only
  19255. as placeholders; there are no actual Calc functions by those names.)
  19256. @kindex H a f
  19257. @tindex factors
  19258. The @kbd{H a f} [@code{factors}] command also factors a polynomial,
  19259. but it returns a list of factors instead of an expression which is the
  19260. product of the factors. Each factor is represented by a sub-vector
  19261. of the factor, and the power with which it appears. For example,
  19262. @cite{x^5 + x^4 - 33 x^3 + 63 x^2} factors to @cite{(x + 7) x^2 (x - 3)^2}
  19263. in @kbd{a f}, or to @cite{[ [x, 2], [x+7, 1], [x-3, 2] ]} in @kbd{H a f}.
  19264. If there is an overall numeric factor, it always comes first in the list.
  19265. The functions @code{factor} and @code{factors} allow a second argument
  19266. when written in algebraic form; @samp{factor(x,v)} factors @cite{x} with
  19267. respect to the specific variable @cite{v}. The default is to factor with
  19268. respect to all the variables that appear in @cite{x}.
  19269. @kindex a c
  19270. @pindex calc-collect
  19271. @tindex collect
  19272. The @kbd{a c} (@code{calc-collect}) [@code{collect}] command rearranges a
  19273. formula as a
  19274. polynomial in a given variable, ordered in decreasing powers of that
  19275. variable. For example, given @cite{1 + 2 x + 3 y + 4 x y^2} on
  19276. the stack, @kbd{a c x} would produce @cite{(2 + 4 y^2) x + (1 + 3 y)},
  19277. and @kbd{a c y} would produce @cite{(4 x) y^2 + 3 y + (1 + 2 x)}.
  19278. The polynomial will be expanded out using the distributive law as
  19279. necessary: Collecting @cite{x} in @cite{(x - 1)^3} produces
  19280. @cite{x^3 - 3 x^2 + 3 x - 1}. Terms not involving @cite{x} will
  19281. not be expanded.
  19282. The ``variable'' you specify at the prompt can actually be any
  19283. expression: @kbd{a c ln(x+1)} will collect together all terms multiplied
  19284. by @samp{ln(x+1)} or integer powers thereof. If @samp{x} also appears
  19285. in the formula in a context other than @samp{ln(x+1)}, @kbd{a c} will
  19286. treat those occurrences as unrelated to @samp{ln(x+1)}, i.e., as constants.
  19287. @kindex a x
  19288. @pindex calc-expand
  19289. @tindex expand
  19290. The @kbd{a x} (@code{calc-expand}) [@code{expand}] command expands an
  19291. expression by applying the distributive law everywhere. It applies to
  19292. products, quotients, and powers involving sums. By default, it fully
  19293. distributes all parts of the expression. With a numeric prefix argument,
  19294. the distributive law is applied only the specified number of times, then
  19295. the partially expanded expression is left on the stack.
  19296. The @kbd{a x} and @kbd{j D} commands are somewhat redundant. Use
  19297. @kbd{a x} if you want to expand all products of sums in your formula.
  19298. Use @kbd{j D} if you want to expand a particular specified term of
  19299. the formula. There is an exactly analogous correspondence between
  19300. @kbd{a f} and @kbd{j M}. (The @kbd{j D} and @kbd{j M} commands
  19301. also know many other kinds of expansions, such as
  19302. @samp{exp(a + b) = exp(a) exp(b)}, which @kbd{a x} and @kbd{a f}
  19303. do not do.)
  19304. Calc's automatic simplifications will sometimes reverse a partial
  19305. expansion. For example, the first step in expanding @cite{(x+1)^3} is
  19306. to write @cite{(x+1) (x+1)^2}. If @kbd{a x} stops there and tries
  19307. to put this formula onto the stack, though, Calc will automatically
  19308. simplify it back to @cite{(x+1)^3} form. The solution is to turn
  19309. simplification off first (@pxref{Simplification Modes}), or to run
  19310. @kbd{a x} without a numeric prefix argument so that it expands all
  19311. the way in one step.
  19312. @kindex a a
  19313. @pindex calc-apart
  19314. @tindex apart
  19315. The @kbd{a a} (@code{calc-apart}) [@code{apart}] command expands a
  19316. rational function by partial fractions. A rational function is the
  19317. quotient of two polynomials; @code{apart} pulls this apart into a
  19318. sum of rational functions with simple denominators. In algebraic
  19319. notation, the @code{apart} function allows a second argument that
  19320. specifies which variable to use as the ``base''; by default, Calc
  19321. chooses the base variable automatically.
  19322. @kindex a n
  19323. @pindex calc-normalize-rat
  19324. @tindex nrat
  19325. The @kbd{a n} (@code{calc-normalize-rat}) [@code{nrat}] command
  19326. attempts to arrange a formula into a quotient of two polynomials.
  19327. For example, given @cite{1 + (a + b/c) / d}, the result would be
  19328. @cite{(b + a c + c d) / c d}. The quotient is reduced, so that
  19329. @kbd{a n} will simplify @cite{(x^2 + 2x + 1) / (x^2 - 1)} by dividing
  19330. out the common factor @cite{x + 1}, yielding @cite{(x + 1) / (x - 1)}.
  19331. @kindex a \
  19332. @pindex calc-poly-div
  19333. @tindex pdiv
  19334. The @kbd{a \} (@code{calc-poly-div}) [@code{pdiv}] command divides
  19335. two polynomials @cite{u} and @cite{v}, yielding a new polynomial
  19336. @cite{q}. If several variables occur in the inputs, the inputs are
  19337. considered multivariate polynomials. (Calc divides by the variable
  19338. with the largest power in @cite{u} first, or, in the case of equal
  19339. powers, chooses the variables in alphabetical order.) For example,
  19340. dividing @cite{x^2 + 3 x + 2} by @cite{x + 2} yields @cite{x + 1}.
  19341. The remainder from the division, if any, is reported at the bottom
  19342. of the screen and is also placed in the Trail along with the quotient.
  19343. Using @code{pdiv} in algebraic notation, you can specify the particular
  19344. variable to be used as the base: @code{pdiv(@var{a},@var{b},@var{x})}.
  19345. If @code{pdiv} is given only two arguments (as is always the case with
  19346. the @kbd{a \} command), then it does a multivariate division as outlined
  19347. above.
  19348. @kindex a %
  19349. @pindex calc-poly-rem
  19350. @tindex prem
  19351. The @kbd{a %} (@code{calc-poly-rem}) [@code{prem}] command divides
  19352. two polynomials and keeps the remainder @cite{r}. The quotient
  19353. @cite{q} is discarded. For any formulas @cite{a} and @cite{b}, the
  19354. results of @kbd{a \} and @kbd{a %} satisfy @cite{a = q b + r}.
  19355. (This is analogous to plain @kbd{\} and @kbd{%}, which compute the
  19356. integer quotient and remainder from dividing two numbers.)
  19357. @kindex a /
  19358. @kindex H a /
  19359. @pindex calc-poly-div-rem
  19360. @tindex pdivrem
  19361. @tindex pdivide
  19362. The @kbd{a /} (@code{calc-poly-div-rem}) [@code{pdivrem}] command
  19363. divides two polynomials and reports both the quotient and the
  19364. remainder as a vector @cite{[q, r]}. The @kbd{H a /} [@code{pdivide}]
  19365. command divides two polynomials and constructs the formula
  19366. @cite{q + r/b} on the stack. (Naturally if the remainder is zero,
  19367. this will immediately simplify to @cite{q}.)
  19368. @kindex a g
  19369. @pindex calc-poly-gcd
  19370. @tindex pgcd
  19371. The @kbd{a g} (@code{calc-poly-gcd}) [@code{pgcd}] command computes
  19372. the greatest common divisor of two polynomials. (The GCD actually
  19373. is unique only to within a constant multiplier; Calc attempts to
  19374. choose a GCD which will be unsurprising.) For example, the @kbd{a n}
  19375. command uses @kbd{a g} to take the GCD of the numerator and denominator
  19376. of a quotient, then divides each by the result using @kbd{a \}. (The
  19377. definition of GCD ensures that this division can take place without
  19378. leaving a remainder.)
  19379. While the polynomials used in operations like @kbd{a /} and @kbd{a g}
  19380. often have integer coefficients, this is not required. Calc can also
  19381. deal with polynomials over the rationals or floating-point reals.
  19382. Polynomials with modulo-form coefficients are also useful in many
  19383. applications; if you enter @samp{(x^2 + 3 x - 1) mod 5}, Calc
  19384. automatically transforms this into a polynomial over the field of
  19385. integers mod 5: @samp{(1 mod 5) x^2 + (3 mod 5) x + (4 mod 5)}.
  19386. Congratulations and thanks go to Ove Ewerlid
  19387. (@code{ewerlid@@mizar.DoCS.UU.SE}), who contributed many of the
  19388. polynomial routines used in the above commands.
  19389. @xref{Decomposing Polynomials}, for several useful functions for
  19390. extracting the individual coefficients of a polynomial.
  19391. @node Calculus, Solving Equations, Polynomials, Algebra
  19392. @section Calculus
  19393. @noindent
  19394. The following calculus commands do not automatically simplify their
  19395. inputs or outputs using @code{calc-simplify}. You may find it helps
  19396. to do this by hand by typing @kbd{a s} or @kbd{a e}. It may also help
  19397. to use @kbd{a x} and/or @kbd{a c} to arrange a result in the most
  19398. readable way.
  19399. @menu
  19400. * Differentiation::
  19401. * Integration::
  19402. * Customizing the Integrator::
  19403. * Numerical Integration::
  19404. * Taylor Series::
  19405. @end menu
  19406. @node Differentiation, Integration, Calculus, Calculus
  19407. @subsection Differentiation
  19408. @noindent
  19409. @kindex a d
  19410. @kindex H a d
  19411. @pindex calc-derivative
  19412. @tindex deriv
  19413. @tindex tderiv
  19414. The @kbd{a d} (@code{calc-derivative}) [@code{deriv}] command computes
  19415. the derivative of the expression on the top of the stack with respect to
  19416. some variable, which it will prompt you to enter. Normally, variables
  19417. in the formula other than the specified differentiation variable are
  19418. considered constant, i.e., @samp{deriv(y,x)} is reduced to zero. With
  19419. the Hyperbolic flag, the @code{tderiv} (total derivative) operation is used
  19420. instead, in which derivatives of variables are not reduced to zero
  19421. unless those variables are known to be ``constant,'' i.e., independent
  19422. of any other variables. (The built-in special variables like @code{pi}
  19423. are considered constant, as are variables that have been declared
  19424. @code{const}; @pxref{Declarations}.)
  19425. With a numeric prefix argument @var{n}, this command computes the
  19426. @var{n}th derivative.
  19427. When working with trigonometric functions, it is best to switch to
  19428. radians mode first (with @w{@kbd{m r}}). The derivative of @samp{sin(x)}
  19429. in degrees is @samp{(pi/180) cos(x)}, probably not the expected
  19430. answer!
  19431. If you use the @code{deriv} function directly in an algebraic formula,
  19432. you can write @samp{deriv(f,x,x0)} which represents the derivative
  19433. of @cite{f} with respect to @cite{x}, evaluated at the point @c{$x=x_0$}
  19434. @cite{x=x0}.
  19435. If the formula being differentiated contains functions which Calc does
  19436. not know, the derivatives of those functions are produced by adding
  19437. primes (apostrophe characters). For example, @samp{deriv(f(2x), x)}
  19438. produces @samp{2 f'(2 x)}, where the function @code{f'} represents the
  19439. derivative of @code{f}.
  19440. For functions you have defined with the @kbd{Z F} command, Calc expands
  19441. the functions according to their defining formulas unless you have
  19442. also defined @code{f'} suitably. For example, suppose we define
  19443. @samp{sinc(x) = sin(x)/x} using @kbd{Z F}. If we then differentiate
  19444. the formula @samp{sinc(2 x)}, the formula will be expanded to
  19445. @samp{sin(2 x) / (2 x)} and differentiated. However, if we also
  19446. define @samp{sinc'(x) = dsinc(x)}, say, then Calc will write the
  19447. result as @samp{2 dsinc(2 x)}. @xref{Algebraic Definitions}.
  19448. For multi-argument functions @samp{f(x,y,z)}, the derivative with respect
  19449. to the first argument is written @samp{f'(x,y,z)}; derivatives with
  19450. respect to the other arguments are @samp{f'2(x,y,z)} and @samp{f'3(x,y,z)}.
  19451. Various higher-order derivatives can be formed in the obvious way, e.g.,
  19452. @samp{f'@var{}'(x)} (the second derivative of @code{f}) or
  19453. @samp{f'@var{}'2'3(x,y,z)} (@code{f} differentiated with respect to each
  19454. argument once).@refill
  19455. @node Integration, Customizing the Integrator, Differentiation, Calculus
  19456. @subsection Integration
  19457. @noindent
  19458. @kindex a i
  19459. @pindex calc-integral
  19460. @tindex integ
  19461. The @kbd{a i} (@code{calc-integral}) [@code{integ}] command computes the
  19462. indefinite integral of the expression on the top of the stack with
  19463. respect to a variable. The integrator is not guaranteed to work for
  19464. all integrable functions, but it is able to integrate several large
  19465. classes of formulas. In particular, any polynomial or rational function
  19466. (a polynomial divided by a polynomial) is acceptable. (Rational functions
  19467. don't have to be in explicit quotient form, however; @c{$x/(1+x^{-2})$}
  19468. @cite{x/(1+x^-2)}
  19469. is not strictly a quotient of polynomials, but it is equivalent to
  19470. @cite{x^3/(x^2+1)}, which is.) Also, square roots of terms involving
  19471. @cite{x} and @cite{x^2} may appear in rational functions being
  19472. integrated. Finally, rational functions involving trigonometric or
  19473. hyperbolic functions can be integrated.
  19474. @ifinfo
  19475. If you use the @code{integ} function directly in an algebraic formula,
  19476. you can also write @samp{integ(f,x,v)} which expresses the resulting
  19477. indefinite integral in terms of variable @code{v} instead of @code{x}.
  19478. With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
  19479. integral from @code{a} to @code{b}.
  19480. @end ifinfo
  19481. @tex
  19482. If you use the @code{integ} function directly in an algebraic formula,
  19483. you can also write @samp{integ(f,x,v)} which expresses the resulting
  19484. indefinite integral in terms of variable @code{v} instead of @code{x}.
  19485. With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
  19486. integral $\int_a^b f(x) \, dx$.
  19487. @end tex
  19488. Please note that the current implementation of Calc's integrator sometimes
  19489. produces results that are significantly more complex than they need to
  19490. be. For example, the integral Calc finds for @c{$1/(x+\sqrt{x^2+1})$}
  19491. @cite{1/(x+sqrt(x^2+1))}
  19492. is several times more complicated than the answer Mathematica
  19493. returns for the same input, although the two forms are numerically
  19494. equivalent. Also, any indefinite integral should be considered to have
  19495. an arbitrary constant of integration added to it, although Calc does not
  19496. write an explicit constant of integration in its result. For example,
  19497. Calc's solution for @c{$1/(1+\tan x)$}
  19498. @cite{1/(1+tan(x))} differs from the solution given
  19499. in the @emph{CRC Math Tables} by a constant factor of @c{$\pi i / 2$}
  19500. @cite{pi i / 2},
  19501. due to a different choice of constant of integration.
  19502. The Calculator remembers all the integrals it has done. If conditions
  19503. change in a way that would invalidate the old integrals, say, a switch
  19504. from degrees to radians mode, then they will be thrown out. If you
  19505. suspect this is not happening when it should, use the
  19506. @code{calc-flush-caches} command; @pxref{Caches}.
  19507. @vindex IntegLimit
  19508. Calc normally will pursue integration by substitution or integration by
  19509. parts up to 3 nested times before abandoning an approach as fruitless.
  19510. If the integrator is taking too long, you can lower this limit by storing
  19511. a number (like 2) in the variable @code{IntegLimit}. (The @kbd{s I}
  19512. command is a convenient way to edit @code{IntegLimit}.) If this variable
  19513. has no stored value or does not contain a nonnegative integer, a limit
  19514. of 3 is used. The lower this limit is, the greater the chance that Calc
  19515. will be unable to integrate a function it could otherwise handle. Raising
  19516. this limit allows the Calculator to solve more integrals, though the time
  19517. it takes may grow exponentially. You can monitor the integrator's actions
  19518. by creating an Emacs buffer called @code{*Trace*}. If such a buffer
  19519. exists, the @kbd{a i} command will write a log of its actions there.
  19520. If you want to manipulate integrals in a purely symbolic way, you can
  19521. set the integration nesting limit to 0 to prevent all but fast
  19522. table-lookup solutions of integrals. You might then wish to define
  19523. rewrite rules for integration by parts, various kinds of substitutions,
  19524. and so on. @xref{Rewrite Rules}.
  19525. @node Customizing the Integrator, Numerical Integration, Integration, Calculus
  19526. @subsection Customizing the Integrator
  19527. @noindent
  19528. @vindex IntegRules
  19529. Calc has two built-in rewrite rules called @code{IntegRules} and
  19530. @code{IntegAfterRules} which you can edit to define new integration
  19531. methods. @xref{Rewrite Rules}. At each step of the integration process,
  19532. Calc wraps the current integrand in a call to the fictitious function
  19533. @samp{integtry(@var{expr},@var{var})}, where @var{expr} is the
  19534. integrand and @var{var} is the integration variable. If your rules
  19535. rewrite this to be a plain formula (not a call to @code{integtry}), then
  19536. Calc will use this formula as the integral of @var{expr}. For example,
  19537. the rule @samp{integtry(mysin(x),x) := -mycos(x)} would define a rule to
  19538. integrate a function @code{mysin} that acts like the sine function.
  19539. Then, putting @samp{4 mysin(2y+1)} on the stack and typing @kbd{a i y}
  19540. will produce the integral @samp{-2 mycos(2y+1)}. Note that Calc has
  19541. automatically made various transformations on the integral to allow it
  19542. to use your rule; integral tables generally give rules for
  19543. @samp{mysin(a x + b)}, but you don't need to use this much generality
  19544. in your @code{IntegRules}.
  19545. @cindex Exponential integral Ei(x)
  19546. @ignore
  19547. @starindex
  19548. @end ignore
  19549. @tindex Ei
  19550. As a more serious example, the expression @samp{exp(x)/x} cannot be
  19551. integrated in terms of the standard functions, so the ``exponential
  19552. integral'' function @c{${\rm Ei}(x)$}
  19553. @cite{Ei(x)} was invented to describe it.
  19554. We can get Calc to do this integral in terms of a made-up @code{Ei}
  19555. function by adding the rule @samp{[integtry(exp(x)/x, x) := Ei(x)]}
  19556. to @code{IntegRules}. Now entering @samp{exp(2x)/x} on the stack
  19557. and typing @kbd{a i x} yields @samp{Ei(2 x)}. This new rule will
  19558. work with Calc's various built-in integration methods (such as
  19559. integration by substitution) to solve a variety of other problems
  19560. involving @code{Ei}: For example, now Calc will also be able to
  19561. integrate @samp{exp(exp(x))} and @samp{ln(ln(x))} (to get @samp{Ei(exp(x))}
  19562. and @samp{x ln(ln(x)) - Ei(ln(x))}, respectively).
  19563. Your rule may do further integration by calling @code{integ}. For
  19564. example, @samp{integtry(twice(u),x) := twice(integ(u))} allows Calc
  19565. to integrate @samp{twice(sin(x))} to get @samp{twice(-cos(x))}.
  19566. Note that @code{integ} was called with only one argument. This notation
  19567. is allowed only within @code{IntegRules}; it means ``integrate this
  19568. with respect to the same integration variable.'' If Calc is unable
  19569. to integrate @code{u}, the integration that invoked @code{IntegRules}
  19570. also fails. Thus integrating @samp{twice(f(x))} fails, returning the
  19571. unevaluated integral @samp{integ(twice(f(x)), x)}. It is still legal
  19572. to call @code{integ} with two or more arguments, however; in this case,
  19573. if @code{u} is not integrable, @code{twice} itself will still be
  19574. integrated: If the above rule is changed to @samp{... := twice(integ(u,x))},
  19575. then integrating @samp{twice(f(x))} will yield @samp{twice(integ(f(x),x))}.
  19576. If a rule instead produces the formula @samp{integsubst(@var{sexpr},
  19577. @var{svar})}, either replacing the top-level @code{integtry} call or
  19578. nested anywhere inside the expression, then Calc will apply the
  19579. substitution @samp{@var{u} = @var{sexpr}(@var{svar})} to try to
  19580. integrate the original @var{expr}. For example, the rule
  19581. @samp{sqrt(a) := integsubst(sqrt(x),x)} says that if Calc ever finds
  19582. a square root in the integrand, it should attempt the substitution
  19583. @samp{u = sqrt(x)}. (This particular rule is unnecessary because
  19584. Calc always tries ``obvious'' substitutions where @var{sexpr} actually
  19585. appears in the integrand.) The variable @var{svar} may be the same
  19586. as the @var{var} that appeared in the call to @code{integtry}, but
  19587. it need not be.
  19588. When integrating according to an @code{integsubst}, Calc uses the
  19589. equation solver to find the inverse of @var{sexpr} (if the integrand
  19590. refers to @var{var} anywhere except in subexpressions that exactly
  19591. match @var{sexpr}). It uses the differentiator to find the derivative
  19592. of @var{sexpr} and/or its inverse (it has two methods that use one
  19593. derivative or the other). You can also specify these items by adding
  19594. extra arguments to the @code{integsubst} your rules construct; the
  19595. general form is @samp{integsubst(@var{sexpr}, @var{svar}, @var{sinv},
  19596. @var{sprime})}, where @var{sinv} is the inverse of @var{sexpr} (still
  19597. written as a function of @var{svar}), and @var{sprime} is the
  19598. derivative of @var{sexpr} with respect to @var{svar}. If you don't
  19599. specify these things, and Calc is not able to work them out on its
  19600. own with the information it knows, then your substitution rule will
  19601. work only in very specific, simple cases.
  19602. Calc applies @code{IntegRules} as if by @kbd{C-u 1 a r IntegRules};
  19603. in other words, Calc stops rewriting as soon as any rule in your rule
  19604. set succeeds. (If it weren't for this, the @samp{integsubst(sqrt(x),x)}
  19605. example above would keep on adding layers of @code{integsubst} calls
  19606. forever!)
  19607. @vindex IntegSimpRules
  19608. Another set of rules, stored in @code{IntegSimpRules}, are applied
  19609. every time the integrator uses @kbd{a s} to simplify an intermediate
  19610. result. For example, putting the rule @samp{twice(x) := 2 x} into
  19611. @code{IntegSimpRules} would tell Calc to convert the @code{twice}
  19612. function into a form it knows whenever integration is attempted.
  19613. One more way to influence the integrator is to define a function with
  19614. the @kbd{Z F} command (@pxref{Algebraic Definitions}). Calc's
  19615. integrator automatically expands such functions according to their
  19616. defining formulas, even if you originally asked for the function to
  19617. be left unevaluated for symbolic arguments. (Certain other Calc
  19618. systems, such as the differentiator and the equation solver, also
  19619. do this.)
  19620. @vindex IntegAfterRules
  19621. Sometimes Calc is able to find a solution to your integral, but it
  19622. expresses the result in a way that is unnecessarily complicated. If
  19623. this happens, you can either use @code{integsubst} as described
  19624. above to try to hint at a more direct path to the desired result, or
  19625. you can use @code{IntegAfterRules}. This is an extra rule set that
  19626. runs after the main integrator returns its result; basically, Calc does
  19627. an @kbd{a r IntegAfterRules} on the result before showing it to you.
  19628. (It also does an @kbd{a s}, without @code{IntegSimpRules}, after that
  19629. to further simplify the result.) For example, Calc's integrator
  19630. sometimes produces expressions of the form @samp{ln(1+x) - ln(1-x)};
  19631. the default @code{IntegAfterRules} rewrite this into the more readable
  19632. form @samp{2 arctanh(x)}. Note that, unlike @code{IntegRules},
  19633. @code{IntegSimpRules} and @code{IntegAfterRules} are applied any number
  19634. of times until no further changes are possible. Rewriting by
  19635. @code{IntegAfterRules} occurs only after the main integrator has
  19636. finished, not at every step as for @code{IntegRules} and
  19637. @code{IntegSimpRules}.
  19638. @node Numerical Integration, Taylor Series, Customizing the Integrator, Calculus
  19639. @subsection Numerical Integration
  19640. @noindent
  19641. @kindex a I
  19642. @pindex calc-num-integral
  19643. @tindex ninteg
  19644. If you want a purely numerical answer to an integration problem, you can
  19645. use the @kbd{a I} (@code{calc-num-integral}) [@code{ninteg}] command. This
  19646. command prompts for an integration variable, a lower limit, and an
  19647. upper limit. Except for the integration variable, all other variables
  19648. that appear in the integrand formula must have stored values. (A stored
  19649. value, if any, for the integration variable itself is ignored.)
  19650. Numerical integration works by evaluating your formula at many points in
  19651. the specified interval. Calc uses an ``open Romberg'' method; this means
  19652. that it does not evaluate the formula actually at the endpoints (so that
  19653. it is safe to integrate @samp{sin(x)/x} from zero, for example). Also,
  19654. the Romberg method works especially well when the function being
  19655. integrated is fairly smooth. If the function is not smooth, Calc will
  19656. have to evaluate it at quite a few points before it can accurately
  19657. determine the value of the integral.
  19658. Integration is much faster when the current precision is small. It is
  19659. best to set the precision to the smallest acceptable number of digits
  19660. before you use @kbd{a I}. If Calc appears to be taking too long, press
  19661. @kbd{C-g} to halt it and try a lower precision. If Calc still appears
  19662. to need hundreds of evaluations, check to make sure your function is
  19663. well-behaved in the specified interval.
  19664. It is possible for the lower integration limit to be @samp{-inf} (minus
  19665. infinity). Likewise, the upper limit may be plus infinity. Calc
  19666. internally transforms the integral into an equivalent one with finite
  19667. limits. However, integration to or across singularities is not supported:
  19668. The integral of @samp{1/sqrt(x)} from 0 to 1 exists (it can be found
  19669. by Calc's symbolic integrator, for example), but @kbd{a I} will fail
  19670. because the integrand goes to infinity at one of the endpoints.
  19671. @node Taylor Series, , Numerical Integration, Calculus
  19672. @subsection Taylor Series
  19673. @noindent
  19674. @kindex a t
  19675. @pindex calc-taylor
  19676. @tindex taylor
  19677. The @kbd{a t} (@code{calc-taylor}) [@code{taylor}] command computes a
  19678. power series expansion or Taylor series of a function. You specify the
  19679. variable and the desired number of terms. You may give an expression of
  19680. the form @samp{@var{var} = @var{a}} or @samp{@var{var} - @var{a}} instead
  19681. of just a variable to produce a Taylor expansion about the point @var{a}.
  19682. You may specify the number of terms with a numeric prefix argument;
  19683. otherwise the command will prompt you for the number of terms. Note that
  19684. many series expansions have coefficients of zero for some terms, so you
  19685. may appear to get fewer terms than you asked for.@refill
  19686. If the @kbd{a i} command is unable to find a symbolic integral for a
  19687. function, you can get an approximation by integrating the function's
  19688. Taylor series.
  19689. @node Solving Equations, Numerical Solutions, Calculus, Algebra
  19690. @section Solving Equations
  19691. @noindent
  19692. @kindex a S
  19693. @pindex calc-solve-for
  19694. @tindex solve
  19695. @cindex Equations, solving
  19696. @cindex Solving equations
  19697. The @kbd{a S} (@code{calc-solve-for}) [@code{solve}] command rearranges
  19698. an equation to solve for a specific variable. An equation is an
  19699. expression of the form @cite{L = R}. For example, the command @kbd{a S x}
  19700. will rearrange @cite{y = 3x + 6} to the form, @cite{x = y/3 - 2}. If the
  19701. input is not an equation, it is treated like an equation of the
  19702. form @cite{X = 0}.
  19703. This command also works for inequalities, as in @cite{y < 3x + 6}.
  19704. Some inequalities cannot be solved where the analogous equation could
  19705. be; for example, solving @c{$a < b \, c$}
  19706. @cite{a < b c} for @cite{b} is impossible
  19707. without knowing the sign of @cite{c}. In this case, @kbd{a S} will
  19708. produce the result @c{$b \mathbin{\hbox{\code{!=}}} a/c$}
  19709. @cite{b != a/c} (using the not-equal-to operator)
  19710. to signify that the direction of the inequality is now unknown. The
  19711. inequality @c{$a \le b \, c$}
  19712. @cite{a <= b c} is not even partially solved.
  19713. @xref{Declarations}, for a way to tell Calc that the signs of the
  19714. variables in a formula are in fact known.
  19715. Two useful commands for working with the result of @kbd{a S} are
  19716. @kbd{a .} (@pxref{Logical Operations}), which converts @cite{x = y/3 - 2}
  19717. to @cite{y/3 - 2}, and @kbd{s l} (@pxref{Let Command}) which evaluates
  19718. another formula with @cite{x} set equal to @cite{y/3 - 2}.
  19719. @menu
  19720. * Multiple Solutions::
  19721. * Solving Systems of Equations::
  19722. * Decomposing Polynomials::
  19723. @end menu
  19724. @node Multiple Solutions, Solving Systems of Equations, Solving Equations, Solving Equations
  19725. @subsection Multiple Solutions
  19726. @noindent
  19727. @kindex H a S
  19728. @tindex fsolve
  19729. Some equations have more than one solution. The Hyperbolic flag
  19730. (@code{H a S}) [@code{fsolve}] tells the solver to report the fully
  19731. general family of solutions. It will invent variables @code{n1},
  19732. @code{n2}, @dots{}, which represent independent arbitrary integers, and
  19733. @code{s1}, @code{s2}, @dots{}, which represent independent arbitrary
  19734. signs (either @i{+1} or @i{-1}). If you don't use the Hyperbolic
  19735. flag, Calc will use zero in place of all arbitrary integers, and plus
  19736. one in place of all arbitrary signs. Note that variables like @code{n1}
  19737. and @code{s1} are not given any special interpretation in Calc except by
  19738. the equation solver itself. As usual, you can use the @w{@kbd{s l}}
  19739. (@code{calc-let}) command to obtain solutions for various actual values
  19740. of these variables.
  19741. For example, @kbd{' x^2 = y @key{RET} H a S x @key{RET}} solves to
  19742. get @samp{x = s1 sqrt(y)}, indicating that the two solutions to the
  19743. equation are @samp{sqrt(y)} and @samp{-sqrt(y)}. Another way to
  19744. think about it is that the square-root operation is really a
  19745. two-valued function; since every Calc function must return a
  19746. single result, @code{sqrt} chooses to return the positive result.
  19747. Then @kbd{H a S} doctors this result using @code{s1} to indicate
  19748. the full set of possible values of the mathematical square-root.
  19749. There is a similar phenomenon going the other direction: Suppose
  19750. we solve @samp{sqrt(y) = x} for @code{y}. Calc squares both sides
  19751. to get @samp{y = x^2}. This is correct, except that it introduces
  19752. some dubious solutions. Consider solving @samp{sqrt(y) = -3}:
  19753. Calc will report @cite{y = 9} as a valid solution, which is true
  19754. in the mathematical sense of square-root, but false (there is no
  19755. solution) for the actual Calc positive-valued @code{sqrt}. This
  19756. happens for both @kbd{a S} and @kbd{H a S}.
  19757. @cindex @code{GenCount} variable
  19758. @vindex GenCount
  19759. @ignore
  19760. @starindex
  19761. @end ignore
  19762. @tindex an
  19763. @ignore
  19764. @starindex
  19765. @end ignore
  19766. @tindex as
  19767. If you store a positive integer in the Calc variable @code{GenCount},
  19768. then Calc will generate formulas of the form @samp{as(@var{n})} for
  19769. arbitrary signs, and @samp{an(@var{n})} for arbitrary integers,
  19770. where @var{n} represents successive values taken by incrementing
  19771. @code{GenCount} by one. While the normal arbitrary sign and
  19772. integer symbols start over at @code{s1} and @code{n1} with each
  19773. new Calc command, the @code{GenCount} approach will give each
  19774. arbitrary value a name that is unique throughout the entire Calc
  19775. session. Also, the arbitrary values are function calls instead
  19776. of variables, which is advantageous in some cases. For example,
  19777. you can make a rewrite rule that recognizes all arbitrary signs
  19778. using a pattern like @samp{as(n)}. The @kbd{s l} command only works
  19779. on variables, but you can use the @kbd{a b} (@code{calc-substitute})
  19780. command to substitute actual values for function calls like @samp{as(3)}.
  19781. The @kbd{s G} (@code{calc-edit-GenCount}) command is a convenient
  19782. way to create or edit this variable. Press @kbd{M-# M-#} to finish.
  19783. If you have not stored a value in @code{GenCount}, or if the value
  19784. in that variable is not a positive integer, the regular
  19785. @code{s1}/@code{n1} notation is used.
  19786. @kindex I a S
  19787. @kindex H I a S
  19788. @tindex finv
  19789. @tindex ffinv
  19790. With the Inverse flag, @kbd{I a S} [@code{finv}] treats the expression
  19791. on top of the stack as a function of the specified variable and solves
  19792. to find the inverse function, written in terms of the same variable.
  19793. For example, @kbd{I a S x} inverts @cite{2x + 6} to @cite{x/2 - 3}.
  19794. You can use both Inverse and Hyperbolic [@code{ffinv}] to obtain a
  19795. fully general inverse, as described above.
  19796. @kindex a P
  19797. @pindex calc-poly-roots
  19798. @tindex roots
  19799. Some equations, specifically polynomials, have a known, finite number
  19800. of solutions. The @kbd{a P} (@code{calc-poly-roots}) [@code{roots}]
  19801. command uses @kbd{H a S} to solve an equation in general form, then, for
  19802. all arbitrary-sign variables like @code{s1}, and all arbitrary-integer
  19803. variables like @code{n1} for which @code{n1} only usefully varies over
  19804. a finite range, it expands these variables out to all their possible
  19805. values. The results are collected into a vector, which is returned.
  19806. For example, @samp{roots(x^4 = 1, x)} returns the four solutions
  19807. @samp{[1, -1, (0, 1), (0, -1)]}. Generally an @var{n}th degree
  19808. polynomial will always have @var{n} roots on the complex plane.
  19809. (If you have given a @code{real} declaration for the solution
  19810. variable, then only the real-valued solutions, if any, will be
  19811. reported; @pxref{Declarations}.)
  19812. Note that because @kbd{a P} uses @kbd{H a S}, it is able to deliver
  19813. symbolic solutions if the polynomial has symbolic coefficients. Also
  19814. note that Calc's solver is not able to get exact symbolic solutions
  19815. to all polynomials. Polynomials containing powers up to @cite{x^4}
  19816. can always be solved exactly; polynomials of higher degree sometimes
  19817. can be: @cite{x^6 + x^3 + 1} is converted to @cite{(x^3)^2 + (x^3) + 1},
  19818. which can be solved for @cite{x^3} using the quadratic equation, and then
  19819. for @cite{x} by taking cube roots. But in many cases, like
  19820. @cite{x^6 + x + 1}, Calc does not know how to rewrite the polynomial
  19821. into a form it can solve. The @kbd{a P} command can still deliver a
  19822. list of numerical roots, however, provided that symbolic mode (@kbd{m s})
  19823. is not turned on. (If you work with symbolic mode on, recall that the
  19824. @kbd{N} (@code{calc-eval-num}) key is a handy way to reevaluate the
  19825. formula on the stack with symbolic mode temporarily off.) Naturally,
  19826. @kbd{a P} can only provide numerical roots if the polynomial coefficents
  19827. are all numbers (real or complex).
  19828. @node Solving Systems of Equations, Decomposing Polynomials, Multiple Solutions, Solving Equations
  19829. @subsection Solving Systems of Equations
  19830. @noindent
  19831. @cindex Systems of equations, symbolic
  19832. You can also use the commands described above to solve systems of
  19833. simultaneous equations. Just create a vector of equations, then
  19834. specify a vector of variables for which to solve. (You can omit
  19835. the surrounding brackets when entering the vector of variables
  19836. at the prompt.)
  19837. For example, putting @samp{[x + y = a, x - y = b]} on the stack
  19838. and typing @kbd{a S x,y @key{RET}} produces the vector of solutions
  19839. @samp{[x = a - (a-b)/2, y = (a-b)/2]}. The result vector will
  19840. have the same length as the variables vector, and the variables
  19841. will be listed in the same order there. Note that the solutions
  19842. are not always simplified as far as possible; the solution for
  19843. @cite{x} here could be improved by an application of the @kbd{a n}
  19844. command.
  19845. Calc's algorithm works by trying to eliminate one variable at a
  19846. time by solving one of the equations for that variable and then
  19847. substituting into the other equations. Calc will try all the
  19848. possibilities, but you can speed things up by noting that Calc
  19849. first tries to eliminate the first variable with the first
  19850. equation, then the second variable with the second equation,
  19851. and so on. It also helps to put the simpler (e.g., more linear)
  19852. equations toward the front of the list. Calc's algorithm will
  19853. solve any system of linear equations, and also many kinds of
  19854. nonlinear systems.
  19855. @ignore
  19856. @starindex
  19857. @end ignore
  19858. @tindex elim
  19859. Normally there will be as many variables as equations. If you
  19860. give fewer variables than equations (an ``over-determined'' system
  19861. of equations), Calc will find a partial solution. For example,
  19862. typing @kbd{a S y @key{RET}} with the above system of equations
  19863. would produce @samp{[y = a - x]}. There are now several ways to
  19864. express this solution in terms of the original variables; Calc uses
  19865. the first one that it finds. You can control the choice by adding
  19866. variable specifiers of the form @samp{elim(@var{v})} to the
  19867. variables list. This says that @var{v} should be eliminated from
  19868. the equations; the variable will not appear at all in the solution.
  19869. For example, typing @kbd{a S y,elim(x)} would yield
  19870. @samp{[y = a - (b+a)/2]}.
  19871. If the variables list contains only @code{elim} specifiers,
  19872. Calc simply eliminates those variables from the equations
  19873. and then returns the resulting set of equations. For example,
  19874. @kbd{a S elim(x)} produces @samp{[a - 2 y = b]}. Every variable
  19875. eliminated will reduce the number of equations in the system
  19876. by one.
  19877. Again, @kbd{a S} gives you one solution to the system of
  19878. equations. If there are several solutions, you can use @kbd{H a S}
  19879. to get a general family of solutions, or, if there is a finite
  19880. number of solutions, you can use @kbd{a P} to get a list. (In
  19881. the latter case, the result will take the form of a matrix where
  19882. the rows are different solutions and the columns correspond to the
  19883. variables you requested.)
  19884. Another way to deal with certain kinds of overdetermined systems of
  19885. equations is the @kbd{a F} command, which does least-squares fitting
  19886. to satisfy the equations. @xref{Curve Fitting}.
  19887. @node Decomposing Polynomials, , Solving Systems of Equations, Solving Equations
  19888. @subsection Decomposing Polynomials
  19889. @noindent
  19890. @ignore
  19891. @starindex
  19892. @end ignore
  19893. @tindex poly
  19894. The @code{poly} function takes a polynomial and a variable as
  19895. arguments, and returns a vector of polynomial coefficients (constant
  19896. coefficient first). For example, @samp{poly(x^3 + 2 x, x)} returns
  19897. @cite{[0, 2, 0, 1]}. If the input is not a polynomial in @cite{x},
  19898. the call to @code{poly} is left in symbolic form. If the input does
  19899. not involve the variable @cite{x}, the input is returned in a list
  19900. of length one, representing a polynomial with only a constant
  19901. coefficient. The call @samp{poly(x, x)} returns the vector @cite{[0, 1]}.
  19902. The last element of the returned vector is guaranteed to be nonzero;
  19903. note that @samp{poly(0, x)} returns the empty vector @cite{[]}.
  19904. Note also that @cite{x} may actually be any formula; for example,
  19905. @samp{poly(sin(x)^2 - sin(x) + 3, sin(x))} returns @cite{[3, -1, 1]}.
  19906. @cindex Coefficients of polynomial
  19907. @cindex Degree of polynomial
  19908. To get the @cite{x^k} coefficient of polynomial @cite{p}, use
  19909. @samp{poly(p, x)_(k+1)}. To get the degree of polynomial @cite{p},
  19910. use @samp{vlen(poly(p, x)) - 1}. For example, @samp{poly((x+1)^4, x)}
  19911. returns @samp{[1, 4, 6, 4, 1]}, so @samp{poly((x+1)^4, x)_(2+1)}
  19912. gives the @cite{x^2} coefficient of this polynomial, 6.
  19913. @ignore
  19914. @starindex
  19915. @end ignore
  19916. @tindex gpoly
  19917. One important feature of the solver is its ability to recognize
  19918. formulas which are ``essentially'' polynomials. This ability is
  19919. made available to the user through the @code{gpoly} function, which
  19920. is used just like @code{poly}: @samp{gpoly(@var{expr}, @var{var})}.
  19921. If @var{expr} is a polynomial in some term which includes @var{var}, then
  19922. this function will return a vector @samp{[@var{x}, @var{c}, @var{a}]}
  19923. where @var{x} is the term that depends on @var{var}, @var{c} is a
  19924. vector of polynomial coefficients (like the one returned by @code{poly}),
  19925. and @var{a} is a multiplier which is usually 1. Basically,
  19926. @samp{@var{expr} = @var{a}*(@var{c}_1 + @var{c}_2 @var{x} +
  19927. @var{c}_3 @var{x}^2 + ...)}. The last element of @var{c} is
  19928. guaranteed to be non-zero, and @var{c} will not equal @samp{[1]}
  19929. (i.e., the trivial decomposition @var{expr} = @var{x} is not
  19930. considered a polynomial). One side effect is that @samp{gpoly(x, x)}
  19931. and @samp{gpoly(6, x)}, both of which might be expected to recognize
  19932. their arguments as polynomials, will not because the decomposition
  19933. is considered trivial.
  19934. For example, @samp{gpoly((x-2)^2, x)} returns @samp{[x, [4, -4, 1], 1]},
  19935. since the expanded form of this polynomial is @cite{4 - 4 x + x^2}.
  19936. The term @var{x} may itself be a polynomial in @var{var}. This is
  19937. done to reduce the size of the @var{c} vector. For example,
  19938. @samp{gpoly(x^4 + x^2 - 1, x)} returns @samp{[x^2, [-1, 1, 1], 1]},
  19939. since a quadratic polynomial in @cite{x^2} is easier to solve than
  19940. a quartic polynomial in @cite{x}.
  19941. A few more examples of the kinds of polynomials @code{gpoly} can
  19942. discover:
  19943. @smallexample
  19944. sin(x) - 1 [sin(x), [-1, 1], 1]
  19945. x + 1/x - 1 [x, [1, -1, 1], 1/x]
  19946. x + 1/x [x^2, [1, 1], 1/x]
  19947. x^3 + 2 x [x^2, [2, 1], x]
  19948. x + x^2:3 + sqrt(x) [x^1:6, [1, 1, 0, 1], x^1:2]
  19949. x^(2a) + 2 x^a + 5 [x^a, [5, 2, 1], 1]
  19950. (exp(-x) + exp(x)) / 2 [e^(2 x), [0.5, 0.5], e^-x]
  19951. @end smallexample
  19952. The @code{poly} and @code{gpoly} functions accept a third integer argument
  19953. which specifies the largest degree of polynomial that is acceptable.
  19954. If this is @cite{n}, then only @var{c} vectors of length @cite{n+1}
  19955. or less will be returned. Otherwise, the @code{poly} or @code{gpoly}
  19956. call will remain in symbolic form. For example, the equation solver
  19957. can handle quartics and smaller polynomials, so it calls
  19958. @samp{gpoly(@var{expr}, @var{var}, 4)} to discover whether @var{expr}
  19959. can be treated by its linear, quadratic, cubic, or quartic formulas.
  19960. @ignore
  19961. @starindex
  19962. @end ignore
  19963. @tindex pdeg
  19964. The @code{pdeg} function computes the degree of a polynomial;
  19965. @samp{pdeg(p,x)} is the highest power of @code{x} that appears in
  19966. @code{p}. This is the same as @samp{vlen(poly(p,x))-1}, but is
  19967. much more efficient. If @code{p} is constant with respect to @code{x},
  19968. then @samp{pdeg(p,x) = 0}. If @code{p} is not a polynomial in @code{x}
  19969. (e.g., @samp{pdeg(2 cos(x), x)}, the function remains unevaluated.
  19970. It is possible to omit the second argument @code{x}, in which case
  19971. @samp{pdeg(p)} returns the highest total degree of any term of the
  19972. polynomial, counting all variables that appear in @code{p}. Note
  19973. that @code{pdeg(c) = pdeg(c,x) = 0} for any nonzero constant @code{c};
  19974. the degree of the constant zero is considered to be @code{-inf}
  19975. (minus infinity).
  19976. @ignore
  19977. @starindex
  19978. @end ignore
  19979. @tindex plead
  19980. The @code{plead} function finds the leading term of a polynomial.
  19981. Thus @samp{plead(p,x)} is equivalent to @samp{poly(p,x)_vlen(poly(p,x))},
  19982. though again more efficient. In particular, @samp{plead((2x+1)^10, x)}
  19983. returns 1024 without expanding out the list of coefficients. The
  19984. value of @code{plead(p,x)} will be zero only if @cite{p = 0}.
  19985. @ignore
  19986. @starindex
  19987. @end ignore
  19988. @tindex pcont
  19989. The @code{pcont} function finds the @dfn{content} of a polynomial. This
  19990. is the greatest common divisor of all the coefficients of the polynomial.
  19991. With two arguments, @code{pcont(p,x)} effectively uses @samp{poly(p,x)}
  19992. to get a list of coefficients, then uses @code{pgcd} (the polynomial
  19993. GCD function) to combine these into an answer. For example,
  19994. @samp{pcont(4 x y^2 + 6 x^2 y, x)} is @samp{2 y}. The content is
  19995. basically the ``biggest'' polynomial that can be divided into @code{p}
  19996. exactly. The sign of the content is the same as the sign of the leading
  19997. coefficient.
  19998. With only one argument, @samp{pcont(p)} computes the numerical
  19999. content of the polynomial, i.e., the @code{gcd} of the numerical
  20000. coefficients of all the terms in the formula. Note that @code{gcd}
  20001. is defined on rational numbers as well as integers; it computes
  20002. the @code{gcd} of the numerators and the @code{lcm} of the
  20003. denominators. Thus @samp{pcont(4:3 x y^2 + 6 x^2 y)} returns 2:3.
  20004. Dividing the polynomial by this number will clear all the
  20005. denominators, as well as dividing by any common content in the
  20006. numerators. The numerical content of a polynomial is negative only
  20007. if all the coefficients in the polynomial are negative.
  20008. @ignore
  20009. @starindex
  20010. @end ignore
  20011. @tindex pprim
  20012. The @code{pprim} function finds the @dfn{primitive part} of a
  20013. polynomial, which is simply the polynomial divided (using @code{pdiv}
  20014. if necessary) by its content. If the input polynomial has rational
  20015. coefficients, the result will have integer coefficients in simplest
  20016. terms.
  20017. @node Numerical Solutions, Curve Fitting, Solving Equations, Algebra
  20018. @section Numerical Solutions
  20019. @noindent
  20020. Not all equations can be solved symbolically. The commands in this
  20021. section use numerical algorithms that can find a solution to a specific
  20022. instance of an equation to any desired accuracy. Note that the
  20023. numerical commands are slower than their algebraic cousins; it is a
  20024. good idea to try @kbd{a S} before resorting to these commands.
  20025. (@xref{Curve Fitting}, for some other, more specialized, operations
  20026. on numerical data.)
  20027. @menu
  20028. * Root Finding::
  20029. * Minimization::
  20030. * Numerical Systems of Equations::
  20031. @end menu
  20032. @node Root Finding, Minimization, Numerical Solutions, Numerical Solutions
  20033. @subsection Root Finding
  20034. @noindent
  20035. @kindex a R
  20036. @pindex calc-find-root
  20037. @tindex root
  20038. @cindex Newton's method
  20039. @cindex Roots of equations
  20040. @cindex Numerical root-finding
  20041. The @kbd{a R} (@code{calc-find-root}) [@code{root}] command finds a
  20042. numerical solution (or @dfn{root}) of an equation. (This command treats
  20043. inequalities the same as equations. If the input is any other kind
  20044. of formula, it is interpreted as an equation of the form @cite{X = 0}.)
  20045. The @kbd{a R} command requires an initial guess on the top of the
  20046. stack, and a formula in the second-to-top position. It prompts for a
  20047. solution variable, which must appear in the formula. All other variables
  20048. that appear in the formula must have assigned values, i.e., when
  20049. a value is assigned to the solution variable and the formula is
  20050. evaluated with @kbd{=}, it should evaluate to a number. Any assigned
  20051. value for the solution variable itself is ignored and unaffected by
  20052. this command.
  20053. When the command completes, the initial guess is replaced on the stack
  20054. by a vector of two numbers: The value of the solution variable that
  20055. solves the equation, and the difference between the lefthand and
  20056. righthand sides of the equation at that value. Ordinarily, the second
  20057. number will be zero or very nearly zero. (Note that Calc uses a
  20058. slightly higher precision while finding the root, and thus the second
  20059. number may be slightly different from the value you would compute from
  20060. the equation yourself.)
  20061. The @kbd{v h} (@code{calc-head}) command is a handy way to extract
  20062. the first element of the result vector, discarding the error term.
  20063. The initial guess can be a real number, in which case Calc searches
  20064. for a real solution near that number, or a complex number, in which
  20065. case Calc searches the whole complex plane near that number for a
  20066. solution, or it can be an interval form which restricts the search
  20067. to real numbers inside that interval.
  20068. Calc tries to use @kbd{a d} to take the derivative of the equation.
  20069. If this succeeds, it uses Newton's method. If the equation is not
  20070. differentiable Calc uses a bisection method. (If Newton's method
  20071. appears to be going astray, Calc switches over to bisection if it
  20072. can, or otherwise gives up. In this case it may help to try again
  20073. with a slightly different initial guess.) If the initial guess is a
  20074. complex number, the function must be differentiable.
  20075. If the formula (or the difference between the sides of an equation)
  20076. is negative at one end of the interval you specify and positive at
  20077. the other end, the root finder is guaranteed to find a root.
  20078. Otherwise, Calc subdivides the interval into small parts looking for
  20079. positive and negative values to bracket the root. When your guess is
  20080. an interval, Calc will not look outside that interval for a root.
  20081. @kindex H a R
  20082. @tindex wroot
  20083. The @kbd{H a R} [@code{wroot}] command is similar to @kbd{a R}, except
  20084. that if the initial guess is an interval for which the function has
  20085. the same sign at both ends, then rather than subdividing the interval
  20086. Calc attempts to widen it to enclose a root. Use this mode if
  20087. you are not sure if the function has a root in your interval.
  20088. If the function is not differentiable, and you give a simple number
  20089. instead of an interval as your initial guess, Calc uses this widening
  20090. process even if you did not type the Hyperbolic flag. (If the function
  20091. @emph{is} differentiable, Calc uses Newton's method which does not
  20092. require a bounding interval in order to work.)
  20093. If Calc leaves the @code{root} or @code{wroot} function in symbolic
  20094. form on the stack, it will normally display an explanation for why
  20095. no root was found. If you miss this explanation, press @kbd{w}
  20096. (@code{calc-why}) to get it back.
  20097. @node Minimization, Numerical Systems of Equations, Root Finding, Numerical Solutions
  20098. @subsection Minimization
  20099. @noindent
  20100. @kindex a N
  20101. @kindex H a N
  20102. @kindex a X
  20103. @kindex H a X
  20104. @pindex calc-find-minimum
  20105. @pindex calc-find-maximum
  20106. @tindex minimize
  20107. @tindex maximize
  20108. @cindex Minimization, numerical
  20109. The @kbd{a N} (@code{calc-find-minimum}) [@code{minimize}] command
  20110. finds a minimum value for a formula. It is very similar in operation
  20111. to @kbd{a R} (@code{calc-find-root}): You give the formula and an initial
  20112. guess on the stack, and are prompted for the name of a variable. The guess
  20113. may be either a number near the desired minimum, or an interval enclosing
  20114. the desired minimum. The function returns a vector containing the
  20115. value of the variable which minimizes the formula's value, along
  20116. with the minimum value itself.
  20117. Note that this command looks for a @emph{local} minimum. Many functions
  20118. have more than one minimum; some, like @c{$x \sin x$}
  20119. @cite{x sin(x)}, have infinitely
  20120. many. In fact, there is no easy way to define the ``global'' minimum
  20121. of @c{$x \sin x$}
  20122. @cite{x sin(x)} but Calc can still locate any particular local minimum
  20123. for you. Calc basically goes downhill from the initial guess until it
  20124. finds a point at which the function's value is greater both to the left
  20125. and to the right. Calc does not use derivatives when minimizing a function.
  20126. If your initial guess is an interval and it looks like the minimum
  20127. occurs at one or the other endpoint of the interval, Calc will return
  20128. that endpoint only if that endpoint is closed; thus, minimizing @cite{17 x}
  20129. over @cite{[2..3]} will return @cite{[2, 38]}, but minimizing over
  20130. @cite{(2..3]} would report no minimum found. In general, you should
  20131. use closed intervals to find literally the minimum value in that
  20132. range of @cite{x}, or open intervals to find the local minimum, if
  20133. any, that happens to lie in that range.
  20134. Most functions are smooth and flat near their minimum values. Because
  20135. of this flatness, if the current precision is, say, 12 digits, the
  20136. variable can only be determined meaningfully to about six digits. Thus
  20137. you should set the precision to twice as many digits as you need in your
  20138. answer.
  20139. @ignore
  20140. @mindex wmin@idots
  20141. @end ignore
  20142. @tindex wminimize
  20143. @ignore
  20144. @mindex wmax@idots
  20145. @end ignore
  20146. @tindex wmaximize
  20147. The @kbd{H a N} [@code{wminimize}] command, analogously to @kbd{H a R},
  20148. expands the guess interval to enclose a minimum rather than requiring
  20149. that the minimum lie inside the interval you supply.
  20150. The @kbd{a X} (@code{calc-find-maximum}) [@code{maximize}] and
  20151. @kbd{H a X} [@code{wmaximize}] commands effectively minimize the
  20152. negative of the formula you supply.
  20153. The formula must evaluate to a real number at all points inside the
  20154. interval (or near the initial guess if the guess is a number). If
  20155. the initial guess is a complex number the variable will be minimized
  20156. over the complex numbers; if it is real or an interval it will
  20157. be minimized over the reals.
  20158. @node Numerical Systems of Equations, , Minimization, Numerical Solutions
  20159. @subsection Systems of Equations
  20160. @noindent
  20161. @cindex Systems of equations, numerical
  20162. The @kbd{a R} command can also solve systems of equations. In this
  20163. case, the equation should instead be a vector of equations, the
  20164. guess should instead be a vector of numbers (intervals are not
  20165. supported), and the variable should be a vector of variables. You
  20166. can omit the brackets while entering the list of variables. Each
  20167. equation must be differentiable by each variable for this mode to
  20168. work. The result will be a vector of two vectors: The variable
  20169. values that solved the system of equations, and the differences
  20170. between the sides of the equations with those variable values.
  20171. There must be the same number of equations as variables. Since
  20172. only plain numbers are allowed as guesses, the Hyperbolic flag has
  20173. no effect when solving a system of equations.
  20174. It is also possible to minimize over many variables with @kbd{a N}
  20175. (or maximize with @kbd{a X}). Once again the variable name should
  20176. be replaced by a vector of variables, and the initial guess should
  20177. be an equal-sized vector of initial guesses. But, unlike the case of
  20178. multidimensional @kbd{a R}, the formula being minimized should
  20179. still be a single formula, @emph{not} a vector. Beware that
  20180. multidimensional minimization is currently @emph{very} slow.
  20181. @node Curve Fitting, Summations, Numerical Solutions, Algebra
  20182. @section Curve Fitting
  20183. @noindent
  20184. The @kbd{a F} command fits a set of data to a @dfn{model formula},
  20185. such as @cite{y = m x + b} where @cite{m} and @cite{b} are parameters
  20186. to be determined. For a typical set of measured data there will be
  20187. no single @cite{m} and @cite{b} that exactly fit the data; in this
  20188. case, Calc chooses values of the parameters that provide the closest
  20189. possible fit.
  20190. @menu
  20191. * Linear Fits::
  20192. * Polynomial and Multilinear Fits::
  20193. * Error Estimates for Fits::
  20194. * Standard Nonlinear Models::
  20195. * Curve Fitting Details::
  20196. * Interpolation::
  20197. @end menu
  20198. @node Linear Fits, Polynomial and Multilinear Fits, Curve Fitting, Curve Fitting
  20199. @subsection Linear Fits
  20200. @noindent
  20201. @kindex a F
  20202. @pindex calc-curve-fit
  20203. @tindex fit
  20204. @cindex Linear regression
  20205. @cindex Least-squares fits
  20206. The @kbd{a F} (@code{calc-curve-fit}) [@code{fit}] command attempts
  20207. to fit a set of data (@cite{x} and @cite{y} vectors of numbers) to a
  20208. straight line, polynomial, or other function of @cite{x}. For the
  20209. moment we will consider only the case of fitting to a line, and we
  20210. will ignore the issue of whether or not the model was in fact a good
  20211. fit for the data.
  20212. In a standard linear least-squares fit, we have a set of @cite{(x,y)}
  20213. data points that we wish to fit to the model @cite{y = m x + b}
  20214. by adjusting the parameters @cite{m} and @cite{b} to make the @cite{y}
  20215. values calculated from the formula be as close as possible to the actual
  20216. @cite{y} values in the data set. (In a polynomial fit, the model is
  20217. instead, say, @cite{y = a x^3 + b x^2 + c x + d}. In a multilinear fit,
  20218. we have data points of the form @cite{(x_1,x_2,x_3,y)} and our model is
  20219. @cite{y = a x_1 + b x_2 + c x_3 + d}. These will be discussed later.)
  20220. In the model formula, variables like @cite{x} and @cite{x_2} are called
  20221. the @dfn{independent variables}, and @cite{y} is the @dfn{dependent
  20222. variable}. Variables like @cite{m}, @cite{a}, and @cite{b} are called
  20223. the @dfn{parameters} of the model.
  20224. The @kbd{a F} command takes the data set to be fitted from the stack.
  20225. By default, it expects the data in the form of a matrix. For example,
  20226. for a linear or polynomial fit, this would be a @c{$2\times N$}
  20227. @asis{2xN} matrix where
  20228. the first row is a list of @cite{x} values and the second row has the
  20229. corresponding @cite{y} values. For the multilinear fit shown above,
  20230. the matrix would have four rows (@cite{x_1}, @cite{x_2}, @cite{x_3}, and
  20231. @cite{y}, respectively).
  20232. If you happen to have an @c{$N\times2$}
  20233. @asis{Nx2} matrix instead of a @c{$2\times N$}
  20234. @asis{2xN} matrix,
  20235. just press @kbd{v t} first to transpose the matrix.
  20236. After you type @kbd{a F}, Calc prompts you to select a model. For a
  20237. linear fit, press the digit @kbd{1}.
  20238. Calc then prompts for you to name the variables. By default it chooses
  20239. high letters like @cite{x} and @cite{y} for independent variables and
  20240. low letters like @cite{a} and @cite{b} for parameters. (The dependent
  20241. variable doesn't need a name.) The two kinds of variables are separated
  20242. by a semicolon. Since you generally care more about the names of the
  20243. independent variables than of the parameters, Calc also allows you to
  20244. name only those and let the parameters use default names.
  20245. For example, suppose the data matrix
  20246. @ifinfo
  20247. @example
  20248. @group
  20249. [ [ 1, 2, 3, 4, 5 ]
  20250. [ 5, 7, 9, 11, 13 ] ]
  20251. @end group
  20252. @end example
  20253. @end ifinfo
  20254. @tex
  20255. \turnoffactive
  20256. \turnoffactive
  20257. \beforedisplay
  20258. $$ \pmatrix{ 1 & 2 & 3 & 4 & 5 \cr
  20259. 5 & 7 & 9 & 11 & 13 }
  20260. $$
  20261. \afterdisplay
  20262. @end tex
  20263. @noindent
  20264. is on the stack and we wish to do a simple linear fit. Type
  20265. @kbd{a F}, then @kbd{1} for the model, then @key{RET} to use
  20266. the default names. The result will be the formula @cite{3 + 2 x}
  20267. on the stack. Calc has created the model expression @kbd{a + b x},
  20268. then found the optimal values of @cite{a} and @cite{b} to fit the
  20269. data. (In this case, it was able to find an exact fit.) Calc then
  20270. substituted those values for @cite{a} and @cite{b} in the model
  20271. formula.
  20272. The @kbd{a F} command puts two entries in the trail. One is, as
  20273. always, a copy of the result that went to the stack; the other is
  20274. a vector of the actual parameter values, written as equations:
  20275. @cite{[a = 3, b = 2]}, in case you'd rather read them in a list
  20276. than pick them out of the formula. (You can type @kbd{t y}
  20277. to move this vector to the stack; see @ref{Trail Commands}.
  20278. Specifying a different independent variable name will affect the
  20279. resulting formula: @kbd{a F 1 k @key{RET}} produces @kbd{3 + 2 k}.
  20280. Changing the parameter names (say, @kbd{a F 1 k;b,m @key{RET}}) will affect
  20281. the equations that go into the trail.
  20282. @tex
  20283. \bigskip
  20284. @end tex
  20285. To see what happens when the fit is not exact, we could change
  20286. the number 13 in the data matrix to 14 and try the fit again.
  20287. The result is:
  20288. @example
  20289. 2.6 + 2.2 x
  20290. @end example
  20291. Evaluating this formula, say with @kbd{v x 5 @key{RET} @key{TAB} V M $ @key{RET}}, shows
  20292. a reasonably close match to the y-values in the data.
  20293. @example
  20294. [4.8, 7., 9.2, 11.4, 13.6]
  20295. @end example
  20296. Since there is no line which passes through all the @var{n} data points,
  20297. Calc has chosen a line that best approximates the data points using
  20298. the method of least squares. The idea is to define the @dfn{chi-square}
  20299. error measure
  20300. @ifinfo
  20301. @example
  20302. chi^2 = sum((y_i - (a + b x_i))^2, i, 1, N)
  20303. @end example
  20304. @end ifinfo
  20305. @tex
  20306. \turnoffactive
  20307. \beforedisplay
  20308. $$ \chi^2 = \sum_{i=1}^N (y_i - (a + b x_i))^2 $$
  20309. \afterdisplay
  20310. @end tex
  20311. @noindent
  20312. which is clearly zero if @cite{a + b x} exactly fits all data points,
  20313. and increases as various @cite{a + b x_i} values fail to match the
  20314. corresponding @cite{y_i} values. There are several reasons why the
  20315. summand is squared, one of them being to ensure that @c{$\chi^2 \ge 0$}
  20316. @cite{chi^2 >= 0}.
  20317. Least-squares fitting simply chooses the values of @cite{a} and @cite{b}
  20318. for which the error @c{$\chi^2$}
  20319. @cite{chi^2} is as small as possible.
  20320. Other kinds of models do the same thing but with a different model
  20321. formula in place of @cite{a + b x_i}.
  20322. @tex
  20323. \bigskip
  20324. @end tex
  20325. A numeric prefix argument causes the @kbd{a F} command to take the
  20326. data in some other form than one big matrix. A positive argument @var{n}
  20327. will take @var{N} items from the stack, corresponding to the @var{n} rows
  20328. of a data matrix. In the linear case, @var{n} must be 2 since there
  20329. is always one independent variable and one dependent variable.
  20330. A prefix of zero or plain @kbd{C-u} is a compromise; Calc takes two
  20331. items from the stack, an @var{n}-row matrix of @cite{x} values, and a
  20332. vector of @cite{y} values. If there is only one independent variable,
  20333. the @cite{x} values can be either a one-row matrix or a plain vector,
  20334. in which case the @kbd{C-u} prefix is the same as a @w{@kbd{C-u 2}} prefix.
  20335. @node Polynomial and Multilinear Fits, Error Estimates for Fits, Linear Fits, Curve Fitting
  20336. @subsection Polynomial and Multilinear Fits
  20337. @noindent
  20338. To fit the data to higher-order polynomials, just type one of the
  20339. digits @kbd{2} through @kbd{9} when prompted for a model. For example,
  20340. we could fit the original data matrix from the previous section
  20341. (with 13, not 14) to a parabola instead of a line by typing
  20342. @kbd{a F 2 @key{RET}}.
  20343. @example
  20344. 2.00000000001 x - 1.5e-12 x^2 + 2.99999999999
  20345. @end example
  20346. Note that since the constant and linear terms are enough to fit the
  20347. data exactly, it's no surprise that Calc chose a tiny contribution
  20348. for @cite{x^2}. (The fact that it's not exactly zero is due only
  20349. to roundoff error. Since our data are exact integers, we could get
  20350. an exact answer by typing @kbd{m f} first to get fraction mode.
  20351. Then the @cite{x^2} term would vanish altogether. Usually, though,
  20352. the data being fitted will be approximate floats so fraction mode
  20353. won't help.)
  20354. Doing the @kbd{a F 2} fit on the data set with 14 instead of 13
  20355. gives a much larger @cite{x^2} contribution, as Calc bends the
  20356. line slightly to improve the fit.
  20357. @example
  20358. 0.142857142855 x^2 + 1.34285714287 x + 3.59999999998
  20359. @end example
  20360. An important result from the theory of polynomial fitting is that it
  20361. is always possible to fit @var{n} data points exactly using a polynomial
  20362. of degree @i{@var{n}-1}, sometimes called an @dfn{interpolating polynomial}.
  20363. Using the modified (14) data matrix, a model number of 4 gives
  20364. a polynomial that exactly matches all five data points:
  20365. @example
  20366. 0.04167 x^4 - 0.4167 x^3 + 1.458 x^2 - 0.08333 x + 4.
  20367. @end example
  20368. The actual coefficients we get with a precision of 12, like
  20369. @cite{0.0416666663588}, clearly suffer from loss of precision.
  20370. It is a good idea to increase the working precision to several
  20371. digits beyond what you need when you do a fitting operation.
  20372. Or, if your data are exact, use fraction mode to get exact
  20373. results.
  20374. You can type @kbd{i} instead of a digit at the model prompt to fit
  20375. the data exactly to a polynomial. This just counts the number of
  20376. columns of the data matrix to choose the degree of the polynomial
  20377. automatically.
  20378. Fitting data ``exactly'' to high-degree polynomials is not always
  20379. a good idea, though. High-degree polynomials have a tendency to
  20380. wiggle uncontrollably in between the fitting data points. Also,
  20381. if the exact-fit polynomial is going to be used to interpolate or
  20382. extrapolate the data, it is numerically better to use the @kbd{a p}
  20383. command described below. @xref{Interpolation}.
  20384. @tex
  20385. \bigskip
  20386. @end tex
  20387. Another generalization of the linear model is to assume the
  20388. @cite{y} values are a sum of linear contributions from several
  20389. @cite{x} values. This is a @dfn{multilinear} fit, and it is also
  20390. selected by the @kbd{1} digit key. (Calc decides whether the fit
  20391. is linear or multilinear by counting the rows in the data matrix.)
  20392. Given the data matrix,
  20393. @example
  20394. @group
  20395. [ [ 1, 2, 3, 4, 5 ]
  20396. [ 7, 2, 3, 5, 2 ]
  20397. [ 14.5, 15, 18.5, 22.5, 24 ] ]
  20398. @end group
  20399. @end example
  20400. @noindent
  20401. the command @kbd{a F 1 @key{RET}} will call the first row @cite{x} and the
  20402. second row @cite{y}, and will fit the values in the third row to the
  20403. model @cite{a + b x + c y}.
  20404. @example
  20405. 8. + 3. x + 0.5 y
  20406. @end example
  20407. Calc can do multilinear fits with any number of independent variables
  20408. (i.e., with any number of data rows).
  20409. @tex
  20410. \bigskip
  20411. @end tex
  20412. Yet another variation is @dfn{homogeneous} linear models, in which
  20413. the constant term is known to be zero. In the linear case, this
  20414. means the model formula is simply @cite{a x}; in the multilinear
  20415. case, the model might be @cite{a x + b y + c z}; and in the polynomial
  20416. case, the model could be @cite{a x + b x^2 + c x^3}. You can get
  20417. a homogeneous linear or multilinear model by pressing the letter
  20418. @kbd{h} followed by a regular model key, like @kbd{1} or @kbd{2}.
  20419. It is certainly possible to have other constrained linear models,
  20420. like @cite{2.3 + a x} or @cite{a - 4 x}. While there is no single
  20421. key to select models like these, a later section shows how to enter
  20422. any desired model by hand. In the first case, for example, you
  20423. would enter @kbd{a F ' 2.3 + a x}.
  20424. Another class of models that will work but must be entered by hand
  20425. are multinomial fits, e.g., @cite{a + b x + c y + d x^2 + e y^2 + f x y}.
  20426. @node Error Estimates for Fits, Standard Nonlinear Models, Polynomial and Multilinear Fits, Curve Fitting
  20427. @subsection Error Estimates for Fits
  20428. @noindent
  20429. @kindex H a F
  20430. @tindex efit
  20431. With the Hyperbolic flag, @kbd{H a F} [@code{efit}] performs the same
  20432. fitting operation as @kbd{a F}, but reports the coefficients as error
  20433. forms instead of plain numbers. Fitting our two data matrices (first
  20434. with 13, then with 14) to a line with @kbd{H a F} gives the results,
  20435. @example
  20436. 3. + 2. x
  20437. 2.6 +/- 0.382970843103 + 2.2 +/- 0.115470053838 x
  20438. @end example
  20439. In the first case the estimated errors are zero because the linear
  20440. fit is perfect. In the second case, the errors are nonzero but
  20441. moderately small, because the data are still very close to linear.
  20442. It is also possible for the @emph{input} to a fitting operation to
  20443. contain error forms. The data values must either all include errors
  20444. or all be plain numbers. Error forms can go anywhere but generally
  20445. go on the numbers in the last row of the data matrix. If the last
  20446. row contains error forms
  20447. `@var{y_i}@w{ @t{+/-} }@c{$\sigma_i$}
  20448. @var{sigma_i}', then the @c{$\chi^2$}
  20449. @cite{chi^2}
  20450. statistic is now,
  20451. @ifinfo
  20452. @example
  20453. chi^2 = sum(((y_i - (a + b x_i)) / sigma_i)^2, i, 1, N)
  20454. @end example
  20455. @end ifinfo
  20456. @tex
  20457. \turnoffactive
  20458. \beforedisplay
  20459. $$ \chi^2 = \sum_{i=1}^N \left(y_i - (a + b x_i) \over \sigma_i\right)^2 $$
  20460. \afterdisplay
  20461. @end tex
  20462. @noindent
  20463. so that data points with larger error estimates contribute less to
  20464. the fitting operation.
  20465. If there are error forms on other rows of the data matrix, all the
  20466. errors for a given data point are combined; the square root of the
  20467. sum of the squares of the errors forms the @c{$\sigma_i$}
  20468. @cite{sigma_i} used for
  20469. the data point.
  20470. Both @kbd{a F} and @kbd{H a F} can accept error forms in the input
  20471. matrix, although if you are concerned about error analysis you will
  20472. probably use @kbd{H a F} so that the output also contains error
  20473. estimates.
  20474. If the input contains error forms but all the @c{$\sigma_i$}
  20475. @cite{sigma_i} values are
  20476. the same, it is easy to see that the resulting fitted model will be
  20477. the same as if the input did not have error forms at all (@c{$\chi^2$}
  20478. @cite{chi^2}
  20479. is simply scaled uniformly by @c{$1 / \sigma^2$}
  20480. @cite{1 / sigma^2}, which doesn't affect
  20481. where it has a minimum). But there @emph{will} be a difference
  20482. in the estimated errors of the coefficients reported by @kbd{H a F}.
  20483. Consult any text on statistical modelling of data for a discussion
  20484. of where these error estimates come from and how they should be
  20485. interpreted.
  20486. @tex
  20487. \bigskip
  20488. @end tex
  20489. @kindex I a F
  20490. @tindex xfit
  20491. With the Inverse flag, @kbd{I a F} [@code{xfit}] produces even more
  20492. information. The result is a vector of six items:
  20493. @enumerate
  20494. @item
  20495. The model formula with error forms for its coefficients or
  20496. parameters. This is the result that @kbd{H a F} would have
  20497. produced.
  20498. @item
  20499. A vector of ``raw'' parameter values for the model. These are the
  20500. polynomial coefficients or other parameters as plain numbers, in the
  20501. same order as the parameters appeared in the final prompt of the
  20502. @kbd{I a F} command. For polynomials of degree @cite{d}, this vector
  20503. will have length @cite{M = d+1} with the constant term first.
  20504. @item
  20505. The covariance matrix @cite{C} computed from the fit. This is
  20506. an @var{m}x@var{m} symmetric matrix; the diagonal elements
  20507. @c{$C_{jj}$}
  20508. @cite{C_j_j} are the variances @c{$\sigma_j^2$}
  20509. @cite{sigma_j^2} of the parameters.
  20510. The other elements are covariances @c{$\sigma_{ij}^2$}
  20511. @cite{sigma_i_j^2} that describe the
  20512. correlation between pairs of parameters. (A related set of
  20513. numbers, the @dfn{linear correlation coefficients} @c{$r_{ij}$}
  20514. @cite{r_i_j},
  20515. are defined as @c{$\sigma_{ij}^2 / \sigma_i \, \sigma_j$}
  20516. @cite{sigma_i_j^2 / sigma_i sigma_j}.)
  20517. @item
  20518. A vector of @cite{M} ``parameter filter'' functions whose
  20519. meanings are described below. If no filters are necessary this
  20520. will instead be an empty vector; this is always the case for the
  20521. polynomial and multilinear fits described so far.
  20522. @item
  20523. The value of @c{$\chi^2$}
  20524. @cite{chi^2} for the fit, calculated by the formulas
  20525. shown above. This gives a measure of the quality of the fit;
  20526. statisticians consider @c{$\chi^2 \approx N - M$}
  20527. @cite{chi^2 = N - M} to indicate a moderately good fit
  20528. (where again @cite{N} is the number of data points and @cite{M}
  20529. is the number of parameters).
  20530. @item
  20531. A measure of goodness of fit expressed as a probability @cite{Q}.
  20532. This is computed from the @code{utpc} probability distribution
  20533. function using @c{$\chi^2$}
  20534. @cite{chi^2} with @cite{N - M} degrees of freedom. A
  20535. value of 0.5 implies a good fit; some texts recommend that often
  20536. @cite{Q = 0.1} or even 0.001 can signify an acceptable fit. In
  20537. particular, @c{$\chi^2$}
  20538. @cite{chi^2} statistics assume the errors in your inputs
  20539. follow a normal (Gaussian) distribution; if they don't, you may
  20540. have to accept smaller values of @cite{Q}.
  20541. The @cite{Q} value is computed only if the input included error
  20542. estimates. Otherwise, Calc will report the symbol @code{nan}
  20543. for @cite{Q}. The reason is that in this case the @c{$\chi^2$}
  20544. @cite{chi^2}
  20545. value has effectively been used to estimate the original errors
  20546. in the input, and thus there is no redundant information left
  20547. over to use for a confidence test.
  20548. @end enumerate
  20549. @node Standard Nonlinear Models, Curve Fitting Details, Error Estimates for Fits, Curve Fitting
  20550. @subsection Standard Nonlinear Models
  20551. @noindent
  20552. The @kbd{a F} command also accepts other kinds of models besides
  20553. lines and polynomials. Some common models have quick single-key
  20554. abbreviations; others must be entered by hand as algebraic formulas.
  20555. Here is a complete list of the standard models recognized by @kbd{a F}:
  20556. @table @kbd
  20557. @item 1
  20558. Linear or multilinear. @i{a + b x + c y + d z}.
  20559. @item 2-9
  20560. Polynomials. @i{a + b x + c x^2 + d x^3}.
  20561. @item e
  20562. Exponential. @i{a} @t{exp}@i{(b x)} @t{exp}@i{(c y)}.
  20563. @item E
  20564. Base-10 exponential. @i{a} @t{10^}@i{(b x)} @t{10^}@i{(c y)}.
  20565. @item x
  20566. Exponential (alternate notation). @t{exp}@i{(a + b x + c y)}.
  20567. @item X
  20568. Base-10 exponential (alternate). @t{10^}@i{(a + b x + c y)}.
  20569. @item l
  20570. Logarithmic. @i{a + b} @t{ln}@i{(x) + c} @t{ln}@i{(y)}.
  20571. @item L
  20572. Base-10 logarithmic. @i{a + b} @t{log10}@i{(x) + c} @t{log10}@i{(y)}.
  20573. @item ^
  20574. General exponential. @i{a b^x c^y}.
  20575. @item p
  20576. Power law. @i{a x^b y^c}.
  20577. @item q
  20578. Quadratic. @i{a + b (x-c)^2 + d (x-e)^2}.
  20579. @item g
  20580. Gaussian. @c{${a \over b \sqrt{2 \pi}} \exp\left( -{1 \over 2} \left( x - c \over b \right)^2 \right)$}
  20581. @i{(a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2)}.
  20582. @end table
  20583. All of these models are used in the usual way; just press the appropriate
  20584. letter at the model prompt, and choose variable names if you wish. The
  20585. result will be a formula as shown in the above table, with the best-fit
  20586. values of the parameters substituted. (You may find it easier to read
  20587. the parameter values from the vector that is placed in the trail.)
  20588. All models except Gaussian and polynomials can generalize as shown to any
  20589. number of independent variables. Also, all the built-in models have an
  20590. additive or multiplicative parameter shown as @cite{a} in the above table
  20591. which can be replaced by zero or one, as appropriate, by typing @kbd{h}
  20592. before the model key.
  20593. Note that many of these models are essentially equivalent, but express
  20594. the parameters slightly differently. For example, @cite{a b^x} and
  20595. the other two exponential models are all algebraic rearrangements of
  20596. each other. Also, the ``quadratic'' model is just a degree-2 polynomial
  20597. with the parameters expressed differently. Use whichever form best
  20598. matches the problem.
  20599. The HP-28/48 calculators support four different models for curve
  20600. fitting, called @code{LIN}, @code{LOG}, @code{EXP}, and @code{PWR}.
  20601. These correspond to Calc models @samp{a + b x}, @samp{a + b ln(x)},
  20602. @samp{a exp(b x)}, and @samp{a x^b}, respectively. In each case,
  20603. @cite{a} is what the HP-48 identifies as the ``intercept,'' and
  20604. @cite{b} is what it calls the ``slope.''
  20605. @tex
  20606. \bigskip
  20607. @end tex
  20608. If the model you want doesn't appear on this list, press @kbd{'}
  20609. (the apostrophe key) at the model prompt to enter any algebraic
  20610. formula, such as @kbd{m x - b}, as the model. (Not all models
  20611. will work, though---see the next section for details.)
  20612. The model can also be an equation like @cite{y = m x + b}.
  20613. In this case, Calc thinks of all the rows of the data matrix on
  20614. equal terms; this model effectively has two parameters
  20615. (@cite{m} and @cite{b}) and two independent variables (@cite{x}
  20616. and @cite{y}), with no ``dependent'' variables. Model equations
  20617. do not need to take this @cite{y =} form. For example, the
  20618. implicit line equation @cite{a x + b y = 1} works fine as a
  20619. model.
  20620. When you enter a model, Calc makes an alphabetical list of all
  20621. the variables that appear in the model. These are used for the
  20622. default parameters, independent variables, and dependent variable
  20623. (in that order). If you enter a plain formula (not an equation),
  20624. Calc assumes the dependent variable does not appear in the formula
  20625. and thus does not need a name.
  20626. For example, if the model formula has the variables @cite{a,mu,sigma,t,x},
  20627. and the data matrix has three rows (meaning two independent variables),
  20628. Calc will use @cite{a,mu,sigma} as the default parameters, and the
  20629. data rows will be named @cite{t} and @cite{x}, respectively. If you
  20630. enter an equation instead of a plain formula, Calc will use @cite{a,mu}
  20631. as the parameters, and @cite{sigma,t,x} as the three independent
  20632. variables.
  20633. You can, of course, override these choices by entering something
  20634. different at the prompt. If you leave some variables out of the list,
  20635. those variables must have stored values and those stored values will
  20636. be used as constants in the model. (Stored values for the parameters
  20637. and independent variables are ignored by the @kbd{a F} command.)
  20638. If you list only independent variables, all the remaining variables
  20639. in the model formula will become parameters.
  20640. If there are @kbd{$} signs in the model you type, they will stand
  20641. for parameters and all other variables (in alphabetical order)
  20642. will be independent. Use @kbd{$} for one parameter, @kbd{$$} for
  20643. another, and so on. Thus @kbd{$ x + $$} is another way to describe
  20644. a linear model.
  20645. If you type a @kbd{$} instead of @kbd{'} at the model prompt itself,
  20646. Calc will take the model formula from the stack. (The data must then
  20647. appear at the second stack level.) The same conventions are used to
  20648. choose which variables in the formula are independent by default and
  20649. which are parameters.
  20650. Models taken from the stack can also be expressed as vectors of
  20651. two or three elements, @cite{[@var{model}, @var{vars}]} or
  20652. @cite{[@var{model}, @var{vars}, @var{params}]}. Each of @var{vars}
  20653. and @var{params} may be either a variable or a vector of variables.
  20654. (If @var{params} is omitted, all variables in @var{model} except
  20655. those listed as @var{vars} are parameters.)@refill
  20656. When you enter a model manually with @kbd{'}, Calc puts a 3-vector
  20657. describing the model in the trail so you can get it back if you wish.
  20658. @tex
  20659. \bigskip
  20660. @end tex
  20661. @vindex Model1
  20662. @vindex Model2
  20663. Finally, you can store a model in one of the Calc variables
  20664. @code{Model1} or @code{Model2}, then use this model by typing
  20665. @kbd{a F u} or @kbd{a F U} (respectively). The value stored in
  20666. the variable can be any of the formats that @kbd{a F $} would
  20667. accept for a model on the stack.
  20668. @tex
  20669. \bigskip
  20670. @end tex
  20671. Calc uses the principal values of inverse functions like @code{ln}
  20672. and @code{arcsin} when doing fits. For example, when you enter
  20673. the model @samp{y = sin(a t + b)} Calc actually uses the easier
  20674. form @samp{arcsin(y) = a t + b}. The @code{arcsin} function always
  20675. returns results in the range from @i{-90} to 90 degrees (or the
  20676. equivalent range in radians). Suppose you had data that you
  20677. believed to represent roughly three oscillations of a sine wave,
  20678. so that the argument of the sine might go from zero to @c{$3\times360$}
  20679. @i{3*360} degrees.
  20680. The above model would appear to be a good way to determine the
  20681. true frequency and phase of the sine wave, but in practice it
  20682. would fail utterly. The righthand side of the actual model
  20683. @samp{arcsin(y) = a t + b} will grow smoothly with @cite{t}, but
  20684. the lefthand side will bounce back and forth between @i{-90} and 90.
  20685. No values of @cite{a} and @cite{b} can make the two sides match,
  20686. even approximately.
  20687. There is no good solution to this problem at present. You could
  20688. restrict your data to small enough ranges so that the above problem
  20689. doesn't occur (i.e., not straddling any peaks in the sine wave).
  20690. Or, in this case, you could use a totally different method such as
  20691. Fourier analysis, which is beyond the scope of the @kbd{a F} command.
  20692. (Unfortunately, Calc does not currently have any facilities for
  20693. taking Fourier and related transforms.)
  20694. @node Curve Fitting Details, Interpolation, Standard Nonlinear Models, Curve Fitting
  20695. @subsection Curve Fitting Details
  20696. @noindent
  20697. Calc's internal least-squares fitter can only handle multilinear
  20698. models. More precisely, it can handle any model of the form
  20699. @cite{a f(x,y,z) + b g(x,y,z) + c h(x,y,z)}, where @cite{a,b,c}
  20700. are the parameters and @cite{x,y,z} are the independent variables
  20701. (of course there can be any number of each, not just three).
  20702. In a simple multilinear or polynomial fit, it is easy to see how
  20703. to convert the model into this form. For example, if the model
  20704. is @cite{a + b x + c x^2}, then @cite{f(x) = 1}, @cite{g(x) = x},
  20705. and @cite{h(x) = x^2} are suitable functions.
  20706. For other models, Calc uses a variety of algebraic manipulations
  20707. to try to put the problem into the form
  20708. @smallexample
  20709. 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)
  20710. @end smallexample
  20711. @noindent
  20712. where @cite{Y,A,B,C,F,G,H} are arbitrary functions. It computes
  20713. @cite{Y}, @cite{F}, @cite{G}, and @cite{H} for all the data points,
  20714. does a standard linear fit to find the values of @cite{A}, @cite{B},
  20715. and @cite{C}, then uses the equation solver to solve for @cite{a,b,c}
  20716. in terms of @cite{A,B,C}.
  20717. A remarkable number of models can be cast into this general form.
  20718. We'll look at two examples here to see how it works. The power-law
  20719. model @cite{y = a x^b} with two independent variables and two parameters
  20720. can be rewritten as follows:
  20721. @example
  20722. y = a x^b
  20723. y = a exp(b ln(x))
  20724. y = exp(ln(a) + b ln(x))
  20725. ln(y) = ln(a) + b ln(x)
  20726. @end example
  20727. @noindent
  20728. which matches the desired form with @c{$Y = \ln(y)$}
  20729. @cite{Y = ln(y)}, @c{$A = \ln(a)$}
  20730. @cite{A = ln(a)},
  20731. @cite{F = 1}, @cite{B = b}, and @c{$G = \ln(x)$}
  20732. @cite{G = ln(x)}. Calc thus computes
  20733. the logarithms of your @cite{y} and @cite{x} values, does a linear fit
  20734. for @cite{A} and @cite{B}, then solves to get @c{$a = \exp(A)$}
  20735. @cite{a = exp(A)} and
  20736. @cite{b = B}.
  20737. Another interesting example is the ``quadratic'' model, which can
  20738. be handled by expanding according to the distributive law.
  20739. @example
  20740. y = a + b*(x - c)^2
  20741. y = a + b c^2 - 2 b c x + b x^2
  20742. @end example
  20743. @noindent
  20744. which matches with @cite{Y = y}, @cite{A = a + b c^2}, @cite{F = 1},
  20745. @cite{B = -2 b c}, @cite{G = x} (the @i{-2} factor could just as easily
  20746. have been put into @cite{G} instead of @cite{B}), @cite{C = b}, and
  20747. @cite{H = x^2}.
  20748. The Gaussian model looks quite complicated, but a closer examination
  20749. shows that it's actually similar to the quadratic model but with an
  20750. exponential that can be brought to the top and moved into @cite{Y}.
  20751. An example of a model that cannot be put into general linear
  20752. form is a Gaussian with a constant background added on, i.e.,
  20753. @cite{d} + the regular Gaussian formula. If you have a model like
  20754. this, your best bet is to replace enough of your parameters with
  20755. constants to make the model linearizable, then adjust the constants
  20756. manually by doing a series of fits. You can compare the fits by
  20757. graphing them, by examining the goodness-of-fit measures returned by
  20758. @kbd{I a F}, or by some other method suitable to your application.
  20759. Note that some models can be linearized in several ways. The
  20760. Gaussian-plus-@var{d} model can be linearized by setting @cite{d}
  20761. (the background) to a constant, or by setting @cite{b} (the standard
  20762. deviation) and @cite{c} (the mean) to constants.
  20763. To fit a model with constants substituted for some parameters, just
  20764. store suitable values in those parameter variables, then omit them
  20765. from the list of parameters when you answer the variables prompt.
  20766. @tex
  20767. \bigskip
  20768. @end tex
  20769. A last desperate step would be to use the general-purpose
  20770. @code{minimize} function rather than @code{fit}. After all, both
  20771. functions solve the problem of minimizing an expression (the @c{$\chi^2$}
  20772. @cite{chi^2}
  20773. sum) by adjusting certain parameters in the expression. The @kbd{a F}
  20774. command is able to use a vastly more efficient algorithm due to its
  20775. special knowledge about linear chi-square sums, but the @kbd{a N}
  20776. command can do the same thing by brute force.
  20777. A compromise would be to pick out a few parameters without which the
  20778. fit is linearizable, and use @code{minimize} on a call to @code{fit}
  20779. which efficiently takes care of the rest of the parameters. The thing
  20780. to be minimized would be the value of @c{$\chi^2$}
  20781. @cite{chi^2} returned as
  20782. the fifth result of the @code{xfit} function:
  20783. @smallexample
  20784. minimize(xfit(gaus(a,b,c,d,x), x, [a,b,c], data)_5, d, guess)
  20785. @end smallexample
  20786. @noindent
  20787. where @code{gaus} represents the Gaussian model with background,
  20788. @code{data} represents the data matrix, and @code{guess} represents
  20789. the initial guess for @cite{d} that @code{minimize} requires.
  20790. This operation will only be, shall we say, extraordinarily slow
  20791. rather than astronomically slow (as would be the case if @code{minimize}
  20792. were used by itself to solve the problem).
  20793. @tex
  20794. \bigskip
  20795. @end tex
  20796. The @kbd{I a F} [@code{xfit}] command is somewhat trickier when
  20797. nonlinear models are used. The second item in the result is the
  20798. vector of ``raw'' parameters @cite{A}, @cite{B}, @cite{C}. The
  20799. covariance matrix is written in terms of those raw parameters.
  20800. The fifth item is a vector of @dfn{filter} expressions. This
  20801. is the empty vector @samp{[]} if the raw parameters were the same
  20802. as the requested parameters, i.e., if @cite{A = a}, @cite{B = b},
  20803. and so on (which is always true if the model is already linear
  20804. in the parameters as written, e.g., for polynomial fits). If the
  20805. parameters had to be rearranged, the fifth item is instead a vector
  20806. of one formula per parameter in the original model. The raw
  20807. parameters are expressed in these ``filter'' formulas as
  20808. @samp{fitdummy(1)} for @cite{A}, @samp{fitdummy(2)} for @cite{B},
  20809. and so on.
  20810. When Calc needs to modify the model to return the result, it replaces
  20811. @samp{fitdummy(1)} in all the filters with the first item in the raw
  20812. parameters list, and so on for the other raw parameters, then
  20813. evaluates the resulting filter formulas to get the actual parameter
  20814. values to be substituted into the original model. In the case of
  20815. @kbd{H a F} and @kbd{I a F} where the parameters must be error forms,
  20816. Calc uses the square roots of the diagonal entries of the covariance
  20817. matrix as error values for the raw parameters, then lets Calc's
  20818. standard error-form arithmetic take it from there.
  20819. If you use @kbd{I a F} with a nonlinear model, be sure to remember
  20820. that the covariance matrix is in terms of the raw parameters,
  20821. @emph{not} the actual requested parameters. It's up to you to
  20822. figure out how to interpret the covariances in the presence of
  20823. nontrivial filter functions.
  20824. Things are also complicated when the input contains error forms.
  20825. Suppose there are three independent and dependent variables, @cite{x},
  20826. @cite{y}, and @cite{z}, one or more of which are error forms in the
  20827. data. Calc combines all the error values by taking the square root
  20828. of the sum of the squares of the errors. It then changes @cite{x}
  20829. and @cite{y} to be plain numbers, and makes @cite{z} into an error
  20830. form with this combined error. The @cite{Y(x,y,z)} part of the
  20831. linearized model is evaluated, and the result should be an error
  20832. form. The error part of that result is used for @c{$\sigma_i$}
  20833. @cite{sigma_i} for
  20834. the data point. If for some reason @cite{Y(x,y,z)} does not return
  20835. an error form, the combined error from @cite{z} is used directly
  20836. for @c{$\sigma_i$}
  20837. @cite{sigma_i}. Finally, @cite{z} is also stripped of its error
  20838. for use in computing @cite{F(x,y,z)}, @cite{G(x,y,z)} and so on;
  20839. the righthand side of the linearized model is computed in regular
  20840. arithmetic with no error forms.
  20841. (While these rules may seem complicated, they are designed to do
  20842. the most reasonable thing in the typical case that @cite{Y(x,y,z)}
  20843. depends only on the dependent variable @cite{z}, and in fact is
  20844. often simply equal to @cite{z}. For common cases like polynomials
  20845. and multilinear models, the combined error is simply used as the
  20846. @c{$\sigma$}
  20847. @cite{sigma} for the data point with no further ado.)
  20848. @tex
  20849. \bigskip
  20850. @end tex
  20851. @vindex FitRules
  20852. It may be the case that the model you wish to use is linearizable,
  20853. but Calc's built-in rules are unable to figure it out. Calc uses
  20854. its algebraic rewrite mechanism to linearize a model. The rewrite
  20855. rules are kept in the variable @code{FitRules}. You can edit this
  20856. variable using the @kbd{s e FitRules} command; in fact, there is
  20857. a special @kbd{s F} command just for editing @code{FitRules}.
  20858. @xref{Operations on Variables}.
  20859. @xref{Rewrite Rules}, for a discussion of rewrite rules.
  20860. @ignore
  20861. @starindex
  20862. @end ignore
  20863. @tindex fitvar
  20864. @ignore
  20865. @starindex
  20866. @end ignore
  20867. @ignore
  20868. @mindex @idots
  20869. @end ignore
  20870. @tindex fitparam
  20871. @ignore
  20872. @starindex
  20873. @end ignore
  20874. @ignore
  20875. @mindex @null
  20876. @end ignore
  20877. @tindex fitmodel
  20878. @ignore
  20879. @starindex
  20880. @end ignore
  20881. @ignore
  20882. @mindex @null
  20883. @end ignore
  20884. @tindex fitsystem
  20885. @ignore
  20886. @starindex
  20887. @end ignore
  20888. @ignore
  20889. @mindex @null
  20890. @end ignore
  20891. @tindex fitdummy
  20892. Calc uses @code{FitRules} as follows. First, it converts the model
  20893. to an equation if necessary and encloses the model equation in a
  20894. call to the function @code{fitmodel} (which is not actually a defined
  20895. function in Calc; it is only used as a placeholder by the rewrite rules).
  20896. Parameter variables are renamed to function calls @samp{fitparam(1)},
  20897. @samp{fitparam(2)}, and so on, and independent variables are renamed
  20898. to @samp{fitvar(1)}, @samp{fitvar(2)}, etc. The dependent variable
  20899. is the highest-numbered @code{fitvar}. For example, the power law
  20900. model @cite{a x^b} is converted to @cite{y = a x^b}, then to
  20901. @smallexample
  20902. @group
  20903. fitmodel(fitvar(2) = fitparam(1) fitvar(1)^fitparam(2))
  20904. @end group
  20905. @end smallexample
  20906. Calc then applies the rewrites as if by @samp{C-u 0 a r FitRules}.
  20907. (The zero prefix means that rewriting should continue until no further
  20908. changes are possible.)
  20909. When rewriting is complete, the @code{fitmodel} call should have
  20910. been replaced by a @code{fitsystem} call that looks like this:
  20911. @example
  20912. fitsystem(@var{Y}, @var{FGH}, @var{abc})
  20913. @end example
  20914. @noindent
  20915. where @var{Y} is a formula that describes the function @cite{Y(x,y,z)},
  20916. @var{FGH} is the vector of formulas @cite{[F(x,y,z), G(x,y,z), H(x,y,z)]},
  20917. and @var{abc} is the vector of parameter filters which refer to the
  20918. raw parameters as @samp{fitdummy(1)} for @cite{A}, @samp{fitdummy(2)}
  20919. for @cite{B}, etc. While the number of raw parameters (the length of
  20920. the @var{FGH} vector) is usually the same as the number of original
  20921. parameters (the length of the @var{abc} vector), this is not required.
  20922. The power law model eventually boils down to
  20923. @smallexample
  20924. @group
  20925. fitsystem(ln(fitvar(2)),
  20926. [1, ln(fitvar(1))],
  20927. [exp(fitdummy(1)), fitdummy(2)])
  20928. @end group
  20929. @end smallexample
  20930. The actual implementation of @code{FitRules} is complicated; it
  20931. proceeds in four phases. First, common rearrangements are done
  20932. to try to bring linear terms together and to isolate functions like
  20933. @code{exp} and @code{ln} either all the way ``out'' (so that they
  20934. can be put into @var{Y}) or all the way ``in'' (so that they can
  20935. be put into @var{abc} or @var{FGH}). In particular, all
  20936. non-constant powers are converted to logs-and-exponentials form,
  20937. and the distributive law is used to expand products of sums.
  20938. Quotients are rewritten to use the @samp{fitinv} function, where
  20939. @samp{fitinv(x)} represents @cite{1/x} while the @code{FitRules}
  20940. are operating. (The use of @code{fitinv} makes recognition of
  20941. linear-looking forms easier.) If you modify @code{FitRules}, you
  20942. will probably only need to modify the rules for this phase.
  20943. Phase two, whose rules can actually also apply during phases one
  20944. and three, first rewrites @code{fitmodel} to a two-argument
  20945. form @samp{fitmodel(@var{Y}, @var{model})}, where @var{Y} is
  20946. initially zero and @var{model} has been changed from @cite{a=b}
  20947. to @cite{a-b} form. It then tries to peel off invertible functions
  20948. from the outside of @var{model} and put them into @var{Y} instead,
  20949. calling the equation solver to invert the functions. Finally, when
  20950. this is no longer possible, the @code{fitmodel} is changed to a
  20951. four-argument @code{fitsystem}, where the fourth argument is
  20952. @var{model} and the @var{FGH} and @var{abc} vectors are initially
  20953. empty. (The last vector is really @var{ABC}, corresponding to
  20954. raw parameters, for now.)
  20955. Phase three converts a sum of items in the @var{model} to a sum
  20956. of @samp{fitpart(@var{a}, @var{b}, @var{c})} terms which represent
  20957. terms @samp{@var{a}*@var{b}*@var{c}} of the sum, where @var{a}
  20958. is all factors that do not involve any variables, @var{b} is all
  20959. factors that involve only parameters, and @var{c} is the factors
  20960. that involve only independent variables. (If this decomposition
  20961. is not possible, the rule set will not complete and Calc will
  20962. complain that the model is too complex.) Then @code{fitpart}s
  20963. with equal @var{b} or @var{c} components are merged back together
  20964. using the distributive law in order to minimize the number of
  20965. raw parameters needed.
  20966. Phase four moves the @code{fitpart} terms into the @var{FGH} and
  20967. @var{ABC} vectors. Also, some of the algebraic expansions that
  20968. were done in phase 1 are undone now to make the formulas more
  20969. computationally efficient. Finally, it calls the solver one more
  20970. time to convert the @var{ABC} vector to an @var{abc} vector, and
  20971. removes the fourth @var{model} argument (which by now will be zero)
  20972. to obtain the three-argument @code{fitsystem} that the linear
  20973. least-squares solver wants to see.
  20974. @ignore
  20975. @starindex
  20976. @end ignore
  20977. @ignore
  20978. @mindex hasfit@idots
  20979. @end ignore
  20980. @tindex hasfitparams
  20981. @ignore
  20982. @starindex
  20983. @end ignore
  20984. @ignore
  20985. @mindex @null
  20986. @end ignore
  20987. @tindex hasfitvars
  20988. Two functions which are useful in connection with @code{FitRules}
  20989. are @samp{hasfitparams(x)} and @samp{hasfitvars(x)}, which check
  20990. whether @cite{x} refers to any parameters or independent variables,
  20991. respectively. Specifically, these functions return ``true'' if the
  20992. argument contains any @code{fitparam} (or @code{fitvar}) function
  20993. calls, and ``false'' otherwise. (Recall that ``true'' means a
  20994. nonzero number, and ``false'' means zero. The actual nonzero number
  20995. returned is the largest @var{n} from all the @samp{fitparam(@var{n})}s
  20996. or @samp{fitvar(@var{n})}s, respectively, that appear in the formula.)
  20997. @tex
  20998. \bigskip
  20999. @end tex
  21000. The @code{fit} function in algebraic notation normally takes four
  21001. arguments, @samp{fit(@var{model}, @var{vars}, @var{params}, @var{data})},
  21002. where @var{model} is the model formula as it would be typed after
  21003. @kbd{a F '}, @var{vars} is the independent variable or a vector of
  21004. independent variables, @var{params} likewise gives the parameter(s),
  21005. and @var{data} is the data matrix. Note that the length of @var{vars}
  21006. must be equal to the number of rows in @var{data} if @var{model} is
  21007. an equation, or one less than the number of rows if @var{model} is
  21008. a plain formula. (Actually, a name for the dependent variable is
  21009. allowed but will be ignored in the plain-formula case.)
  21010. If @var{params} is omitted, the parameters are all variables in
  21011. @var{model} except those that appear in @var{vars}. If @var{vars}
  21012. is also omitted, Calc sorts all the variables that appear in
  21013. @var{model} alphabetically and uses the higher ones for @var{vars}
  21014. and the lower ones for @var{params}.
  21015. Alternatively, @samp{fit(@var{modelvec}, @var{data})} is allowed
  21016. where @var{modelvec} is a 2- or 3-vector describing the model
  21017. and variables, as discussed previously.
  21018. If Calc is unable to do the fit, the @code{fit} function is left
  21019. in symbolic form, ordinarily with an explanatory message. The
  21020. message will be ``Model expression is too complex'' if the
  21021. linearizer was unable to put the model into the required form.
  21022. The @code{efit} (corresponding to @kbd{H a F}) and @code{xfit}
  21023. (for @kbd{I a F}) functions are completely analogous.
  21024. @node Interpolation, , Curve Fitting Details, Curve Fitting
  21025. @subsection Polynomial Interpolation
  21026. @kindex a p
  21027. @pindex calc-poly-interp
  21028. @tindex polint
  21029. The @kbd{a p} (@code{calc-poly-interp}) [@code{polint}] command does
  21030. a polynomial interpolation at a particular @cite{x} value. It takes
  21031. two arguments from the stack: A data matrix of the sort used by
  21032. @kbd{a F}, and a single number which represents the desired @cite{x}
  21033. value. Calc effectively does an exact polynomial fit as if by @kbd{a F i},
  21034. then substitutes the @cite{x} value into the result in order to get an
  21035. approximate @cite{y} value based on the fit. (Calc does not actually
  21036. use @kbd{a F i}, however; it uses a direct method which is both more
  21037. efficient and more numerically stable.)
  21038. The result of @kbd{a p} is actually a vector of two values: The @cite{y}
  21039. value approximation, and an error measure @cite{dy} that reflects Calc's
  21040. estimation of the probable error of the approximation at that value of
  21041. @cite{x}. If the input @cite{x} is equal to any of the @cite{x} values
  21042. in the data matrix, the output @cite{y} will be the corresponding @cite{y}
  21043. value from the matrix, and the output @cite{dy} will be exactly zero.
  21044. A prefix argument of 2 causes @kbd{a p} to take separate x- and
  21045. y-vectors from the stack instead of one data matrix.
  21046. If @cite{x} is a vector of numbers, @kbd{a p} will return a matrix of
  21047. interpolated results for each of those @cite{x} values. (The matrix will
  21048. have two columns, the @cite{y} values and the @cite{dy} values.)
  21049. If @cite{x} is a formula instead of a number, the @code{polint} function
  21050. remains in symbolic form; use the @kbd{a "} command to expand it out to
  21051. a formula that describes the fit in symbolic terms.
  21052. In all cases, the @kbd{a p} command leaves the data vectors or matrix
  21053. on the stack. Only the @cite{x} value is replaced by the result.
  21054. @kindex H a p
  21055. @tindex ratint
  21056. The @kbd{H a p} [@code{ratint}] command does a rational function
  21057. interpolation. It is used exactly like @kbd{a p}, except that it
  21058. uses as its model the quotient of two polynomials. If there are
  21059. @cite{N} data points, the numerator and denominator polynomials will
  21060. each have degree @cite{N/2} (if @cite{N} is odd, the denominator will
  21061. have degree one higher than the numerator).
  21062. Rational approximations have the advantage that they can accurately
  21063. describe functions that have poles (points at which the function's value
  21064. goes to infinity, so that the denominator polynomial of the approximation
  21065. goes to zero). If @cite{x} corresponds to a pole of the fitted rational
  21066. function, then the result will be a division by zero. If Infinite mode
  21067. is enabled, the result will be @samp{[uinf, uinf]}.
  21068. There is no way to get the actual coefficients of the rational function
  21069. used by @kbd{H a p}. (The algorithm never generates these coefficients
  21070. explicitly, and quotients of polynomials are beyond @w{@kbd{a F}}'s
  21071. capabilities to fit.)
  21072. @node Summations, Logical Operations, Curve Fitting, Algebra
  21073. @section Summations
  21074. @noindent
  21075. @cindex Summation of a series
  21076. @kindex a +
  21077. @pindex calc-summation
  21078. @tindex sum
  21079. The @kbd{a +} (@code{calc-summation}) [@code{sum}] command computes
  21080. the sum of a formula over a certain range of index values. The formula
  21081. is taken from the top of the stack; the command prompts for the
  21082. name of the summation index variable, the lower limit of the
  21083. sum (any formula), and the upper limit of the sum. If you
  21084. enter a blank line at any of these prompts, that prompt and
  21085. any later ones are answered by reading additional elements from
  21086. the stack. Thus, @kbd{' k^2 @key{RET} ' k @key{RET} 1 @key{RET} 5 @key{RET} a + @key{RET}}
  21087. produces the result 55.
  21088. @tex
  21089. \turnoffactive
  21090. $$ \sum_{k=1}^5 k^2 = 55 $$
  21091. @end tex
  21092. The choice of index variable is arbitrary, but it's best not to
  21093. use a variable with a stored value. In particular, while
  21094. @code{i} is often a favorite index variable, it should be avoided
  21095. in Calc because @code{i} has the imaginary constant @cite{(0, 1)}
  21096. as a value. If you pressed @kbd{=} on a sum over @code{i}, it would
  21097. be changed to a nonsensical sum over the ``variable'' @cite{(0, 1)}!
  21098. If you really want to use @code{i} as an index variable, use
  21099. @w{@kbd{s u i @key{RET}}} first to ``unstore'' this variable.
  21100. (@xref{Storing Variables}.)
  21101. A numeric prefix argument steps the index by that amount rather
  21102. than by one. Thus @kbd{' a_k @key{RET} C-u -2 a + k @key{RET} 10 @key{RET} 0 @key{RET}}
  21103. yields @samp{a_10 + a_8 + a_6 + a_4 + a_2 + a_0}. A prefix
  21104. argument of plain @kbd{C-u} causes @kbd{a +} to prompt for the
  21105. step value, in which case you can enter any formula or enter
  21106. a blank line to take the step value from the stack. With the
  21107. @kbd{C-u} prefix, @kbd{a +} can take up to five arguments from
  21108. the stack: The formula, the variable, the lower limit, the
  21109. upper limit, and (at the top of the stack), the step value.
  21110. Calc knows how to do certain sums in closed form. For example,
  21111. @samp{sum(6 k^2, k, 1, n) = @w{2 n^3} + 3 n^2 + n}. In particular,
  21112. this is possible if the formula being summed is polynomial or
  21113. exponential in the index variable. Sums of logarithms are
  21114. transformed into logarithms of products. Sums of trigonometric
  21115. and hyperbolic functions are transformed to sums of exponentials
  21116. and then done in closed form. Also, of course, sums in which the
  21117. lower and upper limits are both numbers can always be evaluated
  21118. just by grinding them out, although Calc will use closed forms
  21119. whenever it can for the sake of efficiency.
  21120. The notation for sums in algebraic formulas is
  21121. @samp{sum(@var{expr}, @var{var}, @var{low}, @var{high}, @var{step})}.
  21122. If @var{step} is omitted, it defaults to one. If @var{high} is
  21123. omitted, @var{low} is actually the upper limit and the lower limit
  21124. is one. If @var{low} is also omitted, the limits are @samp{-inf}
  21125. and @samp{inf}, respectively.
  21126. Infinite sums can sometimes be evaluated: @samp{sum(.5^k, k, 1, inf)}
  21127. returns @cite{1}. This is done by evaluating the sum in closed
  21128. form (to @samp{1. - 0.5^n} in this case), then evaluating this
  21129. formula with @code{n} set to @code{inf}. Calc's usual rules
  21130. for ``infinite'' arithmetic can find the answer from there. If
  21131. infinite arithmetic yields a @samp{nan}, or if the sum cannot be
  21132. solved in closed form, Calc leaves the @code{sum} function in
  21133. symbolic form. @xref{Infinities}.
  21134. As a special feature, if the limits are infinite (or omitted, as
  21135. described above) but the formula includes vectors subscripted by
  21136. expressions that involve the iteration variable, Calc narrows
  21137. the limits to include only the range of integers which result in
  21138. legal subscripts for the vector. For example, the sum
  21139. @samp{sum(k [a,b,c,d,e,f,g]_(2k),k)} evaluates to @samp{b + 2 d + 3 f}.
  21140. The limits of a sum do not need to be integers. For example,
  21141. @samp{sum(a_k, k, 0, 2 n, n)} produces @samp{a_0 + a_n + a_(2 n)}.
  21142. Calc computes the number of iterations using the formula
  21143. @samp{1 + (@var{high} - @var{low}) / @var{step}}, which must,
  21144. after simplification as if by @kbd{a s}, evaluate to an integer.
  21145. If the number of iterations according to the above formula does
  21146. not come out to an integer, the sum is illegal and will be left
  21147. in symbolic form. However, closed forms are still supplied, and
  21148. you are on your honor not to misuse the resulting formulas by
  21149. substituting mismatched bounds into them. For example,
  21150. @samp{sum(k, k, 1, 10, 2)} is invalid, but Calc will go ahead and
  21151. evaluate the closed form solution for the limits 1 and 10 to get
  21152. the rather dubious answer, 29.25.
  21153. If the lower limit is greater than the upper limit (assuming a
  21154. positive step size), the result is generally zero. However,
  21155. Calc only guarantees a zero result when the upper limit is
  21156. exactly one step less than the lower limit, i.e., if the number
  21157. of iterations is @i{-1}. Thus @samp{sum(f(k), k, n, n-1)} is zero
  21158. but the sum from @samp{n} to @samp{n-2} may report a nonzero value
  21159. if Calc used a closed form solution.
  21160. Calc's logical predicates like @cite{a < b} return 1 for ``true''
  21161. and 0 for ``false.'' @xref{Logical Operations}. This can be
  21162. used to advantage for building conditional sums. For example,
  21163. @samp{sum(prime(k)*k^2, k, 1, 20)} is the sum of the squares of all
  21164. prime numbers from 1 to 20; the @code{prime} predicate returns 1 if
  21165. its argument is prime and 0 otherwise. You can read this expression
  21166. as ``the sum of @cite{k^2}, where @cite{k} is prime.'' Indeed,
  21167. @samp{sum(prime(k)*k^2, k)} would represent the sum of @emph{all} primes
  21168. squared, since the limits default to plus and minus infinity, but
  21169. there are no such sums that Calc's built-in rules can do in
  21170. closed form.
  21171. As another example, @samp{sum((k != k_0) * f(k), k, 1, n)} is the
  21172. sum of @cite{f(k)} for all @cite{k} from 1 to @cite{n}, excluding
  21173. one value @cite{k_0}. Slightly more tricky is the summand
  21174. @samp{(k != k_0) / (k - k_0)}, which is an attempt to describe
  21175. the sum of all @cite{1/(k-k_0)} except at @cite{k = k_0}, where
  21176. this would be a division by zero. But at @cite{k = k_0}, this
  21177. formula works out to the indeterminate form @cite{0 / 0}, which
  21178. Calc will not assume is zero. Better would be to use
  21179. @samp{(k != k_0) ? 1/(k-k_0) : 0}; the @samp{? :} operator does
  21180. an ``if-then-else'' test: This expression says, ``if @c{$k \ne k_0$}
  21181. @cite{k != k_0},
  21182. then @cite{1/(k-k_0)}, else zero.'' Now the formula @cite{1/(k-k_0)}
  21183. will not even be evaluated by Calc when @cite{k = k_0}.
  21184. @cindex Alternating sums
  21185. @kindex a -
  21186. @pindex calc-alt-summation
  21187. @tindex asum
  21188. The @kbd{a -} (@code{calc-alt-summation}) [@code{asum}] command
  21189. computes an alternating sum. Successive terms of the sequence
  21190. are given alternating signs, with the first term (corresponding
  21191. to the lower index value) being positive. Alternating sums
  21192. are converted to normal sums with an extra term of the form
  21193. @samp{(-1)^(k-@var{low})}. This formula is adjusted appropriately
  21194. if the step value is other than one. For example, the Taylor
  21195. series for the sine function is @samp{asum(x^k / k!, k, 1, inf, 2)}.
  21196. (Calc cannot evaluate this infinite series, but it can approximate
  21197. it if you replace @code{inf} with any particular odd number.)
  21198. Calc converts this series to a regular sum with a step of one,
  21199. namely @samp{sum((-1)^k x^(2k+1) / (2k+1)!, k, 0, inf)}.
  21200. @cindex Product of a sequence
  21201. @kindex a *
  21202. @pindex calc-product
  21203. @tindex prod
  21204. The @kbd{a *} (@code{calc-product}) [@code{prod}] command is
  21205. the analogous way to take a product of many terms. Calc also knows
  21206. some closed forms for products, such as @samp{prod(k, k, 1, n) = n!}.
  21207. Conditional products can be written @samp{prod(k^prime(k), k, 1, n)}
  21208. or @samp{prod(prime(k) ? k : 1, k, 1, n)}.
  21209. @kindex a T
  21210. @pindex calc-tabulate
  21211. @tindex table
  21212. The @kbd{a T} (@code{calc-tabulate}) [@code{table}] command
  21213. evaluates a formula at a series of iterated index values, just
  21214. like @code{sum} and @code{prod}, but its result is simply a
  21215. vector of the results. For example, @samp{table(a_i, i, 1, 7, 2)}
  21216. produces @samp{[a_1, a_3, a_5, a_7]}.
  21217. @node Logical Operations, Rewrite Rules, Summations, Algebra
  21218. @section Logical Operations
  21219. @noindent
  21220. The following commands and algebraic functions return true/false values,
  21221. where 1 represents ``true'' and 0 represents ``false.'' In cases where
  21222. a truth value is required (such as for the condition part of a rewrite
  21223. rule, or as the condition for a @w{@kbd{Z [ Z ]}} control structure), any
  21224. nonzero value is accepted to mean ``true.'' (Specifically, anything
  21225. for which @code{dnonzero} returns 1 is ``true,'' and anything for
  21226. which @code{dnonzero} returns 0 or cannot decide is assumed ``false.''
  21227. Note that this means that @w{@kbd{Z [ Z ]}} will execute the ``then''
  21228. portion if its condition is provably true, but it will execute the
  21229. ``else'' portion for any condition like @cite{a = b} that is not
  21230. provably true, even if it might be true. Algebraic functions that
  21231. have conditions as arguments, like @code{? :} and @code{&&}, remain
  21232. unevaluated if the condition is neither provably true nor provably
  21233. false. @xref{Declarations}.)
  21234. @kindex a =
  21235. @pindex calc-equal-to
  21236. @tindex eq
  21237. @tindex =
  21238. @tindex ==
  21239. The @kbd{a =} (@code{calc-equal-to}) command, or @samp{eq(a,b)} function
  21240. (which can also be written @samp{a = b} or @samp{a == b} in an algebraic
  21241. formula) is true if @cite{a} and @cite{b} are equal, either because they
  21242. are identical expressions, or because they are numbers which are
  21243. numerically equal. (Thus the integer 1 is considered equal to the float
  21244. 1.0.) If the equality of @cite{a} and @cite{b} cannot be determined,
  21245. the comparison is left in symbolic form. Note that as a command, this
  21246. operation pops two values from the stack and pushes back either a 1 or
  21247. a 0, or a formula @samp{a = b} if the values' equality cannot be determined.
  21248. Many Calc commands use @samp{=} formulas to represent @dfn{equations}.
  21249. For example, the @kbd{a S} (@code{calc-solve-for}) command rearranges
  21250. an equation to solve for a given variable. The @kbd{a M}
  21251. (@code{calc-map-equation}) command can be used to apply any
  21252. function to both sides of an equation; for example, @kbd{2 a M *}
  21253. multiplies both sides of the equation by two. Note that just
  21254. @kbd{2 *} would not do the same thing; it would produce the formula
  21255. @samp{2 (a = b)} which represents 2 if the equality is true or
  21256. zero if not.
  21257. The @code{eq} function with more than two arguments (e.g., @kbd{C-u 3 a =}
  21258. or @samp{a = b = c}) tests if all of its arguments are equal. In
  21259. algebraic notation, the @samp{=} operator is unusual in that it is
  21260. neither left- nor right-associative: @samp{a = b = c} is not the
  21261. same as @samp{(a = b) = c} or @samp{a = (b = c)} (which each compare
  21262. one variable with the 1 or 0 that results from comparing two other
  21263. variables).
  21264. @kindex a #
  21265. @pindex calc-not-equal-to
  21266. @tindex neq
  21267. @tindex !=
  21268. The @kbd{a #} (@code{calc-not-equal-to}) command, or @samp{neq(a,b)} or
  21269. @samp{a != b} function, is true if @cite{a} and @cite{b} are not equal.
  21270. This also works with more than two arguments; @samp{a != b != c != d}
  21271. tests that all four of @cite{a}, @cite{b}, @cite{c}, and @cite{d} are
  21272. distinct numbers.
  21273. @kindex a <
  21274. @tindex lt
  21275. @ignore
  21276. @mindex @idots
  21277. @end ignore
  21278. @kindex a >
  21279. @ignore
  21280. @mindex @null
  21281. @end ignore
  21282. @kindex a [
  21283. @ignore
  21284. @mindex @null
  21285. @end ignore
  21286. @kindex a ]
  21287. @pindex calc-less-than
  21288. @pindex calc-greater-than
  21289. @pindex calc-less-equal
  21290. @pindex calc-greater-equal
  21291. @ignore
  21292. @mindex @null
  21293. @end ignore
  21294. @tindex gt
  21295. @ignore
  21296. @mindex @null
  21297. @end ignore
  21298. @tindex leq
  21299. @ignore
  21300. @mindex @null
  21301. @end ignore
  21302. @tindex geq
  21303. @ignore
  21304. @mindex @null
  21305. @end ignore
  21306. @tindex <
  21307. @ignore
  21308. @mindex @null
  21309. @end ignore
  21310. @tindex >
  21311. @ignore
  21312. @mindex @null
  21313. @end ignore
  21314. @tindex <=
  21315. @ignore
  21316. @mindex @null
  21317. @end ignore
  21318. @tindex >=
  21319. The @kbd{a <} (@code{calc-less-than}) [@samp{lt(a,b)} or @samp{a < b}]
  21320. operation is true if @cite{a} is less than @cite{b}. Similar functions
  21321. are @kbd{a >} (@code{calc-greater-than}) [@samp{gt(a,b)} or @samp{a > b}],
  21322. @kbd{a [} (@code{calc-less-equal}) [@samp{leq(a,b)} or @samp{a <= b}], and
  21323. @kbd{a ]} (@code{calc-greater-equal}) [@samp{geq(a,b)} or @samp{a >= b}].
  21324. While the inequality functions like @code{lt} do not accept more
  21325. than two arguments, the syntax @w{@samp{a <= b < c}} is translated to an
  21326. equivalent expression involving intervals: @samp{b in [a .. c)}.
  21327. (See the description of @code{in} below.) All four combinations
  21328. of @samp{<} and @samp{<=} are allowed, or any of the four combinations
  21329. of @samp{>} and @samp{>=}. Four-argument constructions like
  21330. @samp{a < b < c < d}, and mixtures like @w{@samp{a < b = c}} that
  21331. involve both equalities and inequalities, are not allowed.
  21332. @kindex a .
  21333. @pindex calc-remove-equal
  21334. @tindex rmeq
  21335. The @kbd{a .} (@code{calc-remove-equal}) [@code{rmeq}] command extracts
  21336. the righthand side of the equation or inequality on the top of the
  21337. stack. It also works elementwise on vectors. For example, if
  21338. @samp{[x = 2.34, y = z / 2]} is on the stack, then @kbd{a .} produces
  21339. @samp{[2.34, z / 2]}. As a special case, if the righthand side is a
  21340. variable and the lefthand side is a number (as in @samp{2.34 = x}), then
  21341. Calc keeps the lefthand side instead. Finally, this command works with
  21342. assignments @samp{x := 2.34} as well as equations, always taking the
  21343. the righthand side, and for @samp{=>} (evaluates-to) operators, always
  21344. taking the lefthand side.
  21345. @kindex a &
  21346. @pindex calc-logical-and
  21347. @tindex land
  21348. @tindex &&
  21349. The @kbd{a &} (@code{calc-logical-and}) [@samp{land(a,b)} or @samp{a && b}]
  21350. function is true if both of its arguments are true, i.e., are
  21351. non-zero numbers. In this case, the result will be either @cite{a} or
  21352. @cite{b}, chosen arbitrarily. If either argument is zero, the result is
  21353. zero. Otherwise, the formula is left in symbolic form.
  21354. @kindex a |
  21355. @pindex calc-logical-or
  21356. @tindex lor
  21357. @tindex ||
  21358. The @kbd{a |} (@code{calc-logical-or}) [@samp{lor(a,b)} or @samp{a || b}]
  21359. function is true if either or both of its arguments are true (nonzero).
  21360. The result is whichever argument was nonzero, choosing arbitrarily if both
  21361. are nonzero. If both @cite{a} and @cite{b} are zero, the result is
  21362. zero.
  21363. @kindex a !
  21364. @pindex calc-logical-not
  21365. @tindex lnot
  21366. @tindex !
  21367. The @kbd{a !} (@code{calc-logical-not}) [@samp{lnot(a)} or @samp{!@: a}]
  21368. function is true if @cite{a} is false (zero), or false if @cite{a} is
  21369. true (nonzero). It is left in symbolic form if @cite{a} is not a
  21370. number.
  21371. @kindex a :
  21372. @pindex calc-logical-if
  21373. @tindex if
  21374. @ignore
  21375. @mindex ? :
  21376. @end ignore
  21377. @tindex ?
  21378. @ignore
  21379. @mindex @null
  21380. @end ignore
  21381. @tindex :
  21382. @cindex Arguments, not evaluated
  21383. The @kbd{a :} (@code{calc-logical-if}) [@samp{if(a,b,c)} or @samp{a ? b :@: c}]
  21384. function is equal to either @cite{b} or @cite{c} if @cite{a} is a nonzero
  21385. number or zero, respectively. If @cite{a} is not a number, the test is
  21386. left in symbolic form and neither @cite{b} nor @cite{c} is evaluated in
  21387. any way. In algebraic formulas, this is one of the few Calc functions
  21388. whose arguments are not automatically evaluated when the function itself
  21389. is evaluated. The others are @code{lambda}, @code{quote}, and
  21390. @code{condition}.
  21391. One minor surprise to watch out for is that the formula @samp{a?3:4}
  21392. will not work because the @samp{3:4} is parsed as a fraction instead of
  21393. as three separate symbols. Type something like @samp{a ? 3 : 4} or
  21394. @samp{a?(3):4} instead.
  21395. As a special case, if @cite{a} evaluates to a vector, then both @cite{b}
  21396. and @cite{c} are evaluated; the result is a vector of the same length
  21397. as @cite{a} whose elements are chosen from corresponding elements of
  21398. @cite{b} and @cite{c} according to whether each element of @cite{a}
  21399. is zero or nonzero. Each of @cite{b} and @cite{c} must be either a
  21400. vector of the same length as @cite{a}, or a non-vector which is matched
  21401. with all elements of @cite{a}.
  21402. @kindex a @{
  21403. @pindex calc-in-set
  21404. @tindex in
  21405. The @kbd{a @{} (@code{calc-in-set}) [@samp{in(a,b)}] function is true if
  21406. the number @cite{a} is in the set of numbers represented by @cite{b}.
  21407. If @cite{b} is an interval form, @cite{a} must be one of the values
  21408. encompassed by the interval. If @cite{b} is a vector, @cite{a} must be
  21409. equal to one of the elements of the vector. (If any vector elements are
  21410. intervals, @cite{a} must be in any of the intervals.) If @cite{b} is a
  21411. plain number, @cite{a} must be numerically equal to @cite{b}.
  21412. @xref{Set Operations}, for a group of commands that manipulate sets
  21413. of this sort.
  21414. @ignore
  21415. @starindex
  21416. @end ignore
  21417. @tindex typeof
  21418. The @samp{typeof(a)} function produces an integer or variable which
  21419. characterizes @cite{a}. If @cite{a} is a number, vector, or variable,
  21420. the result will be one of the following numbers:
  21421. @example
  21422. 1 Integer
  21423. 2 Fraction
  21424. 3 Floating-point number
  21425. 4 HMS form
  21426. 5 Rectangular complex number
  21427. 6 Polar complex number
  21428. 7 Error form
  21429. 8 Interval form
  21430. 9 Modulo form
  21431. 10 Date-only form
  21432. 11 Date/time form
  21433. 12 Infinity (inf, uinf, or nan)
  21434. 100 Variable
  21435. 101 Vector (but not a matrix)
  21436. 102 Matrix
  21437. @end example
  21438. Otherwise, @cite{a} is a formula, and the result is a variable which
  21439. represents the name of the top-level function call.
  21440. @ignore
  21441. @starindex
  21442. @end ignore
  21443. @tindex integer
  21444. @ignore
  21445. @starindex
  21446. @end ignore
  21447. @tindex real
  21448. @ignore
  21449. @starindex
  21450. @end ignore
  21451. @tindex constant
  21452. The @samp{integer(a)} function returns true if @cite{a} is an integer.
  21453. The @samp{real(a)} function
  21454. is true if @cite{a} is a real number, either integer, fraction, or
  21455. float. The @samp{constant(a)} function returns true if @cite{a} is
  21456. any of the objects for which @code{typeof} would produce an integer
  21457. code result except for variables, and provided that the components of
  21458. an object like a vector or error form are themselves constant.
  21459. Note that infinities do not satisfy any of these tests, nor do
  21460. special constants like @code{pi} and @code{e}.@refill
  21461. @xref{Declarations}, for a set of similar functions that recognize
  21462. formulas as well as actual numbers. For example, @samp{dint(floor(x))}
  21463. is true because @samp{floor(x)} is provably integer-valued, but
  21464. @samp{integer(floor(x))} does not because @samp{floor(x)} is not
  21465. literally an integer constant.
  21466. @ignore
  21467. @starindex
  21468. @end ignore
  21469. @tindex refers
  21470. The @samp{refers(a,b)} function is true if the variable (or sub-expression)
  21471. @cite{b} appears in @cite{a}, or false otherwise. Unlike the other
  21472. tests described here, this function returns a definite ``no'' answer
  21473. even if its arguments are still in symbolic form. The only case where
  21474. @code{refers} will be left unevaluated is if @cite{a} is a plain
  21475. variable (different from @cite{b}).
  21476. @ignore
  21477. @starindex
  21478. @end ignore
  21479. @tindex negative
  21480. The @samp{negative(a)} function returns true if @cite{a} ``looks'' negative,
  21481. because it is a negative number, because it is of the form @cite{-x},
  21482. or because it is a product or quotient with a term that looks negative.
  21483. This is most useful in rewrite rules. Beware that @samp{negative(a)}
  21484. evaluates to 1 or 0 for @emph{any} argument @cite{a}, so it can only
  21485. be stored in a formula if the default simplifications are turned off
  21486. first with @kbd{m O} (or if it appears in an unevaluated context such
  21487. as a rewrite rule condition).
  21488. @ignore
  21489. @starindex
  21490. @end ignore
  21491. @tindex variable
  21492. The @samp{variable(a)} function is true if @cite{a} is a variable,
  21493. or false if not. If @cite{a} is a function call, this test is left
  21494. in symbolic form. Built-in variables like @code{pi} and @code{inf}
  21495. are considered variables like any others by this test.
  21496. @ignore
  21497. @starindex
  21498. @end ignore
  21499. @tindex nonvar
  21500. The @samp{nonvar(a)} function is true if @cite{a} is a non-variable.
  21501. If its argument is a variable it is left unsimplified; it never
  21502. actually returns zero. However, since Calc's condition-testing
  21503. commands consider ``false'' anything not provably true, this is
  21504. often good enough.
  21505. @ignore
  21506. @starindex
  21507. @end ignore
  21508. @tindex lin
  21509. @ignore
  21510. @starindex
  21511. @end ignore
  21512. @tindex linnt
  21513. @ignore
  21514. @starindex
  21515. @end ignore
  21516. @tindex islin
  21517. @ignore
  21518. @starindex
  21519. @end ignore
  21520. @tindex islinnt
  21521. @cindex Linearity testing
  21522. The functions @code{lin}, @code{linnt}, @code{islin}, and @code{islinnt}
  21523. check if an expression is ``linear,'' i.e., can be written in the form
  21524. @cite{a + b x} for some constants @cite{a} and @cite{b}, and some
  21525. variable or subformula @cite{x}. The function @samp{islin(f,x)} checks
  21526. if formula @cite{f} is linear in @cite{x}, returning 1 if so. For
  21527. example, @samp{islin(x,x)}, @samp{islin(-x,x)}, @samp{islin(3,x)}, and
  21528. @samp{islin(x y / 3 - 2, x)} all return 1. The @samp{lin(f,x)} function
  21529. is similar, except that instead of returning 1 it returns the vector
  21530. @cite{[a, b, x]}. For the above examples, this vector would be
  21531. @cite{[0, 1, x]}, @cite{[0, -1, x]}, @cite{[3, 0, x]}, and
  21532. @cite{[-2, y/3, x]}, respectively. Both @code{lin} and @code{islin}
  21533. generally remain unevaluated for expressions which are not linear,
  21534. e.g., @samp{lin(2 x^2, x)} and @samp{lin(sin(x), x)}. The second
  21535. argument can also be a formula; @samp{islin(2 + 3 sin(x), sin(x))}
  21536. returns true.
  21537. The @code{linnt} and @code{islinnt} functions perform a similar check,
  21538. but require a ``non-trivial'' linear form, which means that the
  21539. @cite{b} coefficient must be non-zero. For example, @samp{lin(2,x)}
  21540. returns @cite{[2, 0, x]} and @samp{lin(y,x)} returns @cite{[y, 0, x]},
  21541. but @samp{linnt(2,x)} and @samp{linnt(y,x)} are left unevaluated
  21542. (in other words, these formulas are considered to be only ``trivially''
  21543. linear in @cite{x}).
  21544. All four linearity-testing functions allow you to omit the second
  21545. argument, in which case the input may be linear in any non-constant
  21546. formula. Here, the @cite{a=0}, @cite{b=1} case is also considered
  21547. trivial, and only constant values for @cite{a} and @cite{b} are
  21548. recognized. Thus, @samp{lin(2 x y)} returns @cite{[0, 2, x y]},
  21549. @samp{lin(2 - x y)} returns @cite{[2, -1, x y]}, and @samp{lin(x y)}
  21550. returns @cite{[0, 1, x y]}. The @code{linnt} function would allow the
  21551. first two cases but not the third. Also, neither @code{lin} nor
  21552. @code{linnt} accept plain constants as linear in the one-argument
  21553. case: @samp{islin(2,x)} is true, but @samp{islin(2)} is false.
  21554. @ignore
  21555. @starindex
  21556. @end ignore
  21557. @tindex istrue
  21558. The @samp{istrue(a)} function returns 1 if @cite{a} is a nonzero
  21559. number or provably nonzero formula, or 0 if @cite{a} is anything else.
  21560. Calls to @code{istrue} can only be manipulated if @kbd{m O} mode is
  21561. used to make sure they are not evaluated prematurely. (Note that
  21562. declarations are used when deciding whether a formula is true;
  21563. @code{istrue} returns 1 when @code{dnonzero} would return 1, and
  21564. it returns 0 when @code{dnonzero} would return 0 or leave itself
  21565. in symbolic form.)
  21566. @node Rewrite Rules, , Logical Operations, Algebra
  21567. @section Rewrite Rules
  21568. @noindent
  21569. @cindex Rewrite rules
  21570. @cindex Transformations
  21571. @cindex Pattern matching
  21572. @kindex a r
  21573. @pindex calc-rewrite
  21574. @tindex rewrite
  21575. The @kbd{a r} (@code{calc-rewrite}) [@code{rewrite}] command makes
  21576. substitutions in a formula according to a specified pattern or patterns
  21577. known as @dfn{rewrite rules}. Whereas @kbd{a b} (@code{calc-substitute})
  21578. matches literally, so that substituting @samp{sin(x)} with @samp{cos(x)}
  21579. matches only the @code{sin} function applied to the variable @code{x},
  21580. rewrite rules match general kinds of formulas; rewriting using the rule
  21581. @samp{sin(x) := cos(x)} matches @code{sin} of any argument and replaces
  21582. it with @code{cos} of that same argument. The only significance of the
  21583. name @code{x} is that the same name is used on both sides of the rule.
  21584. Rewrite rules rearrange formulas already in Calc's memory.
  21585. @xref{Syntax Tables}, to read about @dfn{syntax rules}, which are
  21586. similar to algebraic rewrite rules but operate when new algebraic
  21587. entries are being parsed, converting strings of characters into
  21588. Calc formulas.
  21589. @menu
  21590. * Entering Rewrite Rules::
  21591. * Basic Rewrite Rules::
  21592. * Conditional Rewrite Rules::
  21593. * Algebraic Properties of Rewrite Rules::
  21594. * Other Features of Rewrite Rules::
  21595. * Composing Patterns in Rewrite Rules::
  21596. * Nested Formulas with Rewrite Rules::
  21597. * Multi-Phase Rewrite Rules::
  21598. * Selections with Rewrite Rules::
  21599. * Matching Commands::
  21600. * Automatic Rewrites::
  21601. * Debugging Rewrites::
  21602. * Examples of Rewrite Rules::
  21603. @end menu
  21604. @node Entering Rewrite Rules, Basic Rewrite Rules, Rewrite Rules, Rewrite Rules
  21605. @subsection Entering Rewrite Rules
  21606. @noindent
  21607. Rewrite rules normally use the ``assignment'' operator
  21608. @samp{@var{old} := @var{new}}.
  21609. This operator is equivalent to the function call @samp{assign(old, new)}.
  21610. The @code{assign} function is undefined by itself in Calc, so an
  21611. assignment formula such as a rewrite rule will be left alone by ordinary
  21612. Calc commands. But certain commands, like the rewrite system, interpret
  21613. assignments in special ways.@refill
  21614. For example, the rule @samp{sin(x)^2 := 1-cos(x)^2} says to replace
  21615. every occurrence of the sine of something, squared, with one minus the
  21616. square of the cosine of that same thing. All by itself as a formula
  21617. on the stack it does nothing, but when given to the @kbd{a r} command
  21618. it turns that command into a sine-squared-to-cosine-squared converter.
  21619. To specify a set of rules to be applied all at once, make a vector of
  21620. rules.
  21621. When @kbd{a r} prompts you to enter the rewrite rules, you can answer
  21622. in several ways:
  21623. @enumerate
  21624. @item
  21625. With a rule: @kbd{f(x) := g(x) @key{RET}}.
  21626. @item
  21627. With a vector of rules: @kbd{[f1(x) := g1(x), f2(x) := g2(x)] @key{RET}}.
  21628. (You can omit the enclosing square brackets if you wish.)
  21629. @item
  21630. With the name of a variable that contains the rule or rules vector:
  21631. @kbd{myrules @key{RET}}.
  21632. @item
  21633. With any formula except a rule, a vector, or a variable name; this
  21634. will be interpreted as the @var{old} half of a rewrite rule,
  21635. and you will be prompted a second time for the @var{new} half:
  21636. @kbd{f(x) @key{RET} g(x) @key{RET}}.
  21637. @item
  21638. With a blank line, in which case the rule, rules vector, or variable
  21639. will be taken from the top of the stack (and the formula to be
  21640. rewritten will come from the second-to-top position).
  21641. @end enumerate
  21642. If you enter the rules directly (as opposed to using rules stored
  21643. in a variable), those rules will be put into the Trail so that you
  21644. can retrieve them later. @xref{Trail Commands}.
  21645. It is most convenient to store rules you use often in a variable and
  21646. invoke them by giving the variable name. The @kbd{s e}
  21647. (@code{calc-edit-variable}) command is an easy way to create or edit a
  21648. rule set stored in a variable. You may also wish to use @kbd{s p}
  21649. (@code{calc-permanent-variable}) to save your rules permanently;
  21650. @pxref{Operations on Variables}.@refill
  21651. Rewrite rules are compiled into a special internal form for faster
  21652. matching. If you enter a rule set directly it must be recompiled
  21653. every time. If you store the rules in a variable and refer to them
  21654. through that variable, they will be compiled once and saved away
  21655. along with the variable for later reference. This is another good
  21656. reason to store your rules in a variable.
  21657. Calc also accepts an obsolete notation for rules, as vectors
  21658. @samp{[@var{old}, @var{new}]}. But because it is easily confused with a
  21659. vector of two rules, the use of this notation is no longer recommended.
  21660. @node Basic Rewrite Rules, Conditional Rewrite Rules, Entering Rewrite Rules, Rewrite Rules
  21661. @subsection Basic Rewrite Rules
  21662. @noindent
  21663. To match a particular formula @cite{x} with a particular rewrite rule
  21664. @samp{@var{old} := @var{new}}, Calc compares the structure of @cite{x} with
  21665. the structure of @var{old}. Variables that appear in @var{old} are
  21666. treated as @dfn{meta-variables}; the corresponding positions in @cite{x}
  21667. may contain any sub-formulas. For example, the pattern @samp{f(x,y)}
  21668. would match the expression @samp{f(12, a+1)} with the meta-variable
  21669. @samp{x} corresponding to 12 and with @samp{y} corresponding to
  21670. @samp{a+1}. However, this pattern would not match @samp{f(12)} or
  21671. @samp{g(12, a+1)}, since there is no assignment of the meta-variables
  21672. that will make the pattern match these expressions. Notice that if
  21673. the pattern is a single meta-variable, it will match any expression.
  21674. If a given meta-variable appears more than once in @var{old}, the
  21675. corresponding sub-formulas of @cite{x} must be identical. Thus
  21676. the pattern @samp{f(x,x)} would match @samp{f(12, 12)} and
  21677. @samp{f(a+1, a+1)} but not @samp{f(12, a+1)} or @samp{f(a+b, b+a)}.
  21678. (@xref{Conditional Rewrite Rules}, for a way to match the latter.)
  21679. Things other than variables must match exactly between the pattern
  21680. and the target formula. To match a particular variable exactly, use
  21681. the pseudo-function @samp{quote(v)} in the pattern. For example, the
  21682. pattern @samp{x+quote(y)} matches @samp{x+y}, @samp{2+y}, or
  21683. @samp{sin(a)+y}.
  21684. The special variable names @samp{e}, @samp{pi}, @samp{i}, @samp{phi},
  21685. @samp{gamma}, @samp{inf}, @samp{uinf}, and @samp{nan} always match
  21686. literally. Thus the pattern @samp{sin(d + e + f)} acts exactly like
  21687. @samp{sin(d + quote(e) + f)}.
  21688. If the @var{old} pattern is found to match a given formula, that
  21689. formula is replaced by @var{new}, where any occurrences in @var{new}
  21690. of meta-variables from the pattern are replaced with the sub-formulas
  21691. that they matched. Thus, applying the rule @samp{f(x,y) := g(y+x,x)}
  21692. to @samp{f(12, a+1)} would produce @samp{g(a+13, 12)}.
  21693. The normal @kbd{a r} command applies rewrite rules over and over
  21694. throughout the target formula until no further changes are possible
  21695. (up to a limit of 100 times). Use @kbd{C-u 1 a r} to make only one
  21696. change at a time.
  21697. @node Conditional Rewrite Rules, Algebraic Properties of Rewrite Rules, Basic Rewrite Rules, Rewrite Rules
  21698. @subsection Conditional Rewrite Rules
  21699. @noindent
  21700. A rewrite rule can also be @dfn{conditional}, written in the form
  21701. @samp{@var{old} := @var{new} :: @var{cond}}. (There is also the obsolete
  21702. form @samp{[@var{old}, @var{new}, @var{cond}]}.) If a @var{cond} part
  21703. is present in the
  21704. rule, this is an additional condition that must be satisfied before
  21705. the rule is accepted. Once @var{old} has been successfully matched
  21706. to the target expression, @var{cond} is evaluated (with all the
  21707. meta-variables substituted for the values they matched) and simplified
  21708. with @kbd{a s} (@code{calc-simplify}). If the result is a nonzero
  21709. number or any other object known to be nonzero (@pxref{Declarations}),
  21710. the rule is accepted. If the result is zero or if it is a symbolic
  21711. formula that is not known to be nonzero, the rule is rejected.
  21712. @xref{Logical Operations}, for a number of functions that return
  21713. 1 or 0 according to the results of various tests.@refill
  21714. For example, the formula @samp{n > 0} simplifies to 1 or 0 if @cite{n}
  21715. is replaced by a positive or nonpositive number, respectively (or if
  21716. @cite{n} has been declared to be positive or nonpositive). Thus,
  21717. the rule @samp{f(x,y) := g(y+x,x) :: x+y > 0} would apply to
  21718. @samp{f(0, 4)} but not to @samp{f(-3, 2)} or @samp{f(12, a+1)}
  21719. (assuming no outstanding declarations for @cite{a}). In the case of
  21720. @samp{f(-3, 2)}, the condition can be shown not to be satisfied; in
  21721. the case of @samp{f(12, a+1)}, the condition merely cannot be shown
  21722. to be satisfied, but that is enough to reject the rule.
  21723. While Calc will use declarations to reason about variables in the
  21724. formula being rewritten, declarations do not apply to meta-variables.
  21725. For example, the rule @samp{f(a) := g(a+1)} will match for any values
  21726. of @samp{a}, such as complex numbers, vectors, or formulas, even if
  21727. @samp{a} has been declared to be real or scalar. If you want the
  21728. meta-variable @samp{a} to match only literal real numbers, use
  21729. @samp{f(a) := g(a+1) :: real(a)}. If you want @samp{a} to match only
  21730. reals and formulas which are provably real, use @samp{dreal(a)} as
  21731. the condition.
  21732. The @samp{::} operator is a shorthand for the @code{condition}
  21733. function; @samp{@var{old} := @var{new} :: @var{cond}} is equivalent to
  21734. the formula @samp{condition(assign(@var{old}, @var{new}), @var{cond})}.
  21735. If you have several conditions, you can use @samp{... :: c1 :: c2 :: c3}
  21736. or @samp{... :: c1 && c2 && c3}. The two are entirely equivalent.
  21737. It is also possible to embed conditions inside the pattern:
  21738. @samp{f(x :: x>0, y) := g(y+x, x)}. This is purely a notational
  21739. convenience, though; where a condition appears in a rule has no
  21740. effect on when it is tested. The rewrite-rule compiler automatically
  21741. decides when it is best to test each condition while a rule is being
  21742. matched.
  21743. Certain conditions are handled as special cases by the rewrite rule
  21744. system and are tested very efficiently: Where @cite{x} is any
  21745. meta-variable, these conditions are @samp{integer(x)}, @samp{real(x)},
  21746. @samp{constant(x)}, @samp{negative(x)}, @samp{x >= y} where @cite{y}
  21747. is either a constant or another meta-variable and @samp{>=} may be
  21748. replaced by any of the six relational operators, and @samp{x % a = b}
  21749. where @cite{a} and @cite{b} are constants. Other conditions, like
  21750. @samp{x >= y+1} or @samp{dreal(x)}, will be less efficient to check
  21751. since Calc must bring the whole evaluator and simplifier into play.
  21752. An interesting property of @samp{::} is that neither of its arguments
  21753. will be touched by Calc's default simplifications. This is important
  21754. because conditions often are expressions that cannot safely be
  21755. evaluated early. For example, the @code{typeof} function never
  21756. remains in symbolic form; entering @samp{typeof(a)} will put the
  21757. number 100 (the type code for variables like @samp{a}) on the stack.
  21758. But putting the condition @samp{... :: typeof(a) = 6} on the stack
  21759. is safe since @samp{::} prevents the @code{typeof} from being
  21760. evaluated until the condition is actually used by the rewrite system.
  21761. Since @samp{::} protects its lefthand side, too, you can use a dummy
  21762. condition to protect a rule that must itself not evaluate early.
  21763. For example, it's not safe to put @samp{a(f,x) := apply(f, [x])} on
  21764. the stack because it will immediately evaluate to @samp{a(f,x) := f(x)},
  21765. where the meta-variable-ness of @code{f} on the righthand side has been
  21766. lost. But @samp{a(f,x) := apply(f, [x]) :: 1} is safe, and of course
  21767. the condition @samp{1} is always true (nonzero) so it has no effect on
  21768. the functioning of the rule. (The rewrite compiler will ensure that
  21769. it doesn't even impact the speed of matching the rule.)
  21770. @node Algebraic Properties of Rewrite Rules, Other Features of Rewrite Rules, Conditional Rewrite Rules, Rewrite Rules
  21771. @subsection Algebraic Properties of Rewrite Rules
  21772. @noindent
  21773. The rewrite mechanism understands the algebraic properties of functions
  21774. like @samp{+} and @samp{*}. In particular, pattern matching takes
  21775. the associativity and commutativity of the following functions into
  21776. account:
  21777. @smallexample
  21778. + - * = != && || and or xor vint vunion vxor gcd lcm max min beta
  21779. @end smallexample
  21780. For example, the rewrite rule:
  21781. @example
  21782. a x + b x := (a + b) x
  21783. @end example
  21784. @noindent
  21785. will match formulas of the form,
  21786. @example
  21787. a x + b x, x a + x b, a x + x b, x a + b x
  21788. @end example
  21789. Rewrites also understand the relationship between the @samp{+} and @samp{-}
  21790. operators. The above rewrite rule will also match the formulas,
  21791. @example
  21792. a x - b x, x a - x b, a x - x b, x a - b x
  21793. @end example
  21794. @noindent
  21795. by matching @samp{b} in the pattern to @samp{-b} from the formula.
  21796. Applied to a sum of many terms like @samp{r + a x + s + b x + t}, this
  21797. pattern will check all pairs of terms for possible matches. The rewrite
  21798. will take whichever suitable pair it discovers first.
  21799. In general, a pattern using an associative operator like @samp{a + b}
  21800. will try @var{2 n} different ways to match a sum of @var{n} terms
  21801. like @samp{x + y + z - w}. First, @samp{a} is matched against each
  21802. of @samp{x}, @samp{y}, @samp{z}, and @samp{-w} in turn, with @samp{b}
  21803. being matched to the remainders @samp{y + z - w}, @samp{x + z - w}, etc.
  21804. If none of these succeed, then @samp{b} is matched against each of the
  21805. four terms with @samp{a} matching the remainder. Half-and-half matches,
  21806. like @samp{(x + y) + (z - w)}, are not tried.
  21807. Note that @samp{*} is not commutative when applied to matrices, but
  21808. rewrite rules pretend that it is. If you type @kbd{m v} to enable
  21809. matrix mode (@pxref{Matrix Mode}), rewrite rules will match @samp{*}
  21810. literally, ignoring its usual commutativity property. (In the
  21811. current implementation, the associativity also vanishes---it is as
  21812. if the pattern had been enclosed in a @code{plain} marker; see below.)
  21813. If you are applying rewrites to formulas with matrices, it's best to
  21814. enable matrix mode first to prevent algebraically incorrect rewrites
  21815. from occurring.
  21816. The pattern @samp{-x} will actually match any expression. For example,
  21817. the rule
  21818. @example
  21819. f(-x) := -f(x)
  21820. @end example
  21821. @noindent
  21822. will rewrite @samp{f(a)} to @samp{-f(-a)}. To avoid this, either use
  21823. a @code{plain} marker as described below, or add a @samp{negative(x)}
  21824. condition. The @code{negative} function is true if its argument
  21825. ``looks'' negative, for example, because it is a negative number or
  21826. because it is a formula like @samp{-x}. The new rule using this
  21827. condition is:
  21828. @example
  21829. f(x) := -f(-x) :: negative(x) @r{or, equivalently,}
  21830. f(-x) := -f(x) :: negative(-x)
  21831. @end example
  21832. In the same way, the pattern @samp{x - y} will match the sum @samp{a + b}
  21833. by matching @samp{y} to @samp{-b}.
  21834. The pattern @samp{a b} will also match the formula @samp{x/y} if
  21835. @samp{y} is a number. Thus the rule @samp{a x + @w{b x} := (a+b) x}
  21836. will also convert @samp{a x + x / 2} to @samp{(a + 0.5) x} (or
  21837. @samp{(a + 1:2) x}, depending on the current fraction mode).
  21838. Calc will @emph{not} take other liberties with @samp{*}, @samp{/}, and
  21839. @samp{^}. For example, the pattern @samp{f(a b)} will not match
  21840. @samp{f(x^2)}, and @samp{f(a + b)} will not match @samp{f(2 x)}, even
  21841. though conceivably these patterns could match with @samp{a = b = x}.
  21842. Nor will @samp{f(a b)} match @samp{f(x / y)} if @samp{y} is not a
  21843. constant, even though it could be considered to match with @samp{a = x}
  21844. and @samp{b = 1/y}. The reasons are partly for efficiency, and partly
  21845. because while few mathematical operations are substantively different
  21846. for addition and subtraction, often it is preferable to treat the cases
  21847. of multiplication, division, and integer powers separately.
  21848. Even more subtle is the rule set
  21849. @example
  21850. [ f(a) + f(b) := f(a + b), -f(a) := f(-a) ]
  21851. @end example
  21852. @noindent
  21853. attempting to match @samp{f(x) - f(y)}. You might think that Calc
  21854. will view this subtraction as @samp{f(x) + (-f(y))} and then apply
  21855. the above two rules in turn, but actually this will not work because
  21856. Calc only does this when considering rules for @samp{+} (like the
  21857. first rule in this set). So it will see first that @samp{f(x) + (-f(y))}
  21858. does not match @samp{f(a) + f(b)} for any assignments of the
  21859. meta-variables, and then it will see that @samp{f(x) - f(y)} does
  21860. not match @samp{-f(a)} for any assignment of @samp{a}. Because Calc
  21861. tries only one rule at a time, it will not be able to rewrite
  21862. @samp{f(x) - f(y)} with this rule set. An explicit @samp{f(a) - f(b)}
  21863. rule will have to be added.
  21864. Another thing patterns will @emph{not} do is break up complex numbers.
  21865. The pattern @samp{myconj(a + @w{b i)} := a - b i} will work for formulas
  21866. involving the special constant @samp{i} (such as @samp{3 - 4 i}), but
  21867. it will not match actual complex numbers like @samp{(3, -4)}. A version
  21868. of the above rule for complex numbers would be
  21869. @example
  21870. myconj(a) := re(a) - im(a) (0,1) :: im(a) != 0
  21871. @end example
  21872. @noindent
  21873. (Because the @code{re} and @code{im} functions understand the properties
  21874. of the special constant @samp{i}, this rule will also work for
  21875. @samp{3 - 4 i}. In fact, this particular rule would probably be better
  21876. without the @samp{im(a) != 0} condition, since if @samp{im(a) = 0} the
  21877. righthand side of the rule will still give the correct answer for the
  21878. conjugate of a real number.)
  21879. It is also possible to specify optional arguments in patterns. The rule
  21880. @example
  21881. opt(a) x + opt(b) (x^opt(c) + opt(d)) := f(a, b, c, d)
  21882. @end example
  21883. @noindent
  21884. will match the formula
  21885. @example
  21886. 5 (x^2 - 4) + 3 x
  21887. @end example
  21888. @noindent
  21889. in a fairly straightforward manner, but it will also match reduced
  21890. formulas like
  21891. @example
  21892. x + x^2, 2(x + 1) - x, x + x
  21893. @end example
  21894. @noindent
  21895. producing, respectively,
  21896. @example
  21897. f(1, 1, 2, 0), f(-1, 2, 1, 1), f(1, 1, 1, 0)
  21898. @end example
  21899. (The latter two formulas can be entered only if default simplifications
  21900. have been turned off with @kbd{m O}.)
  21901. The default value for a term of a sum is zero. The default value
  21902. for a part of a product, for a power, or for the denominator of a
  21903. quotient, is one. Also, @samp{-x} matches the pattern @samp{opt(a) b}
  21904. with @samp{a = -1}.
  21905. In particular, the distributive-law rule can be refined to
  21906. @example
  21907. opt(a) x + opt(b) x := (a + b) x
  21908. @end example
  21909. @noindent
  21910. so that it will convert, e.g., @samp{a x - x}, to @samp{(a - 1) x}.
  21911. The pattern @samp{opt(a) + opt(b) x} matches almost any formulas which
  21912. are linear in @samp{x}. You can also use the @code{lin} and @code{islin}
  21913. functions with rewrite conditions to test for this; @pxref{Logical
  21914. Operations}. These functions are not as convenient to use in rewrite
  21915. rules, but they recognize more kinds of formulas as linear:
  21916. @samp{x/z} is considered linear with @cite{b = 1/z} by @code{lin},
  21917. but it will not match the above pattern because that pattern calls
  21918. for a multiplication, not a division.
  21919. As another example, the obvious rule to replace @samp{sin(x)^2 + cos(x)^2}
  21920. by 1,
  21921. @example
  21922. sin(x)^2 + cos(x)^2 := 1
  21923. @end example
  21924. @noindent
  21925. misses many cases because the sine and cosine may both be multiplied by
  21926. an equal factor. Here's a more successful rule:
  21927. @example
  21928. opt(a) sin(x)^2 + opt(a) cos(x)^2 := a
  21929. @end example
  21930. Note that this rule will @emph{not} match @samp{sin(x)^2 + 6 cos(x)^2}
  21931. because one @cite{a} would have ``matched'' 1 while the other matched 6.
  21932. Calc automatically converts a rule like
  21933. @example
  21934. f(x-1, x) := g(x)
  21935. @end example
  21936. @noindent
  21937. into the form
  21938. @example
  21939. f(temp, x) := g(x) :: temp = x-1
  21940. @end example
  21941. @noindent
  21942. (where @code{temp} stands for a new, invented meta-variable that
  21943. doesn't actually have a name). This modified rule will successfully
  21944. match @samp{f(6, 7)}, binding @samp{temp} and @samp{x} to 6 and 7,
  21945. respectively, then verifying that they differ by one even though
  21946. @samp{6} does not superficially look like @samp{x-1}.
  21947. However, Calc does not solve equations to interpret a rule. The
  21948. following rule,
  21949. @example
  21950. f(x-1, x+1) := g(x)
  21951. @end example
  21952. @noindent
  21953. will not work. That is, it will match @samp{f(a - 1 + b, a + 1 + b)}
  21954. but not @samp{f(6, 8)}. Calc always interprets at least one occurrence
  21955. of a variable by literal matching. If the variable appears ``isolated''
  21956. then Calc is smart enough to use it for literal matching. But in this
  21957. last example, Calc is forced to rewrite the rule to @samp{f(x-1, temp)
  21958. := g(x) :: temp = x+1} where the @samp{x-1} term must correspond to an
  21959. actual ``something-minus-one'' in the target formula.
  21960. A successful way to write this would be @samp{f(x, x+2) := g(x+1)}.
  21961. You could make this resemble the original form more closely by using
  21962. @code{let} notation, which is described in the next section:
  21963. @example
  21964. f(xm1, x+1) := g(x) :: let(x := xm1+1)
  21965. @end example
  21966. Calc does this rewriting or ``conditionalizing'' for any sub-pattern
  21967. which involves only the functions in the following list, operating
  21968. only on constants and meta-variables which have already been matched
  21969. elsewhere in the pattern. When matching a function call, Calc is
  21970. careful to match arguments which are plain variables before arguments
  21971. which are calls to any of the functions below, so that a pattern like
  21972. @samp{f(x-1, x)} can be conditionalized even though the isolated
  21973. @samp{x} comes after the @samp{x-1}.
  21974. @smallexample
  21975. + - * / \ % ^ abs sign round rounde roundu trunc floor ceil
  21976. max min re im conj arg
  21977. @end smallexample
  21978. You can suppress all of the special treatments described in this
  21979. section by surrounding a function call with a @code{plain} marker.
  21980. This marker causes the function call which is its argument to be
  21981. matched literally, without regard to commutativity, associativity,
  21982. negation, or conditionalization. When you use @code{plain}, the
  21983. ``deep structure'' of the formula being matched can show through.
  21984. For example,
  21985. @example
  21986. plain(a - a b) := f(a, b)
  21987. @end example
  21988. @noindent
  21989. will match only literal subtractions. However, the @code{plain}
  21990. marker does not affect its arguments' arguments. In this case,
  21991. commutativity and associativity is still considered while matching
  21992. the @w{@samp{a b}} sub-pattern, so the whole pattern will match
  21993. @samp{x - y x} as well as @samp{x - x y}. We could go still
  21994. further and use
  21995. @example
  21996. plain(a - plain(a b)) := f(a, b)
  21997. @end example
  21998. @noindent
  21999. which would do a completely strict match for the pattern.
  22000. By contrast, the @code{quote} marker means that not only the
  22001. function name but also the arguments must be literally the same.
  22002. The above pattern will match @samp{x - x y} but
  22003. @example
  22004. quote(a - a b) := f(a, b)
  22005. @end example
  22006. @noindent
  22007. will match only the single formula @samp{a - a b}. Also,
  22008. @example
  22009. quote(a - quote(a b)) := f(a, b)
  22010. @end example
  22011. @noindent
  22012. will match only @samp{a - quote(a b)}---probably not the desired
  22013. effect!
  22014. A certain amount of algebra is also done when substituting the
  22015. meta-variables on the righthand side of a rule. For example,
  22016. in the rule
  22017. @example
  22018. a + f(b) := f(a + b)
  22019. @end example
  22020. @noindent
  22021. matching @samp{f(x) - y} would produce @samp{f((-y) + x)} if
  22022. taken literally, but the rewrite mechanism will simplify the
  22023. righthand side to @samp{f(x - y)} automatically. (Of course,
  22024. the default simplifications would do this anyway, so this
  22025. special simplification is only noticeable if you have turned the
  22026. default simplifications off.) This rewriting is done only when
  22027. a meta-variable expands to a ``negative-looking'' expression.
  22028. If this simplification is not desirable, you can use a @code{plain}
  22029. marker on the righthand side:
  22030. @example
  22031. a + f(b) := f(plain(a + b))
  22032. @end example
  22033. @noindent
  22034. In this example, we are still allowing the pattern-matcher to
  22035. use all the algebra it can muster, but the righthand side will
  22036. always simplify to a literal addition like @samp{f((-y) + x)}.
  22037. @node Other Features of Rewrite Rules, Composing Patterns in Rewrite Rules, Algebraic Properties of Rewrite Rules, Rewrite Rules
  22038. @subsection Other Features of Rewrite Rules
  22039. @noindent
  22040. Certain ``function names'' serve as markers in rewrite rules.
  22041. Here is a complete list of these markers. First are listed the
  22042. markers that work inside a pattern; then come the markers that
  22043. work in the righthand side of a rule.
  22044. @ignore
  22045. @starindex
  22046. @end ignore
  22047. @tindex import
  22048. One kind of marker, @samp{import(x)}, takes the place of a whole
  22049. rule. Here @cite{x} is the name of a variable containing another
  22050. rule set; those rules are ``spliced into'' the rule set that
  22051. imports them. For example, if @samp{[f(a+b) := f(a) + f(b),
  22052. f(a b) := a f(b) :: real(a)]} is stored in variable @samp{linearF},
  22053. then the rule set @samp{[f(0) := 0, import(linearF)]} will apply
  22054. all three rules. It is possible to modify the imported rules
  22055. slightly: @samp{import(x, v1, x1, v2, x2, @dots{})} imports
  22056. the rule set @cite{x} with all occurrences of @c{$v_1$}
  22057. @cite{v1}, as either
  22058. a variable name or a function name, replaced with @c{$x_1$}
  22059. @cite{x1} and
  22060. so on. (If @c{$v_1$}
  22061. @cite{v1} is used as a function name, then @c{$x_1$}
  22062. @cite{x1}
  22063. must be either a function name itself or a @w{@samp{< >}} nameless
  22064. function; @pxref{Specifying Operators}.) For example, @samp{[g(0) := 0,
  22065. import(linearF, f, g)]} applies the linearity rules to the function
  22066. @samp{g} instead of @samp{f}. Imports can be nested, but the
  22067. import-with-renaming feature may fail to rename sub-imports properly.
  22068. The special functions allowed in patterns are:
  22069. @table @samp
  22070. @item quote(x)
  22071. @ignore
  22072. @starindex
  22073. @end ignore
  22074. @tindex quote
  22075. This pattern matches exactly @cite{x}; variable names in @cite{x} are
  22076. not interpreted as meta-variables. The only flexibility is that
  22077. numbers are compared for numeric equality, so that the pattern
  22078. @samp{f(quote(12))} will match both @samp{f(12)} and @samp{f(12.0)}.
  22079. (Numbers are always treated this way by the rewrite mechanism:
  22080. The rule @samp{f(x,x) := g(x)} will match @samp{f(12, 12.0)}.
  22081. The rewrite may produce either @samp{g(12)} or @samp{g(12.0)}
  22082. as a result in this case.)
  22083. @item plain(x)
  22084. @ignore
  22085. @starindex
  22086. @end ignore
  22087. @tindex plain
  22088. Here @cite{x} must be a function call @samp{f(x1,x2,@dots{})}. This
  22089. pattern matches a call to function @cite{f} with the specified
  22090. argument patterns. No special knowledge of the properties of the
  22091. function @cite{f} is used in this case; @samp{+} is not commutative or
  22092. associative. Unlike @code{quote}, the arguments @samp{x1,x2,@dots{}}
  22093. are treated as patterns. If you wish them to be treated ``plainly''
  22094. as well, you must enclose them with more @code{plain} markers:
  22095. @samp{plain(plain(@w{-a}) + plain(b c))}.
  22096. @item opt(x,def)
  22097. @ignore
  22098. @starindex
  22099. @end ignore
  22100. @tindex opt
  22101. Here @cite{x} must be a variable name. This must appear as an
  22102. argument to a function or an element of a vector; it specifies that
  22103. the argument or element is optional.
  22104. As an argument to @samp{+}, @samp{-}, @samp{*}, @samp{&&}, or @samp{||},
  22105. or as the second argument to @samp{/} or @samp{^}, the value @var{def}
  22106. may be omitted. The pattern @samp{x + opt(y)} matches a sum by
  22107. binding one summand to @cite{x} and the other to @cite{y}, and it
  22108. matches anything else by binding the whole expression to @cite{x} and
  22109. zero to @cite{y}. The other operators above work similarly.@refill
  22110. For general miscellanous functions, the default value @code{def}
  22111. must be specified. Optional arguments are dropped starting with
  22112. the rightmost one during matching. For example, the pattern
  22113. @samp{f(opt(a,0), b, opt(c,b))} will match @samp{f(b)}, @samp{f(a,b)},
  22114. or @samp{f(a,b,c)}. Default values of zero and @cite{b} are
  22115. supplied in this example for the omitted arguments. Note that
  22116. the literal variable @cite{b} will be the default in the latter
  22117. case, @emph{not} the value that matched the meta-variable @cite{b}.
  22118. In other words, the default @var{def} is effectively quoted.
  22119. @item condition(x,c)
  22120. @ignore
  22121. @starindex
  22122. @end ignore
  22123. @tindex condition
  22124. @tindex ::
  22125. This matches the pattern @cite{x}, with the attached condition
  22126. @cite{c}. It is the same as @samp{x :: c}.
  22127. @item pand(x,y)
  22128. @ignore
  22129. @starindex
  22130. @end ignore
  22131. @tindex pand
  22132. @tindex &&&
  22133. This matches anything that matches both pattern @cite{x} and
  22134. pattern @cite{y}. It is the same as @samp{x &&& y}.
  22135. @pxref{Composing Patterns in Rewrite Rules}.
  22136. @item por(x,y)
  22137. @ignore
  22138. @starindex
  22139. @end ignore
  22140. @tindex por
  22141. @tindex |||
  22142. This matches anything that matches either pattern @cite{x} or
  22143. pattern @cite{y}. It is the same as @w{@samp{x ||| y}}.
  22144. @item pnot(x)
  22145. @ignore
  22146. @starindex
  22147. @end ignore
  22148. @tindex pnot
  22149. @tindex !!!
  22150. This matches anything that does not match pattern @cite{x}.
  22151. It is the same as @samp{!!! x}.
  22152. @item cons(h,t)
  22153. @ignore
  22154. @mindex cons
  22155. @end ignore
  22156. @tindex cons (rewrites)
  22157. This matches any vector of one or more elements. The first
  22158. element is matched to @cite{h}; a vector of the remaining
  22159. elements is matched to @cite{t}. Note that vectors of fixed
  22160. length can also be matched as actual vectors: The rule
  22161. @samp{cons(a,cons(b,[])) := cons(a+b,[])} is equivalent
  22162. to the rule @samp{[a,b] := [a+b]}.
  22163. @item rcons(t,h)
  22164. @ignore
  22165. @mindex rcons
  22166. @end ignore
  22167. @tindex rcons (rewrites)
  22168. This is like @code{cons}, except that the @emph{last} element
  22169. is matched to @cite{h}, with the remaining elements matched
  22170. to @cite{t}.
  22171. @item apply(f,args)
  22172. @ignore
  22173. @mindex apply
  22174. @end ignore
  22175. @tindex apply (rewrites)
  22176. This matches any function call. The name of the function, in
  22177. the form of a variable, is matched to @cite{f}. The arguments
  22178. of the function, as a vector of zero or more objects, are
  22179. matched to @samp{args}. Constants, variables, and vectors
  22180. do @emph{not} match an @code{apply} pattern. For example,
  22181. @samp{apply(f,x)} matches any function call, @samp{apply(quote(f),x)}
  22182. matches any call to the function @samp{f}, @samp{apply(f,[a,b])}
  22183. matches any function call with exactly two arguments, and
  22184. @samp{apply(quote(f), cons(a,cons(b,x)))} matches any call
  22185. to the function @samp{f} with two or more arguments. Another
  22186. way to implement the latter, if the rest of the rule does not
  22187. need to refer to the first two arguments of @samp{f} by name,
  22188. would be @samp{apply(quote(f), x :: vlen(x) >= 2)}.
  22189. Here's a more interesting sample use of @code{apply}:
  22190. @example
  22191. apply(f,[x+n]) := n + apply(f,[x])
  22192. :: in(f, [floor,ceil,round,trunc]) :: integer(n)
  22193. @end example
  22194. Note, however, that this will be slower to match than a rule
  22195. set with four separate rules. The reason is that Calc sorts
  22196. the rules of a rule set according to top-level function name;
  22197. if the top-level function is @code{apply}, Calc must try the
  22198. rule for every single formula and sub-formula. If the top-level
  22199. function in the pattern is, say, @code{floor}, then Calc invokes
  22200. the rule only for sub-formulas which are calls to @code{floor}.
  22201. Formulas normally written with operators like @code{+} are still
  22202. considered function calls: @code{apply(f,x)} matches @samp{a+b}
  22203. with @samp{f = add}, @samp{x = [a,b]}.
  22204. You must use @code{apply} for meta-variables with function names
  22205. on both sides of a rewrite rule: @samp{apply(f, [x]) := f(x+1)}
  22206. is @emph{not} correct, because it rewrites @samp{spam(6)} into
  22207. @samp{f(7)}. The righthand side should be @samp{apply(f, [x+1])}.
  22208. Also note that you will have to use no-simplify (@kbd{m O})
  22209. mode when entering this rule so that the @code{apply} isn't
  22210. evaluated immediately to get the new rule @samp{f(x) := f(x+1)}.
  22211. Or, use @kbd{s e} to enter the rule without going through the stack,
  22212. or enter the rule as @samp{apply(f, [x]) := apply(f, [x+1]) @w{:: 1}}.
  22213. @xref{Conditional Rewrite Rules}.
  22214. @item select(x)
  22215. @ignore
  22216. @starindex
  22217. @end ignore
  22218. @tindex select
  22219. This is used for applying rules to formulas with selections;
  22220. @pxref{Selections with Rewrite Rules}.
  22221. @end table
  22222. Special functions for the righthand sides of rules are:
  22223. @table @samp
  22224. @item quote(x)
  22225. The notation @samp{quote(x)} is changed to @samp{x} when the
  22226. righthand side is used. As far as the rewrite rule is concerned,
  22227. @code{quote} is invisible. However, @code{quote} has the special
  22228. property in Calc that its argument is not evaluated. Thus,
  22229. while it will not work to put the rule @samp{t(a) := typeof(a)}
  22230. on the stack because @samp{typeof(a)} is evaluated immediately
  22231. to produce @samp{t(a) := 100}, you can use @code{quote} to
  22232. protect the righthand side: @samp{t(a) := quote(typeof(a))}.
  22233. (@xref{Conditional Rewrite Rules}, for another trick for
  22234. protecting rules from evaluation.)
  22235. @item plain(x)
  22236. Special properties of and simplifications for the function call
  22237. @cite{x} are not used. One interesting case where @code{plain}
  22238. is useful is the rule, @samp{q(x) := quote(x)}, trying to expand a
  22239. shorthand notation for the @code{quote} function. This rule will
  22240. not work as shown; instead of replacing @samp{q(foo)} with
  22241. @samp{quote(foo)}, it will replace it with @samp{foo}! The correct
  22242. rule would be @samp{q(x) := plain(quote(x))}.
  22243. @item cons(h,t)
  22244. Where @cite{t} is a vector, this is converted into an expanded
  22245. vector during rewrite processing. Note that @code{cons} is a regular
  22246. Calc function which normally does this anyway; the only way @code{cons}
  22247. is treated specially by rewrites is that @code{cons} on the righthand
  22248. side of a rule will be evaluated even if default simplifications
  22249. have been turned off.
  22250. @item rcons(t,h)
  22251. Analogous to @code{cons} except putting @cite{h} at the @emph{end} of
  22252. the vector @cite{t}.
  22253. @item apply(f,args)
  22254. Where @cite{f} is a variable and @var{args} is a vector, this
  22255. is converted to a function call. Once again, note that @code{apply}
  22256. is also a regular Calc function.
  22257. @item eval(x)
  22258. @ignore
  22259. @starindex
  22260. @end ignore
  22261. @tindex eval
  22262. The formula @cite{x} is handled in the usual way, then the
  22263. default simplifications are applied to it even if they have
  22264. been turned off normally. This allows you to treat any function
  22265. similarly to the way @code{cons} and @code{apply} are always
  22266. treated. However, there is a slight difference: @samp{cons(2+3, [])}
  22267. with default simplifications off will be converted to @samp{[2+3]},
  22268. whereas @samp{eval(cons(2+3, []))} will be converted to @samp{[5]}.
  22269. @item evalsimp(x)
  22270. @ignore
  22271. @starindex
  22272. @end ignore
  22273. @tindex evalsimp
  22274. The formula @cite{x} has meta-variables substituted in the usual
  22275. way, then algebraically simplified as if by the @kbd{a s} command.
  22276. @item evalextsimp(x)
  22277. @ignore
  22278. @starindex
  22279. @end ignore
  22280. @tindex evalextsimp
  22281. The formula @cite{x} has meta-variables substituted in the normal
  22282. way, then ``extendedly'' simplified as if by the @kbd{a e} command.
  22283. @item select(x)
  22284. @xref{Selections with Rewrite Rules}.
  22285. @end table
  22286. There are also some special functions you can use in conditions.
  22287. @table @samp
  22288. @item let(v := x)
  22289. @ignore
  22290. @starindex
  22291. @end ignore
  22292. @tindex let
  22293. The expression @cite{x} is evaluated with meta-variables substituted.
  22294. The @kbd{a s} command's simplifications are @emph{not} applied by
  22295. default, but @cite{x} can include calls to @code{evalsimp} or
  22296. @code{evalextsimp} as described above to invoke higher levels
  22297. of simplification. The
  22298. result of @cite{x} is then bound to the meta-variable @cite{v}. As
  22299. usual, if this meta-variable has already been matched to something
  22300. else the two values must be equal; if the meta-variable is new then
  22301. it is bound to the result of the expression. This variable can then
  22302. appear in later conditions, and on the righthand side of the rule.
  22303. In fact, @cite{v} may be any pattern in which case the result of
  22304. evaluating @cite{x} is matched to that pattern, binding any
  22305. meta-variables that appear in that pattern. Note that @code{let}
  22306. can only appear by itself as a condition, or as one term of an
  22307. @samp{&&} which is a whole condition: It cannot be inside
  22308. an @samp{||} term or otherwise buried.@refill
  22309. The alternate, equivalent form @samp{let(v, x)} is also recognized.
  22310. Note that the use of @samp{:=} by @code{let}, while still being
  22311. assignment-like in character, is unrelated to the use of @samp{:=}
  22312. in the main part of a rewrite rule.
  22313. As an example, @samp{f(a) := g(ia) :: let(ia := 1/a) :: constant(ia)}
  22314. replaces @samp{f(a)} with @samp{g} of the inverse of @samp{a}, if
  22315. that inverse exists and is constant. For example, if @samp{a} is a
  22316. singular matrix the operation @samp{1/a} is left unsimplified and
  22317. @samp{constant(ia)} fails, but if @samp{a} is an invertible matrix
  22318. then the rule succeeds. Without @code{let} there would be no way
  22319. to express this rule that didn't have to invert the matrix twice.
  22320. Note that, because the meta-variable @samp{ia} is otherwise unbound
  22321. in this rule, the @code{let} condition itself always ``succeeds''
  22322. because no matter what @samp{1/a} evaluates to, it can successfully
  22323. be bound to @code{ia}.@refill
  22324. Here's another example, for integrating cosines of linear
  22325. terms: @samp{myint(cos(y),x) := sin(y)/b :: let([a,b,x] := lin(y,x))}.
  22326. The @code{lin} function returns a 3-vector if its argument is linear,
  22327. or leaves itself unevaluated if not. But an unevaluated @code{lin}
  22328. call will not match the 3-vector on the lefthand side of the @code{let},
  22329. so this @code{let} both verifies that @code{y} is linear, and binds
  22330. the coefficients @code{a} and @code{b} for use elsewhere in the rule.
  22331. (It would have been possible to use @samp{sin(a x + b)/b} for the
  22332. righthand side instead, but using @samp{sin(y)/b} avoids gratuitous
  22333. rearrangement of the argument of the sine.)@refill
  22334. @ignore
  22335. @starindex
  22336. @end ignore
  22337. @tindex ierf
  22338. Similarly, here is a rule that implements an inverse-@code{erf}
  22339. function. It uses @code{root} to search for a solution. If
  22340. @code{root} succeeds, it will return a vector of two numbers
  22341. where the first number is the desired solution. If no solution
  22342. is found, @code{root} remains in symbolic form. So we use
  22343. @code{let} to check that the result was indeed a vector.
  22344. @example
  22345. ierf(x) := y :: let([y,z] := root(erf(a) = x, a, .5))
  22346. @end example
  22347. @item matches(v,p)
  22348. The meta-variable @var{v}, which must already have been matched
  22349. to something elsewhere in the rule, is compared against pattern
  22350. @var{p}. Since @code{matches} is a standard Calc function, it
  22351. can appear anywhere in a condition. But if it appears alone or
  22352. as a term of a top-level @samp{&&}, then you get the special
  22353. extra feature that meta-variables which are bound to things
  22354. inside @var{p} can be used elsewhere in the surrounding rewrite
  22355. rule.
  22356. The only real difference between @samp{let(p := v)} and
  22357. @samp{matches(v, p)} is that the former evaluates @samp{v} using
  22358. the default simplifications, while the latter does not.
  22359. @item remember
  22360. @vindex remember
  22361. This is actually a variable, not a function. If @code{remember}
  22362. appears as a condition in a rule, then when that rule succeeds
  22363. the original expression and rewritten expression are added to the
  22364. front of the rule set that contained the rule. If the rule set
  22365. was not stored in a variable, @code{remember} is ignored. The
  22366. lefthand side is enclosed in @code{quote} in the added rule if it
  22367. contains any variables.
  22368. For example, the rule @samp{f(n) := n f(n-1) :: remember} applied
  22369. to @samp{f(7)} will add the rule @samp{f(7) := 7 f(6)} to the front
  22370. of the rule set. The rule set @code{EvalRules} works slightly
  22371. differently: There, the evaluation of @samp{f(6)} will complete before
  22372. the result is added to the rule set, in this case as @samp{f(7) := 5040}.
  22373. Thus @code{remember} is most useful inside @code{EvalRules}.
  22374. It is up to you to ensure that the optimization performed by
  22375. @code{remember} is safe. For example, the rule @samp{foo(n) := n
  22376. :: evalv(eatfoo) > 0 :: remember} is a bad idea (@code{evalv} is
  22377. the function equivalent of the @kbd{=} command); if the variable
  22378. @code{eatfoo} ever contains 1, rules like @samp{foo(7) := 7} will
  22379. be added to the rule set and will continue to operate even if
  22380. @code{eatfoo} is later changed to 0.
  22381. @item remember(c)
  22382. @ignore
  22383. @starindex
  22384. @end ignore
  22385. @tindex remember
  22386. Remember the match as described above, but only if condition @cite{c}
  22387. is true. For example, @samp{remember(n % 4 = 0)} in the above factorial
  22388. rule remembers only every fourth result. Note that @samp{remember(1)}
  22389. is equivalent to @samp{remember}, and @samp{remember(0)} has no effect.
  22390. @end table
  22391. @node Composing Patterns in Rewrite Rules, Nested Formulas with Rewrite Rules, Other Features of Rewrite Rules, Rewrite Rules
  22392. @subsection Composing Patterns in Rewrite Rules
  22393. @noindent
  22394. There are three operators, @samp{&&&}, @samp{|||}, and @samp{!!!},
  22395. that combine rewrite patterns to make larger patterns. The
  22396. combinations are ``and,'' ``or,'' and ``not,'' respectively, and
  22397. these operators are the pattern equivalents of @samp{&&}, @samp{||}
  22398. and @samp{!} (which operate on zero-or-nonzero logical values).
  22399. Note that @samp{&&&}, @samp{|||}, and @samp{!!!} are left in symbolic
  22400. form by all regular Calc features; they have special meaning only in
  22401. the context of rewrite rule patterns.
  22402. The pattern @samp{@var{p1} &&& @var{p2}} matches anything that
  22403. matches both @var{p1} and @var{p2}. One especially useful case is
  22404. when one of @var{p1} or @var{p2} is a meta-variable. For example,
  22405. here is a rule that operates on error forms:
  22406. @example
  22407. f(x &&& a +/- b, x) := g(x)
  22408. @end example
  22409. This does the same thing, but is arguably simpler than, the rule
  22410. @example
  22411. f(a +/- b, a +/- b) := g(a +/- b)
  22412. @end example
  22413. @ignore
  22414. @starindex
  22415. @end ignore
  22416. @tindex ends
  22417. Here's another interesting example:
  22418. @example
  22419. ends(cons(a, x) &&& rcons(y, b)) := [a, b]
  22420. @end example
  22421. @noindent
  22422. which effectively clips out the middle of a vector leaving just
  22423. the first and last elements. This rule will change a one-element
  22424. vector @samp{[a]} to @samp{[a, a]}. The similar rule
  22425. @example
  22426. ends(cons(a, rcons(y, b))) := [a, b]
  22427. @end example
  22428. @noindent
  22429. would do the same thing except that it would fail to match a
  22430. one-element vector.
  22431. @tex
  22432. \bigskip
  22433. @end tex
  22434. The pattern @samp{@var{p1} ||| @var{p2}} matches anything that
  22435. matches either @var{p1} or @var{p2}. Calc first tries matching
  22436. against @var{p1}; if that fails, it goes on to try @var{p2}.
  22437. @ignore
  22438. @starindex
  22439. @end ignore
  22440. @tindex curve
  22441. A simple example of @samp{|||} is
  22442. @example
  22443. curve(inf ||| -inf) := 0
  22444. @end example
  22445. @noindent
  22446. which converts both @samp{curve(inf)} and @samp{curve(-inf)} to zero.
  22447. Here is a larger example:
  22448. @example
  22449. log(a, b) ||| (ln(a) :: let(b := e)) := mylog(a, b)
  22450. @end example
  22451. This matches both generalized and natural logarithms in a single rule.
  22452. Note that the @samp{::} term must be enclosed in parentheses because
  22453. that operator has lower precedence than @samp{|||} or @samp{:=}.
  22454. (In practice this rule would probably include a third alternative,
  22455. omitted here for brevity, to take care of @code{log10}.)
  22456. While Calc generally treats interior conditions exactly the same as
  22457. conditions on the outside of a rule, it does guarantee that if all the
  22458. variables in the condition are special names like @code{e}, or already
  22459. bound in the pattern to which the condition is attached (say, if
  22460. @samp{a} had appeared in this condition), then Calc will process this
  22461. condition right after matching the pattern to the left of the @samp{::}.
  22462. Thus, we know that @samp{b} will be bound to @samp{e} only if the
  22463. @code{ln} branch of the @samp{|||} was taken.
  22464. Note that this rule was careful to bind the same set of meta-variables
  22465. on both sides of the @samp{|||}. Calc does not check this, but if
  22466. you bind a certain meta-variable only in one branch and then use that
  22467. meta-variable elsewhere in the rule, results are unpredictable:
  22468. @example
  22469. f(a,b) ||| g(b) := h(a,b)
  22470. @end example
  22471. Here if the pattern matches @samp{g(17)}, Calc makes no promises about
  22472. the value that will be substituted for @samp{a} on the righthand side.
  22473. @tex
  22474. \bigskip
  22475. @end tex
  22476. The pattern @samp{!!! @var{pat}} matches anything that does not
  22477. match @var{pat}. Any meta-variables that are bound while matching
  22478. @var{pat} remain unbound outside of @var{pat}.
  22479. For example,
  22480. @example
  22481. f(x &&& !!! a +/- b, !!![]) := g(x)
  22482. @end example
  22483. @noindent
  22484. converts @code{f} whose first argument is anything @emph{except} an
  22485. error form, and whose second argument is not the empty vector, into
  22486. a similar call to @code{g} (but without the second argument).
  22487. If we know that the second argument will be a vector (empty or not),
  22488. then an equivalent rule would be:
  22489. @example
  22490. f(x, y) := g(x) :: typeof(x) != 7 :: vlen(y) > 0
  22491. @end example
  22492. @noindent
  22493. where of course 7 is the @code{typeof} code for error forms.
  22494. Another final condition, that works for any kind of @samp{y},
  22495. would be @samp{!istrue(y == [])}. (The @code{istrue} function
  22496. returns an explicit 0 if its argument was left in symbolic form;
  22497. plain @samp{!(y == [])} or @samp{y != []} would not work to replace
  22498. @samp{!!![]} since these would be left unsimplified, and thus cause
  22499. the rule to fail, if @samp{y} was something like a variable name.)
  22500. It is possible for a @samp{!!!} to refer to meta-variables bound
  22501. elsewhere in the pattern. For example,
  22502. @example
  22503. f(a, !!!a) := g(a)
  22504. @end example
  22505. @noindent
  22506. matches any call to @code{f} with different arguments, changing
  22507. this to @code{g} with only the first argument.
  22508. If a function call is to be matched and one of the argument patterns
  22509. contains a @samp{!!!} somewhere inside it, that argument will be
  22510. matched last. Thus
  22511. @example
  22512. f(!!!a, a) := g(a)
  22513. @end example
  22514. @noindent
  22515. will be careful to bind @samp{a} to the second argument of @code{f}
  22516. before testing the first argument. If Calc had tried to match the
  22517. first argument of @code{f} first, the results would have been
  22518. disasterous: Since @code{a} was unbound so far, the pattern @samp{a}
  22519. would have matched anything at all, and the pattern @samp{!!!a}
  22520. therefore would @emph{not} have matched anything at all!
  22521. @node Nested Formulas with Rewrite Rules, Multi-Phase Rewrite Rules, Composing Patterns in Rewrite Rules, Rewrite Rules
  22522. @subsection Nested Formulas with Rewrite Rules
  22523. @noindent
  22524. When @kbd{a r} (@code{calc-rewrite}) is used, it takes an expression from
  22525. the top of the stack and attempts to match any of the specified rules
  22526. to any part of the expression, starting with the whole expression
  22527. and then, if that fails, trying deeper and deeper sub-expressions.
  22528. For each part of the expression, the rules are tried in the order
  22529. they appear in the rules vector. The first rule to match the first
  22530. sub-expression wins; it replaces the matched sub-expression according
  22531. to the @var{new} part of the rule.
  22532. Often, the rule set will match and change the formula several times.
  22533. The top-level formula is first matched and substituted repeatedly until
  22534. it no longer matches the pattern; then, sub-formulas are tried, and
  22535. so on. Once every part of the formula has gotten its chance, the
  22536. rewrite mechanism starts over again with the top-level formula
  22537. (in case a substitution of one of its arguments has caused it again
  22538. to match). This continues until no further matches can be made
  22539. anywhere in the formula.
  22540. It is possible for a rule set to get into an infinite loop. The
  22541. most obvious case, replacing a formula with itself, is not a problem
  22542. because a rule is not considered to ``succeed'' unless the righthand
  22543. side actually comes out to something different than the original
  22544. formula or sub-formula that was matched. But if you accidentally
  22545. had both @samp{ln(a b) := ln(a) + ln(b)} and the reverse
  22546. @samp{ln(a) + ln(b) := ln(a b)} in your rule set, Calc would
  22547. run forever switching a formula back and forth between the two
  22548. forms.
  22549. To avoid disaster, Calc normally stops after 100 changes have been
  22550. made to the formula. This will be enough for most multiple rewrites,
  22551. but it will keep an endless loop of rewrites from locking up the
  22552. computer forever. (On most systems, you can also type @kbd{C-g} to
  22553. halt any Emacs command prematurely.)
  22554. To change this limit, give a positive numeric prefix argument.
  22555. In particular, @kbd{M-1 a r} applies only one rewrite at a time,
  22556. useful when you are first testing your rule (or just if repeated
  22557. rewriting is not what is called for by your application).
  22558. @ignore
  22559. @starindex
  22560. @end ignore
  22561. @ignore
  22562. @mindex iter@idots
  22563. @end ignore
  22564. @tindex iterations
  22565. You can also put a ``function call'' @samp{iterations(@var{n})}
  22566. in place of a rule anywhere in your rules vector (but usually at
  22567. the top). Then, @var{n} will be used instead of 100 as the default
  22568. number of iterations for this rule set. You can use
  22569. @samp{iterations(inf)} if you want no iteration limit by default.
  22570. A prefix argument will override the @code{iterations} limit in the
  22571. rule set.
  22572. @example
  22573. [ iterations(1),
  22574. f(x) := f(x+1) ]
  22575. @end example
  22576. More precisely, the limit controls the number of ``iterations,''
  22577. where each iteration is a successful matching of a rule pattern whose
  22578. righthand side, after substituting meta-variables and applying the
  22579. default simplifications, is different from the original sub-formula
  22580. that was matched.
  22581. A prefix argument of zero sets the limit to infinity. Use with caution!
  22582. Given a negative numeric prefix argument, @kbd{a r} will match and
  22583. substitute the top-level expression up to that many times, but
  22584. will not attempt to match the rules to any sub-expressions.
  22585. In a formula, @code{rewrite(@var{expr}, @var{rules}, @var{n})}
  22586. does a rewriting operation. Here @var{expr} is the expression
  22587. being rewritten, @var{rules} is the rule, vector of rules, or
  22588. variable containing the rules, and @var{n} is the optional
  22589. iteration limit, which may be a positive integer, a negative
  22590. integer, or @samp{inf} or @samp{-inf}. If @var{n} is omitted
  22591. the @code{iterations} value from the rule set is used; if both
  22592. are omitted, 100 is used.
  22593. @node Multi-Phase Rewrite Rules, Selections with Rewrite Rules, Nested Formulas with Rewrite Rules, Rewrite Rules
  22594. @subsection Multi-Phase Rewrite Rules
  22595. @noindent
  22596. It is possible to separate a rewrite rule set into several @dfn{phases}.
  22597. During each phase, certain rules will be enabled while certain others
  22598. will be disabled. A @dfn{phase schedule} controls the order in which
  22599. phases occur during the rewriting process.
  22600. @ignore
  22601. @starindex
  22602. @end ignore
  22603. @tindex phase
  22604. @vindex all
  22605. If a call to the marker function @code{phase} appears in the rules
  22606. vector in place of a rule, all rules following that point will be
  22607. members of the phase(s) identified in the arguments to @code{phase}.
  22608. Phases are given integer numbers. The markers @samp{phase()} and
  22609. @samp{phase(all)} both mean the following rules belong to all phases;
  22610. this is the default at the start of the rule set.
  22611. If you do not explicitly schedule the phases, Calc sorts all phase
  22612. numbers that appear in the rule set and executes the phases in
  22613. ascending order. For example, the rule set
  22614. @example
  22615. @group
  22616. [ f0(x) := g0(x),
  22617. phase(1),
  22618. f1(x) := g1(x),
  22619. phase(2),
  22620. f2(x) := g2(x),
  22621. phase(3),
  22622. f3(x) := g3(x),
  22623. phase(1,2),
  22624. f4(x) := g4(x) ]
  22625. @end group
  22626. @end example
  22627. @noindent
  22628. has three phases, 1 through 3. Phase 1 consists of the @code{f0},
  22629. @code{f1}, and @code{f4} rules (in that order). Phase 2 consists of
  22630. @code{f0}, @code{f2}, and @code{f4}. Phase 3 consists of @code{f0}
  22631. and @code{f3}.
  22632. When Calc rewrites a formula using this rule set, it first rewrites
  22633. the formula using only the phase 1 rules until no further changes are
  22634. possible. Then it switches to the phase 2 rule set and continues
  22635. until no further changes occur, then finally rewrites with phase 3.
  22636. When no more phase 3 rules apply, rewriting finishes. (This is
  22637. assuming @kbd{a r} with a large enough prefix argument to allow the
  22638. rewriting to run to completion; the sequence just described stops
  22639. early if the number of iterations specified in the prefix argument,
  22640. 100 by default, is reached.)
  22641. During each phase, Calc descends through the nested levels of the
  22642. formula as described previously. (@xref{Nested Formulas with Rewrite
  22643. Rules}.) Rewriting starts at the top of the formula, then works its
  22644. way down to the parts, then goes back to the top and works down again.
  22645. The phase 2 rules do not begin until no phase 1 rules apply anywhere
  22646. in the formula.
  22647. @ignore
  22648. @starindex
  22649. @end ignore
  22650. @tindex schedule
  22651. A @code{schedule} marker appearing in the rule set (anywhere, but
  22652. conventionally at the top) changes the default schedule of phases.
  22653. In the simplest case, @code{schedule} has a sequence of phase numbers
  22654. for arguments; each phase number is invoked in turn until the
  22655. arguments to @code{schedule} are exhausted. Thus adding
  22656. @samp{schedule(3,2,1)} at the top of the above rule set would
  22657. reverse the order of the phases; @samp{schedule(1,2,3)} would have
  22658. no effect since this is the default schedule; and @samp{schedule(1,2,1,3)}
  22659. would give phase 1 a second chance after phase 2 has completed, before
  22660. moving on to phase 3.
  22661. Any argument to @code{schedule} can instead be a vector of phase
  22662. numbers (or even of sub-vectors). Then the sub-sequence of phases
  22663. described by the vector are tried repeatedly until no change occurs
  22664. in any phase in the sequence. For example, @samp{schedule([1, 2], 3)}
  22665. tries phase 1, then phase 2, then, if either phase made any changes
  22666. to the formula, repeats these two phases until they can make no
  22667. further progress. Finally, it goes on to phase 3 for finishing
  22668. touches.
  22669. Also, items in @code{schedule} can be variable names as well as
  22670. numbers. A variable name is interpreted as the name of a function
  22671. to call on the whole formula. For example, @samp{schedule(1, simplify)}
  22672. says to apply the phase-1 rules (presumably, all of them), then to
  22673. call @code{simplify} which is the function name equivalent of @kbd{a s}.
  22674. Likewise, @samp{schedule([1, simplify])} says to alternate between
  22675. phase 1 and @kbd{a s} until no further changes occur.
  22676. Phases can be used purely to improve efficiency; if it is known that
  22677. a certain group of rules will apply only at the beginning of rewriting,
  22678. and a certain other group will apply only at the end, then rewriting
  22679. will be faster if these groups are identified as separate phases.
  22680. Once the phase 1 rules are done, Calc can put them aside and no longer
  22681. spend any time on them while it works on phase 2.
  22682. There are also some problems that can only be solved with several
  22683. rewrite phases. For a real-world example of a multi-phase rule set,
  22684. examine the set @code{FitRules}, which is used by the curve-fitting
  22685. command to convert a model expression to linear form.
  22686. @xref{Curve Fitting Details}. This set is divided into four phases.
  22687. The first phase rewrites certain kinds of expressions to be more
  22688. easily linearizable, but less computationally efficient. After the
  22689. linear components have been picked out, the final phase includes the
  22690. opposite rewrites to put each component back into an efficient form.
  22691. If both sets of rules were included in one big phase, Calc could get
  22692. into an infinite loop going back and forth between the two forms.
  22693. Elsewhere in @code{FitRules}, the components are first isolated,
  22694. then recombined where possible to reduce the complexity of the linear
  22695. fit, then finally packaged one component at a time into vectors.
  22696. If the packaging rules were allowed to begin before the recombining
  22697. rules were finished, some components might be put away into vectors
  22698. before they had a chance to recombine. By putting these rules in
  22699. two separate phases, this problem is neatly avoided.
  22700. @node Selections with Rewrite Rules, Matching Commands, Multi-Phase Rewrite Rules, Rewrite Rules
  22701. @subsection Selections with Rewrite Rules
  22702. @noindent
  22703. If a sub-formula of the current formula is selected (as by @kbd{j s};
  22704. @pxref{Selecting Subformulas}), the @kbd{a r} (@code{calc-rewrite})
  22705. command applies only to that sub-formula. Together with a negative
  22706. prefix argument, you can use this fact to apply a rewrite to one
  22707. specific part of a formula without affecting any other parts.
  22708. @kindex j r
  22709. @pindex calc-rewrite-selection
  22710. The @kbd{j r} (@code{calc-rewrite-selection}) command allows more
  22711. sophisticated operations on selections. This command prompts for
  22712. the rules in the same way as @kbd{a r}, but it then applies those
  22713. rules to the whole formula in question even though a sub-formula
  22714. of it has been selected. However, the selected sub-formula will
  22715. first have been surrounded by a @samp{select( )} function call.
  22716. (Calc's evaluator does not understand the function name @code{select};
  22717. this is only a tag used by the @kbd{j r} command.)
  22718. For example, suppose the formula on the stack is @samp{2 (a + b)^2}
  22719. and the sub-formula @samp{a + b} is selected. This formula will
  22720. be rewritten to @samp{2 select(a + b)^2} and then the rewrite
  22721. rules will be applied in the usual way. The rewrite rules can
  22722. include references to @code{select} to tell where in the pattern
  22723. the selected sub-formula should appear.
  22724. If there is still exactly one @samp{select( )} function call in
  22725. the formula after rewriting is done, it indicates which part of
  22726. the formula should be selected afterwards. Otherwise, the
  22727. formula will be unselected.
  22728. You can make @kbd{j r} act much like @kbd{a r} by enclosing both parts
  22729. of the rewrite rule with @samp{select()}. However, @kbd{j r}
  22730. allows you to use the current selection in more flexible ways.
  22731. Suppose you wished to make a rule which removed the exponent from
  22732. the selected term; the rule @samp{select(a)^x := select(a)} would
  22733. work. In the above example, it would rewrite @samp{2 select(a + b)^2}
  22734. to @samp{2 select(a + b)}. This would then be returned to the
  22735. stack as @samp{2 (a + b)} with the @samp{a + b} selected.
  22736. The @kbd{j r} command uses one iteration by default, unlike
  22737. @kbd{a r} which defaults to 100 iterations. A numeric prefix
  22738. argument affects @kbd{j r} in the same way as @kbd{a r}.
  22739. @xref{Nested Formulas with Rewrite Rules}.
  22740. As with other selection commands, @kbd{j r} operates on the stack
  22741. entry that contains the cursor. (If the cursor is on the top-of-stack
  22742. @samp{.} marker, it works as if the cursor were on the formula
  22743. at stack level 1.)
  22744. If you don't specify a set of rules, the rules are taken from the
  22745. top of the stack, just as with @kbd{a r}. In this case, the
  22746. cursor must indicate stack entry 2 or above as the formula to be
  22747. rewritten (otherwise the same formula would be used as both the
  22748. target and the rewrite rules).
  22749. If the indicated formula has no selection, the cursor position within
  22750. the formula temporarily selects a sub-formula for the purposes of this
  22751. command. If the cursor is not on any sub-formula (e.g., it is in
  22752. the line-number area to the left of the formula), the @samp{select( )}
  22753. markers are ignored by the rewrite mechanism and the rules are allowed
  22754. to apply anywhere in the formula.
  22755. As a special feature, the normal @kbd{a r} command also ignores
  22756. @samp{select( )} calls in rewrite rules. For example, if you used the
  22757. above rule @samp{select(a)^x := select(a)} with @kbd{a r}, it would apply
  22758. the rule as if it were @samp{a^x := a}. Thus, you can write general
  22759. purpose rules with @samp{select( )} hints inside them so that they
  22760. will ``do the right thing'' in both @kbd{a r} and @kbd{j r},
  22761. both with and without selections.
  22762. @node Matching Commands, Automatic Rewrites, Selections with Rewrite Rules, Rewrite Rules
  22763. @subsection Matching Commands
  22764. @noindent
  22765. @kindex a m
  22766. @pindex calc-match
  22767. @tindex match
  22768. The @kbd{a m} (@code{calc-match}) [@code{match}] function takes a
  22769. vector of formulas and a rewrite-rule-style pattern, and produces
  22770. a vector of all formulas which match the pattern. The command
  22771. prompts you to enter the pattern; as for @kbd{a r}, you can enter
  22772. a single pattern (i.e., a formula with meta-variables), or a
  22773. vector of patterns, or a variable which contains patterns, or
  22774. you can give a blank response in which case the patterns are taken
  22775. from the top of the stack. The pattern set will be compiled once
  22776. and saved if it is stored in a variable. If there are several
  22777. patterns in the set, vector elements are kept if they match any
  22778. of the patterns.
  22779. For example, @samp{match(a+b, [x, x+y, x-y, 7, x+y+z])}
  22780. will return @samp{[x+y, x-y, x+y+z]}.
  22781. The @code{import} mechanism is not available for pattern sets.
  22782. The @kbd{a m} command can also be used to extract all vector elements
  22783. which satisfy any condition: The pattern @samp{x :: x>0} will select
  22784. all the positive vector elements.
  22785. @kindex I a m
  22786. @tindex matchnot
  22787. With the Inverse flag [@code{matchnot}], this command extracts all
  22788. vector elements which do @emph{not} match the given pattern.
  22789. @ignore
  22790. @starindex
  22791. @end ignore
  22792. @tindex matches
  22793. There is also a function @samp{matches(@var{x}, @var{p})} which
  22794. evaluates to 1 if expression @var{x} matches pattern @var{p}, or
  22795. to 0 otherwise. This is sometimes useful for including into the
  22796. conditional clauses of other rewrite rules.
  22797. @ignore
  22798. @starindex
  22799. @end ignore
  22800. @tindex vmatches
  22801. The function @code{vmatches} is just like @code{matches}, except
  22802. that if the match succeeds it returns a vector of assignments to
  22803. the meta-variables instead of the number 1. For example,
  22804. @samp{vmatches(f(1,2), f(a,b))} returns @samp{[a := 1, b := 2]}.
  22805. If the match fails, the function returns the number 0.
  22806. @node Automatic Rewrites, Debugging Rewrites, Matching Commands, Rewrite Rules
  22807. @subsection Automatic Rewrites
  22808. @noindent
  22809. @cindex @code{EvalRules} variable
  22810. @vindex EvalRules
  22811. It is possible to get Calc to apply a set of rewrite rules on all
  22812. results, effectively adding to the built-in set of default
  22813. simplifications. To do this, simply store your rule set in the
  22814. variable @code{EvalRules}. There is a convenient @kbd{s E} command
  22815. for editing @code{EvalRules}; @pxref{Operations on Variables}.
  22816. For example, suppose you want @samp{sin(a + b)} to be expanded out
  22817. to @samp{sin(b) cos(a) + cos(b) sin(a)} wherever it appears, and
  22818. similarly for @samp{cos(a + b)}. The corresponding rewrite rule
  22819. set would be,
  22820. @smallexample
  22821. @group
  22822. [ sin(a + b) := cos(a) sin(b) + sin(a) cos(b),
  22823. cos(a + b) := cos(a) cos(b) - sin(a) sin(b) ]
  22824. @end group
  22825. @end smallexample
  22826. To apply these manually, you could put them in a variable called
  22827. @code{trigexp} and then use @kbd{a r trigexp} every time you wanted
  22828. to expand trig functions. But if instead you store them in the
  22829. variable @code{EvalRules}, they will automatically be applied to all
  22830. sines and cosines of sums. Then, with @samp{2 x} and @samp{45} on
  22831. the stack, typing @kbd{+ S} will (assuming degrees mode) result in
  22832. @samp{0.7071 sin(2 x) + 0.7071 cos(2 x)} automatically.
  22833. As each level of a formula is evaluated, the rules from
  22834. @code{EvalRules} are applied before the default simplifications.
  22835. Rewriting continues until no further @code{EvalRules} apply.
  22836. Note that this is different from the usual order of application of
  22837. rewrite rules: @code{EvalRules} works from the bottom up, simplifying
  22838. the arguments to a function before the function itself, while @kbd{a r}
  22839. applies rules from the top down.
  22840. Because the @code{EvalRules} are tried first, you can use them to
  22841. override the normal behavior of any built-in Calc function.
  22842. It is important not to write a rule that will get into an infinite
  22843. loop. For example, the rule set @samp{[f(0) := 1, f(n) := n f(n-1)]}
  22844. appears to be a good definition of a factorial function, but it is
  22845. unsafe. Imagine what happens if @samp{f(2.5)} is simplified. Calc
  22846. will continue to subtract 1 from this argument forever without reaching
  22847. zero. A safer second rule would be @samp{f(n) := n f(n-1) :: n>0}.
  22848. Another dangerous rule is @samp{g(x, y) := g(y, x)}. Rewriting
  22849. @samp{g(2, 4)}, this would bounce back and forth between that and
  22850. @samp{g(4, 2)} forever. If an infinite loop in @code{EvalRules}
  22851. occurs, Emacs will eventually stop with a ``Computation got stuck
  22852. or ran too long'' message.
  22853. Another subtle difference between @code{EvalRules} and regular rewrites
  22854. concerns rules that rewrite a formula into an identical formula. For
  22855. example, @samp{f(n) := f(floor(n))} ``fails to match'' when @cite{n} is
  22856. already an integer. But in @code{EvalRules} this case is detected only
  22857. if the righthand side literally becomes the original formula before any
  22858. further simplification. This means that @samp{f(n) := f(floor(n))} will
  22859. get into an infinite loop if it occurs in @code{EvalRules}. Calc will
  22860. replace @samp{f(6)} with @samp{f(floor(6))}, which is different from
  22861. @samp{f(6)}, so it will consider the rule to have matched and will
  22862. continue simplifying that formula; first the argument is simplified
  22863. to get @samp{f(6)}, then the rule matches again to get @samp{f(floor(6))}
  22864. again, ad infinitum. A much safer rule would check its argument first,
  22865. say, with @samp{f(n) := f(floor(n)) :: !dint(n)}.
  22866. (What really happens is that the rewrite mechanism substitutes the
  22867. meta-variables in the righthand side of a rule, compares to see if the
  22868. result is the same as the original formula and fails if so, then uses
  22869. the default simplifications to simplify the result and compares again
  22870. (and again fails if the formula has simplified back to its original
  22871. form). The only special wrinkle for the @code{EvalRules} is that the
  22872. same rules will come back into play when the default simplifications
  22873. are used. What Calc wants to do is build @samp{f(floor(6))}, see that
  22874. this is different from the original formula, simplify to @samp{f(6)},
  22875. see that this is the same as the original formula, and thus halt the
  22876. rewriting. But while simplifying, @samp{f(6)} will again trigger
  22877. the same @code{EvalRules} rule and Calc will get into a loop inside
  22878. the rewrite mechanism itself.)
  22879. The @code{phase}, @code{schedule}, and @code{iterations} markers do
  22880. not work in @code{EvalRules}. If the rule set is divided into phases,
  22881. only the phase 1 rules are applied, and the schedule is ignored.
  22882. The rules are always repeated as many times as possible.
  22883. The @code{EvalRules} are applied to all function calls in a formula,
  22884. but not to numbers (and other number-like objects like error forms),
  22885. nor to vectors or individual variable names. (Though they will apply
  22886. to @emph{components} of vectors and error forms when appropriate.) You
  22887. might try to make a variable @code{phihat} which automatically expands
  22888. to its definition without the need to press @kbd{=} by writing the
  22889. rule @samp{quote(phihat) := (1-sqrt(5))/2}, but unfortunately this rule
  22890. will not work as part of @code{EvalRules}.
  22891. Finally, another limitation is that Calc sometimes calls its built-in
  22892. functions directly rather than going through the default simplifications.
  22893. When it does this, @code{EvalRules} will not be able to override those
  22894. functions. For example, when you take the absolute value of the complex
  22895. number @cite{(2, 3)}, Calc computes @samp{sqrt(2*2 + 3*3)} by calling
  22896. the multiplication, addition, and square root functions directly rather
  22897. than applying the default simplifications to this formula. So an
  22898. @code{EvalRules} rule that (perversely) rewrites @samp{sqrt(13) := 6}
  22899. would not apply. (However, if you put Calc into symbolic mode so that
  22900. @samp{sqrt(13)} will be left in symbolic form by the built-in square
  22901. root function, your rule will be able to apply. But if the complex
  22902. number were @cite{(3,4)}, so that @samp{sqrt(25)} must be calculated,
  22903. then symbolic mode will not help because @samp{sqrt(25)} can be
  22904. evaluated exactly to 5.)
  22905. One subtle restriction that normally only manifests itself with
  22906. @code{EvalRules} is that while a given rewrite rule is in the process
  22907. of being checked, that same rule cannot be recursively applied. Calc
  22908. effectively removes the rule from its rule set while checking the rule,
  22909. then puts it back once the match succeeds or fails. (The technical
  22910. reason for this is that compiled pattern programs are not reentrant.)
  22911. For example, consider the rule @samp{foo(x) := x :: foo(x/2) > 0}
  22912. attempting to match @samp{foo(8)}. This rule will be inactive while
  22913. the condition @samp{foo(4) > 0} is checked, even though it might be
  22914. an integral part of evaluating that condition. Note that this is not
  22915. a problem for the more usual recursive type of rule, such as
  22916. @samp{foo(x) := foo(x/2)}, because there the rule has succeeded and
  22917. been reactivated by the time the righthand side is evaluated.
  22918. If @code{EvalRules} has no stored value (its default state), or if
  22919. anything but a vector is stored in it, then it is ignored.
  22920. Even though Calc's rewrite mechanism is designed to compare rewrite
  22921. rules to formulas as quickly as possible, storing rules in
  22922. @code{EvalRules} may make Calc run substantially slower. This is
  22923. particularly true of rules where the top-level call is a commonly used
  22924. function, or is not fixed. The rule @samp{f(n) := n f(n-1) :: n>0} will
  22925. only activate the rewrite mechanism for calls to the function @code{f},
  22926. but @samp{lg(n) + lg(m) := lg(n m)} will check every @samp{+} operator.
  22927. @smallexample
  22928. apply(f, [a*b]) := apply(f, [a]) + apply(f, [b]) :: in(f, [ln, log10])
  22929. @end smallexample
  22930. @noindent
  22931. may seem more ``efficient'' than two separate rules for @code{ln} and
  22932. @code{log10}, but actually it is vastly less efficient because rules
  22933. with @code{apply} as the top-level pattern must be tested against
  22934. @emph{every} function call that is simplified.
  22935. @cindex @code{AlgSimpRules} variable
  22936. @vindex AlgSimpRules
  22937. Suppose you want @samp{sin(a + b)} to be expanded out not all the time,
  22938. but only when @kbd{a s} is used to simplify the formula. The variable
  22939. @code{AlgSimpRules} holds rules for this purpose. The @kbd{a s} command
  22940. will apply @code{EvalRules} and @code{AlgSimpRules} to the formula, as
  22941. well as all of its built-in simplifications.
  22942. Most of the special limitations for @code{EvalRules} don't apply to
  22943. @code{AlgSimpRules}. Calc simply does an @kbd{a r AlgSimpRules}
  22944. command with an infinite repeat count as the first step of @kbd{a s}.
  22945. It then applies its own built-in simplifications throughout the
  22946. formula, and then repeats these two steps (along with applying the
  22947. default simplifications) until no further changes are possible.
  22948. @cindex @code{ExtSimpRules} variable
  22949. @cindex @code{UnitSimpRules} variable
  22950. @vindex ExtSimpRules
  22951. @vindex UnitSimpRules
  22952. There are also @code{ExtSimpRules} and @code{UnitSimpRules} variables
  22953. that are used by @kbd{a e} and @kbd{u s}, respectively; these commands
  22954. also apply @code{EvalRules} and @code{AlgSimpRules}. The variable
  22955. @code{IntegSimpRules} contains simplification rules that are used
  22956. only during integration by @kbd{a i}.
  22957. @node Debugging Rewrites, Examples of Rewrite Rules, Automatic Rewrites, Rewrite Rules
  22958. @subsection Debugging Rewrites
  22959. @noindent
  22960. If a buffer named @samp{*Trace*} exists, the rewrite mechanism will
  22961. record some useful information there as it operates. The original
  22962. formula is written there, as is the result of each successful rewrite,
  22963. and the final result of the rewriting. All phase changes are also
  22964. noted.
  22965. Calc always appends to @samp{*Trace*}. You must empty this buffer
  22966. yourself periodically if it is in danger of growing unwieldy.
  22967. Note that the rewriting mechanism is substantially slower when the
  22968. @samp{*Trace*} buffer exists, even if the buffer is not visible on
  22969. the screen. Once you are done, you will probably want to kill this
  22970. buffer (with @kbd{C-x k *Trace* @key{RET}}). If you leave it in
  22971. existence and forget about it, all your future rewrite commands will
  22972. be needlessly slow.
  22973. @node Examples of Rewrite Rules, , Debugging Rewrites, Rewrite Rules
  22974. @subsection Examples of Rewrite Rules
  22975. @noindent
  22976. Returning to the example of substituting the pattern
  22977. @samp{sin(x)^2 + cos(x)^2} with 1, we saw that the rule
  22978. @samp{opt(a) sin(x)^2 + opt(a) cos(x)^2 := a} does a good job of
  22979. finding suitable cases. Another solution would be to use the rule
  22980. @samp{cos(x)^2 := 1 - sin(x)^2}, followed by algebraic simplification
  22981. if necessary. This rule will be the most effective way to do the job,
  22982. but at the expense of making some changes that you might not desire.@refill
  22983. Another algebraic rewrite rule is @samp{exp(x+y) := exp(x) exp(y)}.
  22984. To make this work with the @w{@kbd{j r}} command so that it can be
  22985. easily targeted to a particular exponential in a large formula,
  22986. you might wish to write the rule as @samp{select(exp(x+y)) :=
  22987. select(exp(x) exp(y))}. The @samp{select} markers will be
  22988. ignored by the regular @kbd{a r} command
  22989. (@pxref{Selections with Rewrite Rules}).@refill
  22990. A surprisingly useful rewrite rule is @samp{a/(b-c) := a*(b+c)/(b^2-c^2)}.
  22991. This will simplify the formula whenever @cite{b} and/or @cite{c} can
  22992. be made simpler by squaring. For example, applying this rule to
  22993. @samp{2 / (sqrt(2) + 3)} yields @samp{6:7 - 2:7 sqrt(2)} (assuming
  22994. Symbolic Mode has been enabled to keep the square root from being
  22995. evaulated to a floating-point approximation). This rule is also
  22996. useful when working with symbolic complex numbers, e.g.,
  22997. @samp{(a + b i) / (c + d i)}.
  22998. As another example, we could define our own ``triangular numbers'' function
  22999. with the rules @samp{[tri(0) := 0, tri(n) := n + tri(n-1) :: n>0]}. Enter
  23000. this vector and store it in a variable: @kbd{@w{s t} trirules}. Now, given
  23001. a suitable formula like @samp{tri(5)} on the stack, type @samp{a r trirules}
  23002. to apply these rules repeatedly. After six applications, @kbd{a r} will
  23003. stop with 15 on the stack. Once these rules are debugged, it would probably
  23004. be most useful to add them to @code{EvalRules} so that Calc will evaluate
  23005. the new @code{tri} function automatically. We could then use @kbd{Z K} on
  23006. the keyboard macro @kbd{' tri($) @key{RET}} to make a command that applies
  23007. @code{tri} to the value on the top of the stack. @xref{Programming}.
  23008. @cindex Quaternions
  23009. The following rule set, contributed by @c{Fran\c cois}
  23010. @asis{Francois} Pinard, implements
  23011. @dfn{quaternions}, a generalization of the concept of complex numbers.
  23012. Quaternions have four components, and are here represented by function
  23013. calls @samp{quat(@var{w}, [@var{x}, @var{y}, @var{z}])} with ``real
  23014. part'' @var{w} and the three ``imaginary'' parts collected into a
  23015. vector. Various arithmetical operations on quaternions are supported.
  23016. To use these rules, either add them to @code{EvalRules}, or create a
  23017. command based on @kbd{a r} for simplifying quaternion formulas.
  23018. A convenient way to enter quaternions would be a command defined by
  23019. a keyboard macro containing: @kbd{' quat($$$$, [$$$, $$, $]) @key{RET}}.
  23020. @smallexample
  23021. [ quat(w, x, y, z) := quat(w, [x, y, z]),
  23022. quat(w, [0, 0, 0]) := w,
  23023. abs(quat(w, v)) := hypot(w, v),
  23024. -quat(w, v) := quat(-w, -v),
  23025. r + quat(w, v) := quat(r + w, v) :: real(r),
  23026. r - quat(w, v) := quat(r - w, -v) :: real(r),
  23027. quat(w1, v1) + quat(w2, v2) := quat(w1 + w2, v1 + v2),
  23028. r * quat(w, v) := quat(r * w, r * v) :: real(r),
  23029. plain(quat(w1, v1) * quat(w2, v2))
  23030. := quat(w1 * w2 - v1 * v2, w1 * v2 + w2 * v1 + cross(v1, v2)),
  23031. quat(w1, v1) / r := quat(w1 / r, v1 / r) :: real(r),
  23032. z / quat(w, v) := z * quatinv(quat(w, v)),
  23033. quatinv(quat(w, v)) := quat(w, -v) / (w^2 + v^2),
  23034. quatsqr(quat(w, v)) := quat(w^2 - v^2, 2 * w * v),
  23035. quat(w, v)^k := quatsqr(quat(w, v)^(k / 2))
  23036. :: integer(k) :: k > 0 :: k % 2 = 0,
  23037. quat(w, v)^k := quatsqr(quat(w, v)^((k - 1) / 2)) * quat(w, v)
  23038. :: integer(k) :: k > 2,
  23039. quat(w, v)^-k := quatinv(quat(w, v)^k) :: integer(k) :: k > 0 ]
  23040. @end smallexample
  23041. Quaternions, like matrices, have non-commutative multiplication.
  23042. In other words, @cite{q1 * q2 = q2 * q1} is not necessarily true if
  23043. @cite{q1} and @cite{q2} are @code{quat} forms. The @samp{quat*quat}
  23044. rule above uses @code{plain} to prevent Calc from rearranging the
  23045. product. It may also be wise to add the line @samp{[quat(), matrix]}
  23046. to the @code{Decls} matrix, to ensure that Calc's other algebraic
  23047. operations will not rearrange a quaternion product. @xref{Declarations}.
  23048. These rules also accept a four-argument @code{quat} form, converting
  23049. it to the preferred form in the first rule. If you would rather see
  23050. results in the four-argument form, just append the two items
  23051. @samp{phase(2), quat(w, [x, y, z]) := quat(w, x, y, z)} to the end
  23052. of the rule set. (But remember that multi-phase rule sets don't work
  23053. in @code{EvalRules}.)
  23054. @node Units, Store and Recall, Algebra, Top
  23055. @chapter Operating on Units
  23056. @noindent
  23057. One special interpretation of algebraic formulas is as numbers with units.
  23058. For example, the formula @samp{5 m / s^2} can be read ``five meters
  23059. per second squared.'' The commands in this chapter help you
  23060. manipulate units expressions in this form. Units-related commands
  23061. begin with the @kbd{u} prefix key.
  23062. @menu
  23063. * Basic Operations on Units::
  23064. * The Units Table::
  23065. * Predefined Units::
  23066. * User-Defined Units::
  23067. @end menu
  23068. @node Basic Operations on Units, The Units Table, Units, Units
  23069. @section Basic Operations on Units
  23070. @noindent
  23071. A @dfn{units expression} is a formula which is basically a number
  23072. multiplied and/or divided by one or more @dfn{unit names}, which may
  23073. optionally be raised to integer powers. Actually, the value part need not
  23074. be a number; any product or quotient involving unit names is a units
  23075. expression. Many of the units commands will also accept any formula,
  23076. where the command applies to all units expressions which appear in the
  23077. formula.
  23078. A unit name is a variable whose name appears in the @dfn{unit table},
  23079. or a variable whose name is a prefix character like @samp{k} (for ``kilo'')
  23080. or @samp{u} (for ``micro'') followed by a name in the unit table.
  23081. A substantial table of built-in units is provided with Calc;
  23082. @pxref{Predefined Units}. You can also define your own unit names;
  23083. @pxref{User-Defined Units}.@refill
  23084. Note that if the value part of a units expression is exactly @samp{1},
  23085. it will be removed by the Calculator's automatic algebra routines: The
  23086. formula @samp{1 mm} is ``simplified'' to @samp{mm}. This is only a
  23087. display anomaly, however; @samp{mm} will work just fine as a
  23088. representation of one millimeter.@refill
  23089. You may find that Algebraic Mode (@pxref{Algebraic Entry}) makes working
  23090. with units expressions easier. Otherwise, you will have to remember
  23091. to hit the apostrophe key every time you wish to enter units.
  23092. @kindex u s
  23093. @pindex calc-simplify-units
  23094. @ignore
  23095. @mindex usimpl@idots
  23096. @end ignore
  23097. @tindex usimplify
  23098. The @kbd{u s} (@code{calc-simplify-units}) [@code{usimplify}] command
  23099. simplifies a units
  23100. expression. It uses @kbd{a s} (@code{calc-simplify}) to simplify the
  23101. expression first as a regular algebraic formula; it then looks for
  23102. features that can be further simplified by converting one object's units
  23103. to be compatible with another's. For example, @samp{5 m + 23 mm} will
  23104. simplify to @samp{5.023 m}. When different but compatible units are
  23105. added, the righthand term's units are converted to match those of the
  23106. lefthand term. @xref{Simplification Modes}, for a way to have this done
  23107. automatically at all times.@refill
  23108. Units simplification also handles quotients of two units with the same
  23109. dimensionality, as in @w{@samp{2 in s/L cm}} to @samp{5.08 s/L}; fractional
  23110. powers of unit expressions, as in @samp{sqrt(9 mm^2)} to @samp{3 mm} and
  23111. @samp{sqrt(9 acre)} to a quantity in meters; and @code{floor},
  23112. @code{ceil}, @code{round}, @code{rounde}, @code{roundu}, @code{trunc},
  23113. @code{float}, @code{frac}, @code{abs}, and @code{clean}
  23114. applied to units expressions, in which case
  23115. the operation in question is applied only to the numeric part of the
  23116. expression. Finally, trigonometric functions of quantities with units
  23117. of angle are evaluated, regardless of the current angular mode.@refill
  23118. @kindex u c
  23119. @pindex calc-convert-units
  23120. The @kbd{u c} (@code{calc-convert-units}) command converts a units
  23121. expression to new, compatible units. For example, given the units
  23122. expression @samp{55 mph}, typing @kbd{u c m/s @key{RET}} produces
  23123. @samp{24.5872 m/s}. If the units you request are inconsistent with
  23124. the original units, the number will be converted into your units
  23125. times whatever ``remainder'' units are left over. For example,
  23126. converting @samp{55 mph} into acres produces @samp{6.08e-3 acre / m s}.
  23127. (Recall that multiplication binds more strongly than division in Calc
  23128. formulas, so the units here are acres per meter-second.) Remainder
  23129. units are expressed in terms of ``fundamental'' units like @samp{m} and
  23130. @samp{s}, regardless of the input units.
  23131. One special exception is that if you specify a single unit name, and
  23132. a compatible unit appears somewhere in the units expression, then
  23133. that compatible unit will be converted to the new unit and the
  23134. remaining units in the expression will be left alone. For example,
  23135. given the input @samp{980 cm/s^2}, the command @kbd{u c ms} will
  23136. change the @samp{s} to @samp{ms} to get @samp{9.8e-4 cm/ms^2}.
  23137. The ``remainder unit'' @samp{cm} is left alone rather than being
  23138. changed to the base unit @samp{m}.
  23139. You can use explicit unit conversion instead of the @kbd{u s} command
  23140. to gain more control over the units of the result of an expression.
  23141. For example, given @samp{5 m + 23 mm}, you can type @kbd{u c m} or
  23142. @kbd{u c mm} to express the result in either meters or millimeters.
  23143. (For that matter, you could type @kbd{u c fath} to express the result
  23144. in fathoms, if you preferred!)
  23145. In place of a specific set of units, you can also enter one of the
  23146. units system names @code{si}, @code{mks} (equivalent), or @code{cgs}.
  23147. For example, @kbd{u c si @key{RET}} converts the expression into
  23148. International System of Units (SI) base units. Also, @kbd{u c base}
  23149. converts to Calc's base units, which are the same as @code{si} units
  23150. except that @code{base} uses @samp{g} as the fundamental unit of mass
  23151. whereas @code{si} uses @samp{kg}.
  23152. @cindex Composite units
  23153. The @kbd{u c} command also accepts @dfn{composite units}, which
  23154. are expressed as the sum of several compatible unit names. For
  23155. example, converting @samp{30.5 in} to units @samp{mi+ft+in} (miles,
  23156. feet, and inches) produces @samp{2 ft + 6.5 in}. Calc first
  23157. sorts the unit names into order of decreasing relative size.
  23158. It then accounts for as much of the input quantity as it can
  23159. using an integer number times the largest unit, then moves on
  23160. to the next smaller unit, and so on. Only the smallest unit
  23161. may have a non-integer amount attached in the result. A few
  23162. standard unit names exist for common combinations, such as
  23163. @code{mfi} for @samp{mi+ft+in}, and @code{tpo} for @samp{ton+lb+oz}.
  23164. Composite units are expanded as if by @kbd{a x}, so that
  23165. @samp{(ft+in)/hr} is first converted to @samp{ft/hr+in/hr}.
  23166. If the value on the stack does not contain any units, @kbd{u c} will
  23167. prompt first for the old units which this value should be considered
  23168. to have, then for the new units. Assuming the old and new units you
  23169. give are consistent with each other, the result also will not contain
  23170. any units. For example, @kbd{@w{u c} cm @key{RET} in @key{RET}} converts the number
  23171. 2 on the stack to 5.08.
  23172. @kindex u b
  23173. @pindex calc-base-units
  23174. The @kbd{u b} (@code{calc-base-units}) command is shorthand for
  23175. @kbd{u c base}; it converts the units expression on the top of the
  23176. stack into @code{base} units. If @kbd{u s} does not simplify a
  23177. units expression as far as you would like, try @kbd{u b}.
  23178. The @kbd{u c} and @kbd{u b} commands treat temperature units (like
  23179. @samp{degC} and @samp{K}) as relative temperatures. For example,
  23180. @kbd{u c} converts @samp{10 degC} to @samp{18 degF}: A change of 10
  23181. degrees Celsius corresponds to a change of 18 degrees Fahrenheit.
  23182. @kindex u t
  23183. @pindex calc-convert-temperature
  23184. @cindex Temperature conversion
  23185. The @kbd{u t} (@code{calc-convert-temperature}) command converts
  23186. absolute temperatures. The value on the stack must be a simple units
  23187. expression with units of temperature only. This command would convert
  23188. @samp{10 degC} to @samp{50 degF}, the equivalent temperature on the
  23189. Fahrenheit scale.@refill
  23190. @kindex u r
  23191. @pindex calc-remove-units
  23192. @kindex u x
  23193. @pindex calc-extract-units
  23194. The @kbd{u r} (@code{calc-remove-units}) command removes units from the
  23195. formula at the top of the stack. The @kbd{u x}
  23196. (@code{calc-extract-units}) command extracts only the units portion of a
  23197. formula. These commands essentially replace every term of the formula
  23198. that does or doesn't (respectively) look like a unit name by the
  23199. constant 1, then resimplify the formula.@refill
  23200. @kindex u a
  23201. @pindex calc-autorange-units
  23202. The @kbd{u a} (@code{calc-autorange-units}) command turns on and off a
  23203. mode in which unit prefixes like @code{k} (``kilo'') are automatically
  23204. applied to keep the numeric part of a units expression in a reasonable
  23205. range. This mode affects @kbd{u s} and all units conversion commands
  23206. except @kbd{u b}. For example, with autoranging on, @samp{12345 Hz}
  23207. will be simplified to @samp{12.345 kHz}. Autoranging is useful for
  23208. some kinds of units (like @code{Hz} and @code{m}), but is probably
  23209. undesirable for non-metric units like @code{ft} and @code{tbsp}.
  23210. (Composite units are more appropriate for those; see above.)
  23211. Autoranging always applies the prefix to the leftmost unit name.
  23212. Calc chooses the largest prefix that causes the number to be greater
  23213. than or equal to 1.0. Thus an increasing sequence of adjusted times
  23214. would be @samp{1 ms, 10 ms, 100 ms, 1 s, 10 s, 100 s, 1 ks}.
  23215. Generally the rule of thumb is that the number will be adjusted
  23216. to be in the interval @samp{[1 .. 1000)}, although there are several
  23217. exceptions to this rule. First, if the unit has a power then this
  23218. is not possible; @samp{0.1 s^2} simplifies to @samp{100000 ms^2}.
  23219. Second, the ``centi-'' prefix is allowed to form @code{cm} (centimeters),
  23220. but will not apply to other units. The ``deci-,'' ``deka-,'' and
  23221. ``hecto-'' prefixes are never used. Thus the allowable interval is
  23222. @samp{[1 .. 10)} for millimeters and @samp{[1 .. 100)} for centimeters.
  23223. Finally, a prefix will not be added to a unit if the resulting name
  23224. is also the actual name of another unit; @samp{1e-15 t} would normally
  23225. be considered a ``femto-ton,'' but it is written as @samp{1000 at}
  23226. (1000 atto-tons) instead because @code{ft} would be confused with feet.
  23227. @node The Units Table, Predefined Units, Basic Operations on Units, Units
  23228. @section The Units Table
  23229. @noindent
  23230. @kindex u v
  23231. @pindex calc-enter-units-table
  23232. The @kbd{u v} (@code{calc-enter-units-table}) command displays the units table
  23233. in another buffer called @code{*Units Table*}. Each entry in this table
  23234. gives the unit name as it would appear in an expression, the definition
  23235. of the unit in terms of simpler units, and a full name or description of
  23236. the unit. Fundamental units are defined as themselves; these are the
  23237. units produced by the @kbd{u b} command. The fundamental units are
  23238. meters, seconds, grams, kelvins, amperes, candelas, moles, radians,
  23239. and steradians.
  23240. The Units Table buffer also displays the Unit Prefix Table. Note that
  23241. two prefixes, ``kilo'' and ``hecto,'' accept either upper- or lower-case
  23242. prefix letters. @samp{Meg} is also accepted as a synonym for the @samp{M}
  23243. prefix. Whenever a unit name can be interpreted as either a built-in name
  23244. or a prefix followed by another built-in name, the former interpretation
  23245. wins. For example, @samp{2 pt} means two pints, not two pico-tons.
  23246. The Units Table buffer, once created, is not rebuilt unless you define
  23247. new units. To force the buffer to be rebuilt, give any numeric prefix
  23248. argument to @kbd{u v}.
  23249. @kindex u V
  23250. @pindex calc-view-units-table
  23251. The @kbd{u V} (@code{calc-view-units-table}) command is like @kbd{u v} except
  23252. that the cursor is not moved into the Units Table buffer. You can
  23253. type @kbd{u V} again to remove the Units Table from the display. To
  23254. return from the Units Table buffer after a @kbd{u v}, type @kbd{M-# c}
  23255. again or use the regular Emacs @w{@kbd{C-x o}} (@code{other-window})
  23256. command. You can also kill the buffer with @kbd{C-x k} if you wish;
  23257. the actual units table is safely stored inside the Calculator.
  23258. @kindex u g
  23259. @pindex calc-get-unit-definition
  23260. The @kbd{u g} (@code{calc-get-unit-definition}) command retrieves a unit's
  23261. defining expression and pushes it onto the Calculator stack. For example,
  23262. @kbd{u g in} will produce the expression @samp{2.54 cm}. This is the
  23263. same definition for the unit that would appear in the Units Table buffer.
  23264. Note that this command works only for actual unit names; @kbd{u g km}
  23265. will report that no such unit exists, for example, because @code{km} is
  23266. really the unit @code{m} with a @code{k} (``kilo'') prefix. To see a
  23267. definition of a unit in terms of base units, it is easier to push the
  23268. unit name on the stack and then reduce it to base units with @kbd{u b}.
  23269. @kindex u e
  23270. @pindex calc-explain-units
  23271. The @kbd{u e} (@code{calc-explain-units}) command displays an English
  23272. description of the units of the expression on the stack. For example,
  23273. for the expression @samp{62 km^2 g / s^2 mol K}, the description is
  23274. ``Square-Kilometer Gram per (Second-squared Mole Degree-Kelvin).'' This
  23275. command uses the English descriptions that appear in the righthand
  23276. column of the Units Table.
  23277. @node Predefined Units, User-Defined Units, The Units Table, Units
  23278. @section Predefined Units
  23279. @noindent
  23280. Since the exact definitions of many kinds of units have evolved over the
  23281. years, and since certain countries sometimes have local differences in
  23282. their definitions, it is a good idea to examine Calc's definition of a
  23283. unit before depending on its exact value. For example, there are three
  23284. different units for gallons, corresponding to the US (@code{gal}),
  23285. Canadian (@code{galC}), and British (@code{galUK}) definitions. Also,
  23286. note that @code{oz} is a standard ounce of mass, @code{ozt} is a Troy
  23287. ounce, and @code{ozfl} is a fluid ounce.
  23288. The temperature units corresponding to degrees Kelvin and Centigrade
  23289. (Celsius) are the same in this table, since most units commands treat
  23290. temperatures as being relative. The @code{calc-convert-temperature}
  23291. command has special rules for handling the different absolute magnitudes
  23292. of the various temperature scales.
  23293. The unit of volume ``liters'' can be referred to by either the lower-case
  23294. @code{l} or the upper-case @code{L}.
  23295. The unit @code{A} stands for Amperes; the name @code{Ang} is used
  23296. @tex
  23297. for \AA ngstroms.
  23298. @end tex
  23299. @ifinfo
  23300. for Angstroms.
  23301. @end ifinfo
  23302. The unit @code{pt} stands for pints; the name @code{point} stands for
  23303. a typographical point, defined by @samp{72 point = 1 in}. There is
  23304. also @code{tpt}, which stands for a printer's point as defined by the
  23305. @TeX{} typesetting system: @samp{72.27 tpt = 1 in}.
  23306. The unit @code{e} stands for the elementary (electron) unit of charge;
  23307. because algebra command could mistake this for the special constant
  23308. @cite{e}, Calc provides the alternate unit name @code{ech} which is
  23309. preferable to @code{e}.
  23310. The name @code{g} stands for one gram of mass; there is also @code{gf},
  23311. one gram of force. (Likewise for @kbd{lb}, pounds, and @kbd{lbf}.)
  23312. Meanwhile, one ``@cite{g}'' of acceleration is denoted @code{ga}.
  23313. The unit @code{ton} is a U.S. ton of @samp{2000 lb}, and @code{t} is
  23314. a metric ton of @samp{1000 kg}.
  23315. The names @code{s} (or @code{sec}) and @code{min} refer to units of
  23316. time; @code{arcsec} and @code{arcmin} are units of angle.
  23317. Some ``units'' are really physical constants; for example, @code{c}
  23318. represents the speed of light, and @code{h} represents Planck's
  23319. constant. You can use these just like other units: converting
  23320. @samp{.5 c} to @samp{m/s} expresses one-half the speed of light in
  23321. meters per second. You can also use this merely as a handy reference;
  23322. the @kbd{u g} command gets the definition of one of these constants
  23323. in its normal terms, and @kbd{u b} expresses the definition in base
  23324. units.
  23325. Two units, @code{pi} and @code{fsc} (the fine structure constant,
  23326. approximately @i{1/137}) are dimensionless. The units simplification
  23327. commands simply treat these names as equivalent to their corresponding
  23328. values. However you can, for example, use @kbd{u c} to convert a pure
  23329. number into multiples of the fine structure constant, or @kbd{u b} to
  23330. convert this back into a pure number. (When @kbd{u c} prompts for the
  23331. ``old units,'' just enter a blank line to signify that the value
  23332. really is unitless.)
  23333. @c Describe angular units, luminosity vs. steradians problem.
  23334. @node User-Defined Units, , Predefined Units, Units
  23335. @section User-Defined Units
  23336. @noindent
  23337. Calc provides ways to get quick access to your selected ``favorite''
  23338. units, as well as ways to define your own new units.
  23339. @kindex u 0-9
  23340. @pindex calc-quick-units
  23341. @vindex Units
  23342. @cindex @code{Units} variable
  23343. @cindex Quick units
  23344. To select your favorite units, store a vector of unit names or
  23345. expressions in the Calc variable @code{Units}. The @kbd{u 1}
  23346. through @kbd{u 9} commands (@code{calc-quick-units}) provide access
  23347. to these units. If the value on the top of the stack is a plain
  23348. number (with no units attached), then @kbd{u 1} gives it the
  23349. specified units. (Basically, it multiplies the number by the
  23350. first item in the @code{Units} vector.) If the number on the
  23351. stack @emph{does} have units, then @kbd{u 1} converts that number
  23352. to the new units. For example, suppose the vector @samp{[in, ft]}
  23353. is stored in @code{Units}. Then @kbd{30 u 1} will create the
  23354. expression @samp{30 in}, and @kbd{u 2} will convert that expression
  23355. to @samp{2.5 ft}.
  23356. The @kbd{u 0} command accesses the tenth element of @code{Units}.
  23357. Only ten quick units may be defined at a time. If the @code{Units}
  23358. variable has no stored value (the default), or if its value is not
  23359. a vector, then the quick-units commands will not function. The
  23360. @kbd{s U} command is a convenient way to edit the @code{Units}
  23361. variable; @pxref{Operations on Variables}.
  23362. @kindex u d
  23363. @pindex calc-define-unit
  23364. @cindex User-defined units
  23365. The @kbd{u d} (@code{calc-define-unit}) command records the units
  23366. expression on the top of the stack as the definition for a new,
  23367. user-defined unit. For example, putting @samp{16.5 ft} on the stack and
  23368. typing @kbd{u d rod} defines the new unit @samp{rod} to be equivalent to
  23369. 16.5 feet. The unit conversion and simplification commands will now
  23370. treat @code{rod} just like any other unit of length. You will also be
  23371. prompted for an optional English description of the unit, which will
  23372. appear in the Units Table.
  23373. @kindex u u
  23374. @pindex calc-undefine-unit
  23375. The @kbd{u u} (@code{calc-undefine-unit}) command removes a user-defined
  23376. unit. It is not possible to remove one of the predefined units,
  23377. however.
  23378. If you define a unit with an existing unit name, your new definition
  23379. will replace the original definition of that unit. If the unit was a
  23380. predefined unit, the old definition will not be replaced, only
  23381. ``shadowed.'' The built-in definition will reappear if you later use
  23382. @kbd{u u} to remove the shadowing definition.
  23383. To create a new fundamental unit, use either 1 or the unit name itself
  23384. as the defining expression. Otherwise the expression can involve any
  23385. other units that you like (except for composite units like @samp{mfi}).
  23386. You can create a new composite unit with a sum of other units as the
  23387. defining expression. The next unit operation like @kbd{u c} or @kbd{u v}
  23388. will rebuild the internal unit table incorporating your modifications.
  23389. Note that erroneous definitions (such as two units defined in terms of
  23390. each other) will not be detected until the unit table is next rebuilt;
  23391. @kbd{u v} is a convenient way to force this to happen.
  23392. Temperature units are treated specially inside the Calculator; it is not
  23393. possible to create user-defined temperature units.
  23394. @kindex u p
  23395. @pindex calc-permanent-units
  23396. @cindex @file{.emacs} file, user-defined units
  23397. The @kbd{u p} (@code{calc-permanent-units}) command stores the user-defined
  23398. units in your @file{.emacs} file, so that the units will still be
  23399. available in subsequent Emacs sessions. If there was already a set of
  23400. user-defined units in your @file{.emacs} file, it is replaced by the
  23401. new set. (@xref{General Mode Commands}, for a way to tell Calc to use
  23402. a different file instead of @file{.emacs}.)
  23403. @node Store and Recall, Graphics, Units, Top
  23404. @chapter Storing and Recalling
  23405. @noindent
  23406. Calculator variables are really just Lisp variables that contain numbers
  23407. or formulas in a form that Calc can understand. The commands in this
  23408. section allow you to manipulate variables conveniently. Commands related
  23409. to variables use the @kbd{s} prefix key.
  23410. @menu
  23411. * Storing Variables::
  23412. * Recalling Variables::
  23413. * Operations on Variables::
  23414. * Let Command::
  23415. * Evaluates-To Operator::
  23416. @end menu
  23417. @node Storing Variables, Recalling Variables, Store and Recall, Store and Recall
  23418. @section Storing Variables
  23419. @noindent
  23420. @kindex s s
  23421. @pindex calc-store
  23422. @cindex Storing variables
  23423. @cindex Quick variables
  23424. @vindex q0
  23425. @vindex q9
  23426. The @kbd{s s} (@code{calc-store}) command stores the value at the top of
  23427. the stack into a specified variable. It prompts you to enter the
  23428. name of the variable. If you press a single digit, the value is stored
  23429. immediately in one of the ``quick'' variables @code{var-q0} through
  23430. @code{var-q9}. Or you can enter any variable name. The prefix @samp{var-}
  23431. is supplied for you; when a name appears in a formula (as in @samp{a+q2})
  23432. the prefix @samp{var-} is also supplied there, so normally you can simply
  23433. forget about @samp{var-} everywhere. Its only purpose is to enable you to
  23434. use Calc variables without fear of accidentally clobbering some variable in
  23435. another Emacs package. If you really want to store in an arbitrary Lisp
  23436. variable, just backspace over the @samp{var-}.
  23437. @kindex s t
  23438. @pindex calc-store-into
  23439. The @kbd{s s} command leaves the stored value on the stack. There is
  23440. also an @kbd{s t} (@code{calc-store-into}) command, which removes a
  23441. value from the stack and stores it in a variable.
  23442. If the top of stack value is an equation @samp{a = 7} or assignment
  23443. @samp{a := 7} with a variable on the lefthand side, then Calc will
  23444. assign that variable with that value by default, i.e., if you type
  23445. @kbd{s s @key{RET}} or @kbd{s t @key{RET}}. In this example, the
  23446. value 7 would be stored in the variable @samp{a}. (If you do type
  23447. a variable name at the prompt, the top-of-stack value is stored in
  23448. its entirety, even if it is an equation: @samp{s s b @key{RET}}
  23449. with @samp{a := 7} on the stack stores @samp{a := 7} in @code{b}.)
  23450. In fact, the top of stack value can be a vector of equations or
  23451. assignments with different variables on their lefthand sides; the
  23452. default will be to store all the variables with their corresponding
  23453. righthand sides simultaneously.
  23454. It is also possible to type an equation or assignment directly at
  23455. the prompt for the @kbd{s s} or @kbd{s t} command: @kbd{s s foo = 7}.
  23456. In this case the expression to the right of the @kbd{=} or @kbd{:=}
  23457. symbol is evaluated as if by the @kbd{=} command, and that value is
  23458. stored in the variable. No value is taken from the stack; @kbd{s s}
  23459. and @kbd{s t} are equivalent when used in this way.
  23460. @kindex s 0-9
  23461. @kindex t 0-9
  23462. The prefix keys @kbd{s} and @kbd{t} may be followed immediately by a
  23463. digit; @kbd{s 9} is equivalent to @kbd{s s 9}, and @kbd{t 9} is
  23464. equivalent to @kbd{s t 9}. (The @kbd{t} prefix is otherwise used
  23465. for trail and time/date commands.)
  23466. @kindex s +
  23467. @kindex s -
  23468. @ignore
  23469. @mindex @idots
  23470. @end ignore
  23471. @kindex s *
  23472. @ignore
  23473. @mindex @null
  23474. @end ignore
  23475. @kindex s /
  23476. @ignore
  23477. @mindex @null
  23478. @end ignore
  23479. @kindex s ^
  23480. @ignore
  23481. @mindex @null
  23482. @end ignore
  23483. @kindex s |
  23484. @ignore
  23485. @mindex @null
  23486. @end ignore
  23487. @kindex s n
  23488. @ignore
  23489. @mindex @null
  23490. @end ignore
  23491. @kindex s &
  23492. @ignore
  23493. @mindex @null
  23494. @end ignore
  23495. @kindex s [
  23496. @ignore
  23497. @mindex @null
  23498. @end ignore
  23499. @kindex s ]
  23500. @pindex calc-store-plus
  23501. @pindex calc-store-minus
  23502. @pindex calc-store-times
  23503. @pindex calc-store-div
  23504. @pindex calc-store-power
  23505. @pindex calc-store-concat
  23506. @pindex calc-store-neg
  23507. @pindex calc-store-inv
  23508. @pindex calc-store-decr
  23509. @pindex calc-store-incr
  23510. There are also several ``arithmetic store'' commands. For example,
  23511. @kbd{s +} removes a value from the stack and adds it to the specified
  23512. variable. The other arithmetic stores are @kbd{s -}, @kbd{s *}, @kbd{s /},
  23513. @kbd{s ^}, and @w{@kbd{s |}} (vector concatenation), plus @kbd{s n} and
  23514. @kbd{s &} which negate or invert the value in a variable, and @w{@kbd{s [}}
  23515. and @kbd{s ]} which decrease or increase a variable by one.
  23516. All the arithmetic stores accept the Inverse prefix to reverse the
  23517. order of the operands. If @cite{v} represents the contents of the
  23518. variable, and @cite{a} is the value drawn from the stack, then regular
  23519. @w{@kbd{s -}} assigns @c{$v \coloneq v - a$}
  23520. @cite{v := v - a}, but @kbd{I s -} assigns
  23521. @c{$v \coloneq a - v$}
  23522. @cite{v := a - v}. While @kbd{I s *} might seem pointless, it is
  23523. useful if matrix multiplication is involved. Actually, all the
  23524. arithmetic stores use formulas designed to behave usefully both
  23525. forwards and backwards:
  23526. @example
  23527. @group
  23528. s + v := v + a v := a + v
  23529. s - v := v - a v := a - v
  23530. s * v := v * a v := a * v
  23531. s / v := v / a v := a / v
  23532. s ^ v := v ^ a v := a ^ v
  23533. s | v := v | a v := a | v
  23534. s n v := v / (-1) v := (-1) / v
  23535. s & v := v ^ (-1) v := (-1) ^ v
  23536. s [ v := v - 1 v := 1 - v
  23537. s ] v := v - (-1) v := (-1) - v
  23538. @end group
  23539. @end example
  23540. In the last four cases, a numeric prefix argument will be used in
  23541. place of the number one. (For example, @kbd{M-2 s ]} increases
  23542. a variable by 2, and @kbd{M-2 I s ]} replaces a variable by
  23543. minus-two minus the variable.
  23544. The first six arithmetic stores can also be typed @kbd{s t +}, @kbd{s t -},
  23545. etc. The commands @kbd{s s +}, @kbd{s s -}, and so on are analogous
  23546. arithmetic stores that don't remove the value @cite{a} from the stack.
  23547. All arithmetic stores report the new value of the variable in the
  23548. Trail for your information. They signal an error if the variable
  23549. previously had no stored value. If default simplifications have been
  23550. turned off, the arithmetic stores temporarily turn them on for numeric
  23551. arguments only (i.e., they temporarily do an @kbd{m N} command).
  23552. @xref{Simplification Modes}. Large vectors put in the trail by
  23553. these commands always use abbreviated (@kbd{t .}) mode.
  23554. @kindex s m
  23555. @pindex calc-store-map
  23556. The @kbd{s m} command is a general way to adjust a variable's value
  23557. using any Calc function. It is a ``mapping'' command analogous to
  23558. @kbd{V M}, @kbd{V R}, etc. @xref{Reducing and Mapping}, to see
  23559. how to specify a function for a mapping command. Basically,
  23560. all you do is type the Calc command key that would invoke that
  23561. function normally. For example, @kbd{s m n} applies the @kbd{n}
  23562. key to negate the contents of the variable, so @kbd{s m n} is
  23563. equivalent to @kbd{s n}. Also, @kbd{s m Q} takes the square root
  23564. of the value stored in a variable, @kbd{s m v v} uses @kbd{v v} to
  23565. reverse the vector stored in the variable, and @kbd{s m H I S}
  23566. takes the hyperbolic arcsine of the variable contents.
  23567. If the mapping function takes two or more arguments, the additional
  23568. arguments are taken from the stack; the old value of the variable
  23569. is provided as the first argument. Thus @kbd{s m -} with @cite{a}
  23570. on the stack computes @cite{v - a}, just like @kbd{s -}. With the
  23571. Inverse prefix, the variable's original value becomes the @emph{last}
  23572. argument instead of the first. Thus @kbd{I s m -} is also
  23573. equivalent to @kbd{I s -}.
  23574. @kindex s x
  23575. @pindex calc-store-exchange
  23576. The @kbd{s x} (@code{calc-store-exchange}) command exchanges the value
  23577. of a variable with the value on the top of the stack. Naturally, the
  23578. variable must already have a stored value for this to work.
  23579. You can type an equation or assignment at the @kbd{s x} prompt. The
  23580. command @kbd{s x a=6} takes no values from the stack; instead, it
  23581. pushes the old value of @samp{a} on the stack and stores @samp{a = 6}.
  23582. @kindex s u
  23583. @pindex calc-unstore
  23584. @cindex Void variables
  23585. @cindex Un-storing variables
  23586. Until you store something in them, variables are ``void,'' that is, they
  23587. contain no value at all. If they appear in an algebraic formula they
  23588. will be left alone even if you press @kbd{=} (@code{calc-evaluate}).
  23589. The @kbd{s u} (@code{calc-unstore}) command returns a variable to the
  23590. void state.@refill
  23591. The only variables with predefined values are the ``special constants''
  23592. @code{pi}, @code{e}, @code{i}, @code{phi}, and @code{gamma}. You are free
  23593. to unstore these variables or to store new values into them if you like,
  23594. although some of the algebraic-manipulation functions may assume these
  23595. variables represent their standard values. Calc displays a warning if
  23596. you change the value of one of these variables, or of one of the other
  23597. special variables @code{inf}, @code{uinf}, and @code{nan} (which are
  23598. normally void).
  23599. Note that @code{var-pi} doesn't actually have 3.14159265359 stored
  23600. in it, but rather a special magic value that evaluates to @c{$\pi$}
  23601. @cite{pi}
  23602. at the current precision. Likewise @code{var-e}, @code{var-i}, and
  23603. @code{var-phi} evaluate according to the current precision or polar mode.
  23604. If you recall a value from @code{pi} and store it back, this magic
  23605. property will be lost.
  23606. @kindex s c
  23607. @pindex calc-copy-variable
  23608. The @kbd{s c} (@code{calc-copy-variable}) command copies the stored
  23609. value of one variable to another. It differs from a simple @kbd{s r}
  23610. followed by an @kbd{s t} in two important ways. First, the value never
  23611. goes on the stack and thus is never rounded, evaluated, or simplified
  23612. in any way; it is not even rounded down to the current precision.
  23613. Second, the ``magic'' contents of a variable like @code{var-e} can
  23614. be copied into another variable with this command, perhaps because
  23615. you need to unstore @code{var-e} right now but you wish to put it
  23616. back when you're done. The @kbd{s c} command is the only way to
  23617. manipulate these magic values intact.
  23618. @node Recalling Variables, Operations on Variables, Storing Variables, Store and Recall
  23619. @section Recalling Variables
  23620. @noindent
  23621. @kindex s r
  23622. @pindex calc-recall
  23623. @cindex Recalling variables
  23624. The most straightforward way to extract the stored value from a variable
  23625. is to use the @kbd{s r} (@code{calc-recall}) command. This command prompts
  23626. for a variable name (similarly to @code{calc-store}), looks up the value
  23627. of the specified variable, and pushes that value onto the stack. It is
  23628. an error to try to recall a void variable.
  23629. It is also possible to recall the value from a variable by evaluating a
  23630. formula containing that variable. For example, @kbd{' a @key{RET} =} is
  23631. the same as @kbd{s r a @key{RET}} except that if the variable is void, the
  23632. former will simply leave the formula @samp{a} on the stack whereas the
  23633. latter will produce an error message.
  23634. @kindex r 0-9
  23635. The @kbd{r} prefix may be followed by a digit, so that @kbd{r 9} is
  23636. equivalent to @kbd{s r 9}. (The @kbd{r} prefix is otherwise unused
  23637. in the current version of Calc.)
  23638. @node Operations on Variables, Let Command, Recalling Variables, Store and Recall
  23639. @section Other Operations on Variables
  23640. @noindent
  23641. @kindex s e
  23642. @pindex calc-edit-variable
  23643. The @kbd{s e} (@code{calc-edit-variable}) command edits the stored
  23644. value of a variable without ever putting that value on the stack
  23645. or simplifying or evaluating the value. It prompts for the name of
  23646. the variable to edit. If the variable has no stored value, the
  23647. editing buffer will start out empty. If the editing buffer is
  23648. empty when you press @kbd{M-# M-#} to finish, the variable will
  23649. be made void. @xref{Editing Stack Entries}, for a general
  23650. description of editing.
  23651. The @kbd{s e} command is especially useful for creating and editing
  23652. rewrite rules which are stored in variables. Sometimes these rules
  23653. contain formulas which must not be evaluated until the rules are
  23654. actually used. (For example, they may refer to @samp{deriv(x,y)},
  23655. where @code{x} will someday become some expression involving @code{y};
  23656. if you let Calc evaluate the rule while you are defining it, Calc will
  23657. replace @samp{deriv(x,y)} with 0 because the formula @code{x} does
  23658. not itself refer to @code{y}.) By contrast, recalling the variable,
  23659. editing with @kbd{`}, and storing will evaluate the variable's value
  23660. as a side effect of putting the value on the stack.
  23661. @kindex s A
  23662. @kindex s D
  23663. @ignore
  23664. @mindex @idots
  23665. @end ignore
  23666. @kindex s E
  23667. @ignore
  23668. @mindex @null
  23669. @end ignore
  23670. @kindex s F
  23671. @ignore
  23672. @mindex @null
  23673. @end ignore
  23674. @kindex s G
  23675. @ignore
  23676. @mindex @null
  23677. @end ignore
  23678. @kindex s H
  23679. @ignore
  23680. @mindex @null
  23681. @end ignore
  23682. @kindex s I
  23683. @ignore
  23684. @mindex @null
  23685. @end ignore
  23686. @kindex s L
  23687. @ignore
  23688. @mindex @null
  23689. @end ignore
  23690. @kindex s P
  23691. @ignore
  23692. @mindex @null
  23693. @end ignore
  23694. @kindex s R
  23695. @ignore
  23696. @mindex @null
  23697. @end ignore
  23698. @kindex s T
  23699. @ignore
  23700. @mindex @null
  23701. @end ignore
  23702. @kindex s U
  23703. @ignore
  23704. @mindex @null
  23705. @end ignore
  23706. @kindex s X
  23707. @pindex calc-store-AlgSimpRules
  23708. @pindex calc-store-Decls
  23709. @pindex calc-store-EvalRules
  23710. @pindex calc-store-FitRules
  23711. @pindex calc-store-GenCount
  23712. @pindex calc-store-Holidays
  23713. @pindex calc-store-IntegLimit
  23714. @pindex calc-store-LineStyles
  23715. @pindex calc-store-PointStyles
  23716. @pindex calc-store-PlotRejects
  23717. @pindex calc-store-TimeZone
  23718. @pindex calc-store-Units
  23719. @pindex calc-store-ExtSimpRules
  23720. There are several special-purpose variable-editing commands that
  23721. use the @kbd{s} prefix followed by a shifted letter:
  23722. @table @kbd
  23723. @item s A
  23724. Edit @code{AlgSimpRules}. @xref{Algebraic Simplifications}.
  23725. @item s D
  23726. Edit @code{Decls}. @xref{Declarations}.
  23727. @item s E
  23728. Edit @code{EvalRules}. @xref{Default Simplifications}.
  23729. @item s F
  23730. Edit @code{FitRules}. @xref{Curve Fitting}.
  23731. @item s G
  23732. Edit @code{GenCount}. @xref{Solving Equations}.
  23733. @item s H
  23734. Edit @code{Holidays}. @xref{Business Days}.
  23735. @item s I
  23736. Edit @code{IntegLimit}. @xref{Calculus}.
  23737. @item s L
  23738. Edit @code{LineStyles}. @xref{Graphics}.
  23739. @item s P
  23740. Edit @code{PointStyles}. @xref{Graphics}.
  23741. @item s R
  23742. Edit @code{PlotRejects}. @xref{Graphics}.
  23743. @item s T
  23744. Edit @code{TimeZone}. @xref{Time Zones}.
  23745. @item s U
  23746. Edit @code{Units}. @xref{User-Defined Units}.
  23747. @item s X
  23748. Edit @code{ExtSimpRules}. @xref{Unsafe Simplifications}.
  23749. @end table
  23750. These commands are just versions of @kbd{s e} that use fixed variable
  23751. names rather than prompting for the variable name.
  23752. @kindex s p
  23753. @pindex calc-permanent-variable
  23754. @cindex Storing variables
  23755. @cindex Permanent variables
  23756. @cindex @file{.emacs} file, veriables
  23757. The @kbd{s p} (@code{calc-permanent-variable}) command saves a
  23758. variable's value permanently in your @file{.emacs} file, so that its
  23759. value will still be available in future Emacs sessions. You can
  23760. re-execute @w{@kbd{s p}} later on to update the saved value, but the
  23761. only way to remove a saved variable is to edit your @file{.emacs} file
  23762. by hand. (@xref{General Mode Commands}, for a way to tell Calc to
  23763. use a different file instead of @file{.emacs}.)
  23764. If you do not specify the name of a variable to save (i.e.,
  23765. @kbd{s p @key{RET}}), all @samp{var-} variables with defined values
  23766. are saved except for the special constants @code{pi}, @code{e},
  23767. @code{i}, @code{phi}, and @code{gamma}; the variables @code{TimeZone}
  23768. and @code{PlotRejects};
  23769. @code{FitRules}, @code{DistribRules}, and other built-in rewrite
  23770. rules; and @code{PlotData@var{n}} variables generated
  23771. by the graphics commands. (You can still save these variables by
  23772. explicitly naming them in an @kbd{s p} command.)@refill
  23773. @kindex s i
  23774. @pindex calc-insert-variables
  23775. The @kbd{s i} (@code{calc-insert-variables}) command writes
  23776. the values of all @samp{var-} variables into a specified buffer.
  23777. The variables are written in the form of Lisp @code{setq} commands
  23778. which store the values in string form. You can place these commands
  23779. in your @file{.emacs} buffer if you wish, though in this case it
  23780. would be easier to use @kbd{s p @key{RET}}. (Note that @kbd{s i}
  23781. omits the same set of variables as @w{@kbd{s p @key{RET}}}; the difference
  23782. is that @kbd{s i} will store the variables in any buffer, and it also
  23783. stores in a more human-readable format.)
  23784. @node Let Command, Evaluates-To Operator, Operations on Variables, Store and Recall
  23785. @section The Let Command
  23786. @noindent
  23787. @kindex s l
  23788. @pindex calc-let
  23789. @cindex Variables, temporary assignment
  23790. @cindex Temporary assignment to variables
  23791. If you have an expression like @samp{a+b^2} on the stack and you wish to
  23792. compute its value where @cite{b=3}, you can simply store 3 in @cite{b} and
  23793. then press @kbd{=} to reevaluate the formula. This has the side-effect
  23794. of leaving the stored value of 3 in @cite{b} for future operations.
  23795. The @kbd{s l} (@code{calc-let}) command evaluates a formula under a
  23796. @emph{temporary} assignment of a variable. It stores the value on the
  23797. top of the stack into the specified variable, then evaluates the
  23798. second-to-top stack entry, then restores the original value (or lack of one)
  23799. in the variable. Thus after @kbd{'@w{ }a+b^2 @key{RET} 3 s l b @key{RET}},
  23800. the stack will contain the formula @samp{a + 9}. The subsequent command
  23801. @kbd{@w{5 s l a} @key{RET}} will replace this formula with the number 14.
  23802. The variables @samp{a} and @samp{b} are not permanently affected in any way
  23803. by these commands.
  23804. The value on the top of the stack may be an equation or assignment, or
  23805. a vector of equations or assignments, in which case the default will be
  23806. analogous to the case of @kbd{s t @key{RET}}. @xref{Storing Variables}.
  23807. Also, you can answer the variable-name prompt with an equation or
  23808. assignment: @kbd{s l b=3 @key{RET}} is the same as storing 3 on the stack
  23809. and typing @kbd{s l b @key{RET}}.
  23810. The @kbd{a b} (@code{calc-substitute}) command is another way to substitute
  23811. a variable with a value in a formula. It does an actual substitution
  23812. rather than temporarily assigning the variable and evaluating. For
  23813. example, letting @cite{n=2} in @samp{f(n pi)} with @kbd{a b} will
  23814. produce @samp{f(2 pi)}, whereas @kbd{s l} would give @samp{f(6.28)}
  23815. since the evaluation step will also evaluate @code{pi}.
  23816. @node Evaluates-To Operator, , Let Command, Store and Recall
  23817. @section The Evaluates-To Operator
  23818. @noindent
  23819. @tindex evalto
  23820. @tindex =>
  23821. @cindex Evaluates-to operator
  23822. @cindex @samp{=>} operator
  23823. The special algebraic symbol @samp{=>} is known as the @dfn{evaluates-to
  23824. operator}. (It will show up as an @code{evalto} function call in
  23825. other language modes like Pascal and @TeX{}.) This is a binary
  23826. operator, that is, it has a lefthand and a righthand argument,
  23827. although it can be entered with the righthand argument omitted.
  23828. A formula like @samp{@var{a} => @var{b}} is evaluated by Calc as
  23829. follows: First, @var{a} is not simplified or modified in any
  23830. way. The previous value of argument @var{b} is thrown away; the
  23831. formula @var{a} is then copied and evaluated as if by the @kbd{=}
  23832. command according to all current modes and stored variable values,
  23833. and the result is installed as the new value of @var{b}.
  23834. For example, suppose you enter the algebraic formula @samp{2 + 3 => 17}.
  23835. The number 17 is ignored, and the lefthand argument is left in its
  23836. unevaluated form; the result is the formula @samp{2 + 3 => 5}.
  23837. @kindex s =
  23838. @pindex calc-evalto
  23839. You can enter an @samp{=>} formula either directly using algebraic
  23840. entry (in which case the righthand side may be omitted since it is
  23841. going to be replaced right away anyhow), or by using the @kbd{s =}
  23842. (@code{calc-evalto}) command, which takes @var{a} from the stack
  23843. and replaces it with @samp{@var{a} => @var{b}}.
  23844. Calc keeps track of all @samp{=>} operators on the stack, and
  23845. recomputes them whenever anything changes that might affect their
  23846. values, i.e., a mode setting or variable value. This occurs only
  23847. if the @samp{=>} operator is at the top level of the formula, or
  23848. if it is part of a top-level vector. In other words, pushing
  23849. @samp{2 + (a => 17)} will change the 17 to the actual value of
  23850. @samp{a} when you enter the formula, but the result will not be
  23851. dynamically updated when @samp{a} is changed later because the
  23852. @samp{=>} operator is buried inside a sum. However, a vector
  23853. of @samp{=>} operators will be recomputed, since it is convenient
  23854. to push a vector like @samp{[a =>, b =>, c =>]} on the stack to
  23855. make a concise display of all the variables in your problem.
  23856. (Another way to do this would be to use @samp{[a, b, c] =>},
  23857. which provides a slightly different format of display. You
  23858. can use whichever you find easiest to read.)
  23859. @kindex m C
  23860. @pindex calc-auto-recompute
  23861. The @kbd{m C} (@code{calc-auto-recompute}) command allows you to
  23862. turn this automatic recomputation on or off. If you turn
  23863. recomputation off, you must explicitly recompute an @samp{=>}
  23864. operator on the stack in one of the usual ways, such as by
  23865. pressing @kbd{=}. Turning recomputation off temporarily can save
  23866. a lot of time if you will be changing several modes or variables
  23867. before you look at the @samp{=>} entries again.
  23868. Most commands are not especially useful with @samp{=>} operators
  23869. as arguments. For example, given @samp{x + 2 => 17}, it won't
  23870. work to type @kbd{1 +} to get @samp{x + 3 => 18}. If you want
  23871. to operate on the lefthand side of the @samp{=>} operator on
  23872. the top of the stack, type @kbd{j 1} (that's the digit ``one'')
  23873. to select the lefthand side, execute your commands, then type
  23874. @kbd{j u} to unselect.
  23875. All current modes apply when an @samp{=>} operator is computed,
  23876. including the current simplification mode. Recall that the
  23877. formula @samp{x + y + x} is not handled by Calc's default
  23878. simplifications, but the @kbd{a s} command will reduce it to
  23879. the simpler form @samp{y + 2 x}. You can also type @kbd{m A}
  23880. to enable an algebraic-simplification mode in which the
  23881. equivalent of @kbd{a s} is used on all of Calc's results.
  23882. If you enter @samp{x + y + x =>} normally, the result will
  23883. be @samp{x + y + x => x + y + x}. If you change to
  23884. algebraic-simplification mode, the result will be
  23885. @samp{x + y + x => y + 2 x}. However, just pressing @kbd{a s}
  23886. once will have no effect on @samp{x + y + x => x + y + x},
  23887. because the righthand side depends only on the lefthand side
  23888. and the current mode settings, and the lefthand side is not
  23889. affected by commands like @kbd{a s}.
  23890. The ``let'' command (@kbd{s l}) has an interesting interaction
  23891. with the @samp{=>} operator. The @kbd{s l} command evaluates the
  23892. second-to-top stack entry with the top stack entry supplying
  23893. a temporary value for a given variable. As you might expect,
  23894. if that stack entry is an @samp{=>} operator its righthand
  23895. side will temporarily show this value for the variable. In
  23896. fact, all @samp{=>}s on the stack will be updated if they refer
  23897. to that variable. But this change is temporary in the sense
  23898. that the next command that causes Calc to look at those stack
  23899. entries will make them revert to the old variable value.
  23900. @smallexample
  23901. @group
  23902. 2: a => a 2: a => 17 2: a => a
  23903. 1: a + 1 => a + 1 1: a + 1 => 18 1: a + 1 => a + 1
  23904. . . .
  23905. 17 s l a @key{RET} p 8 @key{RET}
  23906. @end group
  23907. @end smallexample
  23908. Here the @kbd{p 8} command changes the current precision,
  23909. thus causing the @samp{=>} forms to be recomputed after the
  23910. influence of the ``let'' is gone. The @kbd{d @key{SPC}} command
  23911. (@code{calc-refresh}) is a handy way to force the @samp{=>}
  23912. operators on the stack to be recomputed without any other
  23913. side effects.
  23914. @kindex s :
  23915. @pindex calc-assign
  23916. @tindex assign
  23917. @tindex :=
  23918. Embedded Mode also uses @samp{=>} operators. In embedded mode,
  23919. the lefthand side of an @samp{=>} operator can refer to variables
  23920. assigned elsewhere in the file by @samp{:=} operators. The
  23921. assignment operator @samp{a := 17} does not actually do anything
  23922. by itself. But Embedded Mode recognizes it and marks it as a sort
  23923. of file-local definition of the variable. You can enter @samp{:=}
  23924. operators in algebraic mode, or by using the @kbd{s :}
  23925. (@code{calc-assign}) [@code{assign}] command which takes a variable
  23926. and value from the stack and replaces them with an assignment.
  23927. @xref{TeX Language Mode}, for the way @samp{=>} appears in
  23928. @TeX{} language output. The @dfn{eqn} mode gives similar
  23929. treatment to @samp{=>}.
  23930. @node Graphics, Kill and Yank, Store and Recall, Top
  23931. @chapter Graphics
  23932. @noindent
  23933. The commands for graphing data begin with the @kbd{g} prefix key. Calc
  23934. uses GNUPLOT 2.0 or 3.0 to do graphics. These commands will only work
  23935. if GNUPLOT is available on your system. (While GNUPLOT sounds like
  23936. a relative of GNU Emacs, it is actually completely unrelated.
  23937. However, it is free software and can be obtained from the Free
  23938. Software Foundation's machine @samp{prep.ai.mit.edu}.)
  23939. @vindex calc-gnuplot-name
  23940. If you have GNUPLOT installed on your system but Calc is unable to
  23941. find it, you may need to set the @code{calc-gnuplot-name} variable
  23942. in your @file{.emacs} file. You may also need to set some Lisp
  23943. variables to show Calc how to run GNUPLOT on your system; these
  23944. are described under @kbd{g D} and @kbd{g O} below. If you are
  23945. using the X window system, Calc will configure GNUPLOT for you
  23946. automatically. If you have GNUPLOT 3.0 and you are not using X,
  23947. Calc will configure GNUPLOT to display graphs using simple character
  23948. graphics that will work on any terminal.
  23949. @menu
  23950. * Basic Graphics::
  23951. * Three Dimensional Graphics::
  23952. * Managing Curves::
  23953. * Graphics Options::
  23954. * Devices::
  23955. @end menu
  23956. @node Basic Graphics, Three Dimensional Graphics, Graphics, Graphics
  23957. @section Basic Graphics
  23958. @noindent
  23959. @kindex g f
  23960. @pindex calc-graph-fast
  23961. The easiest graphics command is @kbd{g f} (@code{calc-graph-fast}).
  23962. This command takes two vectors of equal length from the stack.
  23963. The vector at the top of the stack represents the ``y'' values of
  23964. the various data points. The vector in the second-to-top position
  23965. represents the corresponding ``x'' values. This command runs
  23966. GNUPLOT (if it has not already been started by previous graphing
  23967. commands) and displays the set of data points. The points will
  23968. be connected by lines, and there will also be some kind of symbol
  23969. to indicate the points themselves.
  23970. The ``x'' entry may instead be an interval form, in which case suitable
  23971. ``x'' values are interpolated between the minimum and maximum values of
  23972. the interval (whether the interval is open or closed is ignored).
  23973. The ``x'' entry may also be a number, in which case Calc uses the
  23974. sequence of ``x'' values @cite{x}, @cite{x+1}, @cite{x+2}, etc.
  23975. (Generally the number 0 or 1 would be used for @cite{x} in this case.)
  23976. The ``y'' entry may be any formula instead of a vector. Calc effectively
  23977. uses @kbd{N} (@code{calc-eval-num}) to evaluate variables in the formula;
  23978. the result of this must be a formula in a single (unassigned) variable.
  23979. The formula is plotted with this variable taking on the various ``x''
  23980. values. Graphs of formulas by default use lines without symbols at the
  23981. computed data points. Note that if neither ``x'' nor ``y'' is a vector,
  23982. Calc guesses at a reasonable number of data points to use. See the
  23983. @kbd{g N} command below. (The ``x'' values must be either a vector
  23984. or an interval if ``y'' is a formula.)
  23985. @ignore
  23986. @starindex
  23987. @end ignore
  23988. @tindex xy
  23989. If ``y'' is (or evaluates to) a formula of the form
  23990. @samp{xy(@var{x}, @var{y})} then the result is a
  23991. parametric plot. The two arguments of the fictitious @code{xy} function
  23992. are used as the ``x'' and ``y'' coordinates of the curve, respectively.
  23993. In this case the ``x'' vector or interval you specified is not directly
  23994. visible in the graph. For example, if ``x'' is the interval @samp{[0..360]}
  23995. and ``y'' is the formula @samp{xy(sin(t), cos(t))}, the resulting graph
  23996. will be a circle.@refill
  23997. Also, ``x'' and ``y'' may each be variable names, in which case Calc
  23998. looks for suitable vectors, intervals, or formulas stored in those
  23999. variables.
  24000. The ``x'' and ``y'' values for the data points (as pulled from the vectors,
  24001. calculated from the formulas, or interpolated from the intervals) should
  24002. be real numbers (integers, fractions, or floats). If either the ``x''
  24003. value or the ``y'' value of a given data point is not a real number, that
  24004. data point will be omitted from the graph. The points on either side
  24005. of the invalid point will @emph{not} be connected by a line.
  24006. See the documentation for @kbd{g a} below for a description of the way
  24007. numeric prefix arguments affect @kbd{g f}.
  24008. @cindex @code{PlotRejects} variable
  24009. @vindex PlotRejects
  24010. If you store an empty vector in the variable @code{PlotRejects}
  24011. (i.e., @kbd{[ ] s t PlotRejects}), Calc will append information to
  24012. this vector for every data point which was rejected because its
  24013. ``x'' or ``y'' values were not real numbers. The result will be
  24014. a matrix where each row holds the curve number, data point number,
  24015. ``x'' value, and ``y'' value for a rejected data point.
  24016. @xref{Evaluates-To Operator}, for a handy way to keep tabs on the
  24017. current value of @code{PlotRejects}. @xref{Operations on Variables},
  24018. for the @kbd{s R} command which is another easy way to examine
  24019. @code{PlotRejects}.
  24020. @kindex g c
  24021. @pindex calc-graph-clear
  24022. To clear the graphics display, type @kbd{g c} (@code{calc-graph-clear}).
  24023. If the GNUPLOT output device is an X window, the window will go away.
  24024. Effects on other kinds of output devices will vary. You don't need
  24025. to use @kbd{g c} if you don't want to---if you give another @kbd{g f}
  24026. or @kbd{g p} command later on, it will reuse the existing graphics
  24027. window if there is one.
  24028. @node Three Dimensional Graphics, Managing Curves, Basic Graphics, Graphics
  24029. @section Three-Dimensional Graphics
  24030. @kindex g F
  24031. @pindex calc-graph-fast-3d
  24032. The @kbd{g F} (@code{calc-graph-fast-3d}) command makes a three-dimensional
  24033. graph. It works only if you have GNUPLOT 3.0 or later; with GNUPLOT 2.0,
  24034. you will see a GNUPLOT error message if you try this command.
  24035. The @kbd{g F} command takes three values from the stack, called ``x'',
  24036. ``y'', and ``z'', respectively. As was the case for 2D graphs, there
  24037. are several options for these values.
  24038. In the first case, ``x'' and ``y'' are each vectors (not necessarily of
  24039. the same length); either or both may instead be interval forms. The
  24040. ``z'' value must be a matrix with the same number of rows as elements
  24041. in ``x'', and the same number of columns as elements in ``y''. The
  24042. result is a surface plot where @c{$z_{ij}$}
  24043. @cite{z_ij} is the height of the point
  24044. at coordinate @cite{(x_i, y_j)} on the surface. The 3D graph will
  24045. be displayed from a certain default viewpoint; you can change this
  24046. viewpoint by adding a @samp{set view} to the @samp{*Gnuplot Commands*}
  24047. buffer as described later. See the GNUPLOT 3.0 documentation for a
  24048. description of the @samp{set view} command.
  24049. Each point in the matrix will be displayed as a dot in the graph,
  24050. and these points will be connected by a grid of lines (@dfn{isolines}).
  24051. In the second case, ``x'', ``y'', and ``z'' are all vectors of equal
  24052. length. The resulting graph displays a 3D line instead of a surface,
  24053. where the coordinates of points along the line are successive triplets
  24054. of values from the input vectors.
  24055. In the third case, ``x'' and ``y'' are vectors or interval forms, and
  24056. ``z'' is any formula involving two variables (not counting variables
  24057. with assigned values). These variables are sorted into alphabetical
  24058. order; the first takes on values from ``x'' and the second takes on
  24059. values from ``y'' to form a matrix of results that are graphed as a
  24060. 3D surface.
  24061. @ignore
  24062. @starindex
  24063. @end ignore
  24064. @tindex xyz
  24065. If the ``z'' formula evaluates to a call to the fictitious function
  24066. @samp{xyz(@var{x}, @var{y}, @var{z})}, then the result is a
  24067. ``parametric surface.'' In this case, the axes of the graph are
  24068. taken from the @var{x} and @var{y} values in these calls, and the
  24069. ``x'' and ``y'' values from the input vectors or intervals are used only
  24070. to specify the range of inputs to the formula. For example, plotting
  24071. @samp{[0..360], [0..180], xyz(sin(x)*sin(y), cos(x)*sin(y), cos(y))}
  24072. will draw a sphere. (Since the default resolution for 3D plots is
  24073. 5 steps in each of ``x'' and ``y'', this will draw a very crude
  24074. sphere. You could use the @kbd{g N} command, described below, to
  24075. increase this resolution, or specify the ``x'' and ``y'' values as
  24076. vectors with more than 5 elements.
  24077. It is also possible to have a function in a regular @kbd{g f} plot
  24078. evaluate to an @code{xyz} call. Since @kbd{g f} plots a line, not
  24079. a surface, the result will be a 3D parametric line. For example,
  24080. @samp{[[0..720], xyz(sin(x), cos(x), x)]} will plot two turns of a
  24081. helix (a three-dimensional spiral).
  24082. As for @kbd{g f}, each of ``x'', ``y'', and ``z'' may instead be
  24083. variables containing the relevant data.
  24084. @node Managing Curves, Graphics Options, Three Dimensional Graphics, Graphics
  24085. @section Managing Curves
  24086. @noindent
  24087. The @kbd{g f} command is really shorthand for the following commands:
  24088. @kbd{C-u g d g a g p}. Likewise, @w{@kbd{g F}} is shorthand for
  24089. @kbd{C-u g d g A g p}. You can gain more control over your graph
  24090. by using these commands directly.
  24091. @kindex g a
  24092. @pindex calc-graph-add
  24093. The @kbd{g a} (@code{calc-graph-add}) command adds the ``curve''
  24094. represented by the two values on the top of the stack to the current
  24095. graph. You can have any number of curves in the same graph. When
  24096. you give the @kbd{g p} command, all the curves will be drawn superimposed
  24097. on the same axes.
  24098. The @kbd{g a} command (and many others that affect the current graph)
  24099. will cause a special buffer, @samp{*Gnuplot Commands*}, to be displayed
  24100. in another window. This buffer is a template of the commands that will
  24101. be sent to GNUPLOT when it is time to draw the graph. The first
  24102. @kbd{g a} command adds a @code{plot} command to this buffer. Succeeding
  24103. @kbd{g a} commands add extra curves onto that @code{plot} command.
  24104. Other graph-related commands put other GNUPLOT commands into this
  24105. buffer. In normal usage you never need to work with this buffer
  24106. directly, but you can if you wish. The only constraint is that there
  24107. must be only one @code{plot} command, and it must be the last command
  24108. in the buffer. If you want to save and later restore a complete graph
  24109. configuration, you can use regular Emacs commands to save and restore
  24110. the contents of the @samp{*Gnuplot Commands*} buffer.
  24111. @vindex PlotData1
  24112. @vindex PlotData2
  24113. If the values on the stack are not variable names, @kbd{g a} will invent
  24114. variable names for them (of the form @samp{PlotData@var{n}}) and store
  24115. the values in those variables. The ``x'' and ``y'' variables are what
  24116. go into the @code{plot} command in the template. If you add a curve
  24117. that uses a certain variable and then later change that variable, you
  24118. can replot the graph without having to delete and re-add the curve.
  24119. That's because the variable name, not the vector, interval or formula
  24120. itself, is what was added by @kbd{g a}.
  24121. A numeric prefix argument on @kbd{g a} or @kbd{g f} changes the way
  24122. stack entries are interpreted as curves. With a positive prefix
  24123. argument @cite{n}, the top @cite{n} stack entries are ``y'' values
  24124. for @cite{n} different curves which share a common ``x'' value in
  24125. the @cite{n+1}st stack entry. (Thus @kbd{g a} with no prefix
  24126. argument is equivalent to @kbd{C-u 1 g a}.)
  24127. A prefix of zero or plain @kbd{C-u} means to take two stack entries,
  24128. ``x'' and ``y'' as usual, but to interpret ``y'' as a vector of
  24129. ``y'' values for several curves that share a common ``x''.
  24130. A negative prefix argument tells Calc to read @cite{n} vectors from
  24131. the stack; each vector @cite{[x, y]} describes an independent curve.
  24132. This is the only form of @kbd{g a} that creates several curves at once
  24133. that don't have common ``x'' values. (Of course, the range of ``x''
  24134. values covered by all the curves ought to be roughly the same if
  24135. they are to look nice on the same graph.)
  24136. For example, to plot @c{$\sin n x$}
  24137. @cite{sin(n x)} for integers @cite{n}
  24138. from 1 to 5, you could use @kbd{v x} to create a vector of integers
  24139. (@cite{n}), then @kbd{V M '} or @kbd{V M $} to map @samp{sin(n x)}
  24140. across this vector. The resulting vector of formulas is suitable
  24141. for use as the ``y'' argument to a @kbd{C-u g a} or @kbd{C-u g f}
  24142. command.
  24143. @kindex g A
  24144. @pindex calc-graph-add-3d
  24145. The @kbd{g A} (@code{calc-graph-add-3d}) command adds a 3D curve
  24146. to the graph. It is not legal to intermix 2D and 3D curves in a
  24147. single graph. This command takes three arguments, ``x'', ``y'',
  24148. and ``z'', from the stack. With a positive prefix @cite{n}, it
  24149. takes @cite{n+2} arguments (common ``x'' and ``y'', plus @cite{n}
  24150. separate ``z''s). With a zero prefix, it takes three stack entries
  24151. but the ``z'' entry is a vector of curve values. With a negative
  24152. prefix @cite{-n}, it takes @cite{n} vectors of the form @cite{[x, y, z]}.
  24153. The @kbd{g A} command works by adding a @code{splot} (surface-plot)
  24154. command to the @samp{*Gnuplot Commands*} buffer.
  24155. (Although @kbd{g a} adds a 2D @code{plot} command to the
  24156. @samp{*Gnuplot Commands*} buffer, Calc changes this to @code{splot}
  24157. before sending it to GNUPLOT if it notices that the data points are
  24158. evaluating to @code{xyz} calls. It will not work to mix 2D and 3D
  24159. @kbd{g a} curves in a single graph, although Calc does not currently
  24160. check for this.)
  24161. @kindex g d
  24162. @pindex calc-graph-delete
  24163. The @kbd{g d} (@code{calc-graph-delete}) command deletes the most
  24164. recently added curve from the graph. It has no effect if there are
  24165. no curves in the graph. With a numeric prefix argument of any kind,
  24166. it deletes all of the curves from the graph.
  24167. @kindex g H
  24168. @pindex calc-graph-hide
  24169. The @kbd{g H} (@code{calc-graph-hide}) command ``hides'' or ``unhides''
  24170. the most recently added curve. A hidden curve will not appear in
  24171. the actual plot, but information about it such as its name and line and
  24172. point styles will be retained.
  24173. @kindex g j
  24174. @pindex calc-graph-juggle
  24175. The @kbd{g j} (@code{calc-graph-juggle}) command moves the curve
  24176. at the end of the list (the ``most recently added curve'') to the
  24177. front of the list. The next-most-recent curve is thus exposed for
  24178. @w{@kbd{g d}} or similar commands to use. With @kbd{g j} you can work
  24179. with any curve in the graph even though curve-related commands only
  24180. affect the last curve in the list.
  24181. @kindex g p
  24182. @pindex calc-graph-plot
  24183. The @kbd{g p} (@code{calc-graph-plot}) command uses GNUPLOT to draw
  24184. the graph described in the @samp{*Gnuplot Commands*} buffer. Any
  24185. GNUPLOT parameters which are not defined by commands in this buffer
  24186. are reset to their default values. The variables named in the @code{plot}
  24187. command are written to a temporary data file and the variable names
  24188. are then replaced by the file name in the template. The resulting
  24189. plotting commands are fed to the GNUPLOT program. See the documentation
  24190. for the GNUPLOT program for more specific information. All temporary
  24191. files are removed when Emacs or GNUPLOT exits.
  24192. If you give a formula for ``y'', Calc will remember all the values that
  24193. it calculates for the formula so that later plots can reuse these values.
  24194. Calc throws out these saved values when you change any circumstances
  24195. that may affect the data, such as switching from Degrees to Radians
  24196. mode, or changing the value of a parameter in the formula. You can
  24197. force Calc to recompute the data from scratch by giving a negative
  24198. numeric prefix argument to @kbd{g p}.
  24199. Calc uses a fairly rough step size when graphing formulas over intervals.
  24200. This is to ensure quick response. You can ``refine'' a plot by giving
  24201. a positive numeric prefix argument to @kbd{g p}. Calc goes through
  24202. the data points it has computed and saved from previous plots of the
  24203. function, and computes and inserts a new data point midway between
  24204. each of the existing points. You can refine a plot any number of times,
  24205. but beware that the amount of calculation involved doubles each time.
  24206. Calc does not remember computed values for 3D graphs. This means the
  24207. numerix prefix argument, if any, to @kbd{g p} is effectively ignored if
  24208. the current graph is three-dimensional.
  24209. @kindex g P
  24210. @pindex calc-graph-print
  24211. The @kbd{g P} (@code{calc-graph-print}) command is like @kbd{g p},
  24212. except that it sends the output to a printer instead of to the
  24213. screen. More precisely, @kbd{g p} looks for @samp{set terminal}
  24214. or @samp{set output} commands in the @samp{*Gnuplot Commands*} buffer;
  24215. lacking these it uses the default settings. However, @kbd{g P}
  24216. ignores @samp{set terminal} and @samp{set output} commands and
  24217. uses a different set of default values. All of these values are
  24218. controlled by the @kbd{g D} and @kbd{g O} commands discussed below.
  24219. Provided everything is set up properly, @kbd{g p} will plot to
  24220. the screen unless you have specified otherwise and @kbd{g P} will
  24221. always plot to the printer.
  24222. @node Graphics Options, Devices, Managing Curves, Graphics
  24223. @section Graphics Options
  24224. @noindent
  24225. @kindex g g
  24226. @pindex calc-graph-grid
  24227. The @kbd{g g} (@code{calc-graph-grid}) command turns the ``grid''
  24228. on and off. It is off by default; tick marks appear only at the
  24229. edges of the graph. With the grid turned on, dotted lines appear
  24230. across the graph at each tick mark. Note that this command only
  24231. changes the setting in @samp{*Gnuplot Commands*}; to see the effects
  24232. of the change you must give another @kbd{g p} command.
  24233. @kindex g b
  24234. @pindex calc-graph-border
  24235. The @kbd{g b} (@code{calc-graph-border}) command turns the border
  24236. (the box that surrounds the graph) on and off. It is on by default.
  24237. This command will only work with GNUPLOT 3.0 and later versions.
  24238. @kindex g k
  24239. @pindex calc-graph-key
  24240. The @kbd{g k} (@code{calc-graph-key}) command turns the ``key''
  24241. on and off. The key is a chart in the corner of the graph that
  24242. shows the correspondence between curves and line styles. It is
  24243. off by default, and is only really useful if you have several
  24244. curves on the same graph.
  24245. @kindex g N
  24246. @pindex calc-graph-num-points
  24247. The @kbd{g N} (@code{calc-graph-num-points}) command allows you
  24248. to select the number of data points in the graph. This only affects
  24249. curves where neither ``x'' nor ``y'' is specified as a vector.
  24250. Enter a blank line to revert to the default value (initially 15).
  24251. With no prefix argument, this command affects only the current graph.
  24252. With a positive prefix argument this command changes or, if you enter
  24253. a blank line, displays the default number of points used for all
  24254. graphs created by @kbd{g a} that don't specify the resolution explicitly.
  24255. With a negative prefix argument, this command changes or displays
  24256. the default value (initially 5) used for 3D graphs created by @kbd{g A}.
  24257. Note that a 3D setting of 5 means that a total of @cite{5^2 = 25} points
  24258. will be computed for the surface.
  24259. Data values in the graph of a function are normally computed to a
  24260. precision of five digits, regardless of the current precision at the
  24261. time. This is usually more than adequate, but there are cases where
  24262. it will not be. For example, plotting @cite{1 + x} with @cite{x} in the
  24263. interval @samp{[0 ..@: 1e-6]} will round all the data points down
  24264. to 1.0! Putting the command @samp{set precision @var{n}} in the
  24265. @samp{*Gnuplot Commands*} buffer will cause the data to be computed
  24266. at precision @var{n} instead of 5. Since this is such a rare case,
  24267. there is no keystroke-based command to set the precision.
  24268. @kindex g h
  24269. @pindex calc-graph-header
  24270. The @kbd{g h} (@code{calc-graph-header}) command sets the title
  24271. for the graph. This will show up centered above the graph.
  24272. The default title is blank (no title).
  24273. @kindex g n
  24274. @pindex calc-graph-name
  24275. The @kbd{g n} (@code{calc-graph-name}) command sets the title of an
  24276. individual curve. Like the other curve-manipulating commands, it
  24277. affects the most recently added curve, i.e., the last curve on the
  24278. list in the @samp{*Gnuplot Commands*} buffer. To set the title of
  24279. the other curves you must first juggle them to the end of the list
  24280. with @kbd{g j}, or edit the @samp{*Gnuplot Commands*} buffer by hand.
  24281. Curve titles appear in the key; if the key is turned off they are
  24282. not used.
  24283. @kindex g t
  24284. @kindex g T
  24285. @pindex calc-graph-title-x
  24286. @pindex calc-graph-title-y
  24287. The @kbd{g t} (@code{calc-graph-title-x}) and @kbd{g T}
  24288. (@code{calc-graph-title-y}) commands set the titles on the ``x''
  24289. and ``y'' axes, respectively. These titles appear next to the
  24290. tick marks on the left and bottom edges of the graph, respectively.
  24291. Calc does not have commands to control the tick marks themselves,
  24292. but you can edit them into the @samp{*Gnuplot Commands*} buffer if
  24293. you wish. See the GNUPLOT documentation for details.
  24294. @kindex g r
  24295. @kindex g R
  24296. @pindex calc-graph-range-x
  24297. @pindex calc-graph-range-y
  24298. The @kbd{g r} (@code{calc-graph-range-x}) and @kbd{g R}
  24299. (@code{calc-graph-range-y}) commands set the range of values on the
  24300. ``x'' and ``y'' axes, respectively. You are prompted to enter a
  24301. suitable range. This should be either a pair of numbers of the
  24302. form, @samp{@var{min}:@var{max}}, or a blank line to revert to the
  24303. default behavior of setting the range based on the range of values
  24304. in the data, or @samp{$} to take the range from the top of the stack.
  24305. Ranges on the stack can be represented as either interval forms or
  24306. vectors: @samp{[@var{min} ..@: @var{max}]} or @samp{[@var{min}, @var{max}]}.
  24307. @kindex g l
  24308. @kindex g L
  24309. @pindex calc-graph-log-x
  24310. @pindex calc-graph-log-y
  24311. The @kbd{g l} (@code{calc-graph-log-x}) and @kbd{g L} (@code{calc-graph-log-y})
  24312. commands allow you to set either or both of the axes of the graph to
  24313. be logarithmic instead of linear.
  24314. @kindex g C-l
  24315. @kindex g C-r
  24316. @kindex g C-t
  24317. @pindex calc-graph-log-z
  24318. @pindex calc-graph-range-z
  24319. @pindex calc-graph-title-z
  24320. For 3D plots, @kbd{g C-t}, @kbd{g C-r}, and @kbd{g C-l} (those are
  24321. letters with the Control key held down) are the corresponding commands
  24322. for the ``z'' axis.
  24323. @kindex g z
  24324. @kindex g Z
  24325. @pindex calc-graph-zero-x
  24326. @pindex calc-graph-zero-y
  24327. The @kbd{g z} (@code{calc-graph-zero-x}) and @kbd{g Z}
  24328. (@code{calc-graph-zero-y}) commands control whether a dotted line is
  24329. drawn to indicate the ``x'' and/or ``y'' zero axes. (These are the same
  24330. dotted lines that would be drawn there anyway if you used @kbd{g g} to
  24331. turn the ``grid'' feature on.) Zero-axis lines are on by default, and
  24332. may be turned off only in GNUPLOT 3.0 and later versions. They are
  24333. not available for 3D plots.
  24334. @kindex g s
  24335. @pindex calc-graph-line-style
  24336. The @kbd{g s} (@code{calc-graph-line-style}) command turns the connecting
  24337. lines on or off for the most recently added curve, and optionally selects
  24338. the style of lines to be used for that curve. Plain @kbd{g s} simply
  24339. toggles the lines on and off. With a numeric prefix argument, @kbd{g s}
  24340. turns lines on and sets a particular line style. Line style numbers
  24341. start at one and their meanings vary depending on the output device.
  24342. GNUPLOT guarantees that there will be at least six different line styles
  24343. available for any device.
  24344. @kindex g S
  24345. @pindex calc-graph-point-style
  24346. The @kbd{g S} (@code{calc-graph-point-style}) command similarly turns
  24347. the symbols at the data points on or off, or sets the point style.
  24348. If you turn both lines and points off, the data points will show as
  24349. tiny dots.
  24350. @cindex @code{LineStyles} variable
  24351. @cindex @code{PointStyles} variable
  24352. @vindex LineStyles
  24353. @vindex PointStyles
  24354. Another way to specify curve styles is with the @code{LineStyles} and
  24355. @code{PointStyles} variables. These variables initially have no stored
  24356. values, but if you store a vector of integers in one of these variables,
  24357. the @kbd{g a} and @kbd{g f} commands will use those style numbers
  24358. instead of the defaults for new curves that are added to the graph.
  24359. An entry should be a positive integer for a specific style, or 0 to let
  24360. the style be chosen automatically, or @i{-1} to turn off lines or points
  24361. altogether. If there are more curves than elements in the vector, the
  24362. last few curves will continue to have the default styles. Of course,
  24363. you can later use @kbd{g s} and @kbd{g S} to change any of these styles.
  24364. For example, @kbd{'[2 -1 3] @key{RET} s t LineStyles} causes the first curve
  24365. to have lines in style number 2, the second curve to have no connecting
  24366. lines, and the third curve to have lines in style 3. Point styles will
  24367. still be assigned automatically, but you could store another vector in
  24368. @code{PointStyles} to define them, too.
  24369. @node Devices, , Graphics Options, Graphics
  24370. @section Graphical Devices
  24371. @noindent
  24372. @kindex g D
  24373. @pindex calc-graph-device
  24374. The @kbd{g D} (@code{calc-graph-device}) command sets the device name
  24375. (or ``terminal name'' in GNUPLOT lingo) to be used by @kbd{g p} commands
  24376. on this graph. It does not affect the permanent default device name.
  24377. If you enter a blank name, the device name reverts to the default.
  24378. Enter @samp{?} to see a list of supported devices.
  24379. With a positive numeric prefix argument, @kbd{g D} instead sets
  24380. the default device name, used by all plots in the future which do
  24381. not override it with a plain @kbd{g D} command. If you enter a
  24382. blank line this command shows you the current default. The special
  24383. name @code{default} signifies that Calc should choose @code{x11} if
  24384. the X window system is in use (as indicated by the presence of a
  24385. @code{DISPLAY} environment variable), or otherwise @code{dumb} under
  24386. GNUPLOT 3.0 and later, or @code{postscript} under GNUPLOT 2.0.
  24387. This is the initial default value.
  24388. The @code{dumb} device is an interface to ``dumb terminals,'' i.e.,
  24389. terminals with no special graphics facilities. It writes a crude
  24390. picture of the graph composed of characters like @code{-} and @code{|}
  24391. to a buffer called @samp{*Gnuplot Trail*}, which Calc then displays.
  24392. The graph is made the same size as the Emacs screen, which on most
  24393. dumb terminals will be @c{$80\times24$}
  24394. @asis{80x24} characters. The graph is displayed in
  24395. an Emacs ``recursive edit''; type @kbd{q} or @kbd{M-# M-#} to exit
  24396. the recursive edit and return to Calc. Note that the @code{dumb}
  24397. device is present only in GNUPLOT 3.0 and later versions.
  24398. The word @code{dumb} may be followed by two numbers separated by
  24399. spaces. These are the desired width and height of the graph in
  24400. characters. Also, the device name @code{big} is like @code{dumb}
  24401. but creates a graph four times the width and height of the Emacs
  24402. screen. You will then have to scroll around to view the entire
  24403. graph. In the @samp{*Gnuplot Trail*} buffer, @key{SPC}, @key{DEL},
  24404. @kbd{<}, and @kbd{>} are defined to scroll by one screenful in each
  24405. of the four directions.
  24406. With a negative numeric prefix argument, @kbd{g D} sets or displays
  24407. the device name used by @kbd{g P} (@code{calc-graph-print}). This
  24408. is initially @code{postscript}. If you don't have a PostScript
  24409. printer, you may decide once again to use @code{dumb} to create a
  24410. plot on any text-only printer.
  24411. @kindex g O
  24412. @pindex calc-graph-output
  24413. The @kbd{g O} (@code{calc-graph-output}) command sets the name of
  24414. the output file used by GNUPLOT. For some devices, notably @code{x11},
  24415. there is no output file and this information is not used. Many other
  24416. ``devices'' are really file formats like @code{postscript}; in these
  24417. cases the output in the desired format goes into the file you name
  24418. with @kbd{g O}. Type @kbd{g O stdout @key{RET}} to set GNUPLOT to write
  24419. to its standard output stream, i.e., to @samp{*Gnuplot Trail*}.
  24420. This is the default setting.
  24421. Another special output name is @code{tty}, which means that GNUPLOT
  24422. is going to write graphics commands directly to its standard output,
  24423. which you wish Emacs to pass through to your terminal. Tektronix
  24424. graphics terminals, among other devices, operate this way. Calc does
  24425. this by telling GNUPLOT to write to a temporary file, then running a
  24426. sub-shell executing the command @samp{cat tempfile >/dev/tty}. On
  24427. typical Unix systems, this will copy the temporary file directly to
  24428. the terminal, bypassing Emacs entirely. You will have to type @kbd{C-l}
  24429. to Emacs afterwards to refresh the screen.
  24430. Once again, @kbd{g O} with a positive or negative prefix argument
  24431. sets the default or printer output file names, respectively. In each
  24432. case you can specify @code{auto}, which causes Calc to invent a temporary
  24433. file name for each @kbd{g p} (or @kbd{g P}) command. This temporary file
  24434. will be deleted once it has been displayed or printed. If the output file
  24435. name is not @code{auto}, the file is not automatically deleted.
  24436. The default and printer devices and output files can be saved
  24437. permanently by the @kbd{m m} (@code{calc-save-modes}) command. The
  24438. default number of data points (see @kbd{g N}) and the X geometry
  24439. (see @kbd{g X}) are also saved. Other graph information is @emph{not}
  24440. saved; you can save a graph's configuration simply by saving the contents
  24441. of the @samp{*Gnuplot Commands*} buffer.
  24442. @vindex calc-gnuplot-plot-command
  24443. @vindex calc-gnuplot-default-device
  24444. @vindex calc-gnuplot-default-output
  24445. @vindex calc-gnuplot-print-command
  24446. @vindex calc-gnuplot-print-device
  24447. @vindex calc-gnuplot-print-output
  24448. If you are installing Calc you may wish to configure the default and
  24449. printer devices and output files for the whole system. The relevant
  24450. Lisp variables are @code{calc-gnuplot-default-device} and @code{-output},
  24451. and @code{calc-gnuplot-print-device} and @code{-output}. The output
  24452. file names must be either strings as described above, or Lisp
  24453. expressions which are evaluated on the fly to get the output file names.
  24454. Other important Lisp variables are @code{calc-gnuplot-plot-command} and
  24455. @code{calc-gnuplot-print-command}, which give the system commands to
  24456. display or print the output of GNUPLOT, respectively. These may be
  24457. @code{nil} if no command is necessary, or strings which can include
  24458. @samp{%s} to signify the name of the file to be displayed or printed.
  24459. Or, these variables may contain Lisp expressions which are evaluated
  24460. to display or print the output.
  24461. @kindex g x
  24462. @pindex calc-graph-display
  24463. The @kbd{g x} (@code{calc-graph-display}) command lets you specify
  24464. on which X window system display your graphs should be drawn. Enter
  24465. a blank line to see the current display name. This command has no
  24466. effect unless the current device is @code{x11}.
  24467. @kindex g X
  24468. @pindex calc-graph-geometry
  24469. The @kbd{g X} (@code{calc-graph-geometry}) command is a similar
  24470. command for specifying the position and size of the X window.
  24471. The normal value is @code{default}, which generally means your
  24472. window manager will let you place the window interactively.
  24473. Entering @samp{800x500+0+0} would create an 800-by-500 pixel
  24474. window in the upper-left corner of the screen.
  24475. The buffer called @samp{*Gnuplot Trail*} holds a transcript of the
  24476. session with GNUPLOT. This shows the commands Calc has ``typed'' to
  24477. GNUPLOT and the responses it has received. Calc tries to notice when an
  24478. error message has appeared here and display the buffer for you when
  24479. this happens. You can check this buffer yourself if you suspect
  24480. something has gone wrong.
  24481. @kindex g C
  24482. @pindex calc-graph-command
  24483. The @kbd{g C} (@code{calc-graph-command}) command prompts you to
  24484. enter any line of text, then simply sends that line to the current
  24485. GNUPLOT process. The @samp{*Gnuplot Trail*} buffer looks deceptively
  24486. like a Shell buffer but you can't type commands in it yourself.
  24487. Instead, you must use @kbd{g C} for this purpose.
  24488. @kindex g v
  24489. @kindex g V
  24490. @pindex calc-graph-view-commands
  24491. @pindex calc-graph-view-trail
  24492. The @kbd{g v} (@code{calc-graph-view-commands}) and @kbd{g V}
  24493. (@code{calc-graph-view-trail}) commands display the @samp{*Gnuplot Commands*}
  24494. and @samp{*Gnuplot Trail*} buffers, respectively, in another window.
  24495. This happens automatically when Calc thinks there is something you
  24496. will want to see in either of these buffers. If you type @kbd{g v}
  24497. or @kbd{g V} when the relevant buffer is already displayed, the
  24498. buffer is hidden again.
  24499. One reason to use @kbd{g v} is to add your own commands to the
  24500. @samp{*Gnuplot Commands*} buffer. Press @kbd{g v}, then use
  24501. @kbd{C-x o} to switch into that window. For example, GNUPLOT has
  24502. @samp{set label} and @samp{set arrow} commands that allow you to
  24503. annotate your plots. Since Calc doesn't understand these commands,
  24504. you have to add them to the @samp{*Gnuplot Commands*} buffer
  24505. yourself, then use @w{@kbd{g p}} to replot using these new commands. Note
  24506. that your commands must appear @emph{before} the @code{plot} command.
  24507. To get help on any GNUPLOT feature, type, e.g., @kbd{g C help set label}.
  24508. You may have to type @kbd{g C @key{RET}} a few times to clear the
  24509. ``press return for more'' or ``subtopic of @dots{}'' requests.
  24510. Note that Calc always sends commands (like @samp{set nolabel}) to
  24511. reset all plotting parameters to the defaults before each plot, so
  24512. to delete a label all you need to do is delete the @samp{set label}
  24513. line you added (or comment it out with @samp{#}) and then replot
  24514. with @kbd{g p}.
  24515. @kindex g q
  24516. @pindex calc-graph-quit
  24517. You can use @kbd{g q} (@code{calc-graph-quit}) to kill the GNUPLOT
  24518. process that is running. The next graphing command you give will
  24519. start a fresh GNUPLOT process. The word @samp{Graph} appears in
  24520. the Calc window's mode line whenever a GNUPLOT process is currently
  24521. running. The GNUPLOT process is automatically killed when you
  24522. exit Emacs if you haven't killed it manually by then.
  24523. @kindex g K
  24524. @pindex calc-graph-kill
  24525. The @kbd{g K} (@code{calc-graph-kill}) command is like @kbd{g q}
  24526. except that it also views the @samp{*Gnuplot Trail*} buffer so that
  24527. you can see the process being killed. This is better if you are
  24528. killing GNUPLOT because you think it has gotten stuck.
  24529. @node Kill and Yank, Keypad Mode, Graphics, Top
  24530. @chapter Kill and Yank Functions
  24531. @noindent
  24532. The commands in this chapter move information between the Calculator and
  24533. other Emacs editing buffers.
  24534. In many cases Embedded Mode is an easier and more natural way to
  24535. work with Calc from a regular editing buffer. @xref{Embedded Mode}.
  24536. @menu
  24537. * Killing From Stack::
  24538. * Yanking Into Stack::
  24539. * Grabbing From Buffers::
  24540. * Yanking Into Buffers::
  24541. * X Cut and Paste::
  24542. @end menu
  24543. @node Killing From Stack, Yanking Into Stack, Kill and Yank, Kill and Yank
  24544. @section Killing from the Stack
  24545. @noindent
  24546. @kindex C-k
  24547. @pindex calc-kill
  24548. @kindex M-k
  24549. @pindex calc-copy-as-kill
  24550. @kindex C-w
  24551. @pindex calc-kill-region
  24552. @kindex M-w
  24553. @pindex calc-copy-region-as-kill
  24554. @cindex Kill ring
  24555. @dfn{Kill} commands are Emacs commands that insert text into the
  24556. ``kill ring,'' from which it can later be ``yanked'' by a @kbd{C-y}
  24557. command. Three common kill commands in normal Emacs are @kbd{C-k}, which
  24558. kills one line, @kbd{C-w}, which kills the region between mark and point,
  24559. and @kbd{M-w}, which puts the region into the kill ring without actually
  24560. deleting it. All of these commands work in the Calculator, too. Also,
  24561. @kbd{M-k} has been provided to complete the set; it puts the current line
  24562. into the kill ring without deleting anything.
  24563. The kill commands are unusual in that they pay attention to the location
  24564. of the cursor in the Calculator buffer. If the cursor is on or below the
  24565. bottom line, the kill commands operate on the top of the stack. Otherwise,
  24566. they operate on whatever stack element the cursor is on. Calc's kill
  24567. commands always operate on whole stack entries. (They act the same as their
  24568. standard Emacs cousins except they ``round up'' the specified region to
  24569. encompass full lines.) The text is copied into the kill ring exactly as
  24570. it appears on the screen, including line numbers if they are enabled.
  24571. A numeric prefix argument to @kbd{C-k} or @kbd{M-k} affects the number
  24572. of lines killed. A positive argument kills the current line and @cite{n-1}
  24573. lines below it. A negative argument kills the @cite{-n} lines above the
  24574. current line. Again this mirrors the behavior of the standard Emacs
  24575. @kbd{C-k} command. Although a whole line is always deleted, @kbd{C-k}
  24576. with no argument copies only the number itself into the kill ring, whereas
  24577. @kbd{C-k} with a prefix argument of 1 copies the number with its trailing
  24578. newline.
  24579. @node Yanking Into Stack, Grabbing From Buffers, Killing From Stack, Kill and Yank
  24580. @section Yanking into the Stack
  24581. @noindent
  24582. @kindex C-y
  24583. @pindex calc-yank
  24584. The @kbd{C-y} command yanks the most recently killed text back into the
  24585. Calculator. It pushes this value onto the top of the stack regardless of
  24586. the cursor position. In general it re-parses the killed text as a number
  24587. or formula (or a list of these separated by commas or newlines). However if
  24588. the thing being yanked is something that was just killed from the Calculator
  24589. itself, its full internal structure is yanked. For example, if you have
  24590. set the floating-point display mode to show only four significant digits,
  24591. then killing and re-yanking 3.14159 (which displays as 3.142) will yank the
  24592. full 3.14159, even though yanking it into any other buffer would yank the
  24593. number in its displayed form, 3.142. (Since the default display modes
  24594. show all objects to their full precision, this feature normally makes no
  24595. difference.)
  24596. @node Grabbing From Buffers, Yanking Into Buffers, Yanking Into Stack, Kill and Yank
  24597. @section Grabbing from Other Buffers
  24598. @noindent
  24599. @kindex M-# g
  24600. @pindex calc-grab-region
  24601. The @kbd{M-# g} (@code{calc-grab-region}) command takes the text between
  24602. point and mark in the current buffer and attempts to parse it as a
  24603. vector of values. Basically, it wraps the text in vector brackets
  24604. @samp{[ ]} unless the text already is enclosed in vector brackets,
  24605. then reads the text as if it were an algebraic entry. The contents
  24606. of the vector may be numbers, formulas, or any other Calc objects.
  24607. If the @kbd{M-# g} command works successfully, it does an automatic
  24608. @kbd{M-# c} to enter the Calculator buffer.
  24609. A numeric prefix argument grabs the specified number of lines around
  24610. point, ignoring the mark. A positive prefix grabs from point to the
  24611. @cite{n}th following newline (so that @kbd{M-1 M-# g} grabs from point
  24612. to the end of the current line); a negative prefix grabs from point
  24613. back to the @cite{n+1}st preceding newline. In these cases the text
  24614. that is grabbed is exactly the same as the text that @kbd{C-k} would
  24615. delete given that prefix argument.
  24616. A prefix of zero grabs the current line; point may be anywhere on the
  24617. line.
  24618. A plain @kbd{C-u} prefix interprets the region between point and mark
  24619. as a single number or formula rather than a vector. For example,
  24620. @kbd{M-# g} on the text @samp{2 a b} produces the vector of three
  24621. values @samp{[2, a, b]}, but @kbd{C-u M-# g} on the same region
  24622. reads a formula which is a product of three things: @samp{2 a b}.
  24623. (The text @samp{a + b}, on the other hand, will be grabbed as a
  24624. vector of one element by plain @kbd{M-# g} because the interpretation
  24625. @samp{[a, +, b]} would be a syntax error.)
  24626. If a different language has been specified (@pxref{Language Modes}),
  24627. the grabbed text will be interpreted according to that language.
  24628. @kindex M-# r
  24629. @pindex calc-grab-rectangle
  24630. The @kbd{M-# r} (@code{calc-grab-rectangle}) command takes the text between
  24631. point and mark and attempts to parse it as a matrix. If point and mark
  24632. are both in the leftmost column, the lines in between are parsed in their
  24633. entirety. Otherwise, point and mark define the corners of a rectangle
  24634. whose contents are parsed.
  24635. Each line of the grabbed area becomes a row of the matrix. The result
  24636. will actually be a vector of vectors, which Calc will treat as a matrix
  24637. only if every row contains the same number of values.
  24638. If a line contains a portion surrounded by square brackets (or curly
  24639. braces), that portion is interpreted as a vector which becomes a row
  24640. of the matrix. Any text surrounding the bracketed portion on the line
  24641. is ignored.
  24642. Otherwise, the entire line is interpreted as a row vector as if it
  24643. were surrounded by square brackets. Leading line numbers (in the
  24644. format used in the Calc stack buffer) are ignored. If you wish to
  24645. force this interpretation (even if the line contains bracketed
  24646. portions), give a negative numeric prefix argument to the
  24647. @kbd{M-# r} command.
  24648. If you give a numeric prefix argument of zero or plain @kbd{C-u}, each
  24649. line is instead interpreted as a single formula which is converted into
  24650. a one-element vector. Thus the result of @kbd{C-u M-# r} will be a
  24651. one-column matrix. For example, suppose one line of the data is the
  24652. expression @samp{2 a}. A plain @w{@kbd{M-# r}} will interpret this as
  24653. @samp{[2 a]}, which in turn is read as a two-element vector that forms
  24654. one row of the matrix. But a @kbd{C-u M-# r} will interpret this row
  24655. as @samp{[2*a]}.
  24656. If you give a positive numeric prefix argument @var{n}, then each line
  24657. will be split up into columns of width @var{n}; each column is parsed
  24658. separately as a matrix element. If a line contained
  24659. @w{@samp{2 +/- 3 4 +/- 5}}, then grabbing with a prefix argument of 8
  24660. would correctly split the line into two error forms.@refill
  24661. @xref{Matrix Functions}, to see how to pull the matrix apart into its
  24662. constituent rows and columns. (If it is a @c{$1\times1$}
  24663. @asis{1x1} matrix, just hit @kbd{v u}
  24664. (@code{calc-unpack}) twice.)
  24665. @kindex M-# :
  24666. @kindex M-# _
  24667. @pindex calc-grab-sum-across
  24668. @pindex calc-grab-sum-down
  24669. @cindex Summing rows and columns of data
  24670. The @kbd{M-# :} (@code{calc-grab-sum-down}) command is a handy way to
  24671. grab a rectangle of data and sum its columns. It is equivalent to
  24672. typing @kbd{M-# r}, followed by @kbd{V R : +} (the vector reduction
  24673. command that sums the columns of a matrix; @pxref{Reducing}). The
  24674. result of the command will be a vector of numbers, one for each column
  24675. in the input data. The @kbd{M-# _} (@code{calc-grab-sum-across}) command
  24676. similarly grabs a rectangle and sums its rows by executing @w{@kbd{V R _ +}}.
  24677. As well as being more convenient, @kbd{M-# :} and @kbd{M-# _} are also
  24678. much faster because they don't actually place the grabbed vector on
  24679. the stack. In a @kbd{M-# r V R : +} sequence, formatting the vector
  24680. for display on the stack takes a large fraction of the total time
  24681. (unless you have planned ahead and used @kbd{v .} and @kbd{t .} modes).
  24682. For example, suppose we have a column of numbers in a file which we
  24683. wish to sum. Go to one corner of the column and press @kbd{C-@@} to
  24684. set the mark; go to the other corner and type @kbd{M-# :}. Since there
  24685. is only one column, the result will be a vector of one number, the sum.
  24686. (You can type @kbd{v u} to unpack this vector into a plain number if
  24687. you want to do further arithmetic with it.)
  24688. To compute the product of the column of numbers, we would have to do
  24689. it ``by hand'' since there's no special grab-and-multiply command.
  24690. Use @kbd{M-# r} to grab the column of numbers into the calculator in
  24691. the form of a column matrix. The statistics command @kbd{u *} is a
  24692. handy way to find the product of a vector or matrix of numbers.
  24693. @xref{Statistical Operations}. Another approach would be to use
  24694. an explicit column reduction command, @kbd{V R : *}.
  24695. @node Yanking Into Buffers, X Cut and Paste, Grabbing From Buffers, Kill and Yank
  24696. @section Yanking into Other Buffers
  24697. @noindent
  24698. @kindex y
  24699. @pindex calc-copy-to-buffer
  24700. The plain @kbd{y} (@code{calc-copy-to-buffer}) command inserts the number
  24701. at the top of the stack into the most recently used normal editing buffer.
  24702. (More specifically, this is the most recently used buffer which is displayed
  24703. in a window and whose name does not begin with @samp{*}. If there is no
  24704. such buffer, this is the most recently used buffer except for Calculator
  24705. and Calc Trail buffers.) The number is inserted exactly as it appears and
  24706. without a newline. (If line-numbering is enabled, the line number is
  24707. normally not included.) The number is @emph{not} removed from the stack.
  24708. With a prefix argument, @kbd{y} inserts several numbers, one per line.
  24709. A positive argument inserts the specified number of values from the top
  24710. of the stack. A negative argument inserts the @cite{n}th value from the
  24711. top of the stack. An argument of zero inserts the entire stack. Note
  24712. that @kbd{y} with an argument of 1 is slightly different from @kbd{y}
  24713. with no argument; the former always copies full lines, whereas the
  24714. latter strips off the trailing newline.
  24715. With a lone @kbd{C-u} as a prefix argument, @kbd{y} @emph{replaces} the
  24716. region in the other buffer with the yanked text, then quits the
  24717. Calculator, leaving you in that buffer. A typical use would be to use
  24718. @kbd{M-# g} to read a region of data into the Calculator, operate on the
  24719. data to produce a new matrix, then type @kbd{C-u y} to replace the
  24720. original data with the new data. One might wish to alter the matrix
  24721. display style (@pxref{Vector and Matrix Formats}) or change the current
  24722. display language (@pxref{Language Modes}) before doing this. Also, note
  24723. that this command replaces a linear region of text (as grabbed by
  24724. @kbd{M-# g}), not a rectangle (as grabbed by @kbd{M-# r}).@refill
  24725. If the editing buffer is in overwrite (as opposed to insert) mode,
  24726. and the @kbd{C-u} prefix was not used, then the yanked number will
  24727. overwrite the characters following point rather than being inserted
  24728. before those characters. The usual conventions of overwrite mode
  24729. are observed; for example, characters will be inserted at the end of
  24730. a line rather than overflowing onto the next line. Yanking a multi-line
  24731. object such as a matrix in overwrite mode overwrites the next @var{n}
  24732. lines in the buffer, lengthening or shortening each line as necessary.
  24733. Finally, if the thing being yanked is a simple integer or floating-point
  24734. number (like @samp{-1.2345e-3}) and the characters following point also
  24735. make up such a number, then Calc will replace that number with the new
  24736. number, lengthening or shortening as necessary. The concept of
  24737. ``overwrite mode'' has thus been generalized from overwriting characters
  24738. to overwriting one complete number with another.
  24739. @kindex M-# y
  24740. The @kbd{M-# y} key sequence is equivalent to @kbd{y} except that
  24741. it can be typed anywhere, not just in Calc. This provides an easy
  24742. way to guarantee that Calc knows which editing buffer you want to use!
  24743. @node X Cut and Paste, , Yanking Into Buffers, Kill and Yank
  24744. @section X Cut and Paste
  24745. @noindent
  24746. If you are using Emacs with the X window system, there is an easier
  24747. way to move small amounts of data into and out of the calculator:
  24748. Use the mouse-oriented cut and paste facilities of X.
  24749. The default bindings for a three-button mouse cause the left button
  24750. to move the Emacs cursor to the given place, the right button to
  24751. select the text between the cursor and the clicked location, and
  24752. the middle button to yank the selection into the buffer at the
  24753. clicked location. So, if you have a Calc window and an editing
  24754. window on your Emacs screen, you can use left-click/right-click
  24755. to select a number, vector, or formula from one window, then
  24756. middle-click to paste that value into the other window. When you
  24757. paste text into the Calc window, Calc interprets it as an algebraic
  24758. entry. It doesn't matter where you click in the Calc window; the
  24759. new value is always pushed onto the top of the stack.
  24760. The @code{xterm} program that is typically used for general-purpose
  24761. shell windows in X interprets the mouse buttons in the same way.
  24762. So you can use the mouse to move data between Calc and any other
  24763. Unix program. One nice feature of @code{xterm} is that a double
  24764. left-click selects one word, and a triple left-click selects a
  24765. whole line. So you can usually transfer a single number into Calc
  24766. just by double-clicking on it in the shell, then middle-clicking
  24767. in the Calc window.
  24768. @node Keypad Mode, Embedded Mode, Kill and Yank, Introduction
  24769. @chapter ``Keypad'' Mode
  24770. @noindent
  24771. @kindex M-# k
  24772. @pindex calc-keypad
  24773. The @kbd{M-# k} (@code{calc-keypad}) command starts the Calculator
  24774. and displays a picture of a calculator-style keypad. If you are using
  24775. the X window system, you can click on any of the ``keys'' in the
  24776. keypad using the left mouse button to operate the calculator.
  24777. The original window remains the selected window; in keypad mode
  24778. you can type in your file while simultaneously performing
  24779. calculations with the mouse.
  24780. @pindex full-calc-keypad
  24781. If you have used @kbd{M-# b} first, @kbd{M-# k} instead invokes
  24782. the @code{full-calc-keypad} command, which takes over the whole
  24783. Emacs screen and displays the keypad, the Calc stack, and the Calc
  24784. trail all at once. This mode would normally be used when running
  24785. Calc standalone (@pxref{Standalone Operation}).
  24786. If you aren't using the X window system, you must switch into
  24787. the @samp{*Calc Keypad*} window, place the cursor on the desired
  24788. ``key,'' and type @key{SPC} or @key{RET}. If you think this
  24789. is easier than using Calc normally, go right ahead.
  24790. Calc commands are more or less the same in keypad mode. Certain
  24791. keypad keys differ slightly from the corresponding normal Calc
  24792. keystrokes; all such deviations are described below.
  24793. Keypad Mode includes many more commands than will fit on the keypad
  24794. at once. Click the right mouse button [@code{calc-keypad-menu}]
  24795. to switch to the next menu. The bottom five rows of the keypad
  24796. stay the same; the top three rows change to a new set of commands.
  24797. To return to earlier menus, click the middle mouse button
  24798. [@code{calc-keypad-menu-back}] or simply advance through the menus
  24799. until you wrap around. Typing @key{TAB} inside the keypad window
  24800. is equivalent to clicking the right mouse button there.
  24801. You can always click the @key{EXEC} button and type any normal
  24802. Calc key sequence. This is equivalent to switching into the
  24803. Calc buffer, typing the keys, then switching back to your
  24804. original buffer.
  24805. @menu
  24806. * Keypad Main Menu::
  24807. * Keypad Functions Menu::
  24808. * Keypad Binary Menu::
  24809. * Keypad Vectors Menu::
  24810. * Keypad Modes Menu::
  24811. @end menu
  24812. @node Keypad Main Menu, Keypad Functions Menu, Keypad Mode, Keypad Mode
  24813. @section Main Menu
  24814. @smallexample
  24815. @group
  24816. |----+-----Calc 2.00-----+----1
  24817. |FLR |CEIL|RND |TRNC|CLN2|FLT |
  24818. |----+----+----+----+----+----|
  24819. | LN |EXP | |ABS |IDIV|MOD |
  24820. |----+----+----+----+----+----|
  24821. |SIN |COS |TAN |SQRT|y^x |1/x |
  24822. |----+----+----+----+----+----|
  24823. | ENTER |+/- |EEX |UNDO| <- |
  24824. |-----+---+-+--+--+-+---++----|
  24825. | INV | 7 | 8 | 9 | / |
  24826. |-----+-----+-----+-----+-----|
  24827. | HYP | 4 | 5 | 6 | * |
  24828. |-----+-----+-----+-----+-----|
  24829. |EXEC | 1 | 2 | 3 | - |
  24830. |-----+-----+-----+-----+-----|
  24831. | OFF | 0 | . | PI | + |
  24832. |-----+-----+-----+-----+-----+
  24833. @end group
  24834. @end smallexample
  24835. @noindent
  24836. This is the menu that appears the first time you start Keypad Mode.
  24837. It will show up in a vertical window on the right side of your screen.
  24838. Above this menu is the traditional Calc stack display. On a 24-line
  24839. screen you will be able to see the top three stack entries.
  24840. The ten digit keys, decimal point, and @key{EEX} key are used for
  24841. entering numbers in the obvious way. @key{EEX} begins entry of an
  24842. exponent in scientific notation. Just as with regular Calc, the
  24843. number is pushed onto the stack as soon as you press @key{ENTER}
  24844. or any other function key.
  24845. The @key{+/-} key corresponds to normal Calc's @kbd{n} key. During
  24846. numeric entry it changes the sign of the number or of the exponent.
  24847. At other times it changes the sign of the number on the top of the
  24848. stack.
  24849. The @key{INV} and @key{HYP} keys modify other keys. As well as
  24850. having the effects described elsewhere in this manual, Keypad Mode
  24851. defines several other ``inverse'' operations. These are described
  24852. below and in the following sections.
  24853. The @key{ENTER} key finishes the current numeric entry, or otherwise
  24854. duplicates the top entry on the stack.
  24855. The @key{UNDO} key undoes the most recent Calc operation.
  24856. @kbd{INV UNDO} is the ``redo'' command, and @kbd{HYP UNDO} is
  24857. ``last arguments'' (@kbd{M-@key{RET}}).
  24858. The @key{<-} key acts as a ``backspace'' during numeric entry.
  24859. At other times it removes the top stack entry. @kbd{INV <-}
  24860. clears the entire stack. @kbd{HYP <-} takes an integer from
  24861. the stack, then removes that many additional stack elements.
  24862. The @key{EXEC} key prompts you to enter any keystroke sequence
  24863. that would normally work in Calc mode. This can include a
  24864. numeric prefix if you wish. It is also possible simply to
  24865. switch into the Calc window and type commands in it; there is
  24866. nothing ``magic'' about this window when Keypad Mode is active.
  24867. The other keys in this display perform their obvious calculator
  24868. functions. @key{CLN2} rounds the top-of-stack by temporarily
  24869. reducing the precision by 2 digits. @key{FLT} converts an
  24870. integer or fraction on the top of the stack to floating-point.
  24871. The @key{INV} and @key{HYP} keys combined with several of these keys
  24872. give you access to some common functions even if the appropriate menu
  24873. is not displayed. Obviously you don't need to learn these keys
  24874. unless you find yourself wasting time switching among the menus.
  24875. @table @kbd
  24876. @item INV +/-
  24877. is the same as @key{1/x}.
  24878. @item INV +
  24879. is the same as @key{SQRT}.
  24880. @item INV -
  24881. is the same as @key{CONJ}.
  24882. @item INV *
  24883. is the same as @key{y^x}.
  24884. @item INV /
  24885. is the same as @key{INV y^x} (the @cite{x}th root of @cite{y}).
  24886. @item HYP/INV 1
  24887. are the same as @key{SIN} / @kbd{INV SIN}.
  24888. @item HYP/INV 2
  24889. are the same as @key{COS} / @kbd{INV COS}.
  24890. @item HYP/INV 3
  24891. are the same as @key{TAN} / @kbd{INV TAN}.
  24892. @item INV/HYP 4
  24893. are the same as @key{LN} / @kbd{HYP LN}.
  24894. @item INV/HYP 5
  24895. are the same as @key{EXP} / @kbd{HYP EXP}.
  24896. @item INV 6
  24897. is the same as @key{ABS}.
  24898. @item INV 7
  24899. is the same as @key{RND} (@code{calc-round}).
  24900. @item INV 8
  24901. is the same as @key{CLN2}.
  24902. @item INV 9
  24903. is the same as @key{FLT} (@code{calc-float}).
  24904. @item INV 0
  24905. is the same as @key{IMAG}.
  24906. @item INV .
  24907. is the same as @key{PREC}.
  24908. @item INV ENTER
  24909. is the same as @key{SWAP}.
  24910. @item HYP ENTER
  24911. is the same as @key{RLL3}.
  24912. @item INV HYP ENTER
  24913. is the same as @key{OVER}.
  24914. @item HYP +/-
  24915. packs the top two stack entries as an error form.
  24916. @item HYP EEX
  24917. packs the top two stack entries as a modulo form.
  24918. @item INV EEX
  24919. creates an interval form; this removes an integer which is one
  24920. of 0 @samp{[]}, 1 @samp{[)}, 2 @samp{(]} or 3 @samp{()}, followed
  24921. by the two limits of the interval.
  24922. @end table
  24923. The @kbd{OFF} key turns Calc off; typing @kbd{M-# k} or @kbd{M-# M-#}
  24924. again has the same effect. This is analogous to typing @kbd{q} or
  24925. hitting @kbd{M-# c} again in the normal calculator. If Calc is
  24926. running standalone (the @code{full-calc-keypad} command appeared in the
  24927. command line that started Emacs), then @kbd{OFF} is replaced with
  24928. @kbd{EXIT}; clicking on this actually exits Emacs itself.
  24929. @node Keypad Functions Menu, Keypad Binary Menu, Keypad Main Menu, Keypad Mode
  24930. @section Functions Menu
  24931. @smallexample
  24932. @group
  24933. |----+----+----+----+----+----2
  24934. |IGAM|BETA|IBET|ERF |BESJ|BESY|
  24935. |----+----+----+----+----+----|
  24936. |IMAG|CONJ| RE |ATN2|RAND|RAGN|
  24937. |----+----+----+----+----+----|
  24938. |GCD |FACT|DFCT|BNOM|PERM|NXTP|
  24939. |----+----+----+----+----+----|
  24940. @end group
  24941. @end smallexample
  24942. @noindent
  24943. This menu provides various operations from the @kbd{f} and @kbd{k}
  24944. prefix keys.
  24945. @key{IMAG} multiplies the number on the stack by the imaginary
  24946. number @cite{i = (0, 1)}.
  24947. @key{RE} extracts the real part a complex number. @kbd{INV RE}
  24948. extracts the imaginary part.
  24949. @key{RAND} takes a number from the top of the stack and computes
  24950. a random number greater than or equal to zero but less than that
  24951. number. (@xref{Random Numbers}.) @key{RAGN} is the ``random
  24952. again'' command; it computes another random number using the
  24953. same limit as last time.
  24954. @key{INV GCD} computes the LCM (least common multiple) function.
  24955. @key{INV FACT} is the gamma function. @c{$\Gamma(x) = (x-1)!$}
  24956. @cite{gamma(x) = (x-1)!}.
  24957. @key{PERM} is the number-of-permutations function, which is on the
  24958. @kbd{H k c} key in normal Calc.
  24959. @key{NXTP} finds the next prime after a number. @kbd{INV NXTP}
  24960. finds the previous prime.
  24961. @node Keypad Binary Menu, Keypad Vectors Menu, Keypad Functions Menu, Keypad Mode
  24962. @section Binary Menu
  24963. @smallexample
  24964. @group
  24965. |----+----+----+----+----+----3
  24966. |AND | OR |XOR |NOT |LSH |RSH |
  24967. |----+----+----+----+----+----|
  24968. |DEC |HEX |OCT |BIN |WSIZ|ARSH|
  24969. |----+----+----+----+----+----|
  24970. | A | B | C | D | E | F |
  24971. |----+----+----+----+----+----|
  24972. @end group
  24973. @end smallexample
  24974. @noindent
  24975. The keys in this menu perform operations on binary integers.
  24976. Note that both logical and arithmetic right-shifts are provided.
  24977. @key{INV LSH} rotates one bit to the left.
  24978. The ``difference'' function (normally on @kbd{b d}) is on @key{INV AND}.
  24979. The ``clip'' function (normally on @w{@kbd{b c}}) is on @key{INV NOT}.
  24980. The @key{DEC}, @key{HEX}, @key{OCT}, and @key{BIN} keys select the
  24981. current radix for display and entry of numbers: Decimal, hexadecimal,
  24982. octal, or binary. The six letter keys @key{A} through @key{F} are used
  24983. for entering hexadecimal numbers.
  24984. The @key{WSIZ} key displays the current word size for binary operations
  24985. and allows you to enter a new word size. You can respond to the prompt
  24986. using either the keyboard or the digits and @key{ENTER} from the keypad.
  24987. The initial word size is 32 bits.
  24988. @node Keypad Vectors Menu, Keypad Modes Menu, Keypad Binary Menu, Keypad Mode
  24989. @section Vectors Menu
  24990. @smallexample
  24991. @group
  24992. |----+----+----+----+----+----4
  24993. |SUM |PROD|MAX |MAP*|MAP^|MAP$|
  24994. |----+----+----+----+----+----|
  24995. |MINV|MDET|MTRN|IDNT|CRSS|"x" |
  24996. |----+----+----+----+----+----|
  24997. |PACK|UNPK|INDX|BLD |LEN |... |
  24998. |----+----+----+----+----+----|
  24999. @end group
  25000. @end smallexample
  25001. @noindent
  25002. The keys in this menu operate on vectors and matrices.
  25003. @key{PACK} removes an integer @var{n} from the top of the stack;
  25004. the next @var{n} stack elements are removed and packed into a vector,
  25005. which is replaced onto the stack. Thus the sequence
  25006. @kbd{1 ENTER 3 ENTER 5 ENTER 3 PACK} enters the vector
  25007. @samp{[1, 3, 5]} onto the stack. To enter a matrix, build each row
  25008. on the stack as a vector, then use a final @key{PACK} to collect the
  25009. rows into a matrix.
  25010. @key{UNPK} unpacks the vector on the stack, pushing each of its
  25011. components separately.
  25012. @key{INDX} removes an integer @var{n}, then builds a vector of
  25013. integers from 1 to @var{n}. @kbd{INV INDX} takes three numbers
  25014. from the stack: The vector size @var{n}, the starting number,
  25015. and the increment. @kbd{BLD} takes an integer @var{n} and any
  25016. value @var{x} and builds a vector of @var{n} copies of @var{x}.
  25017. @key{IDNT} removes an integer @var{n}, then builds an @var{n}-by-@var{n}
  25018. identity matrix.
  25019. @key{LEN} replaces a vector by its length, an integer.
  25020. @key{...} turns on or off ``abbreviated'' display mode for large vectors.
  25021. @key{MINV}, @key{MDET}, @key{MTRN}, and @key{CROSS} are the matrix
  25022. inverse, determinant, and transpose, and vector cross product.
  25023. @key{SUM} replaces a vector by the sum of its elements. It is
  25024. equivalent to @kbd{u +} in normal Calc (@pxref{Statistical Operations}).
  25025. @key{PROD} computes the product of the elements of a vector, and
  25026. @key{MAX} computes the maximum of all the elements of a vector.
  25027. @key{INV SUM} computes the alternating sum of the first element
  25028. minus the second, plus the third, minus the fourth, and so on.
  25029. @key{INV MAX} computes the minimum of the vector elements.
  25030. @key{HYP SUM} computes the mean of the vector elements.
  25031. @key{HYP PROD} computes the sample standard deviation.
  25032. @key{HYP MAX} computes the median.
  25033. @key{MAP*} multiplies two vectors elementwise. It is equivalent
  25034. to the @kbd{V M *} command. @key{MAP^} computes powers elementwise.
  25035. The arguments must be vectors of equal length, or one must be a vector
  25036. and the other must be a plain number. For example, @kbd{2 MAP^} squares
  25037. all the elements of a vector.
  25038. @key{MAP$} maps the formula on the top of the stack across the
  25039. vector in the second-to-top position. If the formula contains
  25040. several variables, Calc takes that many vectors starting at the
  25041. second-to-top position and matches them to the variables in
  25042. alphabetical order. The result is a vector of the same size as
  25043. the input vectors, whose elements are the formula evaluated with
  25044. the variables set to the various sets of numbers in those vectors.
  25045. For example, you could simulate @key{MAP^} using @key{MAP$} with
  25046. the formula @samp{x^y}.
  25047. The @kbd{"x"} key pushes the variable name @cite{x} onto the
  25048. stack. To build the formula @cite{x^2 + 6}, you would use the
  25049. key sequence @kbd{"x" 2 y^x 6 +}. This formula would then be
  25050. suitable for use with the @key{MAP$} key described above.
  25051. With @key{INV}, @key{HYP}, or @key{INV} and @key{HYP}, the
  25052. @kbd{"x"} key pushes the variable names @cite{y}, @cite{z}, and
  25053. @cite{t}, respectively.
  25054. @node Keypad Modes Menu, , Keypad Vectors Menu, Keypad Mode
  25055. @section Modes Menu
  25056. @smallexample
  25057. @group
  25058. |----+----+----+----+----+----5
  25059. |FLT |FIX |SCI |ENG |GRP | |
  25060. |----+----+----+----+----+----|
  25061. |RAD |DEG |FRAC|POLR|SYMB|PREC|
  25062. |----+----+----+----+----+----|
  25063. |SWAP|RLL3|RLL4|OVER|STO |RCL |
  25064. |----+----+----+----+----+----|
  25065. @end group
  25066. @end smallexample
  25067. @noindent
  25068. The keys in this menu manipulate modes, variables, and the stack.
  25069. The @key{FLT}, @key{FIX}, @key{SCI}, and @key{ENG} keys select
  25070. floating-point, fixed-point, scientific, or engineering notation.
  25071. @key{FIX} displays two digits after the decimal by default; the
  25072. others display full precision. With the @key{INV} prefix, these
  25073. keys pop a number-of-digits argument from the stack.
  25074. The @key{GRP} key turns grouping of digits with commas on or off.
  25075. @kbd{INV GRP} enables grouping to the right of the decimal point as
  25076. well as to the left.
  25077. The @key{RAD} and @key{DEG} keys switch between radians and degrees
  25078. for trigonometric functions.
  25079. The @key{FRAC} key turns Fraction mode on or off. This affects
  25080. whether commands like @kbd{/} with integer arguments produce
  25081. fractional or floating-point results.
  25082. The @key{POLR} key turns Polar mode on or off, determining whether
  25083. polar or rectangular complex numbers are used by default.
  25084. The @key{SYMB} key turns Symbolic mode on or off, in which
  25085. operations that would produce inexact floating-point results
  25086. are left unevaluated as algebraic formulas.
  25087. The @key{PREC} key selects the current precision. Answer with
  25088. the keyboard or with the keypad digit and @key{ENTER} keys.
  25089. The @key{SWAP} key exchanges the top two stack elements.
  25090. The @key{RLL3} key rotates the top three stack elements upwards.
  25091. The @key{RLL4} key rotates the top four stack elements upwards.
  25092. The @key{OVER} key duplicates the second-to-top stack element.
  25093. The @key{STO} and @key{RCL} keys are analogous to @kbd{s t} and
  25094. @kbd{s r} in regular Calc. @xref{Store and Recall}. Click the
  25095. @key{STO} or @key{RCL} key, then one of the ten digits. (Named
  25096. variables are not available in Keypad Mode.) You can also use,
  25097. for example, @kbd{STO + 3} to add to register 3.
  25098. @node Embedded Mode, Programming, Keypad Mode, Top
  25099. @chapter Embedded Mode
  25100. @noindent
  25101. Embedded Mode in Calc provides an alternative to copying numbers
  25102. and formulas back and forth between editing buffers and the Calc
  25103. stack. In Embedded Mode, your editing buffer becomes temporarily
  25104. linked to the stack and this copying is taken care of automatically.
  25105. @menu
  25106. * Basic Embedded Mode::
  25107. * More About Embedded Mode::
  25108. * Assignments in Embedded Mode::
  25109. * Mode Settings in Embedded Mode::
  25110. * Customizing Embedded Mode::
  25111. @end menu
  25112. @node Basic Embedded Mode, More About Embedded Mode, Embedded Mode, Embedded Mode
  25113. @section Basic Embedded Mode
  25114. @noindent
  25115. @kindex M-# e
  25116. @pindex calc-embedded
  25117. To enter Embedded mode, position the Emacs point (cursor) on a
  25118. formula in any buffer and press @kbd{M-# e} (@code{calc-embedded}).
  25119. Note that @kbd{M-# e} is not to be used in the Calc stack buffer
  25120. like most Calc commands, but rather in regular editing buffers that
  25121. are visiting your own files.
  25122. Calc normally scans backward and forward in the buffer for the
  25123. nearest opening and closing @dfn{formula delimiters}. The simplest
  25124. delimiters are blank lines. Other delimiters that Embedded Mode
  25125. understands are:
  25126. @enumerate
  25127. @item
  25128. The @TeX{} and La@TeX{} math delimiters @samp{$ $}, @samp{$$ $$},
  25129. @samp{\[ \]}, and @samp{\( \)};
  25130. @item
  25131. Lines beginning with @samp{\begin} and @samp{\end};
  25132. @item
  25133. Lines beginning with @samp{@@} (Texinfo delimiters).
  25134. @item
  25135. Lines beginning with @samp{.EQ} and @samp{.EN} (@dfn{eqn} delimiters);
  25136. @item
  25137. Lines containing a single @samp{%} or @samp{.\"} symbol and nothing else.
  25138. @end enumerate
  25139. @xref{Customizing Embedded Mode}, to see how to make Calc recognize
  25140. your own favorite delimiters. Delimiters like @samp{$ $} can appear
  25141. on their own separate lines or in-line with the formula.
  25142. If you give a positive or negative numeric prefix argument, Calc
  25143. instead uses the current point as one end of the formula, and moves
  25144. forward or backward (respectively) by that many lines to find the
  25145. other end. Explicit delimiters are not necessary in this case.
  25146. With a prefix argument of zero, Calc uses the current region
  25147. (delimited by point and mark) instead of formula delimiters.
  25148. @kindex M-# w
  25149. @pindex calc-embedded-word
  25150. With a prefix argument of @kbd{C-u} only, Calc scans for the first
  25151. non-numeric character (i.e., the first character that is not a
  25152. digit, sign, decimal point, or upper- or lower-case @samp{e})
  25153. forward and backward to delimit the formula. @kbd{M-# w}
  25154. (@code{calc-embedded-word}) is equivalent to @kbd{C-u M-# e}.
  25155. When you enable Embedded mode for a formula, Calc reads the text
  25156. between the delimiters and tries to interpret it as a Calc formula.
  25157. It's best if the current Calc language mode is correct for the
  25158. formula, but Calc can generally identify @TeX{} formulas and
  25159. Big-style formulas even if the language mode is wrong. If Calc
  25160. can't make sense of the formula, it beeps and refuses to enter
  25161. Embedded mode. But if the current language is wrong, Calc can
  25162. sometimes parse the formula successfully (but incorrectly);
  25163. for example, the C expression @samp{atan(a[1])} can be parsed
  25164. in Normal language mode, but the @code{atan} won't correspond to
  25165. the built-in @code{arctan} function, and the @samp{a[1]} will be
  25166. interpreted as @samp{a} times the vector @samp{[1]}!
  25167. If you press @kbd{M-# e} or @kbd{M-# w} to activate an embedded
  25168. formula which is blank, say with the cursor on the space between
  25169. the two delimiters @samp{$ $}, Calc will immediately prompt for
  25170. an algebraic entry.
  25171. Only one formula in one buffer can be enabled at a time. If you
  25172. move to another area of the current buffer and give Calc commands,
  25173. Calc turns Embedded mode off for the old formula and then tries
  25174. to restart Embedded mode at the new position. Other buffers are
  25175. not affected by Embedded mode.
  25176. When Embedded mode begins, Calc pushes the current formula onto
  25177. the stack. No Calc stack window is created; however, Calc copies
  25178. the top-of-stack position into the original buffer at all times.
  25179. You can create a Calc window by hand with @kbd{M-# o} if you
  25180. find you need to see the entire stack.
  25181. For example, typing @kbd{M-# e} while somewhere in the formula
  25182. @samp{n>2} in the following line enables Embedded mode on that
  25183. inequality:
  25184. @example
  25185. We define $F_n = F_(n-1)+F_(n-2)$ for all $n>2$.
  25186. @end example
  25187. @noindent
  25188. The formula @cite{n>2} will be pushed onto the Calc stack, and
  25189. the top of stack will be copied back into the editing buffer.
  25190. This means that spaces will appear around the @samp{>} symbol
  25191. to match Calc's usual display style:
  25192. @example
  25193. We define $F_n = F_(n-1)+F_(n-2)$ for all $n > 2$.
  25194. @end example
  25195. @noindent
  25196. No spaces have appeared around the @samp{+} sign because it's
  25197. in a different formula, one which we have not yet touched with
  25198. Embedded mode.
  25199. Now that Embedded mode is enabled, keys you type in this buffer
  25200. are interpreted as Calc commands. At this point we might use
  25201. the ``commute'' command @kbd{j C} to reverse the inequality.
  25202. This is a selection-based command for which we first need to
  25203. move the cursor onto the operator (@samp{>} in this case) that
  25204. needs to be commuted.
  25205. @example
  25206. We define $F_n = F_(n-1)+F_(n-2)$ for all $2 < n$.
  25207. @end example
  25208. The @kbd{M-# o} command is a useful way to open a Calc window
  25209. without actually selecting that window. Giving this command
  25210. verifies that @samp{2 < n} is also on the Calc stack. Typing
  25211. @kbd{17 @key{RET}} would produce:
  25212. @example
  25213. We define $F_n = F_(n-1)+F_(n-2)$ for all $17$.
  25214. @end example
  25215. @noindent
  25216. with @samp{2 < n} and @samp{17} on the stack; typing @key{TAB}
  25217. at this point will exchange the two stack values and restore
  25218. @samp{2 < n} to the embedded formula. Even though you can't
  25219. normally see the stack in Embedded mode, it is still there and
  25220. it still operates in the same way. But, as with old-fashioned
  25221. RPN calculators, you can only see the value at the top of the
  25222. stack at any given time (unless you use @kbd{M-# o}).
  25223. Typing @kbd{M-# e} again turns Embedded mode off. The Calc
  25224. window reveals that the formula @w{@samp{2 < n}} is automatically
  25225. removed from the stack, but the @samp{17} is not. Entering
  25226. Embedded mode always pushes one thing onto the stack, and
  25227. leaving Embedded mode always removes one thing. Anything else
  25228. that happens on the stack is entirely your business as far as
  25229. Embedded mode is concerned.
  25230. If you press @kbd{M-# e} in the wrong place by accident, it is
  25231. possible that Calc will be able to parse the nearby text as a
  25232. formula and will mangle that text in an attempt to redisplay it
  25233. ``properly'' in the current language mode. If this happens,
  25234. press @kbd{M-# e} again to exit Embedded mode, then give the
  25235. regular Emacs ``undo'' command (@kbd{C-_} or @kbd{C-x u}) to put
  25236. the text back the way it was before Calc edited it. Note that Calc's
  25237. own Undo command (typed before you turn Embedded mode back off)
  25238. will not do you any good, because as far as Calc is concerned
  25239. you haven't done anything with this formula yet.
  25240. @node More About Embedded Mode, Assignments in Embedded Mode, Basic Embedded Mode, Embedded Mode
  25241. @section More About Embedded Mode
  25242. @noindent
  25243. When Embedded mode ``activates'' a formula, i.e., when it examines
  25244. the formula for the first time since the buffer was created or
  25245. loaded, Calc tries to sense the language in which the formula was
  25246. written. If the formula contains any @TeX{}-like @samp{\} sequences,
  25247. it is parsed (i.e., read) in @TeX{} mode. If the formula appears to
  25248. be written in multi-line Big mode, it is parsed in Big mode. Otherwise,
  25249. it is parsed according to the current language mode.
  25250. Note that Calc does not change the current language mode according
  25251. to what it finds. Even though it can read a @TeX{} formula when
  25252. not in @TeX{} mode, it will immediately rewrite this formula using
  25253. whatever language mode is in effect. You must then type @kbd{d T}
  25254. to switch Calc permanently into @TeX{} mode if that is what you
  25255. desire.
  25256. @tex
  25257. \bigskip
  25258. @end tex
  25259. @kindex d p
  25260. @pindex calc-show-plain
  25261. Calc's parser is unable to read certain kinds of formulas. For
  25262. example, with @kbd{v ]} (@code{calc-matrix-brackets}) you can
  25263. specify matrix display styles which the parser is unable to
  25264. recognize as matrices. The @kbd{d p} (@code{calc-show-plain})
  25265. command turns on a mode in which a ``plain'' version of a
  25266. formula is placed in front of the fully-formatted version.
  25267. When Calc reads a formula that has such a plain version in
  25268. front, it reads the plain version and ignores the formatted
  25269. version.
  25270. Plain formulas are preceded and followed by @samp{%%%} signs
  25271. by default. This notation has the advantage that the @samp{%}
  25272. character begins a comment in @TeX{}, so if your formula is
  25273. embedded in a @TeX{} document its plain version will be
  25274. invisible in the final printed copy. @xref{Customizing
  25275. Embedded Mode}, to see how to change the ``plain'' formula
  25276. delimiters, say to something that @dfn{eqn} or some other
  25277. formatter will treat as a comment.
  25278. There are several notations which Calc's parser for ``big''
  25279. formatted formulas can't yet recognize. In particular, it can't
  25280. read the large symbols for @code{sum}, @code{prod}, and @code{integ},
  25281. and it can't handle @samp{=>} with the righthand argument omitted.
  25282. Also, Calc won't recognize special formats you have defined with
  25283. the @kbd{Z C} command (@pxref{User-Defined Compositions}). In
  25284. these cases it is important to use ``plain'' mode to make sure
  25285. Calc will be able to read your formula later.
  25286. Another example where ``plain'' mode is important is if you have
  25287. specified a float mode with few digits of precision. Normally
  25288. any digits that are computed but not displayed will simply be
  25289. lost when you save and re-load your embedded buffer, but ``plain''
  25290. mode allows you to make sure that the complete number is present
  25291. in the file as well as the rounded-down number.
  25292. @tex
  25293. \bigskip
  25294. @end tex
  25295. Embedded buffers remember active formulas for as long as they
  25296. exist in Emacs memory. Suppose you have an embedded formula
  25297. which is @c{$\pi$}
  25298. @cite{pi} to the normal 12 decimal places, and then
  25299. type @w{@kbd{C-u 5 d n}} to display only five decimal places.
  25300. If you then type @kbd{d n}, all 12 places reappear because the
  25301. full number is still there on the Calc stack. More surprisingly,
  25302. even if you exit Embedded mode and later re-enter it for that
  25303. formula, typing @kbd{d n} will restore all 12 places because
  25304. each buffer remembers all its active formulas. However, if you
  25305. save the buffer in a file and reload it in a new Emacs session,
  25306. all non-displayed digits will have been lost unless you used
  25307. ``plain'' mode.
  25308. @tex
  25309. \bigskip
  25310. @end tex
  25311. In some applications of Embedded mode, you will want to have a
  25312. sequence of copies of a formula that show its evolution as you
  25313. work on it. For example, you might want to have a sequence
  25314. like this in your file (elaborating here on the example from
  25315. the ``Getting Started'' chapter):
  25316. @smallexample
  25317. The derivative of
  25318. ln(ln(x))
  25319. is
  25320. @r{(the derivative of }ln(ln(x))@r{)}
  25321. whose value at x = 2 is
  25322. @r{(the value)}
  25323. and at x = 3 is
  25324. @r{(the value)}
  25325. @end smallexample
  25326. @kindex M-# d
  25327. @pindex calc-embedded-duplicate
  25328. The @kbd{M-# d} (@code{calc-embedded-duplicate}) command is a
  25329. handy way to make sequences like this. If you type @kbd{M-# d},
  25330. the formula under the cursor (which may or may not have Embedded
  25331. mode enabled for it at the time) is copied immediately below and
  25332. Embedded mode is then enabled for that copy.
  25333. For this example, you would start with just
  25334. @smallexample
  25335. The derivative of
  25336. ln(ln(x))
  25337. @end smallexample
  25338. @noindent
  25339. and press @kbd{M-# d} with the cursor on this formula. The result
  25340. is
  25341. @smallexample
  25342. The derivative of
  25343. ln(ln(x))
  25344. ln(ln(x))
  25345. @end smallexample
  25346. @noindent
  25347. with the second copy of the formula enabled in Embedded mode.
  25348. You can now press @kbd{a d x @key{RET}} to take the derivative, and
  25349. @kbd{M-# d M-# d} to make two more copies of the derivative.
  25350. To complete the computations, type @kbd{3 s l x @key{RET}} to evaluate
  25351. the last formula, then move up to the second-to-last formula
  25352. and type @kbd{2 s l x @key{RET}}.
  25353. Finally, you would want to press @kbd{M-# e} to exit Embedded
  25354. mode, then go up and insert the necessary text in between the
  25355. various formulas and numbers.
  25356. @tex
  25357. \bigskip
  25358. @end tex
  25359. @kindex M-# f
  25360. @kindex M-# '
  25361. @pindex calc-embedded-new-formula
  25362. The @kbd{M-# f} (@code{calc-embedded-new-formula}) command
  25363. creates a new embedded formula at the current point. It inserts
  25364. some default delimiters, which are usually just blank lines,
  25365. and then does an algebraic entry to get the formula (which is
  25366. then enabled for Embedded mode). This is just shorthand for
  25367. typing the delimiters yourself, positioning the cursor between
  25368. the new delimiters, and pressing @kbd{M-# e}. The key sequence
  25369. @kbd{M-# '} is equivalent to @kbd{M-# f}.
  25370. @kindex M-# n
  25371. @kindex M-# p
  25372. @pindex calc-embedded-next
  25373. @pindex calc-embedded-previous
  25374. The @kbd{M-# n} (@code{calc-embedded-next}) and @kbd{M-# p}
  25375. (@code{calc-embedded-previous}) commands move the cursor to the
  25376. next or previous active embedded formula in the buffer. They
  25377. can take positive or negative prefix arguments to move by several
  25378. formulas. Note that these commands do not actually examine the
  25379. text of the buffer looking for formulas; they only see formulas
  25380. which have previously been activated in Embedded mode. In fact,
  25381. @kbd{M-# n} and @kbd{M-# p} are a useful way to tell which
  25382. embedded formulas are currently active. Also, note that these
  25383. commands do not enable Embedded mode on the next or previous
  25384. formula, they just move the cursor. (By the way, @kbd{M-# n} is
  25385. not as awkward to type as it may seem, because @kbd{M-#} ignores
  25386. Shift and Meta on the second keystroke: @kbd{M-# M-N} can be typed
  25387. by holding down Shift and Meta and alternately typing two keys.)
  25388. @kindex M-# `
  25389. @pindex calc-embedded-edit
  25390. The @kbd{M-# `} (@code{calc-embedded-edit}) command edits the
  25391. embedded formula at the current point as if by @kbd{`} (@code{calc-edit}).
  25392. Embedded mode does not have to be enabled for this to work. Press
  25393. @kbd{M-# M-#} to finish the edit, or @kbd{M-# x} to cancel.
  25394. @node Assignments in Embedded Mode, Mode Settings in Embedded Mode, More About Embedded Mode, Embedded Mode
  25395. @section Assignments in Embedded Mode
  25396. @noindent
  25397. The @samp{:=} (assignment) and @samp{=>} (``evaluates-to'') operators
  25398. are especially useful in Embedded mode. They allow you to make
  25399. a definition in one formula, then refer to that definition in
  25400. other formulas embedded in the same buffer.
  25401. An embedded formula which is an assignment to a variable, as in
  25402. @example
  25403. foo := 5
  25404. @end example
  25405. @noindent
  25406. records @cite{5} as the stored value of @code{foo} for the
  25407. purposes of Embedded mode operations in the current buffer. It
  25408. does @emph{not} actually store @cite{5} as the ``global'' value
  25409. of @code{foo}, however. Regular Calc operations, and Embedded
  25410. formulas in other buffers, will not see this assignment.
  25411. One way to use this assigned value is simply to create an
  25412. Embedded formula elsewhere that refers to @code{foo}, and to press
  25413. @kbd{=} in that formula. However, this permanently replaces the
  25414. @code{foo} in the formula with its current value. More interesting
  25415. is to use @samp{=>} elsewhere:
  25416. @example
  25417. foo + 7 => 12
  25418. @end example
  25419. @xref{Evaluates-To Operator}, for a general discussion of @samp{=>}.
  25420. If you move back and change the assignment to @code{foo}, any
  25421. @samp{=>} formulas which refer to it are automatically updated.
  25422. @example
  25423. foo := 17
  25424. foo + 7 => 24
  25425. @end example
  25426. The obvious question then is, @emph{how} can one easily change the
  25427. assignment to @code{foo}? If you simply select the formula in
  25428. Embedded mode and type 17, the assignment itself will be replaced
  25429. by the 17. The effect on the other formula will be that the
  25430. variable @code{foo} becomes unassigned:
  25431. @example
  25432. 17
  25433. foo + 7 => foo + 7
  25434. @end example
  25435. The right thing to do is first to use a selection command (@kbd{j 2}
  25436. will do the trick) to select the righthand side of the assignment.
  25437. Then, @kbd{17 @key{TAB} @key{DEL}} will swap the 17 into place (@pxref{Selecting
  25438. Subformulas}, to see how this works).
  25439. @kindex M-# j
  25440. @pindex calc-embedded-select
  25441. The @kbd{M-# j} (@code{calc-embedded-select}) command provides an
  25442. easy way to operate on assigments. It is just like @kbd{M-# e},
  25443. except that if the enabled formula is an assignment, it uses
  25444. @kbd{j 2} to select the righthand side. If the enabled formula
  25445. is an evaluates-to, it uses @kbd{j 1} to select the lefthand side.
  25446. A formula can also be a combination of both:
  25447. @example
  25448. bar := foo + 3 => 20
  25449. @end example
  25450. @noindent
  25451. in which case @kbd{M-# j} will select the middle part (@samp{foo + 3}).
  25452. The formula is automatically deselected when you leave Embedded
  25453. mode.
  25454. @kindex M-# u
  25455. @kindex M-# =
  25456. @pindex calc-embedded-update
  25457. Another way to change the assignment to @code{foo} would simply be
  25458. to edit the number using regular Emacs editing rather than Embedded
  25459. mode. Then, we have to find a way to get Embedded mode to notice
  25460. the change. The @kbd{M-# u} or @kbd{M-# =}
  25461. (@code{calc-embedded-update-formula}) command is a convenient way
  25462. to do this.@refill
  25463. @example
  25464. foo := 6
  25465. foo + 7 => 13
  25466. @end example
  25467. Pressing @kbd{M-# u} is much like pressing @kbd{M-# e = M-# e}, that
  25468. is, temporarily enabling Embedded mode for the formula under the
  25469. cursor and then evaluating it with @kbd{=}. But @kbd{M-# u} does
  25470. not actually use @kbd{M-# e}, and in fact another formula somewhere
  25471. else can be enabled in Embedded mode while you use @kbd{M-# u} and
  25472. that formula will not be disturbed.
  25473. With a numeric prefix argument, @kbd{M-# u} updates all active
  25474. @samp{=>} formulas in the buffer. Formulas which have not yet
  25475. been activated in Embedded mode, and formulas which do not have
  25476. @samp{=>} as their top-level operator, are not affected by this.
  25477. (This is useful only if you have used @kbd{m C}; see below.)
  25478. With a plain @kbd{C-u} prefix, @kbd{C-u M-# u} updates only in the
  25479. region between mark and point rather than in the whole buffer.
  25480. @kbd{M-# u} is also a handy way to activate a formula, such as an
  25481. @samp{=>} formula that has freshly been typed in or loaded from a
  25482. file.
  25483. @kindex M-# a
  25484. @pindex calc-embedded-activate
  25485. The @kbd{M-# a} (@code{calc-embedded-activate}) command scans
  25486. through the current buffer and activates all embedded formulas
  25487. that contain @samp{:=} or @samp{=>} symbols. This does not mean
  25488. that Embedded mode is actually turned on, but only that the
  25489. formulas' positions are registered with Embedded mode so that
  25490. the @samp{=>} values can be properly updated as assignments are
  25491. changed.
  25492. It is a good idea to type @kbd{M-# a} right after loading a file
  25493. that uses embedded @samp{=>} operators. Emacs includes a nifty
  25494. ``buffer-local variables'' feature that you can use to do this
  25495. automatically. The idea is to place near the end of your file
  25496. a few lines that look like this:
  25497. @example
  25498. --- Local Variables: ---
  25499. --- eval:(calc-embedded-activate) ---
  25500. --- End: ---
  25501. @end example
  25502. @noindent
  25503. where the leading and trailing @samp{---} can be replaced by
  25504. any suitable strings (which must be the same on all three lines)
  25505. or omitted altogether; in a @TeX{} file, @samp{%} would be a good
  25506. leading string and no trailing string would be necessary. In a
  25507. C program, @samp{/*} and @samp{*/} would be good leading and
  25508. trailing strings.
  25509. When Emacs loads a file into memory, it checks for a Local Variables
  25510. section like this one at the end of the file. If it finds this
  25511. section, it does the specified things (in this case, running
  25512. @kbd{M-# a} automatically) before editing of the file begins.
  25513. The Local Variables section must be within 3000 characters of the
  25514. end of the file for Emacs to find it, and it must be in the last
  25515. page of the file if the file has any page separators.
  25516. @xref{File Variables, , Local Variables in Files, emacs, the
  25517. Emacs manual}.
  25518. Note that @kbd{M-# a} does not update the formulas it finds.
  25519. To do this, type, say, @kbd{M-1 M-# u} after @w{@kbd{M-# a}}.
  25520. Generally this should not be a problem, though, because the
  25521. formulas will have been up-to-date already when the file was
  25522. saved.
  25523. Normally, @kbd{M-# a} activates all the formulas it finds, but
  25524. any previous active formulas remain active as well. With a
  25525. positive numeric prefix argument, @kbd{M-# a} first deactivates
  25526. all current active formulas, then actives the ones it finds in
  25527. its scan of the buffer. With a negative prefix argument,
  25528. @kbd{M-# a} simply deactivates all formulas.
  25529. Embedded mode has two symbols, @samp{Active} and @samp{~Active},
  25530. which it puts next to the major mode name in a buffer's mode line.
  25531. It puts @samp{Active} if it has reason to believe that all
  25532. formulas in the buffer are active, because you have typed @kbd{M-# a}
  25533. and Calc has not since had to deactivate any formulas (which can
  25534. happen if Calc goes to update an @samp{=>} formula somewhere because
  25535. a variable changed, and finds that the formula is no longer there
  25536. due to some kind of editing outside of Embedded mode). Calc puts
  25537. @samp{~Active} in the mode line if some, but probably not all,
  25538. formulas in the buffer are active. This happens if you activate
  25539. a few formulas one at a time but never use @kbd{M-# a}, or if you
  25540. used @kbd{M-# a} but then Calc had to deactivate a formula
  25541. because it lost track of it. If neither of these symbols appears
  25542. in the mode line, no embedded formulas are active in the buffer
  25543. (e.g., before Embedded mode has been used, or after a @kbd{M-- M-# a}).
  25544. Embedded formulas can refer to assignments both before and after them
  25545. in the buffer. If there are several assignments to a variable, the
  25546. nearest preceding assignment is used if there is one, otherwise the
  25547. following assignment is used.
  25548. @example
  25549. x => 1
  25550. x := 1
  25551. x => 1
  25552. x := 2
  25553. x => 2
  25554. @end example
  25555. As well as simple variables, you can also assign to subscript
  25556. expressions of the form @samp{@var{var}_@var{number}} (as in
  25557. @code{x_0}), or @samp{@var{var}_@var{var}} (as in @code{x_max}).
  25558. Assignments to other kinds of objects can be represented by Calc,
  25559. but the automatic linkage between assignments and references works
  25560. only for plain variables and these two kinds of subscript expressions.
  25561. If there are no assignments to a given variable, the global
  25562. stored value for the variable is used (@pxref{Storing Variables}),
  25563. or, if no value is stored, the variable is left in symbolic form.
  25564. Note that global stored values will be lost when the file is saved
  25565. and loaded in a later Emacs session, unless you have used the
  25566. @kbd{s p} (@code{calc-permanent-variable}) command to save them;
  25567. @pxref{Operations on Variables}.
  25568. The @kbd{m C} (@code{calc-auto-recompute}) command turns automatic
  25569. recomputation of @samp{=>} forms on and off. If you turn automatic
  25570. recomputation off, you will have to use @kbd{M-# u} to update these
  25571. formulas manually after an assignment has been changed. If you
  25572. plan to change several assignments at once, it may be more efficient
  25573. to type @kbd{m C}, change all the assignments, then use @kbd{M-1 M-# u}
  25574. to update the entire buffer afterwards. The @kbd{m C} command also
  25575. controls @samp{=>} formulas on the stack; @pxref{Evaluates-To
  25576. Operator}. When you turn automatic recomputation back on, the
  25577. stack will be updated but the Embedded buffer will not; you must
  25578. use @kbd{M-# u} to update the buffer by hand.
  25579. @node Mode Settings in Embedded Mode, Customizing Embedded Mode, Assignments in Embedded Mode, Embedded Mode
  25580. @section Mode Settings in Embedded Mode
  25581. @noindent
  25582. Embedded Mode has a rather complicated mechanism for handling mode
  25583. settings in Embedded formulas. It is possible to put annotations
  25584. in the file that specify mode settings either global to the entire
  25585. file or local to a particular formula or formulas. In the latter
  25586. case, different modes can be specified for use when a formula
  25587. is the enabled Embedded Mode formula.
  25588. When you give any mode-setting command, like @kbd{m f} (for fraction
  25589. mode) or @kbd{d s} (for scientific notation), Embedded Mode adds
  25590. a line like the following one to the file just before the opening
  25591. delimiter of the formula.
  25592. @example
  25593. % [calc-mode: fractions: t]
  25594. % [calc-mode: float-format: (sci 0)]
  25595. @end example
  25596. When Calc interprets an embedded formula, it scans the text before
  25597. the formula for mode-setting annotations like these and sets the
  25598. Calc buffer to match these modes. Modes not explicitly described
  25599. in the file are not changed. Calc scans all the way to the top of
  25600. the file, or up to a line of the form
  25601. @example
  25602. % [calc-defaults]
  25603. @end example
  25604. @noindent
  25605. which you can insert at strategic places in the file if this backward
  25606. scan is getting too slow, or just to provide a barrier between one
  25607. ``zone'' of mode settings and another.
  25608. If the file contains several annotations for the same mode, the
  25609. closest one before the formula is used. Annotations after the
  25610. formula are never used (except for global annotations, described
  25611. below).
  25612. The scan does not look for the leading @samp{% }, only for the
  25613. square brackets and the text they enclose. You can edit the mode
  25614. annotations to a style that works better in context if you wish.
  25615. @xref{Customizing Embedded Mode}, to see how to change the style
  25616. that Calc uses when it generates the annotations. You can write
  25617. mode annotations into the file yourself if you know the syntax;
  25618. the easiest way to find the syntax for a given mode is to let
  25619. Calc write the annotation for it once and see what it does.
  25620. If you give a mode-changing command for a mode that already has
  25621. a suitable annotation just above the current formula, Calc will
  25622. modify that annotation rather than generating a new, conflicting
  25623. one.
  25624. Mode annotations have three parts, separated by colons. (Spaces
  25625. after the colons are optional.) The first identifies the kind
  25626. of mode setting, the second is a name for the mode itself, and
  25627. the third is the value in the form of a Lisp symbol, number,
  25628. or list. Annotations with unrecognizable text in the first or
  25629. second parts are ignored. The third part is not checked to make
  25630. sure the value is of a legal type or range; if you write an
  25631. annotation by hand, be sure to give a proper value or results
  25632. will be unpredictable. Mode-setting annotations are case-sensitive.
  25633. While Embedded Mode is enabled, the word @code{Local} appears in
  25634. the mode line. This is to show that mode setting commands generate
  25635. annotations that are ``local'' to the current formula or set of
  25636. formulas. The @kbd{m R} (@code{calc-mode-record-mode}) command
  25637. causes Calc to generate different kinds of annotations. Pressing
  25638. @kbd{m R} repeatedly cycles through the possible modes.
  25639. @code{LocEdit} and @code{LocPerm} modes generate annotations
  25640. that look like this, respectively:
  25641. @example
  25642. % [calc-edit-mode: float-format: (sci 0)]
  25643. % [calc-perm-mode: float-format: (sci 5)]
  25644. @end example
  25645. The first kind of annotation will be used only while a formula
  25646. is enabled in Embedded Mode. The second kind will be used only
  25647. when the formula is @emph{not} enabled. (Whether the formula
  25648. is ``active'' or not, i.e., whether Calc has seen this formula
  25649. yet, is not relevant here.)
  25650. @code{Global} mode generates an annotation like this at the end
  25651. of the file:
  25652. @example
  25653. % [calc-global-mode: fractions t]
  25654. @end example
  25655. Global mode annotations affect all formulas throughout the file,
  25656. and may appear anywhere in the file. This allows you to tuck your
  25657. mode annotations somewhere out of the way, say, on a new page of
  25658. the file, as long as those mode settings are suitable for all
  25659. formulas in the file.
  25660. Enabling a formula with @kbd{M-# e} causes a fresh scan for local
  25661. mode annotations; you will have to use this after adding annotations
  25662. above a formula by hand to get the formula to notice them. Updating
  25663. a formula with @kbd{M-# u} will also re-scan the local modes, but
  25664. global modes are only re-scanned by @kbd{M-# a}.
  25665. Another way that modes can get out of date is if you add a local
  25666. mode annotation to a formula that has another formula after it.
  25667. In this example, we have used the @kbd{d s} command while the
  25668. first of the two embedded formulas is active. But the second
  25669. formula has not changed its style to match, even though by the
  25670. rules of reading annotations the @samp{(sci 0)} applies to it, too.
  25671. @example
  25672. % [calc-mode: float-format: (sci 0)]
  25673. 1.23e2
  25674. 456.
  25675. @end example
  25676. We would have to go down to the other formula and press @kbd{M-# u}
  25677. on it in order to get it to notice the new annotation.
  25678. Two more mode-recording modes selectable by @kbd{m R} are @code{Save}
  25679. (which works even outside of Embedded Mode), in which mode settings
  25680. are recorded permanently in your Emacs startup file @file{~/.emacs}
  25681. rather than by annotating the current document, and no-recording
  25682. mode (where there is no symbol like @code{Save} or @code{Local} in
  25683. the mode line), in which mode-changing commands do not leave any
  25684. annotations at all.
  25685. When Embedded Mode is not enabled, mode-recording modes except
  25686. for @code{Save} have no effect.
  25687. @node Customizing Embedded Mode, , Mode Settings in Embedded Mode, Embedded Mode
  25688. @section Customizing Embedded Mode
  25689. @noindent
  25690. You can modify Embedded Mode's behavior by setting various Lisp
  25691. variables described here. Use @kbd{M-x set-variable} or
  25692. @kbd{M-x edit-options} to adjust a variable on the fly, or
  25693. put a suitable @code{setq} statement in your @file{~/.emacs}
  25694. file to set a variable permanently. (Another possibility would
  25695. be to use a file-local variable annotation at the end of the
  25696. file; @pxref{File Variables, , Local Variables in Files, emacs, the
  25697. Emacs manual}.)
  25698. While none of these variables will be buffer-local by default, you
  25699. can make any of them local to any embedded-mode buffer. (Their
  25700. values in the @samp{*Calculator*} buffer are never used.)
  25701. @vindex calc-embedded-open-formula
  25702. The @code{calc-embedded-open-formula} variable holds a regular
  25703. expression for the opening delimiter of a formula. @xref{Regexp Search,
  25704. , Regular Expression Search, emacs, the Emacs manual}, to see
  25705. how regular expressions work. Basically, a regular expression is a
  25706. pattern that Calc can search for. A regular expression that considers
  25707. blank lines, @samp{$}, and @samp{$$} to be opening delimiters is
  25708. @code{"\\`\\|^\n\\|\\$\\$?"}. Just in case the meaning of this
  25709. regular expression is not completely plain, let's go through it
  25710. in detail.
  25711. The surrounding @samp{" "} marks quote the text between them as a
  25712. Lisp string. If you left them off, @code{set-variable} or
  25713. @code{edit-options} would try to read the regular expression as a
  25714. Lisp program.
  25715. The most obvious property of this regular expression is that it
  25716. contains indecently many backslashes. There are actually two levels
  25717. of backslash usage going on here. First, when Lisp reads a quoted
  25718. string, all pairs of characters beginning with a backslash are
  25719. interpreted as special characters. Here, @code{\n} changes to a
  25720. new-line character, and @code{\\} changes to a single backslash.
  25721. So the actual regular expression seen by Calc is
  25722. @samp{\`\|^ @r{(newline)} \|\$\$?}.
  25723. Regular expressions also consider pairs beginning with backslash
  25724. to have special meanings. Sometimes the backslash is used to quote
  25725. a character that otherwise would have a special meaning in a regular
  25726. expression, like @samp{$}, which normally means ``end-of-line,''
  25727. or @samp{?}, which means that the preceding item is optional. So
  25728. @samp{\$\$?} matches either one or two dollar signs.
  25729. The other codes in this regular expression are @samp{^}, which matches
  25730. ``beginning-of-line,'' @samp{\|}, which means ``or,'' and @samp{\`},
  25731. which matches ``beginning-of-buffer.'' So the whole pattern means
  25732. that a formula begins at the beginning of the buffer, or on a newline
  25733. that occurs at the beginning of a line (i.e., a blank line), or at
  25734. one or two dollar signs.
  25735. The default value of @code{calc-embedded-open-formula} looks just
  25736. like this example, with several more alternatives added on to
  25737. recognize various other common kinds of delimiters.
  25738. By the way, the reason to use @samp{^\n} rather than @samp{^$}
  25739. or @samp{\n\n}, which also would appear to match blank lines,
  25740. is that the former expression actually ``consumes'' only one
  25741. newline character as @emph{part of} the delimiter, whereas the
  25742. latter expressions consume zero or two newlines, respectively.
  25743. The former choice gives the most natural behavior when Calc
  25744. must operate on a whole formula including its delimiters.
  25745. See the Emacs manual for complete details on regular expressions.
  25746. But just for your convenience, here is a list of all characters
  25747. which must be quoted with backslash (like @samp{\$}) to avoid
  25748. some special interpretation: @samp{. * + ? [ ] ^ $ \}. (Note
  25749. the backslash in this list; for example, to match @samp{\[} you
  25750. must use @code{"\\\\\\["}. An exercise for the reader is to
  25751. account for each of these six backslashes!)
  25752. @vindex calc-embedded-close-formula
  25753. The @code{calc-embedded-close-formula} variable holds a regular
  25754. expression for the closing delimiter of a formula. A closing
  25755. regular expression to match the above example would be
  25756. @code{"\\'\\|\n$\\|\\$\\$?"}. This is almost the same as the
  25757. other one, except it now uses @samp{\'} (``end-of-buffer'') and
  25758. @samp{\n$} (newline occurring at end of line, yet another way
  25759. of describing a blank line that is more appropriate for this
  25760. case).
  25761. @vindex calc-embedded-open-word
  25762. @vindex calc-embedded-close-word
  25763. The @code{calc-embedded-open-word} and @code{calc-embedded-close-word}
  25764. variables are similar expressions used when you type @kbd{M-# w}
  25765. instead of @kbd{M-# e} to enable Embedded mode.
  25766. @vindex calc-embedded-open-plain
  25767. The @code{calc-embedded-open-plain} variable is a string which
  25768. begins a ``plain'' formula written in front of the formatted
  25769. formula when @kbd{d p} mode is turned on. Note that this is an
  25770. actual string, not a regular expression, because Calc must be able
  25771. to write this string into a buffer as well as to recognize it.
  25772. The default string is @code{"%%% "} (note the trailing space).
  25773. @vindex calc-embedded-close-plain
  25774. The @code{calc-embedded-close-plain} variable is a string which
  25775. ends a ``plain'' formula. The default is @code{" %%%\n"}. Without
  25776. the trailing newline here, the first line of a ``big'' mode formula
  25777. that followed might be shifted over with respect to the other lines.
  25778. @vindex calc-embedded-open-new-formula
  25779. The @code{calc-embedded-open-new-formula} variable is a string
  25780. which is inserted at the front of a new formula when you type
  25781. @kbd{M-# f}. Its default value is @code{"\n\n"}. If this
  25782. string begins with a newline character and the @kbd{M-# f} is
  25783. typed at the beginning of a line, @kbd{M-# f} will skip this
  25784. first newline to avoid introducing unnecessary blank lines in
  25785. the file.
  25786. @vindex calc-embedded-close-new-formula
  25787. The @code{calc-embedded-close-new-formula} variable is the corresponding
  25788. string which is inserted at the end of a new formula. Its default
  25789. value is also @code{"\n\n"}. The final newline is omitted by
  25790. @w{@kbd{M-# f}} if typed at the end of a line. (It follows that if
  25791. @kbd{M-# f} is typed on a blank line, both a leading opening
  25792. newline and a trailing closing newline are omitted.)
  25793. @vindex calc-embedded-announce-formula
  25794. The @code{calc-embedded-announce-formula} variable is a regular
  25795. expression which is sure to be followed by an embedded formula.
  25796. The @kbd{M-# a} command searches for this pattern as well as for
  25797. @samp{=>} and @samp{:=} operators. Note that @kbd{M-# a} will
  25798. not activate just anything surrounded by formula delimiters; after
  25799. all, blank lines are considered formula delimiters by default!
  25800. But if your language includes a delimiter which can only occur
  25801. actually in front of a formula, you can take advantage of it here.
  25802. The default pattern is @code{"%Embed\n\\(% .*\n\\)*"}, which
  25803. checks for @samp{%Embed} followed by any number of lines beginning
  25804. with @samp{%} and a space. This last is important to make Calc
  25805. consider mode annotations part of the pattern, so that the formula's
  25806. opening delimiter really is sure to follow the pattern.
  25807. @vindex calc-embedded-open-mode
  25808. The @code{calc-embedded-open-mode} variable is a string (not a
  25809. regular expression) which should precede a mode annotation.
  25810. Calc never scans for this string; Calc always looks for the
  25811. annotation itself. But this is the string that is inserted before
  25812. the opening bracket when Calc adds an annotation on its own.
  25813. The default is @code{"% "}.
  25814. @vindex calc-embedded-close-mode
  25815. The @code{calc-embedded-close-mode} variable is a string which
  25816. follows a mode annotation written by Calc. Its default value
  25817. is simply a newline, @code{"\n"}. If you change this, it is a
  25818. good idea still to end with a newline so that mode annotations
  25819. will appear on lines by themselves.
  25820. @node Programming, Installation, Embedded Mode, Top
  25821. @chapter Programming
  25822. @noindent
  25823. There are several ways to ``program'' the Emacs Calculator, depending
  25824. on the nature of the problem you need to solve.
  25825. @enumerate
  25826. @item
  25827. @dfn{Keyboard macros} allow you to record a sequence of keystrokes
  25828. and play them back at a later time. This is just the standard Emacs
  25829. keyboard macro mechanism, dressed up with a few more features such
  25830. as loops and conditionals.
  25831. @item
  25832. @dfn{Algebraic definitions} allow you to use any formula to define a
  25833. new function. This function can then be used in algebraic formulas or
  25834. as an interactive command.
  25835. @item
  25836. @dfn{Rewrite rules} are discussed in the section on algebra commands.
  25837. @xref{Rewrite Rules}. If you put your rewrite rules in the variable
  25838. @code{EvalRules}, they will be applied automatically to all Calc
  25839. results in just the same way as an internal ``rule'' is applied to
  25840. evaluate @samp{sqrt(9)} to 3 and so on. @xref{Automatic Rewrites}.
  25841. @item
  25842. @dfn{Lisp} is the programming language that Calc (and most of Emacs)
  25843. is written in. If the above techniques aren't powerful enough, you
  25844. can write Lisp functions to do anything that built-in Calc commands
  25845. can do. Lisp code is also somewhat faster than keyboard macros or
  25846. rewrite rules.
  25847. @end enumerate
  25848. @kindex z
  25849. Programming features are available through the @kbd{z} and @kbd{Z}
  25850. prefix keys. New commands that you define are two-key sequences
  25851. beginning with @kbd{z}. Commands for managing these definitions
  25852. use the shift-@kbd{Z} prefix. (The @kbd{Z T} (@code{calc-timing})
  25853. command is described elsewhere; @pxref{Troubleshooting Commands}.
  25854. The @kbd{Z C} (@code{calc-user-define-composition}) command is also
  25855. described elsewhere; @pxref{User-Defined Compositions}.)
  25856. @menu
  25857. * Creating User Keys::
  25858. * Keyboard Macros::
  25859. * Invocation Macros::
  25860. * Algebraic Definitions::
  25861. * Lisp Definitions::
  25862. @end menu
  25863. @node Creating User Keys, Keyboard Macros, Programming, Programming
  25864. @section Creating User Keys
  25865. @noindent
  25866. @kindex Z D
  25867. @pindex calc-user-define
  25868. Any Calculator command may be bound to a key using the @kbd{Z D}
  25869. (@code{calc-user-define}) command. Actually, it is bound to a two-key
  25870. sequence beginning with the lower-case @kbd{z} prefix.
  25871. The @kbd{Z D} command first prompts for the key to define. For example,
  25872. press @kbd{Z D a} to define the new key sequence @kbd{z a}. You are then
  25873. prompted for the name of the Calculator command that this key should
  25874. run. For example, the @code{calc-sincos} command is not normally
  25875. available on a key. Typing @kbd{Z D s sincos @key{RET}} programs the
  25876. @kbd{z s} key sequence to run @code{calc-sincos}. This definition will remain
  25877. in effect for the rest of this Emacs session, or until you redefine
  25878. @kbd{z s} to be something else.
  25879. You can actually bind any Emacs command to a @kbd{z} key sequence by
  25880. backspacing over the @samp{calc-} when you are prompted for the command name.
  25881. As with any other prefix key, you can type @kbd{z ?} to see a list of
  25882. all the two-key sequences you have defined that start with @kbd{z}.
  25883. Initially, no @kbd{z} sequences (except @kbd{z ?} itself) are defined.
  25884. User keys are typically letters, but may in fact be any key.
  25885. (@key{META}-keys are not permitted, nor are a terminal's special
  25886. function keys which generate multi-character sequences when pressed.)
  25887. You can define different commands on the shifted and unshifted versions
  25888. of a letter if you wish.
  25889. @kindex Z U
  25890. @pindex calc-user-undefine
  25891. The @kbd{Z U} (@code{calc-user-undefine}) command unbinds a user key.
  25892. For example, the key sequence @kbd{Z U s} will undefine the @code{sincos}
  25893. key we defined above.
  25894. @kindex Z P
  25895. @pindex calc-user-define-permanent
  25896. @cindex Storing user definitions
  25897. @cindex Permanent user definitions
  25898. @cindex @file{.emacs} file, user-defined commands
  25899. The @kbd{Z P} (@code{calc-user-define-permanent}) command makes a key
  25900. binding permanent so that it will remain in effect even in future Emacs
  25901. sessions. (It does this by adding a suitable bit of Lisp code into
  25902. your @file{.emacs} file.) For example, @kbd{Z P s} would register
  25903. our @code{sincos} command permanently. If you later wish to unregister
  25904. this command you must edit your @file{.emacs} file by hand.
  25905. (@xref{General Mode Commands}, for a way to tell Calc to use a
  25906. different file instead of @file{.emacs}.)
  25907. The @kbd{Z P} command also saves the user definition, if any, for the
  25908. command bound to the key. After @kbd{Z F} and @kbd{Z C}, a given user
  25909. key could invoke a command, which in turn calls an algebraic function,
  25910. which might have one or more special display formats. A single @kbd{Z P}
  25911. command will save all of these definitions.
  25912. To save a command or function without its key binding (or if there is
  25913. no key binding for the command or function), type @kbd{'} (the apostrophe)
  25914. when prompted for a key. Then, type the function name, or backspace
  25915. to change the @samp{calcFunc-} prefix to @samp{calc-} and enter a
  25916. command name. (If the command you give implies a function, the function
  25917. will be saved, and if the function has any display formats, those will
  25918. be saved, but not the other way around: Saving a function will not save
  25919. any commands or key bindings associated with the function.)
  25920. @kindex Z E
  25921. @pindex calc-user-define-edit
  25922. @cindex Editing user definitions
  25923. The @kbd{Z E} (@code{calc-user-define-edit}) command edits the definition
  25924. of a user key. This works for keys that have been defined by either
  25925. keyboard macros or formulas; further details are contained in the relevant
  25926. following sections.
  25927. @node Keyboard Macros, Invocation Macros, Creating User Keys, Programming
  25928. @section Programming with Keyboard Macros
  25929. @noindent
  25930. @kindex X
  25931. @cindex Programming with keyboard macros
  25932. @cindex Keyboard macros
  25933. The easiest way to ``program'' the Emacs Calculator is to use standard
  25934. keyboard macros. Press @w{@kbd{C-x (}} to begin recording a macro. From
  25935. this point on, keystrokes you type will be saved away as well as
  25936. performing their usual functions. Press @kbd{C-x )} to end recording.
  25937. Press shift-@kbd{X} (or the standard Emacs key sequence @kbd{C-x e}) to
  25938. execute your keyboard macro by replaying the recorded keystrokes.
  25939. @xref{Keyboard Macros, , , emacs, the Emacs Manual}, for further
  25940. information.@refill
  25941. When you use @kbd{X} to invoke a keyboard macro, the entire macro is
  25942. treated as a single command by the undo and trail features. The stack
  25943. display buffer is not updated during macro execution, but is instead
  25944. fixed up once the macro completes. Thus, commands defined with keyboard
  25945. macros are convenient and efficient. The @kbd{C-x e} command, on the
  25946. other hand, invokes the keyboard macro with no special treatment: Each
  25947. command in the macro will record its own undo information and trail entry,
  25948. and update the stack buffer accordingly. If your macro uses features
  25949. outside of Calc's control to operate on the contents of the Calc stack
  25950. buffer, or if it includes Undo, Redo, or last-arguments commands, you
  25951. must use @kbd{C-x e} to make sure the buffer and undo list are up-to-date
  25952. at all times. You could also consider using @kbd{K} (@code{calc-keep-args})
  25953. instead of @kbd{M-@key{RET}} (@code{calc-last-args}).
  25954. Calc extends the standard Emacs keyboard macros in several ways.
  25955. Keyboard macros can be used to create user-defined commands. Keyboard
  25956. macros can include conditional and iteration structures, somewhat
  25957. analogous to those provided by a traditional programmable calculator.
  25958. @menu
  25959. * Naming Keyboard Macros::
  25960. * Conditionals in Macros::
  25961. * Loops in Macros::
  25962. * Local Values in Macros::
  25963. * Queries in Macros::
  25964. @end menu
  25965. @node Naming Keyboard Macros, Conditionals in Macros, Keyboard Macros, Keyboard Macros
  25966. @subsection Naming Keyboard Macros
  25967. @noindent
  25968. @kindex Z K
  25969. @pindex calc-user-define-kbd-macro
  25970. Once you have defined a keyboard macro, you can bind it to a @kbd{z}
  25971. key sequence with the @kbd{Z K} (@code{calc-user-define-kbd-macro}) command.
  25972. This command prompts first for a key, then for a command name. For
  25973. example, if you type @kbd{C-x ( n @key{TAB} n @key{TAB} C-x )} you will
  25974. define a keyboard macro which negates the top two numbers on the stack
  25975. (@key{TAB} swaps the top two stack elements). Now you can type
  25976. @kbd{Z K n @key{RET}} to define this keyboard macro onto the @kbd{z n} key
  25977. sequence. The default command name (if you answer the second prompt with
  25978. just the @key{RET} key as in this example) will be something like
  25979. @samp{calc-User-n}. The keyboard macro will now be available as both
  25980. @kbd{z n} and @kbd{M-x calc-User-n}. You can backspace and enter a more
  25981. descriptive command name if you wish.@refill
  25982. Macros defined by @kbd{Z K} act like single commands; they are executed
  25983. in the same way as by the @kbd{X} key. If you wish to define the macro
  25984. as a standard no-frills Emacs macro (to be executed as if by @kbd{C-x e}),
  25985. give a negative prefix argument to @kbd{Z K}.
  25986. Once you have bound your keyboard macro to a key, you can use
  25987. @kbd{Z P} to register it permanently with Emacs. @xref{Creating User Keys}.
  25988. @cindex Keyboard macros, editing
  25989. The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
  25990. been defined by a keyboard macro tries to use the @code{edit-kbd-macro}
  25991. command to edit the macro. This command may be found in the
  25992. @file{macedit} package, a copy of which comes with Calc. It decomposes
  25993. the macro definition into full Emacs command names, like @code{calc-pop}
  25994. and @code{calc-add}. Type @kbd{M-# M-#} to finish editing and update
  25995. the definition stored on the key, or, to cancel the edit, type
  25996. @kbd{M-# x}.@refill
  25997. If you give a negative numeric prefix argument to @kbd{Z E}, the keyboard
  25998. macro is edited in spelled-out keystroke form. For example, the editing
  25999. buffer might contain the nine characters @w{@samp{1 @key{RET} 2 +}}. When you press
  26000. @kbd{M-# M-#}, the @code{read-kbd-macro} feature of the @file{macedit}
  26001. package is used to reinterpret these key names. The
  26002. notations @code{RET}, @code{LFD}, @code{TAB}, @code{SPC}, @code{DEL}, and
  26003. @code{NUL} must be written in all uppercase, as must the prefixes @code{C-}
  26004. and @code{M-}. Spaces and line breaks are ignored. Other characters are
  26005. copied verbatim into the keyboard macro. Basically, the notation is the
  26006. same as is used in all of this manual's examples, except that the manual
  26007. takes some liberties with spaces: When we say @kbd{' [1 2 3] @key{RET}}, we take
  26008. it for granted that it is clear we really mean @kbd{' [1 @key{SPC} 2 @key{SPC} 3] @key{RET}},
  26009. which is what @code{read-kbd-macro} wants to see.@refill
  26010. If @file{macedit} is not available, @kbd{Z E} edits the keyboard macro
  26011. in ``raw'' form; the editing buffer simply contains characters like
  26012. @samp{1^M2+} (here @samp{^M} represents the carriage-return character).
  26013. Editing in this mode, you will have to use @kbd{C-q} to enter new
  26014. control characters into the buffer.@refill
  26015. @kindex M-# m
  26016. @pindex read-kbd-macro
  26017. The @kbd{M-# m} (@code{read-kbd-macro}) command reads an Emacs ``region''
  26018. of spelled-out keystrokes and defines it as the current keyboard macro.
  26019. It is a convenient way to define a keyboard macro that has been stored
  26020. in a file, or to define a macro without executing it at the same time.
  26021. The @kbd{M-# m} command works only if @file{macedit} is present.
  26022. @node Conditionals in Macros, Loops in Macros, Naming Keyboard Macros, Keyboard Macros
  26023. @subsection Conditionals in Keyboard Macros
  26024. @noindent
  26025. @kindex Z [
  26026. @kindex Z ]
  26027. @pindex calc-kbd-if
  26028. @pindex calc-kbd-else
  26029. @pindex calc-kbd-else-if
  26030. @pindex calc-kbd-end-if
  26031. @cindex Conditional structures
  26032. The @kbd{Z [} (@code{calc-kbd-if}) and @kbd{Z ]} (@code{calc-kbd-end-if})
  26033. commands allow you to put simple tests in a keyboard macro. When Calc
  26034. sees the @kbd{Z [}, it pops an object from the stack and, if the object is
  26035. a non-zero value, continues executing keystrokes. But if the object is
  26036. zero, or if it is not provably nonzero, Calc skips ahead to the matching
  26037. @kbd{Z ]} keystroke. @xref{Logical Operations}, for a set of commands for
  26038. performing tests which conveniently produce 1 for true and 0 for false.
  26039. For example, @kbd{@key{RET} 0 a < Z [ n Z ]} implements an absolute-value
  26040. function in the form of a keyboard macro. This macro duplicates the
  26041. number on the top of the stack, pushes zero and compares using @kbd{a <}
  26042. (@code{calc-less-than}), then, if the number was less than zero,
  26043. executes @kbd{n} (@code{calc-change-sign}). Otherwise, the change-sign
  26044. command is skipped.
  26045. To program this macro, type @kbd{C-x (}, type the above sequence of
  26046. keystrokes, then type @kbd{C-x )}. Note that the keystrokes will be
  26047. executed while you are making the definition as well as when you later
  26048. re-execute the macro by typing @kbd{X}. Thus you should make sure a
  26049. suitable number is on the stack before defining the macro so that you
  26050. don't get a stack-underflow error during the definition process.
  26051. Conditionals can be nested arbitrarily. However, there should be exactly
  26052. one @kbd{Z ]} for each @kbd{Z [} in a keyboard macro.
  26053. @kindex Z :
  26054. The @kbd{Z :} (@code{calc-kbd-else}) command allows you to choose between
  26055. two keystroke sequences. The general format is @kbd{@var{cond} Z [
  26056. @var{then-part} Z : @var{else-part} Z ]}. If @var{cond} is true
  26057. (i.e., if the top of stack contains a non-zero number after @var{cond}
  26058. has been executed), the @var{then-part} will be executed and the
  26059. @var{else-part} will be skipped. Otherwise, the @var{then-part} will
  26060. be skipped and the @var{else-part} will be executed.
  26061. @kindex Z |
  26062. The @kbd{Z |} (@code{calc-kbd-else-if}) command allows you to choose
  26063. between any number of alternatives. For example,
  26064. @kbd{@var{cond1} Z [ @var{part1} Z : @var{cond2} Z | @var{part2} Z :
  26065. @var{part3} Z ]} will execute @var{part1} if @var{cond1} is true,
  26066. otherwise it will execute @var{part2} if @var{cond2} is true, otherwise
  26067. it will execute @var{part3}.
  26068. More precisely, @kbd{Z [} pops a number and conditionally skips to the
  26069. next matching @kbd{Z :} or @kbd{Z ]} key. @w{@kbd{Z ]}} has no effect when
  26070. actually executed. @kbd{Z :} skips to the next matching @kbd{Z ]}.
  26071. @kbd{Z |} pops a number and conditionally skips to the next matching
  26072. @kbd{Z :} or @kbd{Z ]}; thus, @kbd{Z [} and @kbd{Z |} are functionally
  26073. equivalent except that @kbd{Z [} participates in nesting but @kbd{Z |}
  26074. does not.
  26075. Calc's conditional and looping constructs work by scanning the
  26076. keyboard macro for occurrences of character sequences like @samp{Z:}
  26077. and @samp{Z]}. One side-effect of this is that if you use these
  26078. constructs you must be careful that these character pairs do not
  26079. occur by accident in other parts of the macros. Since Calc rarely
  26080. uses shift-@kbd{Z} for any purpose except as a prefix character, this
  26081. is not likely to be a problem. Another side-effect is that it will
  26082. not work to define your own custom key bindings for these commands.
  26083. Only the standard shift-@kbd{Z} bindings will work correctly.
  26084. @kindex Z C-g
  26085. If Calc gets stuck while skipping characters during the definition of a
  26086. macro, type @kbd{Z C-g} to cancel the definition. (Typing plain @kbd{C-g}
  26087. actually adds a @kbd{C-g} keystroke to the macro.)
  26088. @node Loops in Macros, Local Values in Macros, Conditionals in Macros, Keyboard Macros
  26089. @subsection Loops in Keyboard Macros
  26090. @noindent
  26091. @kindex Z <
  26092. @kindex Z >
  26093. @pindex calc-kbd-repeat
  26094. @pindex calc-kbd-end-repeat
  26095. @cindex Looping structures
  26096. @cindex Iterative structures
  26097. The @kbd{Z <} (@code{calc-kbd-repeat}) and @kbd{Z >}
  26098. (@code{calc-kbd-end-repeat}) commands pop a number from the stack,
  26099. which must be an integer, then repeat the keystrokes between the brackets
  26100. the specified number of times. If the integer is zero or negative, the
  26101. body is skipped altogether. For example, @kbd{1 @key{TAB} Z < 2 * Z >}
  26102. computes two to a nonnegative integer power. First, we push 1 on the
  26103. stack and then swap the integer argument back to the top. The @kbd{Z <}
  26104. pops that argument leaving the 1 back on top of the stack. Then, we
  26105. repeat a multiply-by-two step however many times.@refill
  26106. Once again, the keyboard macro is executed as it is being entered.
  26107. In this case it is especially important to set up reasonable initial
  26108. conditions before making the definition: Suppose the integer 1000 just
  26109. happened to be sitting on the stack before we typed the above definition!
  26110. Another approach is to enter a harmless dummy definition for the macro,
  26111. then go back and edit in the real one with a @kbd{Z E} command. Yet
  26112. another approach is to type the macro as written-out keystroke names
  26113. in a buffer, then use @kbd{M-# m} (@code{read-kbd-macro}) to read the
  26114. macro.
  26115. @kindex Z /
  26116. @pindex calc-break
  26117. The @kbd{Z /} (@code{calc-kbd-break}) command allows you to break out
  26118. of a keyboard macro loop prematurely. It pops an object from the stack;
  26119. if that object is true (a non-zero number), control jumps out of the
  26120. innermost enclosing @kbd{Z <} @dots{} @kbd{Z >} loop and continues
  26121. after the @kbd{Z >}. If the object is false, the @kbd{Z /} has no
  26122. effect. Thus @kbd{@var{cond} Z /} is similar to @samp{if (@var{cond}) break;}
  26123. in the C language.@refill
  26124. @kindex Z (
  26125. @kindex Z )
  26126. @pindex calc-kbd-for
  26127. @pindex calc-kbd-end-for
  26128. The @kbd{Z (} (@code{calc-kbd-for}) and @kbd{Z )} (@code{calc-kbd-end-for})
  26129. commands are similar to @kbd{Z <} and @kbd{Z >}, except that they make the
  26130. value of the counter available inside the loop. The general layout is
  26131. @kbd{@var{init} @var{final} Z ( @var{body} @var{step} Z )}. The @kbd{Z (}
  26132. command pops initial and final values from the stack. It then creates
  26133. a temporary internal counter and initializes it with the value @var{init}.
  26134. The @kbd{Z (} command then repeatedly pushes the counter value onto the
  26135. stack and executes @var{body} and @var{step}, adding @var{step} to the
  26136. counter each time until the loop finishes.@refill
  26137. @cindex Summations (by keyboard macros)
  26138. By default, the loop finishes when the counter becomes greater than (or
  26139. less than) @var{final}, assuming @var{initial} is less than (greater
  26140. than) @var{final}. If @var{initial} is equal to @var{final}, the body
  26141. executes exactly once. The body of the loop always executes at least
  26142. once. For example, @kbd{0 1 10 Z ( 2 ^ + 1 Z )} computes the sum of the
  26143. squares of the integers from 1 to 10, in steps of 1.
  26144. If you give a numeric prefix argument of 1 to @kbd{Z (}, the loop is
  26145. forced to use upward-counting conventions. In this case, if @var{initial}
  26146. is greater than @var{final} the body will not be executed at all.
  26147. Note that @var{step} may still be negative in this loop; the prefix
  26148. argument merely constrains the loop-finished test. Likewise, a prefix
  26149. argument of @i{-1} forces downward-counting conventions.
  26150. @kindex Z @{
  26151. @kindex Z @}
  26152. @pindex calc-kbd-loop
  26153. @pindex calc-kbd-end-loop
  26154. The @kbd{Z @{} (@code{calc-kbd-loop}) and @kbd{Z @}}
  26155. (@code{calc-kbd-end-loop}) commands are similar to @kbd{Z <} and
  26156. @kbd{Z >}, except that they do not pop a count from the stack---they
  26157. effectively create an infinite loop. Every @kbd{Z @{} @dots{} @kbd{Z @}}
  26158. loop ought to include at least one @kbd{Z /} to make sure the loop
  26159. doesn't run forever. (If any error message occurs which causes Emacs
  26160. to beep, the keyboard macro will also be halted; this is a standard
  26161. feature of Emacs. You can also generally press @kbd{C-g} to halt a
  26162. running keyboard macro, although not all versions of Unix support
  26163. this feature.)
  26164. The conditional and looping constructs are not actually tied to
  26165. keyboard macros, but they are most often used in that context.
  26166. For example, the keystrokes @kbd{10 Z < 23 @key{RET} Z >} push
  26167. ten copies of 23 onto the stack. This can be typed ``live'' just
  26168. as easily as in a macro definition.
  26169. @xref{Conditionals in Macros}, for some additional notes about
  26170. conditional and looping commands.
  26171. @node Local Values in Macros, Queries in Macros, Loops in Macros, Keyboard Macros
  26172. @subsection Local Values in Macros
  26173. @noindent
  26174. @cindex Local variables
  26175. @cindex Restoring saved modes
  26176. Keyboard macros sometimes want to operate under known conditions
  26177. without affecting surrounding conditions. For example, a keyboard
  26178. macro may wish to turn on Fraction Mode, or set a particular
  26179. precision, independent of the user's normal setting for those
  26180. modes.
  26181. @kindex Z `
  26182. @kindex Z '
  26183. @pindex calc-kbd-push
  26184. @pindex calc-kbd-pop
  26185. Macros also sometimes need to use local variables. Assignments to
  26186. local variables inside the macro should not affect any variables
  26187. outside the macro. The @kbd{Z `} (@code{calc-kbd-push}) and @kbd{Z '}
  26188. (@code{calc-kbd-pop}) commands give you both of these capabilities.
  26189. When you type @kbd{Z `} (with a backquote or accent grave character),
  26190. the values of various mode settings are saved away. The ten ``quick''
  26191. variables @code{q0} through @code{q9} are also saved. When
  26192. you type @w{@kbd{Z '}} (with an apostrophe), these values are restored.
  26193. Pairs of @kbd{Z `} and @kbd{Z '} commands may be nested.
  26194. If a keyboard macro halts due to an error in between a @kbd{Z `} and
  26195. a @kbd{Z '}, the saved values will be restored correctly even though
  26196. the macro never reaches the @kbd{Z '} command. Thus you can use
  26197. @kbd{Z `} and @kbd{Z '} without having to worry about what happens
  26198. in exceptional conditions.
  26199. If you type @kbd{Z `} ``live'' (not in a keyboard macro), Calc puts
  26200. you into a ``recursive edit.'' You can tell you are in a recursive
  26201. edit because there will be extra square brackets in the mode line,
  26202. as in @samp{[(Calculator)]}. These brackets will go away when you
  26203. type the matching @kbd{Z '} command. The modes and quick variables
  26204. will be saved and restored in just the same way as if actual keyboard
  26205. macros were involved.
  26206. The modes saved by @kbd{Z `} and @kbd{Z '} are the current precision
  26207. and binary word size, the angular mode (Deg, Rad, or HMS), the
  26208. simplification mode, Algebraic mode, Symbolic mode, Infinite mode,
  26209. Matrix or Scalar mode, Fraction mode, and the current complex mode
  26210. (Polar or Rectangular). The ten ``quick'' variables' values (or lack
  26211. thereof) are also saved.
  26212. Most mode-setting commands act as toggles, but with a numeric prefix
  26213. they force the mode either on (positive prefix) or off (negative
  26214. or zero prefix). Since you don't know what the environment might
  26215. be when you invoke your macro, it's best to use prefix arguments
  26216. for all mode-setting commands inside the macro.
  26217. In fact, @kbd{C-u Z `} is like @kbd{Z `} except that it sets the modes
  26218. listed above to their default values. As usual, the matching @kbd{Z '}
  26219. will restore the modes to their settings from before the @kbd{C-u Z `}.
  26220. Also, @w{@kbd{Z `}} with a negative prefix argument resets algebraic mode
  26221. to its default (off) but leaves the other modes the same as they were
  26222. outside the construct.
  26223. The contents of the stack and trail, values of non-quick variables, and
  26224. other settings such as the language mode and the various display modes,
  26225. are @emph{not} affected by @kbd{Z `} and @kbd{Z '}.
  26226. @node Queries in Macros, , Local Values in Macros, Keyboard Macros
  26227. @subsection Queries in Keyboard Macros
  26228. @noindent
  26229. @kindex Z =
  26230. @pindex calc-kbd-report
  26231. The @kbd{Z =} (@code{calc-kbd-report}) command displays an informative
  26232. message including the value on the top of the stack. You are prompted
  26233. to enter a string. That string, along with the top-of-stack value,
  26234. is displayed unless @kbd{m w} (@code{calc-working}) has been used
  26235. to turn such messages off.
  26236. @kindex Z #
  26237. @pindex calc-kbd-query
  26238. The @kbd{Z #} (@code{calc-kbd-query}) command displays a prompt message
  26239. (which you enter during macro definition), then does an algebraic entry
  26240. which takes its input from the keyboard, even during macro execution.
  26241. This command allows your keyboard macros to accept numbers or formulas
  26242. as interactive input. All the normal conventions of algebraic input,
  26243. including the use of @kbd{$} characters, are supported.
  26244. @xref{Kbd Macro Query, , , emacs, the Emacs Manual}, for a description of
  26245. @kbd{C-x q} (@code{kbd-macro-query}), the standard Emacs way to accept
  26246. keyboard input during a keyboard macro. In particular, you can use
  26247. @kbd{C-x q} to enter a recursive edit, which allows the user to perform
  26248. any Calculator operations interactively before pressing @kbd{C-M-c} to
  26249. return control to the keyboard macro.
  26250. @node Invocation Macros, Algebraic Definitions, Keyboard Macros, Programming
  26251. @section Invocation Macros
  26252. @kindex M-# z
  26253. @kindex Z I
  26254. @pindex calc-user-invocation
  26255. @pindex calc-user-define-invocation
  26256. Calc provides one special keyboard macro, called up by @kbd{M-# z}
  26257. (@code{calc-user-invocation}), that is intended to allow you to define
  26258. your own special way of starting Calc. To define this ``invocation
  26259. macro,'' create the macro in the usual way with @kbd{C-x (} and
  26260. @kbd{C-x )}, then type @kbd{Z I} (@code{calc-user-define-invocation}).
  26261. There is only one invocation macro, so you don't need to type any
  26262. additional letters after @kbd{Z I}. From now on, you can type
  26263. @kbd{M-# z} at any time to execute your invocation macro.
  26264. For example, suppose you find yourself often grabbing rectangles of
  26265. numbers into Calc and multiplying their columns. You can do this
  26266. by typing @kbd{M-# r} to grab, and @kbd{V R : *} to multiply columns.
  26267. To make this into an invocation macro, just type @kbd{C-x ( M-# r
  26268. V R : * C-x )}, then @kbd{Z I}. Then, to multiply a rectangle of data,
  26269. just mark the data in its buffer in the usual way and type @kbd{M-# z}.
  26270. Invocation macros are treated like regular Emacs keyboard macros;
  26271. all the special features described above for @kbd{Z K}-style macros
  26272. do not apply. @kbd{M-# z} is just like @kbd{C-x e}, except that it
  26273. uses the macro that was last stored by @kbd{Z I}. (In fact, the
  26274. macro does not even have to have anything to do with Calc!)
  26275. The @kbd{m m} command saves the last invocation macro defined by
  26276. @kbd{Z I} along with all the other Calc mode settings.
  26277. @xref{General Mode Commands}.
  26278. @node Algebraic Definitions, Lisp Definitions, Invocation Macros, Programming
  26279. @section Programming with Formulas
  26280. @noindent
  26281. @kindex Z F
  26282. @pindex calc-user-define-formula
  26283. @cindex Programming with algebraic formulas
  26284. Another way to create a new Calculator command uses algebraic formulas.
  26285. The @kbd{Z F} (@code{calc-user-define-formula}) command stores the
  26286. formula at the top of the stack as the definition for a key. This
  26287. command prompts for five things: The key, the command name, the function
  26288. name, the argument list, and the behavior of the command when given
  26289. non-numeric arguments.
  26290. For example, suppose we type @kbd{' a+2b @key{RET}} to push the formula
  26291. @samp{a + 2*b} onto the stack. We now type @kbd{Z F m} to define this
  26292. formula on the @kbd{z m} key sequence. The next prompt is for a command
  26293. name, beginning with @samp{calc-}, which should be the long (@kbd{M-x}) form
  26294. for the new command. If you simply press @key{RET}, a default name like
  26295. @code{calc-User-m} will be constructed. In our example, suppose we enter
  26296. @kbd{spam @key{RET}} to define the new command as @code{calc-spam}.
  26297. If you want to give the formula a long-style name only, you can press
  26298. @key{SPC} or @key{RET} when asked which single key to use. For example
  26299. @kbd{Z F @key{RET} spam @key{RET}} defines the new command as
  26300. @kbd{M-x calc-spam}, with no keyboard equivalent.
  26301. The third prompt is for a function name. The default is to use the same
  26302. name as the command name but with @samp{calcFunc-} in place of
  26303. @samp{calc-}. This is the name you will use if you want to enter your
  26304. new function in an algebraic formula. Suppose we enter @kbd{yow @key{RET}}.
  26305. Then the new function can be invoked by pushing two numbers on the
  26306. stack and typing @kbd{z m} or @kbd{x spam}, or by entering the algebraic
  26307. formula @samp{yow(x,y)}.@refill
  26308. The fourth prompt is for the function's argument list. This is used to
  26309. associate values on the stack with the variables that appear in the formula.
  26310. The default is a list of all variables which appear in the formula, sorted
  26311. into alphabetical order. In our case, the default would be @samp{(a b)}.
  26312. This means that, when the user types @kbd{z m}, the Calculator will remove
  26313. two numbers from the stack, substitute these numbers for @samp{a} and
  26314. @samp{b} (respectively) in the formula, then simplify the formula and
  26315. push the result on the stack. In other words, @kbd{10 @key{RET} 100 z m}
  26316. would replace the 10 and 100 on the stack with the number 210, which is
  26317. @cite{a + 2 b} with @cite{a=10} and @cite{b=100}. Likewise, the formula
  26318. @samp{yow(10, 100)} will be evaluated by substituting @cite{a=10} and
  26319. @cite{b=100} in the definition.
  26320. You can rearrange the order of the names before pressing @key{RET} to
  26321. control which stack positions go to which variables in the formula. If
  26322. you remove a variable from the argument list, that variable will be left
  26323. in symbolic form by the command. Thus using an argument list of @samp{(b)}
  26324. for our function would cause @kbd{10 z m} to replace the 10 on the stack
  26325. with the formula @samp{a + 20}. If we had used an argument list of
  26326. @samp{(b a)}, the result with inputs 10 and 100 would have been 120.
  26327. You can also put a nameless function on the stack instead of just a
  26328. formula, as in @samp{<a, b : a + 2 b>}. @xref{Specifying Operators}.
  26329. In this example, the command will be defined by the formula @samp{a + 2 b}
  26330. using the argument list @samp{(a b)}.
  26331. The final prompt is a y-or-n question concerning what to do if symbolic
  26332. arguments are given to your function. If you answer @kbd{y}, then
  26333. executing @kbd{z m} (using the original argument list @samp{(a b)}) with
  26334. arguments @cite{10} and @cite{x} will leave the function in symbolic
  26335. form, i.e., @samp{yow(10,x)}. On the other hand, if you answer @kbd{n},
  26336. then the formula will always be expanded, even for non-constant
  26337. arguments: @samp{10 + 2 x}. If you never plan to feed algebraic
  26338. formulas to your new function, it doesn't matter how you answer this
  26339. question.@refill
  26340. If you answered @kbd{y} to this question you can still cause a function
  26341. call to be expanded by typing @kbd{a "} (@code{calc-expand-formula}).
  26342. Also, Calc will expand the function if necessary when you take a
  26343. derivative or integral or solve an equation involving the function.
  26344. @kindex Z G
  26345. @pindex calc-get-user-defn
  26346. Once you have defined a formula on a key, you can retrieve this formula
  26347. with the @kbd{Z G} (@code{calc-user-define-get-defn}) command. Press a
  26348. key, and this command pushes the formula that was used to define that
  26349. key onto the stack. Actually, it pushes a nameless function that
  26350. specifies both the argument list and the defining formula. You will get
  26351. an error message if the key is undefined, or if the key was not defined
  26352. by a @kbd{Z F} command.@refill
  26353. The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
  26354. been defined by a formula uses a variant of the @code{calc-edit} command
  26355. to edit the defining formula. Press @kbd{M-# M-#} to finish editing and
  26356. store the new formula back in the definition, or @kbd{M-# x} to
  26357. cancel the edit. (The argument list and other properties of the
  26358. definition are unchanged; to adjust the argument list, you can use
  26359. @kbd{Z G} to grab the function onto the stack, edit with @kbd{`}, and
  26360. then re-execute the @kbd{Z F} command.)
  26361. As usual, the @kbd{Z P} command records your definition permanently.
  26362. In this case it will permanently record all three of the relevant
  26363. definitions: the key, the command, and the function.
  26364. You may find it useful to turn off the default simplifications with
  26365. @kbd{m O} (@code{calc-no-simplify-mode}) when entering a formula to be
  26366. used as a function definition. For example, the formula @samp{deriv(a^2,v)}
  26367. which might be used to define a new function @samp{dsqr(a,v)} will be
  26368. ``simplified'' to 0 immediately upon entry since @code{deriv} considers
  26369. @cite{a} to be constant with respect to @cite{v}. Turning off
  26370. default simplifications cures this problem: The definition will be stored
  26371. in symbolic form without ever activating the @code{deriv} function. Press
  26372. @kbd{m D} to turn the default simplifications back on afterwards.
  26373. @node Lisp Definitions, , Algebraic Definitions, Programming
  26374. @section Programming with Lisp
  26375. @noindent
  26376. The Calculator can be programmed quite extensively in Lisp. All you
  26377. do is write a normal Lisp function definition, but with @code{defmath}
  26378. in place of @code{defun}. This has the same form as @code{defun}, but it
  26379. automagically replaces calls to standard Lisp functions like @code{+} and
  26380. @code{zerop} with calls to the corresponding functions in Calc's own library.
  26381. Thus you can write natural-looking Lisp code which operates on all of the
  26382. standard Calculator data types. You can then use @kbd{Z D} if you wish to
  26383. bind your new command to a @kbd{z}-prefix key sequence. The @kbd{Z E} command
  26384. will not edit a Lisp-based definition.
  26385. Emacs Lisp is described in the GNU Emacs Lisp Reference Manual. This section
  26386. assumes a familiarity with Lisp programming concepts; if you do not know
  26387. Lisp, you may find keyboard macros or rewrite rules to be an easier way
  26388. to program the Calculator.
  26389. This section first discusses ways to write commands, functions, or
  26390. small programs to be executed inside of Calc. Then it discusses how
  26391. your own separate programs are able to call Calc from the outside.
  26392. Finally, there is a list of internal Calc functions and data structures
  26393. for the true Lisp enthusiast.
  26394. @menu
  26395. * Defining Functions::
  26396. * Defining Simple Commands::
  26397. * Defining Stack Commands::
  26398. * Argument Qualifiers::
  26399. * Example Definitions::
  26400. * Calling Calc from Your Programs::
  26401. * Internals::
  26402. @end menu
  26403. @node Defining Functions, Defining Simple Commands, Lisp Definitions, Lisp Definitions
  26404. @subsection Defining New Functions
  26405. @noindent
  26406. @findex defmath
  26407. The @code{defmath} function (actually a Lisp macro) is like @code{defun}
  26408. except that code in the body of the definition can make use of the full
  26409. range of Calculator data types. The prefix @samp{calcFunc-} is added
  26410. to the specified name to get the actual Lisp function name. As a simple
  26411. example,
  26412. @example
  26413. (defmath myfact (n)
  26414. (if (> n 0)
  26415. (* n (myfact (1- n)))
  26416. 1))
  26417. @end example
  26418. @noindent
  26419. This actually expands to the code,
  26420. @example
  26421. (defun calcFunc-myfact (n)
  26422. (if (math-posp n)
  26423. (math-mul n (calcFunc-myfact (math-add n -1)))
  26424. 1))
  26425. @end example
  26426. @noindent
  26427. This function can be used in algebraic expressions, e.g., @samp{myfact(5)}.
  26428. The @samp{myfact} function as it is defined above has the bug that an
  26429. expression @samp{myfact(a+b)} will be simplified to 1 because the
  26430. formula @samp{a+b} is not considered to be @code{posp}. A robust
  26431. factorial function would be written along the following lines:
  26432. @smallexample
  26433. (defmath myfact (n)
  26434. (if (> n 0)
  26435. (* n (myfact (1- n)))
  26436. (if (= n 0)
  26437. 1
  26438. nil))) ; this could be simplified as: (and (= n 0) 1)
  26439. @end smallexample
  26440. If a function returns @code{nil}, it is left unsimplified by the Calculator
  26441. (except that its arguments will be simplified). Thus, @samp{myfact(a+1+2)}
  26442. will be simplified to @samp{myfact(a+3)} but no further. Beware that every
  26443. time the Calculator reexamines this formula it will attempt to resimplify
  26444. it, so your function ought to detect the returning-@code{nil} case as
  26445. efficiently as possible.
  26446. The following standard Lisp functions are treated by @code{defmath}:
  26447. @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^} or
  26448. @code{expt}, @code{=}, @code{<}, @code{>}, @code{<=}, @code{>=},
  26449. @code{/=}, @code{1+}, @code{1-}, @code{logand}, @code{logior}, @code{logxor},
  26450. @code{logandc2}, @code{lognot}. Also, @code{~=} is an abbreviation for
  26451. @code{math-nearly-equal}, which is useful in implementing Taylor series.@refill
  26452. For other functions @var{func}, if a function by the name
  26453. @samp{calcFunc-@var{func}} exists it is used, otherwise if a function by the
  26454. name @samp{math-@var{func}} exists it is used, otherwise if @var{func} itself
  26455. is defined as a function it is used, otherwise @samp{calcFunc-@var{func}} is
  26456. used on the assumption that this is a to-be-defined math function. Also, if
  26457. the function name is quoted as in @samp{('integerp a)} the function name is
  26458. always used exactly as written (but not quoted).@refill
  26459. Variable names have @samp{var-} prepended to them unless they appear in
  26460. the function's argument list or in an enclosing @code{let}, @code{let*},
  26461. @code{for}, or @code{foreach} form,
  26462. or their names already contain a @samp{-} character. Thus a reference to
  26463. @samp{foo} is the same as a reference to @samp{var-foo}.@refill
  26464. A few other Lisp extensions are available in @code{defmath} definitions:
  26465. @itemize @bullet
  26466. @item
  26467. The @code{elt} function accepts any number of index variables.
  26468. Note that Calc vectors are stored as Lisp lists whose first
  26469. element is the symbol @code{vec}; thus, @samp{(elt v 2)} yields
  26470. the second element of vector @code{v}, and @samp{(elt m i j)}
  26471. yields one element of a Calc matrix.
  26472. @item
  26473. The @code{setq} function has been extended to act like the Common
  26474. Lisp @code{setf} function. (The name @code{setf} is recognized as
  26475. a synonym of @code{setq}.) Specifically, the first argument of
  26476. @code{setq} can be an @code{nth}, @code{elt}, @code{car}, or @code{cdr} form,
  26477. in which case the effect is to store into the specified
  26478. element of a list. Thus, @samp{(setq (elt m i j) x)} stores @cite{x}
  26479. into one element of a matrix.
  26480. @item
  26481. A @code{for} looping construct is available. For example,
  26482. @samp{(for ((i 0 10)) body)} executes @code{body} once for each
  26483. binding of @cite{i} from zero to 10. This is like a @code{let}
  26484. form in that @cite{i} is temporarily bound to the loop count
  26485. without disturbing its value outside the @code{for} construct.
  26486. Nested loops, as in @samp{(for ((i 0 10) (j 0 (1- i) 2)) body)},
  26487. are also available. For each value of @cite{i} from zero to 10,
  26488. @cite{j} counts from 0 to @cite{i-1} in steps of two. Note that
  26489. @code{for} has the same general outline as @code{let*}, except
  26490. that each element of the header is a list of three or four
  26491. things, not just two.
  26492. @item
  26493. The @code{foreach} construct loops over elements of a list.
  26494. For example, @samp{(foreach ((x (cdr v))) body)} executes
  26495. @code{body} with @cite{x} bound to each element of Calc vector
  26496. @cite{v} in turn. The purpose of @code{cdr} here is to skip over
  26497. the initial @code{vec} symbol in the vector.
  26498. @item
  26499. The @code{break} function breaks out of the innermost enclosing
  26500. @code{while}, @code{for}, or @code{foreach} loop. If given a
  26501. value, as in @samp{(break x)}, this value is returned by the
  26502. loop. (Lisp loops otherwise always return @code{nil}.)
  26503. @item
  26504. The @code{return} function prematurely returns from the enclosing
  26505. function. For example, @samp{(return (+ x y))} returns @cite{x+y}
  26506. as the value of a function. You can use @code{return} anywhere
  26507. inside the body of the function.
  26508. @end itemize
  26509. Non-integer numbers (and extremely large integers) cannot be included
  26510. directly into a @code{defmath} definition. This is because the Lisp
  26511. reader will fail to parse them long before @code{defmath} ever gets control.
  26512. Instead, use the notation, @samp{:"3.1415"}. In fact, any algebraic
  26513. formula can go between the quotes. For example,
  26514. @smallexample
  26515. (defmath sqexp (x) ; sqexp(x) == sqrt(exp(x)) == exp(x*0.5)
  26516. (and (numberp x)
  26517. (exp :"x * 0.5")))
  26518. @end smallexample
  26519. expands to
  26520. @smallexample
  26521. (defun calcFunc-sqexp (x)
  26522. (and (math-numberp x)
  26523. (calcFunc-exp (math-mul x '(float 5 -1)))))
  26524. @end smallexample
  26525. Note the use of @code{numberp} as a guard to ensure that the argument is
  26526. a number first, returning @code{nil} if not. The exponential function
  26527. could itself have been included in the expression, if we had preferred:
  26528. @samp{:"exp(x * 0.5)"}. As another example, the multiplication-and-recursion
  26529. step of @code{myfact} could have been written
  26530. @example
  26531. :"n * myfact(n-1)"
  26532. @end example
  26533. If a file named @file{.emacs} exists in your home directory, Emacs reads
  26534. and executes the Lisp forms in this file as it starts up. While it may
  26535. seem like a good idea to put your favorite @code{defmath} commands here,
  26536. this has the unfortunate side-effect that parts of the Calculator must be
  26537. loaded in to process the @code{defmath} commands whether or not you will
  26538. actually use the Calculator! A better effect can be had by writing
  26539. @example
  26540. (put 'calc-define 'thing '(progn
  26541. (defmath ... )
  26542. (defmath ... )
  26543. ))
  26544. @end example
  26545. @noindent
  26546. @vindex calc-define
  26547. The @code{put} function adds a @dfn{property} to a symbol. Each Lisp
  26548. symbol has a list of properties associated with it. Here we add a
  26549. property with a name of @code{thing} and a @samp{(progn ...)} form as
  26550. its value. When Calc starts up, and at the start of every Calc command,
  26551. the property list for the symbol @code{calc-define} is checked and the
  26552. values of any properties found are evaluated as Lisp forms. The
  26553. properties are removed as they are evaluated. The property names
  26554. (like @code{thing}) are not used; you should choose something like the
  26555. name of your project so as not to conflict with other properties.
  26556. The net effect is that you can put the above code in your @file{.emacs}
  26557. file and it will not be executed until Calc is loaded. Or, you can put
  26558. that same code in another file which you load by hand either before or
  26559. after Calc itself is loaded.
  26560. The properties of @code{calc-define} are evaluated in the same order
  26561. that they were added. They can assume that the Calc modules @file{calc.el},
  26562. @file{calc-ext.el}, and @file{calc-macs.el} have been fully loaded, and
  26563. that the @samp{*Calculator*} buffer will be the current buffer.
  26564. If your @code{calc-define} property only defines algebraic functions,
  26565. you can be sure that it will have been evaluated before Calc tries to
  26566. call your function, even if the file defining the property is loaded
  26567. after Calc is loaded. But if the property defines commands or key
  26568. sequences, it may not be evaluated soon enough. (Suppose it defines the
  26569. new command @code{tweak-calc}; the user can load your file, then type
  26570. @kbd{M-x tweak-calc} before Calc has had chance to do anything.) To
  26571. protect against this situation, you can put
  26572. @example
  26573. (run-hooks 'calc-check-defines)
  26574. @end example
  26575. @findex calc-check-defines
  26576. @noindent
  26577. at the end of your file. The @code{calc-check-defines} function is what
  26578. looks for and evaluates properties on @code{calc-define}; @code{run-hooks}
  26579. has the advantage that it is quietly ignored if @code{calc-check-defines}
  26580. is not yet defined because Calc has not yet been loaded.
  26581. Examples of things that ought to be enclosed in a @code{calc-define}
  26582. property are @code{defmath} calls, @code{define-key} calls that modify
  26583. the Calc key map, and any calls that redefine things defined inside Calc.
  26584. Ordinary @code{defun}s need not be enclosed with @code{calc-define}.
  26585. @node Defining Simple Commands, Defining Stack Commands, Defining Functions, Lisp Definitions
  26586. @subsection Defining New Simple Commands
  26587. @noindent
  26588. @findex interactive
  26589. If a @code{defmath} form contains an @code{interactive} clause, it defines
  26590. a Calculator command. Actually such a @code{defmath} results in @emph{two}
  26591. function definitions: One, a @samp{calcFunc-} function as was just described,
  26592. with the @code{interactive} clause removed. Two, a @samp{calc-} function
  26593. with a suitable @code{interactive} clause and some sort of wrapper to make
  26594. the command work in the Calc environment.
  26595. In the simple case, the @code{interactive} clause has the same form as
  26596. for normal Emacs Lisp commands:
  26597. @smallexample
  26598. (defmath increase-precision (delta)
  26599. "Increase precision by DELTA." ; This is the "documentation string"
  26600. (interactive "p") ; Register this as a M-x-able command
  26601. (setq calc-internal-prec (+ calc-internal-prec delta)))
  26602. @end smallexample
  26603. This expands to the pair of definitions,
  26604. @smallexample
  26605. (defun calc-increase-precision (delta)
  26606. "Increase precision by DELTA."
  26607. (interactive "p")
  26608. (calc-wrapper
  26609. (setq calc-internal-prec (math-add calc-internal-prec delta))))
  26610. (defun calcFunc-increase-precision (delta)
  26611. "Increase precision by DELTA."
  26612. (setq calc-internal-prec (math-add calc-internal-prec delta)))
  26613. @end smallexample
  26614. @noindent
  26615. where in this case the latter function would never really be used! Note
  26616. that since the Calculator stores small integers as plain Lisp integers,
  26617. the @code{math-add} function will work just as well as the native
  26618. @code{+} even when the intent is to operate on native Lisp integers.
  26619. @findex calc-wrapper
  26620. The @samp{calc-wrapper} call invokes a macro which surrounds the body of
  26621. the function with code that looks roughly like this:
  26622. @smallexample
  26623. (let ((calc-command-flags nil))
  26624. (unwind-protect
  26625. (save-excursion
  26626. (calc-select-buffer)
  26627. @emph{body of function}
  26628. @emph{renumber stack}
  26629. @emph{clear} Working @emph{message})
  26630. @emph{realign cursor and window}
  26631. @emph{clear Inverse, Hyperbolic, and Keep Args flags}
  26632. @emph{update Emacs mode line}))
  26633. @end smallexample
  26634. @findex calc-select-buffer
  26635. The @code{calc-select-buffer} function selects the @samp{*Calculator*}
  26636. buffer if necessary, say, because the command was invoked from inside
  26637. the @samp{*Calc Trail*} window.
  26638. @findex calc-set-command-flag
  26639. You can call, for example, @code{(calc-set-command-flag 'no-align)} to
  26640. set the above-mentioned command flags. Calc routines recognize the
  26641. following command flags:
  26642. @table @code
  26643. @item renum-stack
  26644. Stack line numbers @samp{1:}, @samp{2:}, and so on must be renumbered
  26645. after this command completes. This is set by routines like
  26646. @code{calc-push}.
  26647. @item clear-message
  26648. Calc should call @samp{(message "")} if this command completes normally
  26649. (to clear a ``Working@dots{}'' message out of the echo area).
  26650. @item no-align
  26651. Do not move the cursor back to the @samp{.} top-of-stack marker.
  26652. @item position-point
  26653. Use the variables @code{calc-position-point-line} and
  26654. @code{calc-position-point-column} to position the cursor after
  26655. this command finishes.
  26656. @item keep-flags
  26657. Do not clear @code{calc-inverse-flag}, @code{calc-hyperbolic-flag},
  26658. and @code{calc-keep-args-flag} at the end of this command.
  26659. @item do-edit
  26660. Switch to buffer @samp{*Calc Edit*} after this command.
  26661. @item hold-trail
  26662. Do not move trail pointer to end of trail when something is recorded
  26663. there.
  26664. @end table
  26665. @kindex Y
  26666. @kindex Y ?
  26667. @vindex calc-Y-help-msgs
  26668. Calc reserves a special prefix key, shift-@kbd{Y}, for user-written
  26669. extensions to Calc. There are no built-in commands that work with
  26670. this prefix key; you must call @code{define-key} from Lisp (probably
  26671. from inside a @code{calc-define} property) to add to it. Initially only
  26672. @kbd{Y ?} is defined; it takes help messages from a list of strings
  26673. (initially @code{nil}) in the variable @code{calc-Y-help-msgs}. All
  26674. other undefined keys except for @kbd{Y} are reserved for use by
  26675. future versions of Calc.
  26676. If you are writing a Calc enhancement which you expect to give to
  26677. others, it is best to minimize the number of @kbd{Y}-key sequences
  26678. you use. In fact, if you have more than one key sequence you should
  26679. consider defining three-key sequences with a @kbd{Y}, then a key that
  26680. stands for your package, then a third key for the particular command
  26681. within your package.
  26682. Users may wish to install several Calc enhancements, and it is possible
  26683. that several enhancements will choose to use the same key. In the
  26684. example below, a variable @code{inc-prec-base-key} has been defined
  26685. to contain the key that identifies the @code{inc-prec} package. Its
  26686. value is initially @code{"P"}, but a user can change this variable
  26687. if necessary without having to modify the file.
  26688. Here is a complete file, @file{inc-prec.el}, which makes a @kbd{Y P I}
  26689. command that increases the precision, and a @kbd{Y P D} command that
  26690. decreases the precision.
  26691. @smallexample
  26692. ;;; Increase and decrease Calc precision. Dave Gillespie, 5/31/91.
  26693. ;;; (Include copyright or copyleft stuff here.)
  26694. (defvar inc-prec-base-key "P"
  26695. "Base key for inc-prec.el commands.")
  26696. (put 'calc-define 'inc-prec '(progn
  26697. (define-key calc-mode-map (format "Y%sI" inc-prec-base-key)
  26698. 'increase-precision)
  26699. (define-key calc-mode-map (format "Y%sD" inc-prec-base-key)
  26700. 'decrease-precision)
  26701. (setq calc-Y-help-msgs
  26702. (cons (format "%s + Inc-prec, Dec-prec" inc-prec-base-key)
  26703. calc-Y-help-msgs))
  26704. (defmath increase-precision (delta)
  26705. "Increase precision by DELTA."
  26706. (interactive "p")
  26707. (setq calc-internal-prec (+ calc-internal-prec delta)))
  26708. (defmath decrease-precision (delta)
  26709. "Decrease precision by DELTA."
  26710. (interactive "p")
  26711. (setq calc-internal-prec (- calc-internal-prec delta)))
  26712. )) ; end of calc-define property
  26713. (run-hooks 'calc-check-defines)
  26714. @end smallexample
  26715. @node Defining Stack Commands, Argument Qualifiers, Defining Simple Commands, Lisp Definitions
  26716. @subsection Defining New Stack-Based Commands
  26717. @noindent
  26718. To define a new computational command which takes and/or leaves arguments
  26719. on the stack, a special form of @code{interactive} clause is used.
  26720. @example
  26721. (interactive @var{num} @var{tag})
  26722. @end example
  26723. @noindent
  26724. where @var{num} is an integer, and @var{tag} is a string. The effect is
  26725. to pop @var{num} values off the stack, resimplify them by calling
  26726. @code{calc-normalize}, and hand them to your function according to the
  26727. function's argument list. Your function may include @code{&optional} and
  26728. @code{&rest} parameters, so long as calling the function with @var{num}
  26729. parameters is legal.
  26730. Your function must return either a number or a formula in a form
  26731. acceptable to Calc, or a list of such numbers or formulas. These value(s)
  26732. are pushed onto the stack when the function completes. They are also
  26733. recorded in the Calc Trail buffer on a line beginning with @var{tag},
  26734. a string of (normally) four characters or less. If you omit @var{tag}
  26735. or use @code{nil} as a tag, the result is not recorded in the trail.
  26736. As an example, the definition
  26737. @smallexample
  26738. (defmath myfact (n)
  26739. "Compute the factorial of the integer at the top of the stack."
  26740. (interactive 1 "fact")
  26741. (if (> n 0)
  26742. (* n (myfact (1- n)))
  26743. (and (= n 0) 1)))
  26744. @end smallexample
  26745. @noindent
  26746. is a version of the factorial function shown previously which can be used
  26747. as a command as well as an algebraic function. It expands to
  26748. @smallexample
  26749. (defun calc-myfact ()
  26750. "Compute the factorial of the integer at the top of the stack."
  26751. (interactive)
  26752. (calc-slow-wrapper
  26753. (calc-enter-result 1 "fact"
  26754. (cons 'calcFunc-myfact (calc-top-list-n 1)))))
  26755. (defun calcFunc-myfact (n)
  26756. "Compute the factorial of the integer at the top of the stack."
  26757. (if (math-posp n)
  26758. (math-mul n (calcFunc-myfact (math-add n -1)))
  26759. (and (math-zerop n) 1)))
  26760. @end smallexample
  26761. @findex calc-slow-wrapper
  26762. The @code{calc-slow-wrapper} function is a version of @code{calc-wrapper}
  26763. that automatically puts up a @samp{Working...} message before the
  26764. computation begins. (This message can be turned off by the user
  26765. with an @kbd{m w} (@code{calc-working}) command.)
  26766. @findex calc-top-list-n
  26767. The @code{calc-top-list-n} function returns a list of the specified number
  26768. of values from the top of the stack. It resimplifies each value by
  26769. calling @code{calc-normalize}. If its argument is zero it returns an
  26770. empty list. It does not actually remove these values from the stack.
  26771. @findex calc-enter-result
  26772. The @code{calc-enter-result} function takes an integer @var{num} and string
  26773. @var{tag} as described above, plus a third argument which is either a
  26774. Calculator data object or a list of such objects. These objects are
  26775. resimplified and pushed onto the stack after popping the specified number
  26776. of values from the stack. If @var{tag} is non-@code{nil}, the values
  26777. being pushed are also recorded in the trail.
  26778. Note that if @code{calcFunc-myfact} returns @code{nil} this represents
  26779. ``leave the function in symbolic form.'' To return an actual empty list,
  26780. in the sense that @code{calc-enter-result} will push zero elements back
  26781. onto the stack, you should return the special value @samp{'(nil)}, a list
  26782. containing the single symbol @code{nil}.
  26783. The @code{interactive} declaration can actually contain a limited
  26784. Emacs-style code string as well which comes just before @var{num} and
  26785. @var{tag}. Currently the only Emacs code supported is @samp{"p"}, as in
  26786. @example
  26787. (defmath foo (a b &optional c)
  26788. (interactive "p" 2 "foo")
  26789. @var{body})
  26790. @end example
  26791. In this example, the command @code{calc-foo} will evaluate the expression
  26792. @samp{foo(a,b)} if executed with no argument, or @samp{foo(a,b,n)} if
  26793. executed with a numeric prefix argument of @cite{n}.
  26794. The other code string allowed is @samp{"m"} (unrelated to the usual @samp{"m"}
  26795. code as used with @code{defun}). It uses the numeric prefix argument as the
  26796. number of objects to remove from the stack and pass to the function.
  26797. In this case, the integer @var{num} serves as a default number of
  26798. arguments to be used when no prefix is supplied.
  26799. @node Argument Qualifiers, Example Definitions, Defining Stack Commands, Lisp Definitions
  26800. @subsection Argument Qualifiers
  26801. @noindent
  26802. Anywhere a parameter name can appear in the parameter list you can also use
  26803. an @dfn{argument qualifier}. Thus the general form of a definition is:
  26804. @example
  26805. (defmath @var{name} (@var{param} @var{param...}
  26806. &optional @var{param} @var{param...}
  26807. &rest @var{param})
  26808. @var{body})
  26809. @end example
  26810. @noindent
  26811. where each @var{param} is either a symbol or a list of the form
  26812. @example
  26813. (@var{qual} @var{param})
  26814. @end example
  26815. The following qualifiers are recognized:
  26816. @table @samp
  26817. @item complete
  26818. @findex complete
  26819. The argument must not be an incomplete vector, interval, or complex number.
  26820. (This is rarely needed since the Calculator itself will never call your
  26821. function with an incomplete argument. But there is nothing stopping your
  26822. own Lisp code from calling your function with an incomplete argument.)@refill
  26823. @item integer
  26824. @findex integer
  26825. The argument must be an integer. If it is an integer-valued float
  26826. it will be accepted but converted to integer form. Non-integers and
  26827. formulas are rejected.
  26828. @item natnum
  26829. @findex natnum
  26830. Like @samp{integer}, but the argument must be non-negative.
  26831. @item fixnum
  26832. @findex fixnum
  26833. Like @samp{integer}, but the argument must fit into a native Lisp integer,
  26834. which on most systems means less than 2^23 in absolute value. The
  26835. argument is converted into Lisp-integer form if necessary.
  26836. @item float
  26837. @findex float
  26838. The argument is converted to floating-point format if it is a number or
  26839. vector. If it is a formula it is left alone. (The argument is never
  26840. actually rejected by this qualifier.)
  26841. @item @var{pred}
  26842. The argument must satisfy predicate @var{pred}, which is one of the
  26843. standard Calculator predicates. @xref{Predicates}.
  26844. @item not-@var{pred}
  26845. The argument must @emph{not} satisfy predicate @var{pred}.
  26846. @end table
  26847. For example,
  26848. @example
  26849. (defmath foo (a (constp (not-matrixp b)) &optional (float c)
  26850. &rest (integer d))
  26851. @var{body})
  26852. @end example
  26853. @noindent
  26854. expands to
  26855. @example
  26856. (defun calcFunc-foo (a b &optional c &rest d)
  26857. (and (math-matrixp b)
  26858. (math-reject-arg b 'not-matrixp))
  26859. (or (math-constp b)
  26860. (math-reject-arg b 'constp))
  26861. (and c (setq c (math-check-float c)))
  26862. (setq d (mapcar 'math-check-integer d))
  26863. @var{body})
  26864. @end example
  26865. @noindent
  26866. which performs the necessary checks and conversions before executing the
  26867. body of the function.
  26868. @node Example Definitions, Calling Calc from Your Programs, Argument Qualifiers, Lisp Definitions
  26869. @subsection Example Definitions
  26870. @noindent
  26871. This section includes some Lisp programming examples on a larger scale.
  26872. These programs make use of some of the Calculator's internal functions;
  26873. @pxref{Internals}.
  26874. @menu
  26875. * Bit Counting Example::
  26876. * Sine Example::
  26877. @end menu
  26878. @node Bit Counting Example, Sine Example, Example Definitions, Example Definitions
  26879. @subsubsection Bit-Counting
  26880. @noindent
  26881. @ignore
  26882. @starindex
  26883. @end ignore
  26884. @tindex bcount
  26885. Calc does not include a built-in function for counting the number of
  26886. ``one'' bits in a binary integer. It's easy to invent one using @kbd{b u}
  26887. to convert the integer to a set, and @kbd{V #} to count the elements of
  26888. that set; let's write a function that counts the bits without having to
  26889. create an intermediate set.
  26890. @smallexample
  26891. (defmath bcount ((natnum n))
  26892. (interactive 1 "bcnt")
  26893. (let ((count 0))
  26894. (while (> n 0)
  26895. (if (oddp n)
  26896. (setq count (1+ count)))
  26897. (setq n (lsh n -1)))
  26898. count))
  26899. @end smallexample
  26900. @noindent
  26901. When this is expanded by @code{defmath}, it will become the following
  26902. Emacs Lisp function:
  26903. @smallexample
  26904. (defun calcFunc-bcount (n)
  26905. (setq n (math-check-natnum n))
  26906. (let ((count 0))
  26907. (while (math-posp n)
  26908. (if (math-oddp n)
  26909. (setq count (math-add count 1)))
  26910. (setq n (calcFunc-lsh n -1)))
  26911. count))
  26912. @end smallexample
  26913. If the input numbers are large, this function involves a fair amount
  26914. of arithmetic. A binary right shift is essentially a division by two;
  26915. recall that Calc stores integers in decimal form so bit shifts must
  26916. involve actual division.
  26917. To gain a bit more efficiency, we could divide the integer into
  26918. @var{n}-bit chunks, each of which can be handled quickly because
  26919. they fit into Lisp integers. It turns out that Calc's arithmetic
  26920. routines are especially fast when dividing by an integer less than
  26921. 1000, so we can set @var{n = 9} bits and use repeated division by 512:
  26922. @smallexample
  26923. (defmath bcount ((natnum n))
  26924. (interactive 1 "bcnt")
  26925. (let ((count 0))
  26926. (while (not (fixnump n))
  26927. (let ((qr (idivmod n 512)))
  26928. (setq count (+ count (bcount-fixnum (cdr qr)))
  26929. n (car qr))))
  26930. (+ count (bcount-fixnum n))))
  26931. (defun bcount-fixnum (n)
  26932. (let ((count 0))
  26933. (while (> n 0)
  26934. (setq count (+ count (logand n 1))
  26935. n (lsh n -1)))
  26936. count))
  26937. @end smallexample
  26938. @noindent
  26939. Note that the second function uses @code{defun}, not @code{defmath}.
  26940. Because this function deals only with native Lisp integers (``fixnums''),
  26941. it can use the actual Emacs @code{+} and related functions rather
  26942. than the slower but more general Calc equivalents which @code{defmath}
  26943. uses.
  26944. The @code{idivmod} function does an integer division, returning both
  26945. the quotient and the remainder at once. Again, note that while it
  26946. might seem that @samp{(logand n 511)} and @samp{(lsh n -9)} are
  26947. more efficient ways to split off the bottom nine bits of @code{n},
  26948. actually they are less efficient because each operation is really
  26949. a division by 512 in disguise; @code{idivmod} allows us to do the
  26950. same thing with a single division by 512.
  26951. @node Sine Example, , Bit Counting Example, Example Definitions
  26952. @subsubsection The Sine Function
  26953. @noindent
  26954. @ignore
  26955. @starindex
  26956. @end ignore
  26957. @tindex mysin
  26958. A somewhat limited sine function could be defined as follows, using the
  26959. well-known Taylor series expansion for @c{$\sin x$}
  26960. @samp{sin(x)}:
  26961. @smallexample
  26962. (defmath mysin ((float (anglep x)))
  26963. (interactive 1 "mysn")
  26964. (setq x (to-radians x)) ; Convert from current angular mode.
  26965. (let ((sum x) ; Initial term of Taylor expansion of sin.
  26966. newsum
  26967. (nfact 1) ; "nfact" equals "n" factorial at all times.
  26968. (xnegsqr :"-(x^2)")) ; "xnegsqr" equals -x^2.
  26969. (for ((n 3 100 2)) ; Upper limit of 100 is a good precaution.
  26970. (working "mysin" sum) ; Display "Working" message, if enabled.
  26971. (setq nfact (* nfact (1- n) n)
  26972. x (* x xnegsqr)
  26973. newsum (+ sum (/ x nfact)))
  26974. (if (~= newsum sum) ; If newsum is "nearly equal to" sum,
  26975. (break)) ; then we are done.
  26976. (setq sum newsum))
  26977. sum))
  26978. @end smallexample
  26979. The actual @code{sin} function in Calc works by first reducing the problem
  26980. to a sine or cosine of a nonnegative number less than @c{$\pi \over 4$}
  26981. @cite{pi/4}. This
  26982. ensures that the Taylor series will converge quickly. Also, the calculation
  26983. is carried out with two extra digits of precision to guard against cumulative
  26984. round-off in @samp{sum}. Finally, complex arguments are allowed and handled
  26985. by a separate algorithm.
  26986. @smallexample
  26987. (defmath mysin ((float (scalarp x)))
  26988. (interactive 1 "mysn")
  26989. (setq x (to-radians x)) ; Convert from current angular mode.
  26990. (with-extra-prec 2 ; Evaluate with extra precision.
  26991. (cond ((complexp x)
  26992. (mysin-complex x))
  26993. ((< x 0)
  26994. (- (mysin-raw (- x))) ; Always call mysin-raw with x >= 0.
  26995. (t (mysin-raw x))))))
  26996. (defmath mysin-raw (x)
  26997. (cond ((>= x 7)
  26998. (mysin-raw (% x (two-pi)))) ; Now x < 7.
  26999. ((> x (pi-over-2))
  27000. (- (mysin-raw (- x (pi))))) ; Now -pi/2 <= x <= pi/2.
  27001. ((> x (pi-over-4))
  27002. (mycos-raw (- x (pi-over-2)))) ; Now -pi/2 <= x <= pi/4.
  27003. ((< x (- (pi-over-4)))
  27004. (- (mycos-raw (+ x (pi-over-2))))) ; Now -pi/4 <= x <= pi/4,
  27005. (t (mysin-series x)))) ; so the series will be efficient.
  27006. @end smallexample
  27007. @noindent
  27008. where @code{mysin-complex} is an appropriate function to handle complex
  27009. numbers, @code{mysin-series} is the routine to compute the sine Taylor
  27010. series as before, and @code{mycos-raw} is a function analogous to
  27011. @code{mysin-raw} for cosines.
  27012. The strategy is to ensure that @cite{x} is nonnegative before calling
  27013. @code{mysin-raw}. This function then recursively reduces its argument
  27014. to a suitable range, namely, plus-or-minus @c{$\pi \over 4$}
  27015. @cite{pi/4}. Note that each
  27016. test, and particularly the first comparison against 7, is designed so
  27017. that small roundoff errors cannnot produce an infinite loop. (Suppose
  27018. we compared with @samp{(two-pi)} instead; if due to roundoff problems
  27019. the modulo operator ever returned @samp{(two-pi)} exactly, an infinite
  27020. recursion could result!) We use modulo only for arguments that will
  27021. clearly get reduced, knowing that the next rule will catch any reductions
  27022. that this rule misses.
  27023. If a program is being written for general use, it is important to code
  27024. it carefully as shown in this second example. For quick-and-dirty programs,
  27025. when you know that your own use of the sine function will never encounter
  27026. a large argument, a simpler program like the first one shown is fine.
  27027. @node Calling Calc from Your Programs, Internals, Example Definitions, Lisp Definitions
  27028. @subsection Calling Calc from Your Lisp Programs
  27029. @noindent
  27030. A later section (@pxref{Internals}) gives a full description of
  27031. Calc's internal Lisp functions. It's not hard to call Calc from
  27032. inside your programs, but the number of these functions can be daunting.
  27033. So Calc provides one special ``programmer-friendly'' function called
  27034. @code{calc-eval} that can be made to do just about everything you
  27035. need. It's not as fast as the low-level Calc functions, but it's
  27036. much simpler to use!
  27037. It may seem that @code{calc-eval} itself has a daunting number of
  27038. options, but they all stem from one simple operation.
  27039. In its simplest manifestation, @samp{(calc-eval "1+2")} parses the
  27040. string @code{"1+2"} as if it were a Calc algebraic entry and returns
  27041. the result formatted as a string: @code{"3"}.
  27042. Since @code{calc-eval} is on the list of recommended @code{autoload}
  27043. functions, you don't need to make any special preparations to load
  27044. Calc before calling @code{calc-eval} the first time. Calc will be
  27045. loaded and initialized for you.
  27046. All the Calc modes that are currently in effect will be used when
  27047. evaluating the expression and formatting the result.
  27048. @ifinfo
  27049. @example
  27050. @end example
  27051. @end ifinfo
  27052. @subsubsection Additional Arguments to @code{calc-eval}
  27053. @noindent
  27054. If the input string parses to a list of expressions, Calc returns
  27055. the results separated by @code{", "}. You can specify a different
  27056. separator by giving a second string argument to @code{calc-eval}:
  27057. @samp{(calc-eval "1+2,3+4" ";")} returns @code{"3;7"}.
  27058. The ``separator'' can also be any of several Lisp symbols which
  27059. request other behaviors from @code{calc-eval}. These are discussed
  27060. one by one below.
  27061. You can give additional arguments to be substituted for
  27062. @samp{$}, @samp{$$}, and so on in the main expression. For
  27063. example, @samp{(calc-eval "$/$$" nil "7" "1+1")} evaluates the
  27064. expression @code{"7/(1+1)"} to yield the result @code{"3.5"}
  27065. (assuming Fraction mode is not in effect). Note the @code{nil}
  27066. used as a placeholder for the item-separator argument.
  27067. @ifinfo
  27068. @example
  27069. @end example
  27070. @end ifinfo
  27071. @subsubsection Error Handling
  27072. @noindent
  27073. If @code{calc-eval} encounters an error, it returns a list containing
  27074. the character position of the error, plus a suitable message as a
  27075. string. Note that @samp{1 / 0} is @emph{not} an error by Calc's
  27076. standards; it simply returns the string @code{"1 / 0"} which is the
  27077. division left in symbolic form. But @samp{(calc-eval "1/")} will
  27078. return the list @samp{(2 "Expected a number")}.
  27079. If you bind the variable @code{calc-eval-error} to @code{t}
  27080. using a @code{let} form surrounding the call to @code{calc-eval},
  27081. errors instead call the Emacs @code{error} function which aborts
  27082. to the Emacs command loop with a beep and an error message.
  27083. If you bind this variable to the symbol @code{string}, error messages
  27084. are returned as strings instead of lists. The character position is
  27085. ignored.
  27086. As a courtesy to other Lisp code which may be using Calc, be sure
  27087. to bind @code{calc-eval-error} using @code{let} rather than changing
  27088. it permanently with @code{setq}.
  27089. @ifinfo
  27090. @example
  27091. @end example
  27092. @end ifinfo
  27093. @subsubsection Numbers Only
  27094. @noindent
  27095. Sometimes it is preferable to treat @samp{1 / 0} as an error
  27096. rather than returning a symbolic result. If you pass the symbol
  27097. @code{num} as the second argument to @code{calc-eval}, results
  27098. that are not constants are treated as errors. The error message
  27099. reported is the first @code{calc-why} message if there is one,
  27100. or otherwise ``Number expected.''
  27101. A result is ``constant'' if it is a number, vector, or other
  27102. object that does not include variables or function calls. If it
  27103. is a vector, the components must themselves be constants.
  27104. @ifinfo
  27105. @example
  27106. @end example
  27107. @end ifinfo
  27108. @subsubsection Default Modes
  27109. @noindent
  27110. If the first argument to @code{calc-eval} is a list whose first
  27111. element is a formula string, then @code{calc-eval} sets all the
  27112. various Calc modes to their default values while the formula is
  27113. evaluated and formatted. For example, the precision is set to 12
  27114. digits, digit grouping is turned off, and the normal language
  27115. mode is used.
  27116. This same principle applies to the other options discussed below.
  27117. If the first argument would normally be @var{x}, then it can also
  27118. be the list @samp{(@var{x})} to use the default mode settings.
  27119. If there are other elements in the list, they are taken as
  27120. variable-name/value pairs which override the default mode
  27121. settings. Look at the documentation at the front of the
  27122. @file{calc.el} file to find the names of the Lisp variables for
  27123. the various modes. The mode settings are restored to their
  27124. original values when @code{calc-eval} is done.
  27125. For example, @samp{(calc-eval '("$+$$" calc-internal-prec 8) 'num a b)}
  27126. computes the sum of two numbers, requiring a numeric result, and
  27127. using default mode settings except that the precision is 8 instead
  27128. of the default of 12.
  27129. It's usually best to use this form of @code{calc-eval} unless your
  27130. program actually considers the interaction with Calc's mode settings
  27131. to be a feature. This will avoid all sorts of potential ``gotchas'';
  27132. consider what happens with @samp{(calc-eval "sqrt(2)" 'num)}
  27133. when the user has left Calc in symbolic mode or no-simplify mode.
  27134. As another example, @samp{(equal (calc-eval '("$<$$") nil a b) "1")}
  27135. checks if the number in string @cite{a} is less than the one in
  27136. string @cite{b}. Without using a list, the integer 1 might
  27137. come out in a variety of formats which would be hard to test for
  27138. conveniently: @code{"1"}, @code{"8#1"}, @code{"00001"}. (But
  27139. see ``Predicates'' mode, below.)
  27140. @ifinfo
  27141. @example
  27142. @end example
  27143. @end ifinfo
  27144. @subsubsection Raw Numbers
  27145. @noindent
  27146. Normally all input and output for @code{calc-eval} is done with strings.
  27147. You can do arithmetic with, say, @samp{(calc-eval "$+$$" nil a b)}
  27148. in place of @samp{(+ a b)}, but this is very inefficient since the
  27149. numbers must be converted to and from string format as they are passed
  27150. from one @code{calc-eval} to the next.
  27151. If the separator is the symbol @code{raw}, the result will be returned
  27152. as a raw Calc data structure rather than a string. You can read about
  27153. how these objects look in the following sections, but usually you can
  27154. treat them as ``black box'' objects with no important internal
  27155. structure.
  27156. There is also a @code{rawnum} symbol, which is a combination of
  27157. @code{raw} (returning a raw Calc object) and @code{num} (signalling
  27158. an error if that object is not a constant).
  27159. You can pass a raw Calc object to @code{calc-eval} in place of a
  27160. string, either as the formula itself or as one of the @samp{$}
  27161. arguments. Thus @samp{(calc-eval "$+$$" 'raw a b)} is an
  27162. addition function that operates on raw Calc objects. Of course
  27163. in this case it would be easier to call the low-level @code{math-add}
  27164. function in Calc, if you can remember its name.
  27165. In particular, note that a plain Lisp integer is acceptable to Calc
  27166. as a raw object. (All Lisp integers are accepted on input, but
  27167. integers of more than six decimal digits are converted to ``big-integer''
  27168. form for output. @xref{Data Type Formats}.)
  27169. When it comes time to display the object, just use @samp{(calc-eval a)}
  27170. to format it as a string.
  27171. It is an error if the input expression evaluates to a list of
  27172. values. The separator symbol @code{list} is like @code{raw}
  27173. except that it returns a list of one or more raw Calc objects.
  27174. Note that a Lisp string is not a valid Calc object, nor is a list
  27175. containing a string. Thus you can still safely distinguish all the
  27176. various kinds of error returns discussed above.
  27177. @ifinfo
  27178. @example
  27179. @end example
  27180. @end ifinfo
  27181. @subsubsection Predicates
  27182. @noindent
  27183. If the separator symbol is @code{pred}, the result of the formula is
  27184. treated as a true/false value; @code{calc-eval} returns @code{t} or
  27185. @code{nil}, respectively. A value is considered ``true'' if it is a
  27186. non-zero number, or false if it is zero or if it is not a number.
  27187. For example, @samp{(calc-eval "$<$$" 'pred a b)} tests whether
  27188. one value is less than another.
  27189. As usual, it is also possible for @code{calc-eval} to return one of
  27190. the error indicators described above. Lisp will interpret such an
  27191. indicator as ``true'' if you don't check for it explicitly. If you
  27192. wish to have an error register as ``false'', use something like
  27193. @samp{(eq (calc-eval ...) t)}.
  27194. @ifinfo
  27195. @example
  27196. @end example
  27197. @end ifinfo
  27198. @subsubsection Variable Values
  27199. @noindent
  27200. Variables in the formula passed to @code{calc-eval} are not normally
  27201. replaced by their values. If you wish this, you can use the
  27202. @code{evalv} function (@pxref{Algebraic Manipulation}). For example,
  27203. if 4 is stored in Calc variable @code{a} (i.e., in Lisp variable
  27204. @code{var-a}), then @samp{(calc-eval "a+pi")} will return the
  27205. formula @code{"a + pi"}, but @samp{(calc-eval "evalv(a+pi)")}
  27206. will return @code{"7.14159265359"}.
  27207. To store in a Calc variable, just use @code{setq} to store in the
  27208. corresponding Lisp variable. (This is obtained by prepending
  27209. @samp{var-} to the Calc variable name.) Calc routines will
  27210. understand either string or raw form values stored in variables,
  27211. although raw data objects are much more efficient. For example,
  27212. to increment the Calc variable @code{a}:
  27213. @example
  27214. (setq var-a (calc-eval "evalv(a+1)" 'raw))
  27215. @end example
  27216. @ifinfo
  27217. @example
  27218. @end example
  27219. @end ifinfo
  27220. @subsubsection Stack Access
  27221. @noindent
  27222. If the separator symbol is @code{push}, the formula argument is
  27223. evaluated (with possible @samp{$} expansions, as usual). The
  27224. result is pushed onto the Calc stack. The return value is @code{nil}
  27225. (unless there is an error from evaluating the formula, in which
  27226. case the return value depends on @code{calc-eval-error} in the
  27227. usual way).
  27228. If the separator symbol is @code{pop}, the first argument to
  27229. @code{calc-eval} must be an integer instead of a string. That
  27230. many values are popped from the stack and thrown away. A negative
  27231. argument deletes the entry at that stack level. The return value
  27232. is the number of elements remaining in the stack after popping;
  27233. @samp{(calc-eval 0 'pop)} is a good way to measure the size of
  27234. the stack.
  27235. If the separator symbol is @code{top}, the first argument to
  27236. @code{calc-eval} must again be an integer. The value at that
  27237. stack level is formatted as a string and returned. Thus
  27238. @samp{(calc-eval 1 'top)} returns the top-of-stack value. If the
  27239. integer is out of range, @code{nil} is returned.
  27240. The separator symbol @code{rawtop} is just like @code{top} except
  27241. that the stack entry is returned as a raw Calc object instead of
  27242. as a string.
  27243. In all of these cases the first argument can be made a list in
  27244. order to force the default mode settings, as described above.
  27245. Thus @samp{(calc-eval '(2 calc-number-radix 16) 'top)} returns the
  27246. second-to-top stack entry, formatted as a string using the default
  27247. instead of current display modes, except that the radix is
  27248. hexadecimal instead of decimal.
  27249. It is, of course, polite to put the Calc stack back the way you
  27250. found it when you are done, unless the user of your program is
  27251. actually expecting it to affect the stack.
  27252. Note that you do not actually have to switch into the @samp{*Calculator*}
  27253. buffer in order to use @code{calc-eval}; it temporarily switches into
  27254. the stack buffer if necessary.
  27255. @ifinfo
  27256. @example
  27257. @end example
  27258. @end ifinfo
  27259. @subsubsection Keyboard Macros
  27260. @noindent
  27261. If the separator symbol is @code{macro}, the first argument must be a
  27262. string of characters which Calc can execute as a sequence of keystrokes.
  27263. This switches into the Calc buffer for the duration of the macro.
  27264. For example, @samp{(calc-eval "vx5\rVR+" 'macro)} pushes the
  27265. vector @samp{[1,2,3,4,5]} on the stack and then replaces it
  27266. with the sum of those numbers. Note that @samp{\r} is the Lisp
  27267. notation for the carriage-return, @key{RET}, character.
  27268. If your keyboard macro wishes to pop the stack, @samp{\C-d} is
  27269. safer than @samp{\177} (the @key{DEL} character) because some
  27270. installations may have switched the meanings of @key{DEL} and
  27271. @kbd{C-h}. Calc always interprets @kbd{C-d} as a synonym for
  27272. ``pop-stack'' regardless of key mapping.
  27273. If you provide a third argument to @code{calc-eval}, evaluation
  27274. of the keyboard macro will leave a record in the Trail using
  27275. that argument as a tag string. Normally the Trail is unaffected.
  27276. The return value in this case is always @code{nil}.
  27277. @ifinfo
  27278. @example
  27279. @end example
  27280. @end ifinfo
  27281. @subsubsection Lisp Evaluation
  27282. @noindent
  27283. Finally, if the separator symbol is @code{eval}, then the Lisp
  27284. @code{eval} function is called on the first argument, which must
  27285. be a Lisp expression rather than a Calc formula. Remember to
  27286. quote the expression so that it is not evaluated until inside
  27287. @code{calc-eval}.
  27288. The difference from plain @code{eval} is that @code{calc-eval}
  27289. switches to the Calc buffer before evaluating the expression.
  27290. For example, @samp{(calc-eval '(setq calc-internal-prec 17) 'eval)}
  27291. will correctly affect the buffer-local Calc precision variable.
  27292. An alternative would be @samp{(calc-eval '(calc-precision 17) 'eval)}.
  27293. This is evaluating a call to the function that is normally invoked
  27294. by the @kbd{p} key, giving it 17 as its ``numeric prefix argument.''
  27295. Note that this function will leave a message in the echo area as
  27296. a side effect. Also, all Calc functions switch to the Calc buffer
  27297. automatically if not invoked from there, so the above call is
  27298. also equivalent to @samp{(calc-precision 17)} by itself.
  27299. In all cases, Calc uses @code{save-excursion} to switch back to
  27300. your original buffer when it is done.
  27301. As usual the first argument can be a list that begins with a Lisp
  27302. expression to use default instead of current mode settings.
  27303. The result of @code{calc-eval} in this usage is just the result
  27304. returned by the evaluated Lisp expression.
  27305. @ifinfo
  27306. @example
  27307. @end example
  27308. @end ifinfo
  27309. @subsubsection Example
  27310. @noindent
  27311. @findex convert-temp
  27312. Here is a sample Emacs command that uses @code{calc-eval}. Suppose
  27313. you have a document with lots of references to temperatures on the
  27314. Fahrenheit scale, say ``98.6 F'', and you wish to convert these
  27315. references to Centigrade. The following command does this conversion.
  27316. Place the Emacs cursor right after the letter ``F'' and invoke the
  27317. command to change ``98.6 F'' to ``37 C''. Or, if the temperature is
  27318. already in Centigrade form, the command changes it back to Fahrenheit.
  27319. @example
  27320. (defun convert-temp ()
  27321. (interactive)
  27322. (save-excursion
  27323. (re-search-backward "[^-.0-9]\\([-.0-9]+\\) *\\([FC]\\)")
  27324. (let* ((top1 (match-beginning 1))
  27325. (bot1 (match-end 1))
  27326. (number (buffer-substring top1 bot1))
  27327. (top2 (match-beginning 2))
  27328. (bot2 (match-end 2))
  27329. (type (buffer-substring top2 bot2)))
  27330. (if (equal type "F")
  27331. (setq type "C"
  27332. number (calc-eval "($ - 32)*5/9" nil number))
  27333. (setq type "F"
  27334. number (calc-eval "$*9/5 + 32" nil number)))
  27335. (goto-char top2)
  27336. (delete-region top2 bot2)
  27337. (insert-before-markers type)
  27338. (goto-char top1)
  27339. (delete-region top1 bot1)
  27340. (if (string-match "\\.$" number) ; change "37." to "37"
  27341. (setq number (substring number 0 -1)))
  27342. (insert number))))
  27343. @end example
  27344. Note the use of @code{insert-before-markers} when changing between
  27345. ``F'' and ``C'', so that the character winds up before the cursor
  27346. instead of after it.
  27347. @node Internals, , Calling Calc from Your Programs, Lisp Definitions
  27348. @subsection Calculator Internals
  27349. @noindent
  27350. This section describes the Lisp functions defined by the Calculator that
  27351. may be of use to user-written Calculator programs (as described in the
  27352. rest of this chapter). These functions are shown by their names as they
  27353. conventionally appear in @code{defmath}. Their full Lisp names are
  27354. generally gotten by prepending @samp{calcFunc-} or @samp{math-} to their
  27355. apparent names. (Names that begin with @samp{calc-} are already in
  27356. their full Lisp form.) You can use the actual full names instead if you
  27357. prefer them, or if you are calling these functions from regular Lisp.
  27358. The functions described here are scattered throughout the various
  27359. Calc component files. Note that @file{calc.el} includes @code{autoload}s
  27360. for only a few component files; when Calc wants to call an advanced
  27361. function it calls @samp{(calc-extensions)} first; this function
  27362. autoloads @file{calc-ext.el}, which in turn autoloads all the functions
  27363. in the remaining component files.
  27364. Because @code{defmath} itself uses the extensions, user-written code
  27365. generally always executes with the extensions already loaded, so
  27366. normally you can use any Calc function and be confident that it will
  27367. be autoloaded for you when necessary. If you are doing something
  27368. special, check carefully to make sure each function you are using is
  27369. from @file{calc.el} or its components, and call @samp{(calc-extensions)}
  27370. before using any function based in @file{calc-ext.el} if you can't
  27371. prove this file will already be loaded.
  27372. @menu
  27373. * Data Type Formats::
  27374. * Interactive Lisp Functions::
  27375. * Stack Lisp Functions::
  27376. * Predicates::
  27377. * Computational Lisp Functions::
  27378. * Vector Lisp Functions::
  27379. * Symbolic Lisp Functions::
  27380. * Formatting Lisp Functions::
  27381. * Hooks::
  27382. @end menu
  27383. @node Data Type Formats, Interactive Lisp Functions, Internals, Internals
  27384. @subsubsection Data Type Formats
  27385. @noindent
  27386. Integers are stored in either of two ways, depending on their magnitude.
  27387. Integers less than one million in absolute value are stored as standard
  27388. Lisp integers. This is the only storage format for Calc data objects
  27389. which is not a Lisp list.
  27390. Large integers are stored as lists of the form @samp{(bigpos @var{d0}
  27391. @var{d1} @var{d2} @dots{})} for positive integers 1000000 or more, or
  27392. @samp{(bigneg @var{d0} @var{d1} @var{d2} @dots{})} for negative integers
  27393. @i{-1000000} or less. Each @var{d} is a base-1000 ``digit,'' a Lisp integer
  27394. from 0 to 999. The least significant digit is @var{d0}; the last digit,
  27395. @var{dn}, which is always nonzero, is the most significant digit. For
  27396. example, the integer @i{-12345678} is stored as @samp{(bigneg 678 345 12)}.
  27397. The distinction between small and large integers is entirely hidden from
  27398. the user. In @code{defmath} definitions, the Lisp predicate @code{integerp}
  27399. returns true for either kind of integer, and in general both big and small
  27400. integers are accepted anywhere the word ``integer'' is used in this manual.
  27401. If the distinction must be made, native Lisp integers are called @dfn{fixnums}
  27402. and large integers are called @dfn{bignums}.
  27403. Fractions are stored as a list of the form, @samp{(frac @var{n} @var{d})}
  27404. where @var{n} is an integer (big or small) numerator, @var{d} is an
  27405. integer denominator greater than one, and @var{n} and @var{d} are relatively
  27406. prime. Note that fractions where @var{d} is one are automatically converted
  27407. to plain integers by all math routines; fractions where @var{d} is negative
  27408. are normalized by negating the numerator and denominator.
  27409. Floating-point numbers are stored in the form, @samp{(float @var{mant}
  27410. @var{exp})}, where @var{mant} (the ``mantissa'') is an integer less than
  27411. @samp{10^@var{p}} in absolute value (@var{p} represents the current
  27412. precision), and @var{exp} (the ``exponent'') is a fixnum. The value of
  27413. the float is @samp{@var{mant} * 10^@var{exp}}. For example, the number
  27414. @i{-3.14} is stored as @samp{(float -314 -2) = -314*10^-2}. Other constraints
  27415. are that the number 0.0 is always stored as @samp{(float 0 0)}, and,
  27416. except for the 0.0 case, the rightmost base-10 digit of @var{mant} is
  27417. always nonzero. (If the rightmost digit is zero, the number is
  27418. rearranged by dividing @var{mant} by ten and incrementing @var{exp}.)@refill
  27419. Rectangular complex numbers are stored in the form @samp{(cplx @var{re}
  27420. @var{im})}, where @var{re} and @var{im} are each real numbers, either
  27421. integers, fractions, or floats. The value is @samp{@var{re} + @var{im}i}.
  27422. The @var{im} part is nonzero; complex numbers with zero imaginary
  27423. components are converted to real numbers automatically.@refill
  27424. Polar complex numbers are stored in the form @samp{(polar @var{r}
  27425. @var{theta})}, where @var{r} is a positive real value and @var{theta}
  27426. is a real value or HMS form representing an angle. This angle is
  27427. usually normalized to lie in the interval @samp{(-180 ..@: 180)} degrees,
  27428. or @samp{(-pi ..@: pi)} radians, according to the current angular mode.
  27429. If the angle is 0 the value is converted to a real number automatically.
  27430. (If the angle is 180 degrees, the value is usually also converted to a
  27431. negative real number.)@refill
  27432. Hours-minutes-seconds forms are stored as @samp{(hms @var{h} @var{m}
  27433. @var{s})}, where @var{h} is an integer or an integer-valued float (i.e.,
  27434. a float with @samp{@var{exp} >= 0}), @var{m} is an integer or integer-valued
  27435. float in the range @w{@samp{[0 ..@: 60)}}, and @var{s} is any real number
  27436. in the range @samp{[0 ..@: 60)}.@refill
  27437. Date forms are stored as @samp{(date @var{n})}, where @var{n} is
  27438. a real number that counts days since midnight on the morning of
  27439. January 1, 1 AD. If @var{n} is an integer, this is a pure date
  27440. form. If @var{n} is a fraction or float, this is a date/time form.
  27441. Modulo forms are stored as @samp{(mod @var{n} @var{m})}, where @var{m} is a
  27442. positive real number or HMS form, and @var{n} is a real number or HMS
  27443. form in the range @samp{[0 ..@: @var{m})}.
  27444. Error forms are stored as @samp{(sdev @var{x} @var{sigma})}, where @var{x}
  27445. is the mean value and @var{sigma} is the standard deviation. Each
  27446. component is either a number, an HMS form, or a symbolic object
  27447. (a variable or function call). If @var{sigma} is zero, the value is
  27448. converted to a plain real number. If @var{sigma} is negative or
  27449. complex, it is automatically normalized to be a positive real.
  27450. Interval forms are stored as @samp{(intv @var{mask} @var{lo} @var{hi})},
  27451. where @var{mask} is one of the integers 0, 1, 2, or 3, and @var{lo} and
  27452. @var{hi} are real numbers, HMS forms, or symbolic objects. The @var{mask}
  27453. is a binary integer where 1 represents the fact that the interval is
  27454. closed on the high end, and 2 represents the fact that it is closed on
  27455. the low end. (Thus 3 represents a fully closed interval.) The interval
  27456. @w{@samp{(intv 3 @var{x} @var{x})}} is converted to the plain number @var{x};
  27457. intervals @samp{(intv @var{mask} @var{x} @var{x})} for any other @var{mask}
  27458. represent empty intervals. If @var{hi} is less than @var{lo}, the interval
  27459. is converted to a standard empty interval by replacing @var{hi} with @var{lo}.
  27460. Vectors are stored as @samp{(vec @var{v1} @var{v2} @dots{})}, where @var{v1}
  27461. is the first element of the vector, @var{v2} is the second, and so on.
  27462. An empty vector is stored as @samp{(vec)}. A matrix is simply a vector
  27463. where all @var{v}'s are themselves vectors of equal lengths. Note that
  27464. Calc vectors are unrelated to the Emacs Lisp ``vector'' type, which is
  27465. generally unused by Calc data structures.
  27466. Variables are stored as @samp{(var @var{name} @var{sym})}, where
  27467. @var{name} is a Lisp symbol whose print name is used as the visible name
  27468. of the variable, and @var{sym} is a Lisp symbol in which the variable's
  27469. value is actually stored. Thus, @samp{(var pi var-pi)} represents the
  27470. special constant @samp{pi}. Almost always, the form is @samp{(var
  27471. @var{v} var-@var{v})}. If the variable name was entered with @code{#}
  27472. signs (which are converted to hyphens internally), the form is
  27473. @samp{(var @var{u} @var{v})}, where @var{u} is a symbol whose name
  27474. contains @code{#} characters, and @var{v} is a symbol that contains
  27475. @code{-} characters instead. The value of a variable is the Calc
  27476. object stored in its @var{sym} symbol's value cell. If the symbol's
  27477. value cell is void or if it contains @code{nil}, the variable has no
  27478. value. Special constants have the form @samp{(special-const
  27479. @var{value})} stored in their value cell, where @var{value} is a formula
  27480. which is evaluated when the constant's value is requested. Variables
  27481. which represent units are not stored in any special way; they are units
  27482. only because their names appear in the units table. If the value
  27483. cell contains a string, it is parsed to get the variable's value when
  27484. the variable is used.@refill
  27485. A Lisp list with any other symbol as the first element is a function call.
  27486. The symbols @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^},
  27487. and @code{|} represent special binary operators; these lists are always
  27488. of the form @samp{(@var{op} @var{lhs} @var{rhs})} where @var{lhs} is the
  27489. sub-formula on the lefthand side and @var{rhs} is the sub-formula on the
  27490. right. The symbol @code{neg} represents unary negation; this list is always
  27491. of the form @samp{(neg @var{arg})}. Any other symbol @var{func} represents a
  27492. function that would be displayed in function-call notation; the symbol
  27493. @var{func} is in general always of the form @samp{calcFunc-@var{name}}.
  27494. The function cell of the symbol @var{func} should contain a Lisp function
  27495. for evaluating a call to @var{func}. This function is passed the remaining
  27496. elements of the list (themselves already evaluated) as arguments; such
  27497. functions should return @code{nil} or call @code{reject-arg} to signify
  27498. that they should be left in symbolic form, or they should return a Calc
  27499. object which represents their value, or a list of such objects if they
  27500. wish to return multiple values. (The latter case is allowed only for
  27501. functions which are the outer-level call in an expression whose value is
  27502. about to be pushed on the stack; this feature is considered obsolete
  27503. and is not used by any built-in Calc functions.)@refill
  27504. @node Interactive Lisp Functions, Stack Lisp Functions, Data Type Formats, Internals
  27505. @subsubsection Interactive Functions
  27506. @noindent
  27507. The functions described here are used in implementing interactive Calc
  27508. commands. Note that this list is not exhaustive! If there is an
  27509. existing command that behaves similarly to the one you want to define,
  27510. you may find helpful tricks by checking the source code for that command.
  27511. @defun calc-set-command-flag flag
  27512. Set the command flag @var{flag}. This is generally a Lisp symbol, but
  27513. may in fact be anything. The effect is to add @var{flag} to the list
  27514. stored in the variable @code{calc-command-flags}, unless it is already
  27515. there. @xref{Defining Simple Commands}.
  27516. @end defun
  27517. @defun calc-clear-command-flag flag
  27518. If @var{flag} appears among the list of currently-set command flags,
  27519. remove it from that list.
  27520. @end defun
  27521. @defun calc-record-undo rec
  27522. Add the ``undo record'' @var{rec} to the list of steps to take if the
  27523. current operation should need to be undone. Stack push and pop functions
  27524. automatically call @code{calc-record-undo}, so the kinds of undo records
  27525. you might need to create take the form @samp{(set @var{sym} @var{value})},
  27526. which says that the Lisp variable @var{sym} was changed and had previously
  27527. contained @var{value}; @samp{(store @var{var} @var{value})} which says that
  27528. the Calc variable @var{var} (a string which is the name of the symbol that
  27529. contains the variable's value) was stored and its previous value was
  27530. @var{value} (either a Calc data object, or @code{nil} if the variable was
  27531. previously void); or @samp{(eval @var{undo} @var{redo} @var{args} @dots{})},
  27532. which means that to undo requires calling the function @samp{(@var{undo}
  27533. @var{args} @dots{})} and, if the undo is later redone, calling
  27534. @samp{(@var{redo} @var{args} @dots{})}.@refill
  27535. @end defun
  27536. @defun calc-record-why msg args
  27537. Record the error or warning message @var{msg}, which is normally a string.
  27538. This message will be replayed if the user types @kbd{w} (@code{calc-why});
  27539. if the message string begins with a @samp{*}, it is considered important
  27540. enough to display even if the user doesn't type @kbd{w}. If one or more
  27541. @var{args} are present, the displayed message will be of the form,
  27542. @samp{@var{msg}: @var{arg1}, @var{arg2}, @dots{}}, where the arguments are
  27543. formatted on the assumption that they are either strings or Calc objects of
  27544. some sort. If @var{msg} is a symbol, it is the name of a Calc predicate
  27545. (such as @code{integerp} or @code{numvecp}) which the arguments did not
  27546. satisfy; it is expanded to a suitable string such as ``Expected an
  27547. integer.'' The @code{reject-arg} function calls @code{calc-record-why}
  27548. automatically; @pxref{Predicates}.@refill
  27549. @end defun
  27550. @defun calc-is-inverse
  27551. This predicate returns true if the current command is inverse,
  27552. i.e., if the Inverse (@kbd{I} key) flag was set.
  27553. @end defun
  27554. @defun calc-is-hyperbolic
  27555. This predicate is the analogous function for the @kbd{H} key.
  27556. @end defun
  27557. @node Stack Lisp Functions, Predicates, Interactive Lisp Functions, Internals
  27558. @subsubsection Stack-Oriented Functions
  27559. @noindent
  27560. The functions described here perform various operations on the Calc
  27561. stack and trail. They are to be used in interactive Calc commands.
  27562. @defun calc-push-list vals n
  27563. Push the Calc objects in list @var{vals} onto the stack at stack level
  27564. @var{n}. If @var{n} is omitted it defaults to 1, so that the elements
  27565. are pushed at the top of the stack. If @var{n} is greater than 1, the
  27566. elements will be inserted into the stack so that the last element will
  27567. end up at level @var{n}, the next-to-last at level @var{n}+1, etc.
  27568. The elements of @var{vals} are assumed to be valid Calc objects, and
  27569. are not evaluated, rounded, or renormalized in any way. If @var{vals}
  27570. is an empty list, nothing happens.@refill
  27571. The stack elements are pushed without any sub-formula selections.
  27572. You can give an optional third argument to this function, which must
  27573. be a list the same size as @var{vals} of selections. Each selection
  27574. must be @code{eq} to some sub-formula of the corresponding formula
  27575. in @var{vals}, or @code{nil} if that formula should have no selection.
  27576. @end defun
  27577. @defun calc-top-list n m
  27578. Return a list of the @var{n} objects starting at level @var{m} of the
  27579. stack. If @var{m} is omitted it defaults to 1, so that the elements are
  27580. taken from the top of the stack. If @var{n} is omitted, it also
  27581. defaults to 1, so that the top stack element (in the form of a
  27582. one-element list) is returned. If @var{m} is greater than 1, the
  27583. @var{m}th stack element will be at the end of the list, the @var{m}+1st
  27584. element will be next-to-last, etc. If @var{n} or @var{m} are out of
  27585. range, the command is aborted with a suitable error message. If @var{n}
  27586. is zero, the function returns an empty list. The stack elements are not
  27587. evaluated, rounded, or renormalized.@refill
  27588. If any stack elements contain selections, and selections have not
  27589. been disabled by the @kbd{j e} (@code{calc-enable-selections}) command,
  27590. this function returns the selected portions rather than the entire
  27591. stack elements. It can be given a third ``selection-mode'' argument
  27592. which selects other behaviors. If it is the symbol @code{t}, then
  27593. a selection in any of the requested stack elements produces an
  27594. ``illegal operation on selections'' error. If it is the symbol @code{full},
  27595. the whole stack entry is always returned regardless of selections.
  27596. If it is the symbol @code{sel}, the selected portion is always returned,
  27597. or @code{nil} if there is no selection. (This mode ignores the @kbd{j e}
  27598. command.) If the symbol is @code{entry}, the complete stack entry in
  27599. list form is returned; the first element of this list will be the whole
  27600. formula, and the third element will be the selection (or @code{nil}).
  27601. @end defun
  27602. @defun calc-pop-stack n m
  27603. Remove the specified elements from the stack. The parameters @var{n}
  27604. and @var{m} are defined the same as for @code{calc-top-list}. The return
  27605. value of @code{calc-pop-stack} is uninteresting.
  27606. If there are any selected sub-formulas among the popped elements, and
  27607. @kbd{j e} has not been used to disable selections, this produces an
  27608. error without changing the stack. If you supply an optional third
  27609. argument of @code{t}, the stack elements are popped even if they
  27610. contain selections.
  27611. @end defun
  27612. @defun calc-record-list vals tag
  27613. This function records one or more results in the trail. The @var{vals}
  27614. are a list of strings or Calc objects. The @var{tag} is the four-character
  27615. tag string to identify the values. If @var{tag} is omitted, a blank tag
  27616. will be used.
  27617. @end defun
  27618. @defun calc-normalize n
  27619. This function takes a Calc object and ``normalizes'' it. At the very
  27620. least this involves re-rounding floating-point values according to the
  27621. current precision and other similar jobs. Also, unless the user has
  27622. selected no-simplify mode (@pxref{Simplification Modes}), this involves
  27623. actually evaluating a formula object by executing the function calls
  27624. it contains, and possibly also doing algebraic simplification, etc.
  27625. @end defun
  27626. @defun calc-top-list-n n m
  27627. This function is identical to @code{calc-top-list}, except that it calls
  27628. @code{calc-normalize} on the values that it takes from the stack. They
  27629. are also passed through @code{check-complete}, so that incomplete
  27630. objects will be rejected with an error message. All computational
  27631. commands should use this in preference to @code{calc-top-list}; the only
  27632. standard Calc commands that operate on the stack without normalizing
  27633. are stack management commands like @code{calc-enter} and @code{calc-roll-up}.
  27634. This function accepts the same optional selection-mode argument as
  27635. @code{calc-top-list}.
  27636. @end defun
  27637. @defun calc-top-n m
  27638. This function is a convenient form of @code{calc-top-list-n} in which only
  27639. a single element of the stack is taken and returned, rather than a list
  27640. of elements. This also accepts an optional selection-mode argument.
  27641. @end defun
  27642. @defun calc-enter-result n tag vals
  27643. This function is a convenient interface to most of the above functions.
  27644. The @var{vals} argument should be either a single Calc object, or a list
  27645. of Calc objects; the object or objects are normalized, and the top @var{n}
  27646. stack entries are replaced by the normalized objects. If @var{tag} is
  27647. non-@code{nil}, the normalized objects are also recorded in the trail.
  27648. A typical stack-based computational command would take the form,
  27649. @smallexample
  27650. (calc-enter-result @var{n} @var{tag} (cons 'calcFunc-@var{func}
  27651. (calc-top-list-n @var{n})))
  27652. @end smallexample
  27653. If any of the @var{n} stack elements replaced contain sub-formula
  27654. selections, and selections have not been disabled by @kbd{j e},
  27655. this function takes one of two courses of action. If @var{n} is
  27656. equal to the number of elements in @var{vals}, then each element of
  27657. @var{vals} is spliced into the corresponding selection; this is what
  27658. happens when you use the @key{TAB} key, or when you use a unary
  27659. arithmetic operation like @code{sqrt}. If @var{vals} has only one
  27660. element but @var{n} is greater than one, there must be only one
  27661. selection among the top @var{n} stack elements; the element from
  27662. @var{vals} is spliced into that selection. This is what happens when
  27663. you use a binary arithmetic operation like @kbd{+}. Any other
  27664. combination of @var{n} and @var{vals} is an error when selections
  27665. are present.
  27666. @end defun
  27667. @defun calc-unary-op tag func arg
  27668. This function implements a unary operator that allows a numeric prefix
  27669. argument to apply the operator over many stack entries. If the prefix
  27670. argument @var{arg} is @code{nil}, this uses @code{calc-enter-result}
  27671. as outlined above. Otherwise, it maps the function over several stack
  27672. elements; @pxref{Prefix Arguments}. For example,@refill
  27673. @smallexample
  27674. (defun calc-zeta (arg)
  27675. (interactive "P")
  27676. (calc-unary-op "zeta" 'calcFunc-zeta arg))
  27677. @end smallexample
  27678. @end defun
  27679. @defun calc-binary-op tag func arg ident unary
  27680. This function implements a binary operator, analogously to
  27681. @code{calc-unary-op}. The optional @var{ident} and @var{unary}
  27682. arguments specify the behavior when the prefix argument is zero or
  27683. one, respectively. If the prefix is zero, the value @var{ident}
  27684. is pushed onto the stack, if specified, otherwise an error message
  27685. is displayed. If the prefix is one, the unary function @var{unary}
  27686. is applied to the top stack element, or, if @var{unary} is not
  27687. specified, nothing happens. When the argument is two or more,
  27688. the binary function @var{func} is reduced across the top @var{arg}
  27689. stack elements; when the argument is negative, the function is
  27690. mapped between the next-to-top @i{-@var{arg}} stack elements and the
  27691. top element.@refill
  27692. @end defun
  27693. @defun calc-stack-size
  27694. Return the number of elements on the stack as an integer. This count
  27695. does not include elements that have been temporarily hidden by stack
  27696. truncation; @pxref{Truncating the Stack}.
  27697. @end defun
  27698. @defun calc-cursor-stack-index n
  27699. Move the point to the @var{n}th stack entry. If @var{n} is zero, this
  27700. will be the @samp{.} line. If @var{n} is from 1 to the current stack size,
  27701. this will be the beginning of the first line of that stack entry's display.
  27702. If line numbers are enabled, this will move to the first character of the
  27703. line number, not the stack entry itself.@refill
  27704. @end defun
  27705. @defun calc-substack-height n
  27706. Return the number of lines between the beginning of the @var{n}th stack
  27707. entry and the bottom of the buffer. If @var{n} is zero, this
  27708. will be one (assuming no stack truncation). If all stack entries are
  27709. one line long (i.e., no matrices are displayed), the return value will
  27710. be equal @var{n}+1 as long as @var{n} is in range. (Note that in Big
  27711. mode, the return value includes the blank lines that separate stack
  27712. entries.)@refill
  27713. @end defun
  27714. @defun calc-refresh
  27715. Erase the @code{*Calculator*} buffer and reformat its contents from memory.
  27716. This must be called after changing any parameter, such as the current
  27717. display radix, which might change the appearance of existing stack
  27718. entries. (During a keyboard macro invoked by the @kbd{X} key, refreshing
  27719. is suppressed, but a flag is set so that the entire stack will be refreshed
  27720. rather than just the top few elements when the macro finishes.)@refill
  27721. @end defun
  27722. @node Predicates, Computational Lisp Functions, Stack Lisp Functions, Internals
  27723. @subsubsection Predicates
  27724. @noindent
  27725. The functions described here are predicates, that is, they return a
  27726. true/false value where @code{nil} means false and anything else means
  27727. true. These predicates are expanded by @code{defmath}, for example,
  27728. from @code{zerop} to @code{math-zerop}. In many cases they correspond
  27729. to native Lisp functions by the same name, but are extended to cover
  27730. the full range of Calc data types.
  27731. @defun zerop x
  27732. Returns true if @var{x} is numerically zero, in any of the Calc data
  27733. types. (Note that for some types, such as error forms and intervals,
  27734. it never makes sense to return true.) In @code{defmath}, the expression
  27735. @samp{(= x 0)} will automatically be converted to @samp{(math-zerop x)},
  27736. and @samp{(/= x 0)} will be converted to @samp{(not (math-zerop x))}.
  27737. @end defun
  27738. @defun negp x
  27739. Returns true if @var{x} is negative. This accepts negative real numbers
  27740. of various types, negative HMS and date forms, and intervals in which
  27741. all included values are negative. In @code{defmath}, the expression
  27742. @samp{(< x 0)} will automatically be converted to @samp{(math-negp x)},
  27743. and @samp{(>= x 0)} will be converted to @samp{(not (math-negp x))}.
  27744. @end defun
  27745. @defun posp x
  27746. Returns true if @var{x} is positive (and non-zero). For complex
  27747. numbers, none of these three predicates will return true.
  27748. @end defun
  27749. @defun looks-negp x
  27750. Returns true if @var{x} is ``negative-looking.'' This returns true if
  27751. @var{x} is a negative number, or a formula with a leading minus sign
  27752. such as @samp{-a/b}. In other words, this is an object which can be
  27753. made simpler by calling @code{(- @var{x})}.
  27754. @end defun
  27755. @defun integerp x
  27756. Returns true if @var{x} is an integer of any size.
  27757. @end defun
  27758. @defun fixnump x
  27759. Returns true if @var{x} is a native Lisp integer.
  27760. @end defun
  27761. @defun natnump x
  27762. Returns true if @var{x} is a nonnegative integer of any size.
  27763. @end defun
  27764. @defun fixnatnump x
  27765. Returns true if @var{x} is a nonnegative Lisp integer.
  27766. @end defun
  27767. @defun num-integerp x
  27768. Returns true if @var{x} is numerically an integer, i.e., either a
  27769. true integer or a float with no significant digits to the right of
  27770. the decimal point.
  27771. @end defun
  27772. @defun messy-integerp x
  27773. Returns true if @var{x} is numerically, but not literally, an integer.
  27774. A value is @code{num-integerp} if it is @code{integerp} or
  27775. @code{messy-integerp} (but it is never both at once).
  27776. @end defun
  27777. @defun num-natnump x
  27778. Returns true if @var{x} is numerically a nonnegative integer.
  27779. @end defun
  27780. @defun evenp x
  27781. Returns true if @var{x} is an even integer.
  27782. @end defun
  27783. @defun looks-evenp x
  27784. Returns true if @var{x} is an even integer, or a formula with a leading
  27785. multiplicative coefficient which is an even integer.
  27786. @end defun
  27787. @defun oddp x
  27788. Returns true if @var{x} is an odd integer.
  27789. @end defun
  27790. @defun ratp x
  27791. Returns true if @var{x} is a rational number, i.e., an integer or a
  27792. fraction.
  27793. @end defun
  27794. @defun realp x
  27795. Returns true if @var{x} is a real number, i.e., an integer, fraction,
  27796. or floating-point number.
  27797. @end defun
  27798. @defun anglep x
  27799. Returns true if @var{x} is a real number or HMS form.
  27800. @end defun
  27801. @defun floatp x
  27802. Returns true if @var{x} is a float, or a complex number, error form,
  27803. interval, date form, or modulo form in which at least one component
  27804. is a float.
  27805. @end defun
  27806. @defun complexp x
  27807. Returns true if @var{x} is a rectangular or polar complex number
  27808. (but not a real number).
  27809. @end defun
  27810. @defun rect-complexp x
  27811. Returns true if @var{x} is a rectangular complex number.
  27812. @end defun
  27813. @defun polar-complexp x
  27814. Returns true if @var{x} is a polar complex number.
  27815. @end defun
  27816. @defun numberp x
  27817. Returns true if @var{x} is a real number or a complex number.
  27818. @end defun
  27819. @defun scalarp x
  27820. Returns true if @var{x} is a real or complex number or an HMS form.
  27821. @end defun
  27822. @defun vectorp x
  27823. Returns true if @var{x} is a vector (this simply checks if its argument
  27824. is a list whose first element is the symbol @code{vec}).
  27825. @end defun
  27826. @defun numvecp x
  27827. Returns true if @var{x} is a number or vector.
  27828. @end defun
  27829. @defun matrixp x
  27830. Returns true if @var{x} is a matrix, i.e., a vector of one or more vectors,
  27831. all of the same size.
  27832. @end defun
  27833. @defun square-matrixp x
  27834. Returns true if @var{x} is a square matrix.
  27835. @end defun
  27836. @defun objectp x
  27837. Returns true if @var{x} is any numeric Calc object, including real and
  27838. complex numbers, HMS forms, date forms, error forms, intervals, and
  27839. modulo forms. (Note that error forms and intervals may include formulas
  27840. as their components; see @code{constp} below.)
  27841. @end defun
  27842. @defun objvecp x
  27843. Returns true if @var{x} is an object or a vector. This also accepts
  27844. incomplete objects, but it rejects variables and formulas (except as
  27845. mentioned above for @code{objectp}).
  27846. @end defun
  27847. @defun primp x
  27848. Returns true if @var{x} is a ``primitive'' or ``atomic'' Calc object,
  27849. i.e., one whose components cannot be regarded as sub-formulas. This
  27850. includes variables, and all @code{objectp} types except error forms
  27851. and intervals.
  27852. @end defun
  27853. @defun constp x
  27854. Returns true if @var{x} is constant, i.e., a real or complex number,
  27855. HMS form, date form, or error form, interval, or vector all of whose
  27856. components are @code{constp}.
  27857. @end defun
  27858. @defun lessp x y
  27859. Returns true if @var{x} is numerically less than @var{y}. Returns false
  27860. if @var{x} is greater than or equal to @var{y}, or if the order is
  27861. undefined or cannot be determined. Generally speaking, this works
  27862. by checking whether @samp{@var{x} - @var{y}} is @code{negp}. In
  27863. @code{defmath}, the expression @samp{(< x y)} will automatically be
  27864. converted to @samp{(lessp x y)}; expressions involving @code{>}, @code{<=},
  27865. and @code{>=} are similarly converted in terms of @code{lessp}.@refill
  27866. @end defun
  27867. @defun beforep x y
  27868. Returns true if @var{x} comes before @var{y} in a canonical ordering
  27869. of Calc objects. If @var{x} and @var{y} are both real numbers, this
  27870. will be the same as @code{lessp}. But whereas @code{lessp} considers
  27871. other types of objects to be unordered, @code{beforep} puts any two
  27872. objects into a definite, consistent order. The @code{beforep}
  27873. function is used by the @kbd{V S} vector-sorting command, and also
  27874. by @kbd{a s} to put the terms of a product into canonical order:
  27875. This allows @samp{x y + y x} to be simplified easily to @samp{2 x y}.
  27876. @end defun
  27877. @defun equal x y
  27878. This is the standard Lisp @code{equal} predicate; it returns true if
  27879. @var{x} and @var{y} are structurally identical. This is the usual way
  27880. to compare numbers for equality, but note that @code{equal} will treat
  27881. 0 and 0.0 as different.
  27882. @end defun
  27883. @defun math-equal x y
  27884. Returns true if @var{x} and @var{y} are numerically equal, either because
  27885. they are @code{equal}, or because their difference is @code{zerop}. In
  27886. @code{defmath}, the expression @samp{(= x y)} will automatically be
  27887. converted to @samp{(math-equal x y)}.
  27888. @end defun
  27889. @defun equal-int x n
  27890. Returns true if @var{x} and @var{n} are numerically equal, where @var{n}
  27891. is a fixnum which is not a multiple of 10. This will automatically be
  27892. used by @code{defmath} in place of the more general @code{math-equal}
  27893. whenever possible.@refill
  27894. @end defun
  27895. @defun nearly-equal x y
  27896. Returns true if @var{x} and @var{y}, as floating-point numbers, are
  27897. equal except possibly in the last decimal place. For example,
  27898. 314.159 and 314.166 are considered nearly equal if the current
  27899. precision is 6 (since they differ by 7 units), but not if the current
  27900. precision is 7 (since they differ by 70 units). Most functions which
  27901. use series expansions use @code{with-extra-prec} to evaluate the
  27902. series with 2 extra digits of precision, then use @code{nearly-equal}
  27903. to decide when the series has converged; this guards against cumulative
  27904. error in the series evaluation without doing extra work which would be
  27905. lost when the result is rounded back down to the current precision.
  27906. In @code{defmath}, this can be written @samp{(~= @var{x} @var{y})}.
  27907. The @var{x} and @var{y} can be numbers of any kind, including complex.
  27908. @end defun
  27909. @defun nearly-zerop x y
  27910. Returns true if @var{x} is nearly zero, compared to @var{y}. This
  27911. checks whether @var{x} plus @var{y} would by be @code{nearly-equal}
  27912. to @var{y} itself, to within the current precision, in other words,
  27913. if adding @var{x} to @var{y} would have a negligible effect on @var{y}
  27914. due to roundoff error. @var{X} may be a real or complex number, but
  27915. @var{y} must be real.
  27916. @end defun
  27917. @defun is-true x
  27918. Return true if the formula @var{x} represents a true value in
  27919. Calc, not Lisp, terms. It tests if @var{x} is a non-zero number
  27920. or a provably non-zero formula.
  27921. @end defun
  27922. @defun reject-arg val pred
  27923. Abort the current function evaluation due to unacceptable argument values.
  27924. This calls @samp{(calc-record-why @var{pred} @var{val})}, then signals a
  27925. Lisp error which @code{normalize} will trap. The net effect is that the
  27926. function call which led here will be left in symbolic form.@refill
  27927. @end defun
  27928. @defun inexact-value
  27929. If Symbolic Mode is enabled, this will signal an error that causes
  27930. @code{normalize} to leave the formula in symbolic form, with the message
  27931. ``Inexact result.'' (This function has no effect when not in Symbolic Mode.)
  27932. Note that if your function calls @samp{(sin 5)} in Symbolic Mode, the
  27933. @code{sin} function will call @code{inexact-value}, which will cause your
  27934. function to be left unsimplified. You may instead wish to call
  27935. @samp{(normalize (list 'calcFunc-sin 5))}, which in Symbolic Mode will
  27936. return the formula @samp{sin(5)} to your function.@refill
  27937. @end defun
  27938. @defun overflow
  27939. This signals an error that will be reported as a floating-point overflow.
  27940. @end defun
  27941. @defun underflow
  27942. This signals a floating-point underflow.
  27943. @end defun
  27944. @node Computational Lisp Functions, Vector Lisp Functions, Predicates, Internals
  27945. @subsubsection Computational Functions
  27946. @noindent
  27947. The functions described here do the actual computational work of the
  27948. Calculator. In addition to these, note that any function described in
  27949. the main body of this manual may be called from Lisp; for example, if
  27950. the documentation refers to the @code{calc-sqrt} [@code{sqrt}] command,
  27951. this means @code{calc-sqrt} is an interactive stack-based square-root
  27952. command and @code{sqrt} (which @code{defmath} expands to @code{calcFunc-sqrt})
  27953. is the actual Lisp function for taking square roots.@refill
  27954. The functions @code{math-add}, @code{math-sub}, @code{math-mul},
  27955. @code{math-div}, @code{math-mod}, and @code{math-neg} are not included
  27956. in this list, since @code{defmath} allows you to write native Lisp
  27957. @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, and unary @code{-},
  27958. respectively, instead.@refill
  27959. @defun normalize val
  27960. (Full form: @code{math-normalize}.)
  27961. Reduce the value @var{val} to standard form. For example, if @var{val}
  27962. is a fixnum, it will be converted to a bignum if it is too large, and
  27963. if @var{val} is a bignum it will be normalized by clipping off trailing
  27964. (i.e., most-significant) zero digits and converting to a fixnum if it is
  27965. small. All the various data types are similarly converted to their standard
  27966. forms. Variables are left alone, but function calls are actually evaluated
  27967. in formulas. For example, normalizing @samp{(+ 2 (calcFunc-abs -4))} will
  27968. return 6.@refill
  27969. If a function call fails, because the function is void or has the wrong
  27970. number of parameters, or because it returns @code{nil} or calls
  27971. @code{reject-arg} or @code{inexact-result}, @code{normalize} returns
  27972. the formula still in symbolic form.@refill
  27973. If the current Simplification Mode is ``none'' or ``numeric arguments
  27974. only,'' @code{normalize} will act appropriately. However, the more
  27975. powerful simplification modes (like algebraic simplification) are
  27976. not handled by @code{normalize}. They are handled by @code{calc-normalize},
  27977. which calls @code{normalize} and possibly some other routines, such
  27978. as @code{simplify} or @code{simplify-units}. Programs generally will
  27979. never call @code{calc-normalize} except when popping or pushing values
  27980. on the stack.@refill
  27981. @end defun
  27982. @defun evaluate-expr expr
  27983. Replace all variables in @var{expr} that have values with their values,
  27984. then use @code{normalize} to simplify the result. This is what happens
  27985. when you press the @kbd{=} key interactively.@refill
  27986. @end defun
  27987. @defmac with-extra-prec n body
  27988. Evaluate the Lisp forms in @var{body} with precision increased by @var{n}
  27989. digits. This is a macro which expands to
  27990. @smallexample
  27991. (math-normalize
  27992. (let ((calc-internal-prec (+ calc-internal-prec @var{n})))
  27993. @var{body}))
  27994. @end smallexample
  27995. The surrounding call to @code{math-normalize} causes a floating-point
  27996. result to be rounded down to the original precision afterwards. This
  27997. is important because some arithmetic operations assume a number's
  27998. mantissa contains no more digits than the current precision allows.
  27999. @end defmac
  28000. @defun make-frac n d
  28001. Build a fraction @samp{@var{n}:@var{d}}. This is equivalent to calling
  28002. @samp{(normalize (list 'frac @var{n} @var{d}))}, but more efficient.
  28003. @end defun
  28004. @defun make-float mant exp
  28005. Build a floating-point value out of @var{mant} and @var{exp}, both
  28006. of which are arbitrary integers. This function will return a
  28007. properly normalized float value, or signal an overflow or underflow
  28008. if @var{exp} is out of range.
  28009. @end defun
  28010. @defun make-sdev x sigma
  28011. Build an error form out of @var{x} and the absolute value of @var{sigma}.
  28012. If @var{sigma} is zero, the result is the number @var{x} directly.
  28013. If @var{sigma} is negative or complex, its absolute value is used.
  28014. If @var{x} or @var{sigma} is not a valid type of object for use in
  28015. error forms, this calls @code{reject-arg}.
  28016. @end defun
  28017. @defun make-intv mask lo hi
  28018. Build an interval form out of @var{mask} (which is assumed to be an
  28019. integer from 0 to 3), and the limits @var{lo} and @var{hi}. If
  28020. @var{lo} is greater than @var{hi}, an empty interval form is returned.
  28021. This calls @code{reject-arg} if @var{lo} or @var{hi} is unsuitable.
  28022. @end defun
  28023. @defun sort-intv mask lo hi
  28024. Build an interval form, similar to @code{make-intv}, except that if
  28025. @var{lo} is less than @var{hi} they are simply exchanged, and the
  28026. bits of @var{mask} are swapped accordingly.
  28027. @end defun
  28028. @defun make-mod n m
  28029. Build a modulo form out of @var{n} and the modulus @var{m}. Since modulo
  28030. forms do not allow formulas as their components, if @var{n} or @var{m}
  28031. is not a real number or HMS form the result will be a formula which
  28032. is a call to @code{makemod}, the algebraic version of this function.
  28033. @end defun
  28034. @defun float x
  28035. Convert @var{x} to floating-point form. Integers and fractions are
  28036. converted to numerically equivalent floats; components of complex
  28037. numbers, vectors, HMS forms, date forms, error forms, intervals, and
  28038. modulo forms are recursively floated. If the argument is a variable
  28039. or formula, this calls @code{reject-arg}.
  28040. @end defun
  28041. @defun compare x y
  28042. Compare the numbers @var{x} and @var{y}, and return @i{-1} if
  28043. @samp{(lessp @var{x} @var{y})}, 1 if @samp{(lessp @var{y} @var{x})},
  28044. 0 if @samp{(math-equal @var{x} @var{y})}, or 2 if the order is
  28045. undefined or cannot be determined.@refill
  28046. @end defun
  28047. @defun numdigs n
  28048. Return the number of digits of integer @var{n}, effectively
  28049. @samp{ceil(log10(@var{n}))}, but much more efficient. Zero is
  28050. considered to have zero digits.
  28051. @end defun
  28052. @defun scale-int x n
  28053. Shift integer @var{x} left @var{n} decimal digits, or right @i{-@var{n}}
  28054. digits with truncation toward zero.
  28055. @end defun
  28056. @defun scale-rounding x n
  28057. Like @code{scale-int}, except that a right shift rounds to the nearest
  28058. integer rather than truncating.
  28059. @end defun
  28060. @defun fixnum n
  28061. Return the integer @var{n} as a fixnum, i.e., a native Lisp integer.
  28062. If @var{n} is outside the permissible range for Lisp integers (usually
  28063. 24 binary bits) the result is undefined.
  28064. @end defun
  28065. @defun sqr x
  28066. Compute the square of @var{x}; short for @samp{(* @var{x} @var{x})}.
  28067. @end defun
  28068. @defun quotient x y
  28069. Divide integer @var{x} by integer @var{y}; return an integer quotient
  28070. and discard the remainder. If @var{x} or @var{y} is negative, the
  28071. direction of rounding is undefined.
  28072. @end defun
  28073. @defun idiv x y
  28074. Perform an integer division; if @var{x} and @var{y} are both nonnegative
  28075. integers, this uses the @code{quotient} function, otherwise it computes
  28076. @samp{floor(@var{x}/@var{y})}. Thus the result is well-defined but
  28077. slower than for @code{quotient}.
  28078. @end defun
  28079. @defun imod x y
  28080. Divide integer @var{x} by integer @var{y}; return the integer remainder
  28081. and discard the quotient. Like @code{quotient}, this works only for
  28082. integer arguments and is not well-defined for negative arguments.
  28083. For a more well-defined result, use @samp{(% @var{x} @var{y})}.
  28084. @end defun
  28085. @defun idivmod x y
  28086. Divide integer @var{x} by integer @var{y}; return a cons cell whose
  28087. @code{car} is @samp{(quotient @var{x} @var{y})} and whose @code{cdr}
  28088. is @samp{(imod @var{x} @var{y})}.@refill
  28089. @end defun
  28090. @defun pow x y
  28091. Compute @var{x} to the power @var{y}. In @code{defmath} code, this can
  28092. also be written @samp{(^ @var{x} @var{y})} or
  28093. @w{@samp{(expt @var{x} @var{y})}}.@refill
  28094. @end defun
  28095. @defun abs-approx x
  28096. Compute a fast approximation to the absolute value of @var{x}. For
  28097. example, for a rectangular complex number the result is the sum of
  28098. the absolute values of the components.
  28099. @end defun
  28100. @findex two-pi
  28101. @findex pi-over-2
  28102. @findex pi-over-4
  28103. @findex pi-over-180
  28104. @findex sqrt-two-pi
  28105. @findex sqrt-e
  28106. @findex e
  28107. @findex ln-2
  28108. @findex ln-10
  28109. @defun pi
  28110. The function @samp{(pi)} computes @samp{pi} to the current precision.
  28111. Other related constant-generating functions are @code{two-pi},
  28112. @code{pi-over-2}, @code{pi-over-4}, @code{pi-over-180}, @code{sqrt-two-pi},
  28113. @code{e}, @code{sqrt-e}, @code{ln-2}, and @code{ln-10}. Each function
  28114. returns a floating-point value in the current precision, and each uses
  28115. caching so that all calls after the first are essentially free.@refill
  28116. @end defun
  28117. @defmac math-defcache @var{func} @var{initial} @var{form}
  28118. This macro, usually used as a top-level call like @code{defun} or
  28119. @code{defvar}, defines a new cached constant analogous to @code{pi}, etc.
  28120. It defines a function @code{func} which returns the requested value;
  28121. if @var{initial} is non-@code{nil} it must be a @samp{(float @dots{})}
  28122. form which serves as an initial value for the cache. If @var{func}
  28123. is called when the cache is empty or does not have enough digits to
  28124. satisfy the current precision, the Lisp expression @var{form} is evaluated
  28125. with the current precision increased by four, and the result minus its
  28126. two least significant digits is stored in the cache. For example,
  28127. calling @samp{(pi)} with a precision of 30 computes @samp{pi} to 34
  28128. digits, rounds it down to 32 digits for future use, then rounds it
  28129. again to 30 digits for use in the present request.@refill
  28130. @end defmac
  28131. @findex half-circle
  28132. @findex quarter-circle
  28133. @defun full-circle symb
  28134. If the current angular mode is Degrees or HMS, this function returns the
  28135. integer 360. In Radians mode, this function returns either the
  28136. corresponding value in radians to the current precision, or the formula
  28137. @samp{2*pi}, depending on the Symbolic Mode. There are also similar
  28138. function @code{half-circle} and @code{quarter-circle}.
  28139. @end defun
  28140. @defun power-of-2 n
  28141. Compute two to the integer power @var{n}, as a (potentially very large)
  28142. integer. Powers of two are cached, so only the first call for a
  28143. particular @var{n} is expensive.
  28144. @end defun
  28145. @defun integer-log2 n
  28146. Compute the base-2 logarithm of @var{n}, which must be an integer which
  28147. is a power of two. If @var{n} is not a power of two, this function will
  28148. return @code{nil}.
  28149. @end defun
  28150. @defun div-mod a b m
  28151. Divide @var{a} by @var{b}, modulo @var{m}. This returns @code{nil} if
  28152. there is no solution, or if any of the arguments are not integers.@refill
  28153. @end defun
  28154. @defun pow-mod a b m
  28155. Compute @var{a} to the power @var{b}, modulo @var{m}. If @var{a},
  28156. @var{b}, and @var{m} are integers, this uses an especially efficient
  28157. algorithm. Otherwise, it simply computes @samp{(% (^ a b) m)}.
  28158. @end defun
  28159. @defun isqrt n
  28160. Compute the integer square root of @var{n}. This is the square root
  28161. of @var{n} rounded down toward zero, i.e., @samp{floor(sqrt(@var{n}))}.
  28162. If @var{n} is itself an integer, the computation is especially efficient.
  28163. @end defun
  28164. @defun to-hms a ang
  28165. Convert the argument @var{a} into an HMS form. If @var{ang} is specified,
  28166. it is the angular mode in which to interpret @var{a}, either @code{deg}
  28167. or @code{rad}. Otherwise, the current angular mode is used. If @var{a}
  28168. is already an HMS form it is returned as-is.
  28169. @end defun
  28170. @defun from-hms a ang
  28171. Convert the HMS form @var{a} into a real number. If @var{ang} is specified,
  28172. it is the angular mode in which to express the result, otherwise the
  28173. current angular mode is used. If @var{a} is already a real number, it
  28174. is returned as-is.
  28175. @end defun
  28176. @defun to-radians a
  28177. Convert the number or HMS form @var{a} to radians from the current
  28178. angular mode.
  28179. @end defun
  28180. @defun from-radians a
  28181. Convert the number @var{a} from radians to the current angular mode.
  28182. If @var{a} is a formula, this returns the formula @samp{deg(@var{a})}.
  28183. @end defun
  28184. @defun to-radians-2 a
  28185. Like @code{to-radians}, except that in Symbolic Mode a degrees to
  28186. radians conversion yields a formula like @samp{@var{a}*pi/180}.
  28187. @end defun
  28188. @defun from-radians-2 a
  28189. Like @code{from-radians}, except that in Symbolic Mode a radians to
  28190. degrees conversion yields a formula like @samp{@var{a}*180/pi}.
  28191. @end defun
  28192. @defun random-digit
  28193. Produce a random base-1000 digit in the range 0 to 999.
  28194. @end defun
  28195. @defun random-digits n
  28196. Produce a random @var{n}-digit integer; this will be an integer
  28197. in the interval @samp{[0, 10^@var{n})}.
  28198. @end defun
  28199. @defun random-float
  28200. Produce a random float in the interval @samp{[0, 1)}.
  28201. @end defun
  28202. @defun prime-test n iters
  28203. Determine whether the integer @var{n} is prime. Return a list which has
  28204. one of these forms: @samp{(nil @var{f})} means the number is non-prime
  28205. because it was found to be divisible by @var{f}; @samp{(nil)} means it
  28206. was found to be non-prime by table look-up (so no factors are known);
  28207. @samp{(nil unknown)} means it is definitely non-prime but no factors
  28208. are known because @var{n} was large enough that Fermat's probabilistic
  28209. test had to be used; @samp{(t)} means the number is definitely prime;
  28210. and @samp{(maybe @var{i} @var{p})} means that Fermat's test, after @var{i}
  28211. iterations, is @var{p} percent sure that the number is prime. The
  28212. @var{iters} parameter is the number of Fermat iterations to use, in the
  28213. case that this is necessary. If @code{prime-test} returns ``maybe,''
  28214. you can call it again with the same @var{n} to get a greater certainty;
  28215. @code{prime-test} remembers where it left off.@refill
  28216. @end defun
  28217. @defun to-simple-fraction f
  28218. If @var{f} is a floating-point number which can be represented exactly
  28219. as a small rational number. return that number, else return @var{f}.
  28220. For example, 0.75 would be converted to 3:4. This function is very
  28221. fast.
  28222. @end defun
  28223. @defun to-fraction f tol
  28224. Find a rational approximation to floating-point number @var{f} to within
  28225. a specified tolerance @var{tol}; this corresponds to the algebraic
  28226. function @code{frac}, and can be rather slow.
  28227. @end defun
  28228. @defun quarter-integer n
  28229. If @var{n} is an integer or integer-valued float, this function
  28230. returns zero. If @var{n} is a half-integer (i.e., an integer plus
  28231. @i{1:2} or 0.5), it returns 2. If @var{n} is a quarter-integer,
  28232. it returns 1 or 3. If @var{n} is anything else, this function
  28233. returns @code{nil}.
  28234. @end defun
  28235. @node Vector Lisp Functions, Symbolic Lisp Functions, Computational Lisp Functions, Internals
  28236. @subsubsection Vector Functions
  28237. @noindent
  28238. The functions described here perform various operations on vectors and
  28239. matrices.
  28240. @defun math-concat x y
  28241. Do a vector concatenation; this operation is written @samp{@var{x} | @var{y}}
  28242. in a symbolic formula. @xref{Building Vectors}.
  28243. @end defun
  28244. @defun vec-length v
  28245. Return the length of vector @var{v}. If @var{v} is not a vector, the
  28246. result is zero. If @var{v} is a matrix, this returns the number of
  28247. rows in the matrix.
  28248. @end defun
  28249. @defun mat-dimens m
  28250. Determine the dimensions of vector or matrix @var{m}. If @var{m} is not
  28251. a vector, the result is an empty list. If @var{m} is a plain vector
  28252. but not a matrix, the result is a one-element list containing the length
  28253. of the vector. If @var{m} is a matrix with @var{r} rows and @var{c} columns,
  28254. the result is the list @samp{(@var{r} @var{c})}. Higher-order tensors
  28255. produce lists of more than two dimensions. Note that the object
  28256. @samp{[[1, 2, 3], [4, 5]]} is a vector of vectors not all the same size,
  28257. and is treated by this and other Calc routines as a plain vector of two
  28258. elements.@refill
  28259. @end defun
  28260. @defun dimension-error
  28261. Abort the current function with a message of ``Dimension error.''
  28262. The Calculator will leave the function being evaluated in symbolic
  28263. form; this is really just a special case of @code{reject-arg}.
  28264. @end defun
  28265. @defun build-vector args
  28266. Return a Calc vector with @var{args} as elements.
  28267. For example, @samp{(build-vector 1 2 3)} returns the Calc vector
  28268. @samp{[1, 2, 3]}, stored internally as the list @samp{(vec 1 2 3)}.
  28269. @end defun
  28270. @defun make-vec obj dims
  28271. Return a Calc vector or matrix all of whose elements are equal to
  28272. @var{obj}. For example, @samp{(make-vec 27 3 4)} returns a 3x4 matrix
  28273. filled with 27's.
  28274. @end defun
  28275. @defun row-matrix v
  28276. If @var{v} is a plain vector, convert it into a row matrix, i.e.,
  28277. a matrix whose single row is @var{v}. If @var{v} is already a matrix,
  28278. leave it alone.
  28279. @end defun
  28280. @defun col-matrix v
  28281. If @var{v} is a plain vector, convert it into a column matrix, i.e., a
  28282. matrix with each element of @var{v} as a separate row. If @var{v} is
  28283. already a matrix, leave it alone.
  28284. @end defun
  28285. @defun map-vec f v
  28286. Map the Lisp function @var{f} over the Calc vector @var{v}. For example,
  28287. @samp{(map-vec 'math-floor v)} returns a vector of the floored components
  28288. of vector @var{v}.
  28289. @end defun
  28290. @defun map-vec-2 f a b
  28291. Map the Lisp function @var{f} over the two vectors @var{a} and @var{b}.
  28292. If @var{a} and @var{b} are vectors of equal length, the result is a
  28293. vector of the results of calling @samp{(@var{f} @var{ai} @var{bi})}
  28294. for each pair of elements @var{ai} and @var{bi}. If either @var{a} or
  28295. @var{b} is a scalar, it is matched with each value of the other vector.
  28296. For example, @samp{(map-vec-2 'math-add v 1)} returns the vector @var{v}
  28297. with each element increased by one. Note that using @samp{'+} would not
  28298. work here, since @code{defmath} does not expand function names everywhere,
  28299. just where they are in the function position of a Lisp expression.@refill
  28300. @end defun
  28301. @defun reduce-vec f v
  28302. Reduce the function @var{f} over the vector @var{v}. For example, if
  28303. @var{v} is @samp{[10, 20, 30, 40]}, this calls @samp{(f (f (f 10 20) 30) 40)}.
  28304. If @var{v} is a matrix, this reduces over the rows of @var{v}.
  28305. @end defun
  28306. @defun reduce-cols f m
  28307. Reduce the function @var{f} over the columns of matrix @var{m}. For
  28308. example, if @var{m} is @samp{[[1, 2], [3, 4], [5, 6]]}, the result
  28309. is a vector of the two elements @samp{(f (f 1 3) 5)} and @samp{(f (f 2 4) 6)}.
  28310. @end defun
  28311. @defun mat-row m n
  28312. Return the @var{n}th row of matrix @var{m}. This is equivalent to
  28313. @samp{(elt m n)}. For a slower but safer version, use @code{mrow}.
  28314. (@xref{Extracting Elements}.)
  28315. @end defun
  28316. @defun mat-col m n
  28317. Return the @var{n}th column of matrix @var{m}, in the form of a vector.
  28318. The arguments are not checked for correctness.
  28319. @end defun
  28320. @defun mat-less-row m n
  28321. Return a copy of matrix @var{m} with its @var{n}th row deleted. The
  28322. number @var{n} must be in range from 1 to the number of rows in @var{m}.
  28323. @end defun
  28324. @defun mat-less-col m n
  28325. Return a copy of matrix @var{m} with its @var{n}th column deleted.
  28326. @end defun
  28327. @defun transpose m
  28328. Return the transpose of matrix @var{m}.
  28329. @end defun
  28330. @defun flatten-vector v
  28331. Flatten nested vector @var{v} into a vector of scalars. For example,
  28332. if @var{v} is @samp{[[1, 2, 3], [4, 5]]} the result is @samp{[1, 2, 3, 4, 5]}.
  28333. @end defun
  28334. @defun copy-matrix m
  28335. If @var{m} is a matrix, return a copy of @var{m}. This maps
  28336. @code{copy-sequence} over the rows of @var{m}; in Lisp terms, each
  28337. element of the result matrix will be @code{eq} to the corresponding
  28338. element of @var{m}, but none of the @code{cons} cells that make up
  28339. the structure of the matrix will be @code{eq}. If @var{m} is a plain
  28340. vector, this is the same as @code{copy-sequence}.@refill
  28341. @end defun
  28342. @defun swap-rows m r1 r2
  28343. Exchange rows @var{r1} and @var{r2} of matrix @var{m} in-place. In
  28344. other words, unlike most of the other functions described here, this
  28345. function changes @var{m} itself rather than building up a new result
  28346. matrix. The return value is @var{m}, i.e., @samp{(eq (swap-rows m 1 2) m)}
  28347. is true, with the side effect of exchanging the first two rows of
  28348. @var{m}.@refill
  28349. @end defun
  28350. @node Symbolic Lisp Functions, Formatting Lisp Functions, Vector Lisp Functions, Internals
  28351. @subsubsection Symbolic Functions
  28352. @noindent
  28353. The functions described here operate on symbolic formulas in the
  28354. Calculator.
  28355. @defun calc-prepare-selection num
  28356. Prepare a stack entry for selection operations. If @var{num} is
  28357. omitted, the stack entry containing the cursor is used; otherwise,
  28358. it is the number of the stack entry to use. This function stores
  28359. useful information about the current stack entry into a set of
  28360. variables. @code{calc-selection-cache-num} contains the number of
  28361. the stack entry involved (equal to @var{num} if you specified it);
  28362. @code{calc-selection-cache-entry} contains the stack entry as a
  28363. list (such as @code{calc-top-list} would return with @code{entry}
  28364. as the selection mode); and @code{calc-selection-cache-comp} contains
  28365. a special ``tagged'' composition (@pxref{Formatting Lisp Functions})
  28366. which allows Calc to relate cursor positions in the buffer with
  28367. their corresponding sub-formulas.
  28368. A slight complication arises in the selection mechanism because
  28369. formulas may contain small integers. For example, in the vector
  28370. @samp{[1, 2, 1]} the first and last elements are @code{eq} to each
  28371. other; selections are recorded as the actual Lisp object that
  28372. appears somewhere in the tree of the whole formula, but storing
  28373. @code{1} would falsely select both @code{1}'s in the vector. So
  28374. @code{calc-prepare-selection} also checks the stack entry and
  28375. replaces any plain integers with ``complex number'' lists of the form
  28376. @samp{(cplx @var{n} 0)}. This list will be displayed the same as a
  28377. plain @var{n} and the change will be completely invisible to the
  28378. user, but it will guarantee that no two sub-formulas of the stack
  28379. entry will be @code{eq} to each other. Next time the stack entry
  28380. is involved in a computation, @code{calc-normalize} will replace
  28381. these lists with plain numbers again, again invisibly to the user.
  28382. @end defun
  28383. @defun calc-encase-atoms x
  28384. This modifies the formula @var{x} to ensure that each part of the
  28385. formula is a unique atom, using the @samp{(cplx @var{n} 0)} trick
  28386. described above. This function may use @code{setcar} to modify
  28387. the formula in-place.
  28388. @end defun
  28389. @defun calc-find-selected-part
  28390. Find the smallest sub-formula of the current formula that contains
  28391. the cursor. This assumes @code{calc-prepare-selection} has been
  28392. called already. If the cursor is not actually on any part of the
  28393. formula, this returns @code{nil}.
  28394. @end defun
  28395. @defun calc-change-current-selection selection
  28396. Change the currently prepared stack element's selection to
  28397. @var{selection}, which should be @code{eq} to some sub-formula
  28398. of the stack element, or @code{nil} to unselect the formula.
  28399. The stack element's appearance in the Calc buffer is adjusted
  28400. to reflect the new selection.
  28401. @end defun
  28402. @defun calc-find-nth-part expr n
  28403. Return the @var{n}th sub-formula of @var{expr}. This function is used
  28404. by the selection commands, and (unless @kbd{j b} has been used) treats
  28405. sums and products as flat many-element formulas. Thus if @var{expr}
  28406. is @samp{((a + b) - c) + d}, calling @code{calc-find-nth-part} with
  28407. @var{n} equal to four will return @samp{d}.
  28408. @end defun
  28409. @defun calc-find-parent-formula expr part
  28410. Return the sub-formula of @var{expr} which immediately contains
  28411. @var{part}. If @var{expr} is @samp{a*b + (c+1)*d} and @var{part}
  28412. is @code{eq} to the @samp{c+1} term of @var{expr}, then this function
  28413. will return @samp{(c+1)*d}. If @var{part} turns out not to be a
  28414. sub-formula of @var{expr}, the function returns @code{nil}. If
  28415. @var{part} is @code{eq} to @var{expr}, the function returns @code{t}.
  28416. This function does not take associativity into account.
  28417. @end defun
  28418. @defun calc-find-assoc-parent-formula expr part
  28419. This is the same as @code{calc-find-parent-formula}, except that
  28420. (unless @kbd{j b} has been used) it continues widening the selection
  28421. to contain a complete level of the formula. Given @samp{a} from
  28422. @samp{((a + b) - c) + d}, @code{calc-find-parent-formula} will
  28423. return @samp{a + b} but @code{calc-find-assoc-parent-formula} will
  28424. return the whole expression.
  28425. @end defun
  28426. @defun calc-grow-assoc-formula expr part
  28427. This expands sub-formula @var{part} of @var{expr} to encompass a
  28428. complete level of the formula. If @var{part} and its immediate
  28429. parent are not compatible associative operators, or if @kbd{j b}
  28430. has been used, this simply returns @var{part}.
  28431. @end defun
  28432. @defun calc-find-sub-formula expr part
  28433. This finds the immediate sub-formula of @var{expr} which contains
  28434. @var{part}. It returns an index @var{n} such that
  28435. @samp{(calc-find-nth-part @var{expr} @var{n})} would return @var{part}.
  28436. If @var{part} is not a sub-formula of @var{expr}, it returns @code{nil}.
  28437. If @var{part} is @code{eq} to @var{expr}, it returns @code{t}. This
  28438. function does not take associativity into account.
  28439. @end defun
  28440. @defun calc-replace-sub-formula expr old new
  28441. This function returns a copy of formula @var{expr}, with the
  28442. sub-formula that is @code{eq} to @var{old} replaced by @var{new}.
  28443. @end defun
  28444. @defun simplify expr
  28445. Simplify the expression @var{expr} by applying various algebraic rules.
  28446. This is what the @w{@kbd{a s}} (@code{calc-simplify}) command uses. This
  28447. always returns a copy of the expression; the structure @var{expr} points
  28448. to remains unchanged in memory.
  28449. More precisely, here is what @code{simplify} does: The expression is
  28450. first normalized and evaluated by calling @code{normalize}. If any
  28451. @code{AlgSimpRules} have been defined, they are then applied. Then
  28452. the expression is traversed in a depth-first, bottom-up fashion; at
  28453. each level, any simplifications that can be made are made until no
  28454. further changes are possible. Once the entire formula has been
  28455. traversed in this way, it is compared with the original formula (from
  28456. before the call to @code{normalize}) and, if it has changed,
  28457. the entire procedure is repeated (starting with @code{normalize})
  28458. until no further changes occur. Usually only two iterations are
  28459. needed:@: one to simplify the formula, and another to verify that no
  28460. further simplifications were possible.
  28461. @end defun
  28462. @defun simplify-extended expr
  28463. Simplify the expression @var{expr}, with additional rules enabled that
  28464. help do a more thorough job, while not being entirely ``safe'' in all
  28465. circumstances. (For example, this mode will simplify @samp{sqrt(x^2)}
  28466. to @samp{x}, which is only valid when @var{x} is positive.) This is
  28467. implemented by temporarily binding the variable @code{math-living-dangerously}
  28468. to @code{t} (using a @code{let} form) and calling @code{simplify}.
  28469. Dangerous simplification rules are written to check this variable
  28470. before taking any action.@refill
  28471. @end defun
  28472. @defun simplify-units expr
  28473. Simplify the expression @var{expr}, treating variable names as units
  28474. whenever possible. This works by binding the variable
  28475. @code{math-simplifying-units} to @code{t} while calling @code{simplify}.
  28476. @end defun
  28477. @defmac math-defsimplify funcs body
  28478. Register a new simplification rule; this is normally called as a top-level
  28479. form, like @code{defun} or @code{defmath}. If @var{funcs} is a symbol
  28480. (like @code{+} or @code{calcFunc-sqrt}), this simplification rule is
  28481. applied to the formulas which are calls to the specified function. Or,
  28482. @var{funcs} can be a list of such symbols; the rule applies to all
  28483. functions on the list. The @var{body} is written like the body of a
  28484. function with a single argument called @code{expr}. The body will be
  28485. executed with @code{expr} bound to a formula which is a call to one of
  28486. the functions @var{funcs}. If the function body returns @code{nil}, or
  28487. if it returns a result @code{equal} to the original @code{expr}, it is
  28488. ignored and Calc goes on to try the next simplification rule that applies.
  28489. If the function body returns something different, that new formula is
  28490. substituted for @var{expr} in the original formula.@refill
  28491. At each point in the formula, rules are tried in the order of the
  28492. original calls to @code{math-defsimplify}; the search stops after the
  28493. first rule that makes a change. Thus later rules for that same
  28494. function will not have a chance to trigger until the next iteration
  28495. of the main @code{simplify} loop.
  28496. Note that, since @code{defmath} is not being used here, @var{body} must
  28497. be written in true Lisp code without the conveniences that @code{defmath}
  28498. provides. If you prefer, you can have @var{body} simply call another
  28499. function (defined with @code{defmath}) which does the real work.
  28500. The arguments of a function call will already have been simplified
  28501. before any rules for the call itself are invoked. Since a new argument
  28502. list is consed up when this happens, this means that the rule's body is
  28503. allowed to rearrange the function's arguments destructively if that is
  28504. convenient. Here is a typical example of a simplification rule:
  28505. @smallexample
  28506. (math-defsimplify calcFunc-arcsinh
  28507. (or (and (math-looks-negp (nth 1 expr))
  28508. (math-neg (list 'calcFunc-arcsinh
  28509. (math-neg (nth 1 expr)))))
  28510. (and (eq (car-safe (nth 1 expr)) 'calcFunc-sinh)
  28511. (or math-living-dangerously
  28512. (math-known-realp (nth 1 (nth 1 expr))))
  28513. (nth 1 (nth 1 expr)))))
  28514. @end smallexample
  28515. This is really a pair of rules written with one @code{math-defsimplify}
  28516. for convenience; the first replaces @samp{arcsinh(-x)} with
  28517. @samp{-arcsinh(x)}, and the second, which is safe only for real @samp{x},
  28518. replaces @samp{arcsinh(sinh(x))} with @samp{x}.@refill
  28519. @end defmac
  28520. @defun common-constant-factor expr
  28521. Check @var{expr} to see if it is a sum of terms all multiplied by the
  28522. same rational value. If so, return this value. If not, return @code{nil}.
  28523. For example, if called on @samp{6x + 9y + 12z}, it would return 3, since
  28524. 3 is a common factor of all the terms.
  28525. @end defun
  28526. @defun cancel-common-factor expr factor
  28527. Assuming @var{expr} is a sum with @var{factor} as a common factor,
  28528. divide each term of the sum by @var{factor}. This is done by
  28529. destructively modifying parts of @var{expr}, on the assumption that
  28530. it is being used by a simplification rule (where such things are
  28531. allowed; see above). For example, consider this built-in rule for
  28532. square roots:
  28533. @smallexample
  28534. (math-defsimplify calcFunc-sqrt
  28535. (let ((fac (math-common-constant-factor (nth 1 expr))))
  28536. (and fac (not (eq fac 1))
  28537. (math-mul (math-normalize (list 'calcFunc-sqrt fac))
  28538. (math-normalize
  28539. (list 'calcFunc-sqrt
  28540. (math-cancel-common-factor
  28541. (nth 1 expr) fac)))))))
  28542. @end smallexample
  28543. @end defun
  28544. @defun frac-gcd a b
  28545. Compute a ``rational GCD'' of @var{a} and @var{b}, which must both be
  28546. rational numbers. This is the fraction composed of the GCD of the
  28547. numerators of @var{a} and @var{b}, over the GCD of the denominators.
  28548. It is used by @code{common-constant-factor}. Note that the standard
  28549. @code{gcd} function uses the LCM to combine the denominators.@refill
  28550. @end defun
  28551. @defun map-tree func expr many
  28552. Try applying Lisp function @var{func} to various sub-expressions of
  28553. @var{expr}. Initially, call @var{func} with @var{expr} itself as an
  28554. argument. If this returns an expression which is not @code{equal} to
  28555. @var{expr}, apply @var{func} again until eventually it does return
  28556. @var{expr} with no changes. Then, if @var{expr} is a function call,
  28557. recursively apply @var{func} to each of the arguments. This keeps going
  28558. until no changes occur anywhere in the expression; this final expression
  28559. is returned by @code{map-tree}. Note that, unlike simplification rules,
  28560. @var{func} functions may @emph{not} make destructive changes to
  28561. @var{expr}. If a third argument @var{many} is provided, it is an
  28562. integer which says how many times @var{func} may be applied; the
  28563. default, as described above, is infinitely many times.@refill
  28564. @end defun
  28565. @defun compile-rewrites rules
  28566. Compile the rewrite rule set specified by @var{rules}, which should
  28567. be a formula that is either a vector or a variable name. If the latter,
  28568. the compiled rules are saved so that later @code{compile-rules} calls
  28569. for that same variable can return immediately. If there are problems
  28570. with the rules, this function calls @code{error} with a suitable
  28571. message.
  28572. @end defun
  28573. @defun apply-rewrites expr crules heads
  28574. Apply the compiled rewrite rule set @var{crules} to the expression
  28575. @var{expr}. This will make only one rewrite and only checks at the
  28576. top level of the expression. The result @code{nil} if no rules
  28577. matched, or if the only rules that matched did not actually change
  28578. the expression. The @var{heads} argument is optional; if is given,
  28579. it should be a list of all function names that (may) appear in
  28580. @var{expr}. The rewrite compiler tags each rule with the
  28581. rarest-looking function name in the rule; if you specify @var{heads},
  28582. @code{apply-rewrites} can use this information to narrow its search
  28583. down to just a few rules in the rule set.
  28584. @end defun
  28585. @defun rewrite-heads expr
  28586. Compute a @var{heads} list for @var{expr} suitable for use with
  28587. @code{apply-rewrites}, as discussed above.
  28588. @end defun
  28589. @defun rewrite expr rules many
  28590. This is an all-in-one rewrite function. It compiles the rule set
  28591. specified by @var{rules}, then uses @code{map-tree} to apply the
  28592. rules throughout @var{expr} up to @var{many} (default infinity)
  28593. times.
  28594. @end defun
  28595. @defun match-patterns pat vec not-flag
  28596. Given a Calc vector @var{vec} and an uncompiled pattern set or
  28597. pattern set variable @var{pat}, this function returns a new vector
  28598. of all elements of @var{vec} which do (or don't, if @var{not-flag} is
  28599. non-@code{nil}) match any of the patterns in @var{pat}.
  28600. @end defun
  28601. @defun deriv expr var value symb
  28602. Compute the derivative of @var{expr} with respect to variable @var{var}
  28603. (which may actually be any sub-expression). If @var{value} is specified,
  28604. the derivative is evaluated at the value of @var{var}; otherwise, the
  28605. derivative is left in terms of @var{var}. If the expression contains
  28606. functions for which no derivative formula is known, new derivative
  28607. functions are invented by adding primes to the names; @pxref{Calculus}.
  28608. However, if @var{symb} is non-@code{nil}, the presence of undifferentiable
  28609. functions in @var{expr} instead cancels the whole differentiation, and
  28610. @code{deriv} returns @code{nil} instead.
  28611. Derivatives of an @var{n}-argument function can be defined by
  28612. adding a @code{math-derivative-@var{n}} property to the property list
  28613. of the symbol for the function's derivative, which will be the
  28614. function name followed by an apostrophe. The value of the property
  28615. should be a Lisp function; it is called with the same arguments as the
  28616. original function call that is being differentiated. It should return
  28617. a formula for the derivative. For example, the derivative of @code{ln}
  28618. is defined by
  28619. @smallexample
  28620. (put 'calcFunc-ln\' 'math-derivative-1
  28621. (function (lambda (u) (math-div 1 u))))
  28622. @end smallexample
  28623. The two-argument @code{log} function has two derivatives,
  28624. @smallexample
  28625. (put 'calcFunc-log\' 'math-derivative-2 ; d(log(x,b)) / dx
  28626. (function (lambda (x b) ... )))
  28627. (put 'calcFunc-log\'2 'math-derivative-2 ; d(log(x,b)) / db
  28628. (function (lambda (x b) ... )))
  28629. @end smallexample
  28630. @end defun
  28631. @defun tderiv expr var value symb
  28632. Compute the total derivative of @var{expr}. This is the same as
  28633. @code{deriv}, except that variables other than @var{var} are not
  28634. assumed to be constant with respect to @var{var}.
  28635. @end defun
  28636. @defun integ expr var low high
  28637. Compute the integral of @var{expr} with respect to @var{var}.
  28638. @xref{Calculus}, for further details.
  28639. @end defun
  28640. @defmac math-defintegral funcs body
  28641. Define a rule for integrating a function or functions of one argument;
  28642. this macro is very similar in format to @code{math-defsimplify}.
  28643. The main difference is that here @var{body} is the body of a function
  28644. with a single argument @code{u} which is bound to the argument to the
  28645. function being integrated, not the function call itself. Also, the
  28646. variable of integration is available as @code{math-integ-var}. If
  28647. evaluation of the integral requires doing further integrals, the body
  28648. should call @samp{(math-integral @var{x})} to find the integral of
  28649. @var{x} with respect to @code{math-integ-var}; this function returns
  28650. @code{nil} if the integral could not be done. Some examples:
  28651. @smallexample
  28652. (math-defintegral calcFunc-conj
  28653. (let ((int (math-integral u)))
  28654. (and int
  28655. (list 'calcFunc-conj int))))
  28656. (math-defintegral calcFunc-cos
  28657. (and (equal u math-integ-var)
  28658. (math-from-radians-2 (list 'calcFunc-sin u))))
  28659. @end smallexample
  28660. In the @code{cos} example, we define only the integral of @samp{cos(x) dx},
  28661. relying on the general integration-by-substitution facility to handle
  28662. cosines of more complicated arguments. An integration rule should return
  28663. @code{nil} if it can't do the integral; if several rules are defined for
  28664. the same function, they are tried in order until one returns a non-@code{nil}
  28665. result.@refill
  28666. @end defmac
  28667. @defmac math-defintegral-2 funcs body
  28668. Define a rule for integrating a function or functions of two arguments.
  28669. This is exactly analogous to @code{math-defintegral}, except that @var{body}
  28670. is written as the body of a function with two arguments, @var{u} and
  28671. @var{v}.@refill
  28672. @end defmac
  28673. @defun solve-for lhs rhs var full
  28674. Attempt to solve the equation @samp{@var{lhs} = @var{rhs}} by isolating
  28675. the variable @var{var} on the lefthand side; return the resulting righthand
  28676. side, or @code{nil} if the equation cannot be solved. The variable
  28677. @var{var} must appear at least once in @var{lhs} or @var{rhs}. Note that
  28678. the return value is a formula which does not contain @var{var}; this is
  28679. different from the user-level @code{solve} and @code{finv} functions,
  28680. which return a rearranged equation or a functional inverse, respectively.
  28681. If @var{full} is non-@code{nil}, a full solution including dummy signs
  28682. and dummy integers will be produced. User-defined inverses are provided
  28683. as properties in a manner similar to derivatives:@refill
  28684. @smallexample
  28685. (put 'calcFunc-ln 'math-inverse
  28686. (function (lambda (x) (list 'calcFunc-exp x))))
  28687. @end smallexample
  28688. This function can call @samp{(math-solve-get-sign @var{x})} to create
  28689. a new arbitrary sign variable, returning @var{x} times that sign, and
  28690. @samp{(math-solve-get-int @var{x})} to create a new arbitrary integer
  28691. variable multiplied by @var{x}. These functions simply return @var{x}
  28692. if the caller requested a non-``full'' solution.
  28693. @end defun
  28694. @defun solve-eqn expr var full
  28695. This version of @code{solve-for} takes an expression which will
  28696. typically be an equation or inequality. (If it is not, it will be
  28697. interpreted as the equation @samp{@var{expr} = 0}.) It returns an
  28698. equation or inequality, or @code{nil} if no solution could be found.
  28699. @end defun
  28700. @defun solve-system exprs vars full
  28701. This function solves a system of equations. Generally, @var{exprs}
  28702. and @var{vars} will be vectors of equal length.
  28703. @xref{Solving Systems of Equations}, for other options.
  28704. @end defun
  28705. @defun expr-contains expr var
  28706. Returns a non-@code{nil} value if @var{var} occurs as a subexpression
  28707. of @var{expr}.
  28708. This function might seem at first to be identical to
  28709. @code{calc-find-sub-formula}. The key difference is that
  28710. @code{expr-contains} uses @code{equal} to test for matches, whereas
  28711. @code{calc-find-sub-formula} uses @code{eq}. In the formula
  28712. @samp{f(a, a)}, the two @samp{a}s will be @code{equal} but not
  28713. @code{eq} to each other.@refill
  28714. @end defun
  28715. @defun expr-contains-count expr var
  28716. Returns the number of occurrences of @var{var} as a subexpression
  28717. of @var{expr}, or @code{nil} if there are no occurrences.@refill
  28718. @end defun
  28719. @defun expr-depends expr var
  28720. Returns true if @var{expr} refers to any variable the occurs in @var{var}.
  28721. In other words, it checks if @var{expr} and @var{var} have any variables
  28722. in common.
  28723. @end defun
  28724. @defun expr-contains-vars expr
  28725. Return true if @var{expr} contains any variables, or @code{nil} if @var{expr}
  28726. contains only constants and functions with constant arguments.
  28727. @end defun
  28728. @defun expr-subst expr old new
  28729. Returns a copy of @var{expr}, with all occurrences of @var{old} replaced
  28730. by @var{new}. This treats @code{lambda} forms specially with respect
  28731. to the dummy argument variables, so that the effect is always to return
  28732. @var{expr} evaluated at @var{old} = @var{new}.@refill
  28733. @end defun
  28734. @defun multi-subst expr old new
  28735. This is like @code{expr-subst}, except that @var{old} and @var{new}
  28736. are lists of expressions to be substituted simultaneously. If one
  28737. list is shorter than the other, trailing elements of the longer list
  28738. are ignored.
  28739. @end defun
  28740. @defun expr-weight expr
  28741. Returns the ``weight'' of @var{expr}, basically a count of the total
  28742. number of objects and function calls that appear in @var{expr}. For
  28743. ``primitive'' objects, this will be one.
  28744. @end defun
  28745. @defun expr-height expr
  28746. Returns the ``height'' of @var{expr}, which is the deepest level to
  28747. which function calls are nested. (Note that @samp{@var{a} + @var{b}}
  28748. counts as a function call.) For primitive objects, this returns zero.@refill
  28749. @end defun
  28750. @defun polynomial-p expr var
  28751. Check if @var{expr} is a polynomial in variable (or sub-expression)
  28752. @var{var}. If so, return the degree of the polynomial, that is, the
  28753. highest power of @var{var} that appears in @var{expr}. For example,
  28754. for @samp{(x^2 + 3)^3 + 4} this would return 6. This function returns
  28755. @code{nil} unless @var{expr}, when expanded out by @kbd{a x}
  28756. (@code{calc-expand}), would consist of a sum of terms in which @var{var}
  28757. appears only raised to nonnegative integer powers. Note that if
  28758. @var{var} does not occur in @var{expr}, then @var{expr} is considered
  28759. a polynomial of degree 0.@refill
  28760. @end defun
  28761. @defun is-polynomial expr var degree loose
  28762. Check if @var{expr} is a polynomial in variable or sub-expression
  28763. @var{var}, and, if so, return a list representation of the polynomial
  28764. where the elements of the list are coefficients of successive powers of
  28765. @var{var}: @samp{@var{a} + @var{b} x + @var{c} x^3} would produce the
  28766. list @samp{(@var{a} @var{b} 0 @var{c})}, and @samp{(x + 1)^2} would
  28767. produce the list @samp{(1 2 1)}. The highest element of the list will
  28768. be non-zero, with the special exception that if @var{expr} is the
  28769. constant zero, the returned value will be @samp{(0)}. Return @code{nil}
  28770. if @var{expr} is not a polynomial in @var{var}. If @var{degree} is
  28771. specified, this will not consider polynomials of degree higher than that
  28772. value. This is a good precaution because otherwise an input of
  28773. @samp{(x+1)^1000} will cause a huge coefficient list to be built. If
  28774. @var{loose} is non-@code{nil}, then a looser definition of a polynomial
  28775. is used in which coefficients are no longer required not to depend on
  28776. @var{var}, but are only required not to take the form of polynomials
  28777. themselves. For example, @samp{sin(x) x^2 + cos(x)} is a loose
  28778. polynomial with coefficients @samp{((calcFunc-cos x) 0 (calcFunc-sin
  28779. x))}. The result will never be @code{nil} in loose mode, since any
  28780. expression can be interpreted as a ``constant'' loose polynomial.@refill
  28781. @end defun
  28782. @defun polynomial-base expr pred
  28783. Check if @var{expr} is a polynomial in any variable that occurs in it;
  28784. if so, return that variable. (If @var{expr} is a multivariate polynomial,
  28785. this chooses one variable arbitrarily.) If @var{pred} is specified, it should
  28786. be a Lisp function which is called as @samp{(@var{pred} @var{subexpr})},
  28787. and which should return true if @code{mpb-top-expr} (a global name for
  28788. the original @var{expr}) is a suitable polynomial in @var{subexpr}.
  28789. The default predicate uses @samp{(polynomial-p mpb-top-expr @var{subexpr})};
  28790. you can use @var{pred} to specify additional conditions. Or, you could
  28791. have @var{pred} build up a list of every suitable @var{subexpr} that
  28792. is found.@refill
  28793. @end defun
  28794. @defun poly-simplify poly
  28795. Simplify polynomial coefficient list @var{poly} by (destructively)
  28796. clipping off trailing zeros.
  28797. @end defun
  28798. @defun poly-mix a ac b bc
  28799. Mix two polynomial lists @var{a} and @var{b} (in the form returned by
  28800. @code{is-polynomial}) in a linear combination with coefficient expressions
  28801. @var{ac} and @var{bc}. The result is a (not necessarily simplified)
  28802. polynomial list representing @samp{@var{ac} @var{a} + @var{bc} @var{b}}.@refill
  28803. @end defun
  28804. @defun poly-mul a b
  28805. Multiply two polynomial coefficient lists @var{a} and @var{b}. The
  28806. result will be in simplified form if the inputs were simplified.
  28807. @end defun
  28808. @defun build-polynomial-expr poly var
  28809. Construct a Calc formula which represents the polynomial coefficient
  28810. list @var{poly} applied to variable @var{var}. The @kbd{a c}
  28811. (@code{calc-collect}) command uses @code{is-polynomial} to turn an
  28812. expression into a coefficient list, then @code{build-polynomial-expr}
  28813. to turn the list back into an expression in regular form.@refill
  28814. @end defun
  28815. @defun check-unit-name var
  28816. Check if @var{var} is a variable which can be interpreted as a unit
  28817. name. If so, return the units table entry for that unit. This
  28818. will be a list whose first element is the unit name (not counting
  28819. prefix characters) as a symbol and whose second element is the
  28820. Calc expression which defines the unit. (Refer to the Calc sources
  28821. for details on the remaining elements of this list.) If @var{var}
  28822. is not a variable or is not a unit name, return @code{nil}.
  28823. @end defun
  28824. @defun units-in-expr-p expr sub-exprs
  28825. Return true if @var{expr} contains any variables which can be
  28826. interpreted as units. If @var{sub-exprs} is @code{t}, the entire
  28827. expression is searched. If @var{sub-exprs} is @code{nil}, this
  28828. checks whether @var{expr} is directly a units expression.@refill
  28829. @end defun
  28830. @defun single-units-in-expr-p expr
  28831. Check whether @var{expr} contains exactly one units variable. If so,
  28832. return the units table entry for the variable. If @var{expr} does
  28833. not contain any units, return @code{nil}. If @var{expr} contains
  28834. two or more units, return the symbol @code{wrong}.
  28835. @end defun
  28836. @defun to-standard-units expr which
  28837. Convert units expression @var{expr} to base units. If @var{which}
  28838. is @code{nil}, use Calc's native base units. Otherwise, @var{which}
  28839. can specify a units system, which is a list of two-element lists,
  28840. where the first element is a Calc base symbol name and the second
  28841. is an expression to substitute for it.@refill
  28842. @end defun
  28843. @defun remove-units expr
  28844. Return a copy of @var{expr} with all units variables replaced by ones.
  28845. This expression is generally normalized before use.
  28846. @end defun
  28847. @defun extract-units expr
  28848. Return a copy of @var{expr} with everything but units variables replaced
  28849. by ones.
  28850. @end defun
  28851. @node Formatting Lisp Functions, Hooks, Symbolic Lisp Functions, Internals
  28852. @subsubsection I/O and Formatting Functions
  28853. @noindent
  28854. The functions described here are responsible for parsing and formatting
  28855. Calc numbers and formulas.
  28856. @defun calc-eval str sep arg1 arg2 @dots{}
  28857. This is the simplest interface to the Calculator from another Lisp program.
  28858. @xref{Calling Calc from Your Programs}.
  28859. @end defun
  28860. @defun read-number str
  28861. If string @var{str} contains a valid Calc number, either integer,
  28862. fraction, float, or HMS form, this function parses and returns that
  28863. number. Otherwise, it returns @code{nil}.
  28864. @end defun
  28865. @defun read-expr str
  28866. Read an algebraic expression from string @var{str}. If @var{str} does
  28867. not have the form of a valid expression, return a list of the form
  28868. @samp{(error @var{pos} @var{msg})} where @var{pos} is an integer index
  28869. into @var{str} of the general location of the error, and @var{msg} is
  28870. a string describing the problem.@refill
  28871. @end defun
  28872. @defun read-exprs str
  28873. Read a list of expressions separated by commas, and return it as a
  28874. Lisp list. If an error occurs in any expressions, an error list as
  28875. shown above is returned instead.
  28876. @end defun
  28877. @defun calc-do-alg-entry initial prompt no-norm
  28878. Read an algebraic formula or formulas using the minibuffer. All
  28879. conventions of regular algebraic entry are observed. The return value
  28880. is a list of Calc formulas; there will be more than one if the user
  28881. entered a list of values separated by commas. The result is @code{nil}
  28882. if the user presses Return with a blank line. If @var{initial} is
  28883. given, it is a string which the minibuffer will initially contain.
  28884. If @var{prompt} is given, it is the prompt string to use; the default
  28885. is ``Algebraic:''. If @var{no-norm} is @code{t}, the formulas will
  28886. be returned exactly as parsed; otherwise, they will be passed through
  28887. @code{calc-normalize} first.@refill
  28888. To support the use of @kbd{$} characters in the algebraic entry, use
  28889. @code{let} to bind @code{calc-dollar-values} to a list of the values
  28890. to be substituted for @kbd{$}, @kbd{$$}, and so on, and bind
  28891. @code{calc-dollar-used} to 0. Upon return, @code{calc-dollar-used}
  28892. will have been changed to the highest number of consecutive @kbd{$}s
  28893. that actually appeared in the input.@refill
  28894. @end defun
  28895. @defun format-number a
  28896. Convert the real or complex number or HMS form @var{a} to string form.
  28897. @end defun
  28898. @defun format-flat-expr a prec
  28899. Convert the arbitrary Calc number or formula @var{a} to string form,
  28900. in the style used by the trail buffer and the @code{calc-edit} command.
  28901. This is a simple format designed
  28902. mostly to guarantee the string is of a form that can be re-parsed by
  28903. @code{read-expr}. Most formatting modes, such as digit grouping,
  28904. complex number format, and point character, are ignored to ensure the
  28905. result will be re-readable. The @var{prec} parameter is normally 0; if
  28906. you pass a large integer like 1000 instead, the expression will be
  28907. surrounded by parentheses unless it is a plain number or variable name.@refill
  28908. @end defun
  28909. @defun format-nice-expr a width
  28910. This is like @code{format-flat-expr} (with @var{prec} equal to 0),
  28911. except that newlines will be inserted to keep lines down to the
  28912. specified @var{width}, and vectors that look like matrices or rewrite
  28913. rules are written in a pseudo-matrix format. The @code{calc-edit}
  28914. command uses this when only one stack entry is being edited.
  28915. @end defun
  28916. @defun format-value a width
  28917. Convert the Calc number or formula @var{a} to string form, using the
  28918. format seen in the stack buffer. Beware the string returned may
  28919. not be re-readable by @code{read-expr}, for example, because of digit
  28920. grouping. Multi-line objects like matrices produce strings that
  28921. contain newline characters to separate the lines. The @var{w}
  28922. parameter, if given, is the target window size for which to format
  28923. the expressions. If @var{w} is omitted, the width of the Calculator
  28924. window is used.@refill
  28925. @end defun
  28926. @defun compose-expr a prec
  28927. Format the Calc number or formula @var{a} according to the current
  28928. language mode, returning a ``composition.'' To learn about the
  28929. structure of compositions, see the comments in the Calc source code.
  28930. You can specify the format of a given type of function call by putting
  28931. a @code{math-compose-@var{lang}} property on the function's symbol,
  28932. whose value is a Lisp function that takes @var{a} and @var{prec} as
  28933. arguments and returns a composition. Here @var{lang} is a language
  28934. mode name, one of @code{normal}, @code{big}, @code{c}, @code{pascal},
  28935. @code{fortran}, @code{tex}, @code{eqn}, @code{math}, or @code{maple}.
  28936. In Big mode, Calc actually tries @code{math-compose-big} first, then
  28937. tries @code{math-compose-normal}. If this property does not exist,
  28938. or if the function returns @code{nil}, the function is written in the
  28939. normal function-call notation for that language.
  28940. @end defun
  28941. @defun composition-to-string c w
  28942. Convert a composition structure returned by @code{compose-expr} into
  28943. a string. Multi-line compositions convert to strings containing
  28944. newline characters. The target window size is given by @var{w}.
  28945. The @code{format-value} function basically calls @code{compose-expr}
  28946. followed by @code{composition-to-string}.
  28947. @end defun
  28948. @defun comp-width c
  28949. Compute the width in characters of composition @var{c}.
  28950. @end defun
  28951. @defun comp-height c
  28952. Compute the height in lines of composition @var{c}.
  28953. @end defun
  28954. @defun comp-ascent c
  28955. Compute the portion of the height of composition @var{c} which is on or
  28956. above the baseline. For a one-line composition, this will be one.
  28957. @end defun
  28958. @defun comp-descent c
  28959. Compute the portion of the height of composition @var{c} which is below
  28960. the baseline. For a one-line composition, this will be zero.
  28961. @end defun
  28962. @defun comp-first-char c
  28963. If composition @var{c} is a ``flat'' composition, return the first
  28964. (leftmost) character of the composition as an integer. Otherwise,
  28965. return @code{nil}.@refill
  28966. @end defun
  28967. @defun comp-last-char c
  28968. If composition @var{c} is a ``flat'' composition, return the last
  28969. (rightmost) character, otherwise return @code{nil}.
  28970. @end defun
  28971. @comment @node Lisp Variables, Hooks, Formatting Lisp Functions, Internals
  28972. @comment @subsubsection Lisp Variables
  28973. @comment
  28974. @comment @noindent
  28975. @comment (This section is currently unfinished.)
  28976. @node Hooks, , Formatting Lisp Functions, Internals
  28977. @subsubsection Hooks
  28978. @noindent
  28979. Hooks are variables which contain Lisp functions (or lists of functions)
  28980. which are called at various times. Calc defines a number of hooks
  28981. that help you to customize it in various ways. Calc uses the Lisp
  28982. function @code{run-hooks} to invoke the hooks shown below. Several
  28983. other customization-related variables are also described here.
  28984. @defvar calc-load-hook
  28985. This hook is called at the end of @file{calc.el}, after the file has
  28986. been loaded, before any functions in it have been called, but after
  28987. @code{calc-mode-map} and similar variables have been set up.
  28988. @end defvar
  28989. @defvar calc-ext-load-hook
  28990. This hook is called at the end of @file{calc-ext.el}.
  28991. @end defvar
  28992. @defvar calc-start-hook
  28993. This hook is called as the last step in a @kbd{M-x calc} command.
  28994. At this point, the Calc buffer has been created and initialized if
  28995. necessary, the Calc window and trail window have been created,
  28996. and the ``Welcome to Calc'' message has been displayed.
  28997. @end defvar
  28998. @defvar calc-mode-hook
  28999. This hook is called when the Calc buffer is being created. Usually
  29000. this will only happen once per Emacs session. The hook is called
  29001. after Emacs has switched to the new buffer, the mode-settings file
  29002. has been read if necessary, and all other buffer-local variables
  29003. have been set up. After this hook returns, Calc will perform a
  29004. @code{calc-refresh} operation, set up the mode line display, then
  29005. evaluate any deferred @code{calc-define} properties that have not
  29006. been evaluated yet.
  29007. @end defvar
  29008. @defvar calc-trail-mode-hook
  29009. This hook is called when the Calc Trail buffer is being created.
  29010. It is called as the very last step of setting up the Trail buffer.
  29011. Like @code{calc-mode-hook}, this will normally happen only once
  29012. per Emacs session.
  29013. @end defvar
  29014. @defvar calc-end-hook
  29015. This hook is called by @code{calc-quit}, generally because the user
  29016. presses @kbd{q} or @kbd{M-# c} while in Calc. The Calc buffer will
  29017. be the current buffer. The hook is called as the very first
  29018. step, before the Calc window is destroyed.
  29019. @end defvar
  29020. @defvar calc-window-hook
  29021. If this hook exists, it is called to create the Calc window.
  29022. Upon return, this new Calc window should be the current window.
  29023. (The Calc buffer will already be the current buffer when the
  29024. hook is called.) If the hook is not defined, Calc will
  29025. generally use @code{split-window}, @code{set-window-buffer},
  29026. and @code{select-window} to create the Calc window.
  29027. @end defvar
  29028. @defvar calc-trail-window-hook
  29029. If this hook exists, it is called to create the Calc Trail window.
  29030. The variable @code{calc-trail-buffer} will contain the buffer
  29031. which the window should use. Unlike @code{calc-window-hook},
  29032. this hook must @emph{not} switch into the new window.
  29033. @end defvar
  29034. @defvar calc-edit-mode-hook
  29035. This hook is called by @code{calc-edit} (and the other ``edit''
  29036. commands) when the temporary editing buffer is being created.
  29037. The buffer will have been selected and set up to be in
  29038. @code{calc-edit-mode}, but will not yet have been filled with
  29039. text. (In fact it may still have leftover text from a previous
  29040. @code{calc-edit} command.)
  29041. @end defvar
  29042. @defvar calc-mode-save-hook
  29043. This hook is called by the @code{calc-save-modes} command,
  29044. after Calc's own mode features have been inserted into the
  29045. @file{.emacs} buffer and just before the ``End of mode settings''
  29046. message is inserted.
  29047. @end defvar
  29048. @defvar calc-reset-hook
  29049. This hook is called after @kbd{M-# 0} (@code{calc-reset}) has
  29050. reset all modes. The Calc buffer will be the current buffer.
  29051. @end defvar
  29052. @defvar calc-other-modes
  29053. This variable contains a list of strings. The strings are
  29054. concatenated at the end of the modes portion of the Calc
  29055. mode line (after standard modes such as ``Deg'', ``Inv'' and
  29056. ``Hyp''). Each string should be a short, single word followed
  29057. by a space. The variable is @code{nil} by default.
  29058. @end defvar
  29059. @defvar calc-mode-map
  29060. This is the keymap that is used by Calc mode. The best time
  29061. to adjust it is probably in a @code{calc-mode-hook}. If the
  29062. Calc extensions package (@file{calc-ext.el}) has not yet been
  29063. loaded, many of these keys will be bound to @code{calc-missing-key},
  29064. which is a command that loads the extensions package and
  29065. ``retypes'' the key. If your @code{calc-mode-hook} rebinds
  29066. one of these keys, it will probably be overridden when the
  29067. extensions are loaded.
  29068. @end defvar
  29069. @defvar calc-digit-map
  29070. This is the keymap that is used during numeric entry. Numeric
  29071. entry uses the minibuffer, but this map binds every non-numeric
  29072. key to @code{calcDigit-nondigit} which generally calls
  29073. @code{exit-minibuffer} and ``retypes'' the key.
  29074. @end defvar
  29075. @defvar calc-alg-ent-map
  29076. This is the keymap that is used during algebraic entry. This is
  29077. mostly a copy of @code{minibuffer-local-map}.
  29078. @end defvar
  29079. @defvar calc-store-var-map
  29080. This is the keymap that is used during entry of variable names for
  29081. commands like @code{calc-store} and @code{calc-recall}. This is
  29082. mostly a copy of @code{minibuffer-local-completion-map}.
  29083. @end defvar
  29084. @defvar calc-edit-mode-map
  29085. This is the (sparse) keymap used by @code{calc-edit} and other
  29086. temporary editing commands. It binds @key{RET}, @key{LFD},
  29087. and @kbd{C-c C-c} to @code{calc-edit-finish}.
  29088. @end defvar
  29089. @defvar calc-mode-var-list
  29090. This is a list of variables which are saved by @code{calc-save-modes}.
  29091. Each entry is a list of two items, the variable (as a Lisp symbol)
  29092. and its default value. When modes are being saved, each variable
  29093. is compared with its default value (using @code{equal}) and any
  29094. non-default variables are written out.
  29095. @end defvar
  29096. @defvar calc-local-var-list
  29097. This is a list of variables which should be buffer-local to the
  29098. Calc buffer. Each entry is a variable name (as a Lisp symbol).
  29099. These variables also have their default values manipulated by
  29100. the @code{calc} and @code{calc-quit} commands; @pxref{Multiple Calculators}.
  29101. Since @code{calc-mode-hook} is called after this list has been
  29102. used the first time, your hook should add a variable to the
  29103. list and also call @code{make-local-variable} itself.
  29104. @end defvar
  29105. @node Installation, Reporting Bugs, Programming, Top
  29106. @appendix Installation
  29107. @noindent
  29108. As of Calc 2.02g, Calc is integrated with GNU Emacs, and thus requires
  29109. no separate installation of its Lisp files and this manual.
  29110. @appendixsec The GNUPLOT Program
  29111. @noindent
  29112. Calc's graphing commands use the GNUPLOT program. If you have GNUPLOT
  29113. but you must type some command other than @file{gnuplot} to get it,
  29114. you should add a command to set the Lisp variable @code{calc-gnuplot-name}
  29115. to the appropriate file name. You may also need to change the variables
  29116. @code{calc-gnuplot-plot-command} and @code{calc-gnuplot-print-command} in
  29117. order to get correct displays and hardcopies, respectively, of your
  29118. plots.@refill
  29119. @ifinfo
  29120. @example
  29121. @end example
  29122. @end ifinfo
  29123. @appendixsec Printed Documentation
  29124. @noindent
  29125. Because the Calc manual is so large, you should only make a printed
  29126. copy if you really need it. To print the manual, you will need the
  29127. @TeX{} typesetting program (this is a free program by Donald Knuth
  29128. at Stanford University) as well as the @file{texindex} program and
  29129. @file{texinfo.tex} file, both of which can be obtained from the FSF
  29130. as part of the @code{texinfo} package.@refill
  29131. To print the Calc manual in one huge 470 page tome, you will need the
  29132. source code to this manual, @file{calc.texi}, available as part of the
  29133. Emacs source. Once you have this file, type @kbd{texi2dvi calc.texi}.
  29134. Alternatively, change to the @file{man} subdirectory of the Emacs
  29135. source distribution, and type @kbd{make calc.dvi}. (Don't worry if you
  29136. get some ``overfull box'' warnings while @TeX{} runs.)
  29137. The result will be a device-independent output file called
  29138. @file{calc.dvi}, which you must print in whatever way is right
  29139. for your system. On many systems, the command is
  29140. @example
  29141. lpr -d calc.dvi
  29142. @end example
  29143. @noindent
  29144. or
  29145. @example
  29146. dvips calc.dvi
  29147. @end example
  29148. @c the bumpoddpages macro was deleted
  29149. @ignore
  29150. @cindex Marginal notes, adjusting
  29151. Marginal notes for each function and key sequence normally alternate
  29152. between the left and right sides of the page, which is correct if the
  29153. manual is going to be bound as double-sided pages. Near the top of
  29154. the file @file{calc.texi} you will find alternate definitions of
  29155. the @code{\bumpoddpages} macro that put the marginal notes always on
  29156. the same side, best if you plan to be binding single-sided pages.
  29157. @end ignore
  29158. @appendixsec Settings File
  29159. @noindent
  29160. @vindex calc-settings-file
  29161. Another variable you might want to set is @code{calc-settings-file},
  29162. which holds the file name in which commands like @kbd{m m} and @kbd{Z P}
  29163. store ``permanent'' definitions. The default value for this variable
  29164. is @code{"~/.emacs"}. If @code{calc-settings-file} does not contain
  29165. @code{".emacs"} as a substring, and if the variable
  29166. @code{calc-loaded-settings-file} is @code{nil}, then Calc will
  29167. automatically load your settings file (if it exists) the first time
  29168. Calc is invoked.@refill
  29169. @ifinfo
  29170. @example
  29171. @end example
  29172. @end ifinfo
  29173. @appendixsec Testing the Installation
  29174. @noindent
  29175. To test your installation of Calc, start a new Emacs and type @kbd{M-# c}
  29176. to make sure the autoloads and key bindings work. Type @kbd{M-# i}
  29177. to make sure Calc can find its Info documentation. Press @kbd{q} to
  29178. exit the Info system and @kbd{M-# c} to re-enter the Calculator.
  29179. Type @kbd{20 S} to compute the sine of 20 degrees; this will test the
  29180. autoloading of the extensions modules. The result should be
  29181. 0.342020143326. Finally, press @kbd{M-# c} again to make sure the
  29182. Calculator can exit.
  29183. You may also wish to test the GNUPLOT interface; to plot a sine wave,
  29184. type @kbd{' [0 ..@: 360], sin(x) @key{RET} g f}. Type @kbd{g q} when you
  29185. are done viewing the plot.
  29186. Calc is now ready to use. If you wish to go through the Calc Tutorial,
  29187. press @kbd{M-# t} to begin.
  29188. @example
  29189. @end example
  29190. @node Reporting Bugs, Summary, Installation, Top
  29191. @appendix Reporting Bugs
  29192. @noindent
  29193. If you find a bug in Calc, send e-mail to Colin Walters,
  29194. @example
  29195. walters@@debian.org @r{or}
  29196. walters@@verbum.org
  29197. @end example
  29198. @noindent
  29199. (In the following text, ``I'' refers to the original Calc author, Dave
  29200. Gillespie).
  29201. While I cannot guarantee that I will have time to work on your bug,
  29202. I do try to fix bugs quickly whenever I can.
  29203. The latest version of Calc is available from Savannah, in the Emacs
  29204. CVS tree. See @uref{http://savannah.gnu.org/projects/emacs}.
  29205. There is an automatic command @kbd{M-x report-calc-bug} which helps
  29206. you to report bugs. This command prompts you for a brief subject
  29207. line, then leaves you in a mail editing buffer. Type @kbd{C-c C-c} to
  29208. send your mail. Make sure your subject line indicates that you are
  29209. reporting a Calc bug; this command sends mail to the maintainer's
  29210. regular mailbox.
  29211. If you have suggestions for additional features for Calc, I would
  29212. love to hear them. Some have dared to suggest that Calc is already
  29213. top-heavy with features; I really don't see what they're talking
  29214. about, so, if you have ideas, send them right in. (I may even have
  29215. time to implement them!)
  29216. At the front of the source file, @file{calc.el}, is a list of ideas for
  29217. future work which I have not had time to do. If any enthusiastic souls
  29218. wish to take it upon themselves to work on these, I would be delighted.
  29219. Please let me know if you plan to contribute to Calc so I can coordinate
  29220. your efforts with mine and those of others. I will do my best to help
  29221. you in whatever way I can.
  29222. @c [summary]
  29223. @node Summary, Key Index, Reporting Bugs, Top
  29224. @appendix Calc Summary
  29225. @noindent
  29226. This section includes a complete list of Calc 2.02 keystroke commands.
  29227. Each line lists the stack entries used by the command (top-of-stack
  29228. last), the keystrokes themselves, the prompts asked by the command,
  29229. and the result of the command (also with top-of-stack last).
  29230. The result is expressed using the equivalent algebraic function.
  29231. Commands which put no results on the stack show the full @kbd{M-x}
  29232. command name in that position. Numbers preceding the result or
  29233. command name refer to notes at the end.
  29234. Algebraic functions and @kbd{M-x} commands that don't have corresponding
  29235. keystrokes are not listed in this summary.
  29236. @xref{Command Index}. @xref{Function Index}.
  29237. @iftex
  29238. @begingroup
  29239. @tex
  29240. \vskip-2\baselineskip \null
  29241. \gdef\sumrow#1{\sumrowx#1\relax}%
  29242. \gdef\sumrowx#1\:#2\:#3\:#4\:#5\:#6\relax{%
  29243. \leavevmode%
  29244. {\smallfonts
  29245. \hbox to5em{\sl\hss#1}%
  29246. \hbox to5em{\tt#2\hss}%
  29247. \hbox to4em{\sl#3\hss}%
  29248. \hbox to5em{\rm\hss#4}%
  29249. \thinspace%
  29250. {\tt#5}%
  29251. {\sl#6}%
  29252. }}%
  29253. \gdef\sumlpar{{\rm(}}%
  29254. \gdef\sumrpar{{\rm)}}%
  29255. \gdef\sumcomma{{\rm,\thinspace}}%
  29256. \gdef\sumexcl{{\rm!}}%
  29257. \gdef\sumbreak{\vskip-2.5\baselineskip\goodbreak}%
  29258. \gdef\minus#1{{\tt-}}%
  29259. @end tex
  29260. @let@:=@sumsep
  29261. @let@r=@sumrow
  29262. @catcode`@(=@active @let(=@sumlpar
  29263. @catcode`@)=@active @let)=@sumrpar
  29264. @catcode`@,=@active @let,=@sumcomma
  29265. @catcode`@!=@active @let!=@sumexcl
  29266. @end iftex
  29267. @format
  29268. @iftex
  29269. @advance@baselineskip-2.5pt
  29270. @let@c@sumbreak
  29271. @end iftex
  29272. @r{ @: M-# a @: @: 33 @:calc-embedded-activate@:}
  29273. @r{ @: M-# b @: @: @:calc-big-or-small@:}
  29274. @r{ @: M-# c @: @: @:calc@:}
  29275. @r{ @: M-# d @: @: @:calc-embedded-duplicate@:}
  29276. @r{ @: M-# e @: @: 34 @:calc-embedded@:}
  29277. @r{ @: M-# f @:formula @: @:calc-embedded-new-formula@:}
  29278. @r{ @: M-# g @: @: 35 @:calc-grab-region@:}
  29279. @r{ @: M-# i @: @: @:calc-info@:}
  29280. @r{ @: M-# j @: @: @:calc-embedded-select@:}
  29281. @r{ @: M-# k @: @: @:calc-keypad@:}
  29282. @r{ @: M-# l @: @: @:calc-load-everything@:}
  29283. @r{ @: M-# m @: @: @:read-kbd-macro@:}
  29284. @r{ @: M-# n @: @: 4 @:calc-embedded-next@:}
  29285. @r{ @: M-# o @: @: @:calc-other-window@:}
  29286. @r{ @: M-# p @: @: 4 @:calc-embedded-previous@:}
  29287. @r{ @: M-# q @:formula @: @:quick-calc@:}
  29288. @r{ @: M-# r @: @: 36 @:calc-grab-rectangle@:}
  29289. @r{ @: M-# s @: @: @:calc-info-summary@:}
  29290. @r{ @: M-# t @: @: @:calc-tutorial@:}
  29291. @r{ @: M-# u @: @: @:calc-embedded-update@:}
  29292. @r{ @: M-# w @: @: @:calc-embedded-word@:}
  29293. @r{ @: M-# x @: @: @:calc-quit@:}
  29294. @r{ @: M-# y @: @:1,28,49 @:calc-copy-to-buffer@:}
  29295. @r{ @: M-# z @: @: @:calc-user-invocation@:}
  29296. @r{ @: M-# : @: @: 36 @:calc-grab-sum-down@:}
  29297. @r{ @: M-# _ @: @: 36 @:calc-grab-sum-across@:}
  29298. @r{ @: M-# ` @:editing @: 30 @:calc-embedded-edit@:}
  29299. @r{ @: M-# 0 @:(zero) @: @:calc-reset@:}
  29300. @c
  29301. @r{ @: 0-9 @:number @: @:@:number}
  29302. @r{ @: . @:number @: @:@:0.number}
  29303. @r{ @: _ @:number @: @:-@:number}
  29304. @r{ @: e @:number @: @:@:1e number}
  29305. @r{ @: # @:number @: @:@:current-radix@t{#}number}
  29306. @r{ @: P @:(in number) @: @:+/-@:}
  29307. @r{ @: M @:(in number) @: @:mod@:}
  29308. @r{ @: @@ ' " @: (in number)@: @:@:HMS form}
  29309. @r{ @: h m s @: (in number)@: @:@:HMS form}
  29310. @c
  29311. @r{ @: ' @:formula @: 37,46 @:@:formula}
  29312. @r{ @: $ @:formula @: 37,46 @:$@:formula}
  29313. @r{ @: " @:string @: 37,46 @:@:string}
  29314. @c
  29315. @r{ a b@: + @: @: 2 @:add@:(a,b) a+b}
  29316. @r{ a b@: - @: @: 2 @:sub@:(a,b) a@minus{}b}
  29317. @r{ a b@: * @: @: 2 @:mul@:(a,b) a b, a*b}
  29318. @r{ a b@: / @: @: 2 @:div@:(a,b) a/b}
  29319. @r{ a b@: ^ @: @: 2 @:pow@:(a,b) a^b}
  29320. @r{ a b@: I ^ @: @: 2 @:nroot@:(a,b) a^(1/b)}
  29321. @r{ a b@: % @: @: 2 @:mod@:(a,b) a%b}
  29322. @r{ a b@: \ @: @: 2 @:idiv@:(a,b) a\b}
  29323. @r{ a b@: : @: @: 2 @:fdiv@:(a,b)}
  29324. @r{ a b@: | @: @: 2 @:vconcat@:(a,b) a|b}
  29325. @r{ a b@: I | @: @: @:vconcat@:(b,a) b|a}
  29326. @r{ a b@: H | @: @: 2 @:append@:(a,b)}
  29327. @r{ a b@: I H | @: @: @:append@:(b,a)}
  29328. @r{ a@: & @: @: 1 @:inv@:(a) 1/a}
  29329. @r{ a@: ! @: @: 1 @:fact@:(a) a!}
  29330. @r{ a@: = @: @: 1 @:evalv@:(a)}
  29331. @r{ a@: M-% @: @: @:percent@:(a) a%}
  29332. @c
  29333. @r{ ... a@: @key{RET} @: @: 1 @:@:... a a}
  29334. @r{ ... a@: @key{SPC} @: @: 1 @:@:... a a}
  29335. @r{... a b@: @key{TAB} @: @: 3 @:@:... b a}
  29336. @r{. a b c@: M-@key{TAB} @: @: 3 @:@:... b c a}
  29337. @r{... a b@: @key{LFD} @: @: 1 @:@:... a b a}
  29338. @r{ ... a@: @key{DEL} @: @: 1 @:@:...}
  29339. @r{... a b@: M-@key{DEL} @: @: 1 @:@:... b}
  29340. @r{ @: M-@key{RET} @: @: 4 @:calc-last-args@:}
  29341. @r{ a@: ` @:editing @: 1,30 @:calc-edit@:}
  29342. @c
  29343. @r{ ... a@: C-d @: @: 1 @:@:...}
  29344. @r{ @: C-k @: @: 27 @:calc-kill@:}
  29345. @r{ @: C-w @: @: 27 @:calc-kill-region@:}
  29346. @r{ @: C-y @: @: @:calc-yank@:}
  29347. @r{ @: C-_ @: @: 4 @:calc-undo@:}
  29348. @r{ @: M-k @: @: 27 @:calc-copy-as-kill@:}
  29349. @r{ @: M-w @: @: 27 @:calc-copy-region-as-kill@:}
  29350. @c
  29351. @r{ @: [ @: @: @:@:[...}
  29352. @r{[.. a b@: ] @: @: @:@:[a,b]}
  29353. @r{ @: ( @: @: @:@:(...}
  29354. @r{(.. a b@: ) @: @: @:@:(a,b)}
  29355. @r{ @: , @: @: @:@:vector or rect complex}
  29356. @r{ @: ; @: @: @:@:matrix or polar complex}
  29357. @r{ @: .. @: @: @:@:interval}
  29358. @c
  29359. @r{ @: ~ @: @: @:calc-num-prefix@:}
  29360. @r{ @: < @: @: 4 @:calc-scroll-left@:}
  29361. @r{ @: > @: @: 4 @:calc-scroll-right@:}
  29362. @r{ @: @{ @: @: 4 @:calc-scroll-down@:}
  29363. @r{ @: @} @: @: 4 @:calc-scroll-up@:}
  29364. @r{ @: ? @: @: @:calc-help@:}
  29365. @c
  29366. @r{ a@: n @: @: 1 @:neg@:(a) @minus{}a}
  29367. @r{ @: o @: @: 4 @:calc-realign@:}
  29368. @r{ @: p @:precision @: 31 @:calc-precision@:}
  29369. @r{ @: q @: @: @:calc-quit@:}
  29370. @r{ @: w @: @: @:calc-why@:}
  29371. @r{ @: x @:command @: @:M-x calc-@:command}
  29372. @r{ a@: y @: @:1,28,49 @:calc-copy-to-buffer@:}
  29373. @c
  29374. @r{ a@: A @: @: 1 @:abs@:(a)}
  29375. @r{ a b@: B @: @: 2 @:log@:(a,b)}
  29376. @r{ a b@: I B @: @: 2 @:alog@:(a,b) b^a}
  29377. @r{ a@: C @: @: 1 @:cos@:(a)}
  29378. @r{ a@: I C @: @: 1 @:arccos@:(a)}
  29379. @r{ a@: H C @: @: 1 @:cosh@:(a)}
  29380. @r{ a@: I H C @: @: 1 @:arccosh@:(a)}
  29381. @r{ @: D @: @: 4 @:calc-redo@:}
  29382. @r{ a@: E @: @: 1 @:exp@:(a)}
  29383. @r{ a@: H E @: @: 1 @:exp10@:(a) 10.^a}
  29384. @r{ a@: F @: @: 1,11 @:floor@:(a,d)}
  29385. @r{ a@: I F @: @: 1,11 @:ceil@:(a,d)}
  29386. @r{ a@: H F @: @: 1,11 @:ffloor@:(a,d)}
  29387. @r{ a@: I H F @: @: 1,11 @:fceil@:(a,d)}
  29388. @r{ a@: G @: @: 1 @:arg@:(a)}
  29389. @r{ @: H @:command @: 32 @:@:Hyperbolic}
  29390. @r{ @: I @:command @: 32 @:@:Inverse}
  29391. @r{ a@: J @: @: 1 @:conj@:(a)}
  29392. @r{ @: K @:command @: 32 @:@:Keep-args}
  29393. @r{ a@: L @: @: 1 @:ln@:(a)}
  29394. @r{ a@: H L @: @: 1 @:log10@:(a)}
  29395. @r{ @: M @: @: @:calc-more-recursion-depth@:}
  29396. @r{ @: I M @: @: @:calc-less-recursion-depth@:}
  29397. @r{ a@: N @: @: 5 @:evalvn@:(a)}
  29398. @r{ @: P @: @: @:@:pi}
  29399. @r{ @: I P @: @: @:@:gamma}
  29400. @r{ @: H P @: @: @:@:e}
  29401. @r{ @: I H P @: @: @:@:phi}
  29402. @r{ a@: Q @: @: 1 @:sqrt@:(a)}
  29403. @r{ a@: I Q @: @: 1 @:sqr@:(a) a^2}
  29404. @r{ a@: R @: @: 1,11 @:round@:(a,d)}
  29405. @r{ a@: I R @: @: 1,11 @:trunc@:(a,d)}
  29406. @r{ a@: H R @: @: 1,11 @:fround@:(a,d)}
  29407. @r{ a@: I H R @: @: 1,11 @:ftrunc@:(a,d)}
  29408. @r{ a@: S @: @: 1 @:sin@:(a)}
  29409. @r{ a@: I S @: @: 1 @:arcsin@:(a)}
  29410. @r{ a@: H S @: @: 1 @:sinh@:(a)}
  29411. @r{ a@: I H S @: @: 1 @:arcsinh@:(a)}
  29412. @r{ a@: T @: @: 1 @:tan@:(a)}
  29413. @r{ a@: I T @: @: 1 @:arctan@:(a)}
  29414. @r{ a@: H T @: @: 1 @:tanh@:(a)}
  29415. @r{ a@: I H T @: @: 1 @:arctanh@:(a)}
  29416. @r{ @: U @: @: 4 @:calc-undo@:}
  29417. @r{ @: X @: @: 4 @:calc-call-last-kbd-macro@:}
  29418. @c
  29419. @r{ a b@: a = @: @: 2 @:eq@:(a,b) a=b}
  29420. @r{ a b@: a # @: @: 2 @:neq@:(a,b) a!=b}
  29421. @r{ a b@: a < @: @: 2 @:lt@:(a,b) a<b}
  29422. @r{ a b@: a > @: @: 2 @:gt@:(a,b) a>b}
  29423. @r{ a b@: a [ @: @: 2 @:leq@:(a,b) a<=b}
  29424. @r{ a b@: a ] @: @: 2 @:geq@:(a,b) a>=b}
  29425. @r{ a b@: a @{ @: @: 2 @:in@:(a,b)}
  29426. @r{ a b@: a & @: @: 2,45 @:land@:(a,b) a&&b}
  29427. @r{ a b@: a | @: @: 2,45 @:lor@:(a,b) a||b}
  29428. @r{ a@: a ! @: @: 1,45 @:lnot@:(a) !a}
  29429. @r{ a b c@: a : @: @: 45 @:if@:(a,b,c) a?b:c}
  29430. @r{ a@: a . @: @: 1 @:rmeq@:(a)}
  29431. @r{ a@: a " @: @: 7,8 @:calc-expand-formula@:}
  29432. @c
  29433. @r{ a@: a + @:i, l, h @: 6,38 @:sum@:(a,i,l,h)}
  29434. @r{ a@: a - @:i, l, h @: 6,38 @:asum@:(a,i,l,h)}
  29435. @r{ a@: a * @:i, l, h @: 6,38 @:prod@:(a,i,l,h)}
  29436. @r{ a b@: a _ @: @: 2 @:subscr@:(a,b) a_b}
  29437. @c
  29438. @r{ a b@: a \ @: @: 2 @:pdiv@:(a,b)}
  29439. @r{ a b@: a % @: @: 2 @:prem@:(a,b)}
  29440. @r{ a b@: a / @: @: 2 @:pdivrem@:(a,b) [q,r]}
  29441. @r{ a b@: H a / @: @: 2 @:pdivide@:(a,b) q+r/b}
  29442. @c
  29443. @r{ a@: a a @: @: 1 @:apart@:(a)}
  29444. @r{ a@: a b @:old, new @: 38 @:subst@:(a,old,new)}
  29445. @r{ a@: a c @:v @: 38 @:collect@:(a,v)}
  29446. @r{ a@: a d @:v @: 4,38 @:deriv@:(a,v)}
  29447. @r{ a@: H a d @:v @: 4,38 @:tderiv@:(a,v)}
  29448. @r{ a@: a e @: @: @:esimplify@:(a)}
  29449. @r{ a@: a f @: @: 1 @:factor@:(a)}
  29450. @r{ a@: H a f @: @: 1 @:factors@:(a)}
  29451. @r{ a b@: a g @: @: 2 @:pgcd@:(a,b)}
  29452. @r{ a@: a i @:v @: 38 @:integ@:(a,v)}
  29453. @r{ a@: a m @:pats @: 38 @:match@:(a,pats)}
  29454. @r{ a@: I a m @:pats @: 38 @:matchnot@:(a,pats)}
  29455. @r{ data x@: a p @: @: 28 @:polint@:(data,x)}
  29456. @r{ data x@: H a p @: @: 28 @:ratint@:(data,x)}
  29457. @r{ a@: a n @: @: 1 @:nrat@:(a)}
  29458. @r{ a@: a r @:rules @:4,8,38 @:rewrite@:(a,rules,n)}
  29459. @r{ a@: a s @: @: @:simplify@:(a)}
  29460. @r{ a@: a t @:v, n @: 31,39 @:taylor@:(a,v,n)}
  29461. @r{ a@: a v @: @: 7,8 @:calc-alg-evaluate@:}
  29462. @r{ a@: a x @: @: 4,8 @:expand@:(a)}
  29463. @c
  29464. @r{ data@: a F @:model, vars @: 48 @:fit@:(m,iv,pv,data)}
  29465. @r{ data@: I a F @:model, vars @: 48 @:xfit@:(m,iv,pv,data)}
  29466. @r{ data@: H a F @:model, vars @: 48 @:efit@:(m,iv,pv,data)}
  29467. @r{ a@: a I @:v, l, h @: 38 @:ninteg@:(a,v,l,h)}
  29468. @r{ a b@: a M @:op @: 22 @:mapeq@:(op,a,b)}
  29469. @r{ a b@: I a M @:op @: 22 @:mapeqr@:(op,a,b)}
  29470. @r{ a b@: H a M @:op @: 22 @:mapeqp@:(op,a,b)}
  29471. @r{ a g@: a N @:v @: 38 @:minimize@:(a,v,g)}
  29472. @r{ a g@: H a N @:v @: 38 @:wminimize@:(a,v,g)}
  29473. @r{ a@: a P @:v @: 38 @:roots@:(a,v)}
  29474. @r{ a g@: a R @:v @: 38 @:root@:(a,v,g)}
  29475. @r{ a g@: H a R @:v @: 38 @:wroot@:(a,v,g)}
  29476. @r{ a@: a S @:v @: 38 @:solve@:(a,v)}
  29477. @r{ a@: I a S @:v @: 38 @:finv@:(a,v)}
  29478. @r{ a@: H a S @:v @: 38 @:fsolve@:(a,v)}
  29479. @r{ a@: I H a S @:v @: 38 @:ffinv@:(a,v)}
  29480. @r{ a@: a T @:i, l, h @: 6,38 @:table@:(a,i,l,h)}
  29481. @r{ a g@: a X @:v @: 38 @:maximize@:(a,v,g)}
  29482. @r{ a g@: H a X @:v @: 38 @:wmaximize@:(a,v,g)}
  29483. @c
  29484. @r{ a b@: b a @: @: 9 @:and@:(a,b,w)}
  29485. @r{ a@: b c @: @: 9 @:clip@:(a,w)}
  29486. @r{ a b@: b d @: @: 9 @:diff@:(a,b,w)}
  29487. @r{ a@: b l @: @: 10 @:lsh@:(a,n,w)}
  29488. @r{ a n@: H b l @: @: 9 @:lsh@:(a,n,w)}
  29489. @r{ a@: b n @: @: 9 @:not@:(a,w)}
  29490. @r{ a b@: b o @: @: 9 @:or@:(a,b,w)}
  29491. @r{ v@: b p @: @: 1 @:vpack@:(v)}
  29492. @r{ a@: b r @: @: 10 @:rsh@:(a,n,w)}
  29493. @r{ a n@: H b r @: @: 9 @:rsh@:(a,n,w)}
  29494. @r{ a@: b t @: @: 10 @:rot@:(a,n,w)}
  29495. @r{ a n@: H b t @: @: 9 @:rot@:(a,n,w)}
  29496. @r{ a@: b u @: @: 1 @:vunpack@:(a)}
  29497. @r{ @: b w @:w @: 9,50 @:calc-word-size@:}
  29498. @r{ a b@: b x @: @: 9 @:xor@:(a,b,w)}
  29499. @c
  29500. @r{c s l p@: b D @: @: @:ddb@:(c,s,l,p)}
  29501. @r{ r n p@: b F @: @: @:fv@:(r,n,p)}
  29502. @r{ r n p@: I b F @: @: @:fvb@:(r,n,p)}
  29503. @r{ r n p@: H b F @: @: @:fvl@:(r,n,p)}
  29504. @r{ v@: b I @: @: 19 @:irr@:(v)}
  29505. @r{ v@: I b I @: @: 19 @:irrb@:(v)}
  29506. @r{ a@: b L @: @: 10 @:ash@:(a,n,w)}
  29507. @r{ a n@: H b L @: @: 9 @:ash@:(a,n,w)}
  29508. @r{ r n a@: b M @: @: @:pmt@:(r,n,a)}
  29509. @r{ r n a@: I b M @: @: @:pmtb@:(r,n,a)}
  29510. @r{ r n a@: H b M @: @: @:pmtl@:(r,n,a)}
  29511. @r{ r v@: b N @: @: 19 @:npv@:(r,v)}
  29512. @r{ r v@: I b N @: @: 19 @:npvb@:(r,v)}
  29513. @r{ r n p@: b P @: @: @:pv@:(r,n,p)}
  29514. @r{ r n p@: I b P @: @: @:pvb@:(r,n,p)}
  29515. @r{ r n p@: H b P @: @: @:pvl@:(r,n,p)}
  29516. @r{ a@: b R @: @: 10 @:rash@:(a,n,w)}
  29517. @r{ a n@: H b R @: @: 9 @:rash@:(a,n,w)}
  29518. @r{ c s l@: b S @: @: @:sln@:(c,s,l)}
  29519. @r{ n p a@: b T @: @: @:rate@:(n,p,a)}
  29520. @r{ n p a@: I b T @: @: @:rateb@:(n,p,a)}
  29521. @r{ n p a@: H b T @: @: @:ratel@:(n,p,a)}
  29522. @r{c s l p@: b Y @: @: @:syd@:(c,s,l,p)}
  29523. @r{ r p a@: b # @: @: @:nper@:(r,p,a)}
  29524. @r{ r p a@: I b # @: @: @:nperb@:(r,p,a)}
  29525. @r{ r p a@: H b # @: @: @:nperl@:(r,p,a)}
  29526. @r{ a b@: b % @: @: @:relch@:(a,b)}
  29527. @c
  29528. @r{ a@: c c @: @: 5 @:pclean@:(a,p)}
  29529. @r{ a@: c 0-9 @: @: @:pclean@:(a,p)}
  29530. @r{ a@: H c c @: @: 5 @:clean@:(a,p)}
  29531. @r{ a@: H c 0-9 @: @: @:clean@:(a,p)}
  29532. @r{ a@: c d @: @: 1 @:deg@:(a)}
  29533. @r{ a@: c f @: @: 1 @:pfloat@:(a)}
  29534. @r{ a@: H c f @: @: 1 @:float@:(a)}
  29535. @r{ a@: c h @: @: 1 @:hms@:(a)}
  29536. @r{ a@: c p @: @: @:polar@:(a)}
  29537. @r{ a@: I c p @: @: @:rect@:(a)}
  29538. @r{ a@: c r @: @: 1 @:rad@:(a)}
  29539. @c
  29540. @r{ a@: c F @: @: 5 @:pfrac@:(a,p)}
  29541. @r{ a@: H c F @: @: 5 @:frac@:(a,p)}
  29542. @c
  29543. @r{ a@: c % @: @: @:percent@:(a*100)}
  29544. @c
  29545. @r{ @: d . @:char @: 50 @:calc-point-char@:}
  29546. @r{ @: d , @:char @: 50 @:calc-group-char@:}
  29547. @r{ @: d < @: @: 13,50 @:calc-left-justify@:}
  29548. @r{ @: d = @: @: 13,50 @:calc-center-justify@:}
  29549. @r{ @: d > @: @: 13,50 @:calc-right-justify@:}
  29550. @r{ @: d @{ @:label @: 50 @:calc-left-label@:}
  29551. @r{ @: d @} @:label @: 50 @:calc-right-label@:}
  29552. @r{ @: d [ @: @: 4 @:calc-truncate-up@:}
  29553. @r{ @: d ] @: @: 4 @:calc-truncate-down@:}
  29554. @r{ @: d " @: @: 12,50 @:calc-display-strings@:}
  29555. @r{ @: d @key{SPC} @: @: @:calc-refresh@:}
  29556. @r{ @: d @key{RET} @: @: 1 @:calc-refresh-top@:}
  29557. @c
  29558. @r{ @: d 0 @: @: 50 @:calc-decimal-radix@:}
  29559. @r{ @: d 2 @: @: 50 @:calc-binary-radix@:}
  29560. @r{ @: d 6 @: @: 50 @:calc-hex-radix@:}
  29561. @r{ @: d 8 @: @: 50 @:calc-octal-radix@:}
  29562. @c
  29563. @r{ @: d b @: @:12,13,50 @:calc-line-breaking@:}
  29564. @r{ @: d c @: @: 50 @:calc-complex-notation@:}
  29565. @r{ @: d d @:format @: 50 @:calc-date-notation@:}
  29566. @r{ @: d e @: @: 5,50 @:calc-eng-notation@:}
  29567. @r{ @: d f @:num @: 31,50 @:calc-fix-notation@:}
  29568. @r{ @: d g @: @:12,13,50 @:calc-group-digits@:}
  29569. @r{ @: d h @:format @: 50 @:calc-hms-notation@:}
  29570. @r{ @: d i @: @: 50 @:calc-i-notation@:}
  29571. @r{ @: d j @: @: 50 @:calc-j-notation@:}
  29572. @r{ @: d l @: @: 12,50 @:calc-line-numbering@:}
  29573. @r{ @: d n @: @: 5,50 @:calc-normal-notation@:}
  29574. @r{ @: d o @:format @: 50 @:calc-over-notation@:}
  29575. @r{ @: d p @: @: 12,50 @:calc-show-plain@:}
  29576. @r{ @: d r @:radix @: 31,50 @:calc-radix@:}
  29577. @r{ @: d s @: @: 5,50 @:calc-sci-notation@:}
  29578. @r{ @: d t @: @: 27 @:calc-truncate-stack@:}
  29579. @r{ @: d w @: @: 12,13 @:calc-auto-why@:}
  29580. @r{ @: d z @: @: 12,50 @:calc-leading-zeros@:}
  29581. @c
  29582. @r{ @: d B @: @: 50 @:calc-big-language@:}
  29583. @r{ @: d C @: @: 50 @:calc-c-language@:}
  29584. @r{ @: d E @: @: 50 @:calc-eqn-language@:}
  29585. @r{ @: d F @: @: 50 @:calc-fortran-language@:}
  29586. @r{ @: d M @: @: 50 @:calc-mathematica-language@:}
  29587. @r{ @: d N @: @: 50 @:calc-normal-language@:}
  29588. @r{ @: d O @: @: 50 @:calc-flat-language@:}
  29589. @r{ @: d P @: @: 50 @:calc-pascal-language@:}
  29590. @r{ @: d T @: @: 50 @:calc-tex-language@:}
  29591. @r{ @: d U @: @: 50 @:calc-unformatted-language@:}
  29592. @r{ @: d W @: @: 50 @:calc-maple-language@:}
  29593. @c
  29594. @r{ a@: f [ @: @: 4 @:decr@:(a,n)}
  29595. @r{ a@: f ] @: @: 4 @:incr@:(a,n)}
  29596. @c
  29597. @r{ a b@: f b @: @: 2 @:beta@:(a,b)}
  29598. @r{ a@: f e @: @: 1 @:erf@:(a)}
  29599. @r{ a@: I f e @: @: 1 @:erfc@:(a)}
  29600. @r{ a@: f g @: @: 1 @:gamma@:(a)}
  29601. @r{ a b@: f h @: @: 2 @:hypot@:(a,b)}
  29602. @r{ a@: f i @: @: 1 @:im@:(a)}
  29603. @r{ n a@: f j @: @: 2 @:besJ@:(n,a)}
  29604. @r{ a b@: f n @: @: 2 @:min@:(a,b)}
  29605. @r{ a@: f r @: @: 1 @:re@:(a)}
  29606. @r{ a@: f s @: @: 1 @:sign@:(a)}
  29607. @r{ a b@: f x @: @: 2 @:max@:(a,b)}
  29608. @r{ n a@: f y @: @: 2 @:besY@:(n,a)}
  29609. @c
  29610. @r{ a@: f A @: @: 1 @:abssqr@:(a)}
  29611. @r{ x a b@: f B @: @: @:betaI@:(x,a,b)}
  29612. @r{ x a b@: H f B @: @: @:betaB@:(x,a,b)}
  29613. @r{ a@: f E @: @: 1 @:expm1@:(a)}
  29614. @r{ a x@: f G @: @: 2 @:gammaP@:(a,x)}
  29615. @r{ a x@: I f G @: @: 2 @:gammaQ@:(a,x)}
  29616. @r{ a x@: H f G @: @: 2 @:gammag@:(a,x)}
  29617. @r{ a x@: I H f G @: @: 2 @:gammaG@:(a,x)}
  29618. @r{ a b@: f I @: @: 2 @:ilog@:(a,b)}
  29619. @r{ a b@: I f I @: @: 2 @:alog@:(a,b) b^a}
  29620. @r{ a@: f L @: @: 1 @:lnp1@:(a)}
  29621. @r{ a@: f M @: @: 1 @:mant@:(a)}
  29622. @r{ a@: f Q @: @: 1 @:isqrt@:(a)}
  29623. @r{ a@: I f Q @: @: 1 @:sqr@:(a) a^2}
  29624. @r{ a n@: f S @: @: 2 @:scf@:(a,n)}
  29625. @r{ y x@: f T @: @: @:arctan2@:(y,x)}
  29626. @r{ a@: f X @: @: 1 @:xpon@:(a)}
  29627. @c
  29628. @r{ x y@: g a @: @: 28,40 @:calc-graph-add@:}
  29629. @r{ @: g b @: @: 12 @:calc-graph-border@:}
  29630. @r{ @: g c @: @: @:calc-graph-clear@:}
  29631. @r{ @: g d @: @: 41 @:calc-graph-delete@:}
  29632. @r{ x y@: g f @: @: 28,40 @:calc-graph-fast@:}
  29633. @r{ @: g g @: @: 12 @:calc-graph-grid@:}
  29634. @r{ @: g h @:title @: @:calc-graph-header@:}
  29635. @r{ @: g j @: @: 4 @:calc-graph-juggle@:}
  29636. @r{ @: g k @: @: 12 @:calc-graph-key@:}
  29637. @r{ @: g l @: @: 12 @:calc-graph-log-x@:}
  29638. @r{ @: g n @:name @: @:calc-graph-name@:}
  29639. @r{ @: g p @: @: 42 @:calc-graph-plot@:}
  29640. @r{ @: g q @: @: @:calc-graph-quit@:}
  29641. @r{ @: g r @:range @: @:calc-graph-range-x@:}
  29642. @r{ @: g s @: @: 12,13 @:calc-graph-line-style@:}
  29643. @r{ @: g t @:title @: @:calc-graph-title-x@:}
  29644. @r{ @: g v @: @: @:calc-graph-view-commands@:}
  29645. @r{ @: g x @:display @: @:calc-graph-display@:}
  29646. @r{ @: g z @: @: 12 @:calc-graph-zero-x@:}
  29647. @c
  29648. @r{ x y z@: g A @: @: 28,40 @:calc-graph-add-3d@:}
  29649. @r{ @: g C @:command @: @:calc-graph-command@:}
  29650. @r{ @: g D @:device @: 43,44 @:calc-graph-device@:}
  29651. @r{ x y z@: g F @: @: 28,40 @:calc-graph-fast-3d@:}
  29652. @r{ @: g H @: @: 12 @:calc-graph-hide@:}
  29653. @r{ @: g K @: @: @:calc-graph-kill@:}
  29654. @r{ @: g L @: @: 12 @:calc-graph-log-y@:}
  29655. @r{ @: g N @:number @: 43,51 @:calc-graph-num-points@:}
  29656. @r{ @: g O @:filename @: 43,44 @:calc-graph-output@:}
  29657. @r{ @: g P @: @: 42 @:calc-graph-print@:}
  29658. @r{ @: g R @:range @: @:calc-graph-range-y@:}
  29659. @r{ @: g S @: @: 12,13 @:calc-graph-point-style@:}
  29660. @r{ @: g T @:title @: @:calc-graph-title-y@:}
  29661. @r{ @: g V @: @: @:calc-graph-view-trail@:}
  29662. @r{ @: g X @:format @: @:calc-graph-geometry@:}
  29663. @r{ @: g Z @: @: 12 @:calc-graph-zero-y@:}
  29664. @c
  29665. @r{ @: g C-l @: @: 12 @:calc-graph-log-z@:}
  29666. @r{ @: g C-r @:range @: @:calc-graph-range-z@:}
  29667. @r{ @: g C-t @:title @: @:calc-graph-title-z@:}
  29668. @c
  29669. @r{ @: h b @: @: @:calc-describe-bindings@:}
  29670. @r{ @: h c @:key @: @:calc-describe-key-briefly@:}
  29671. @r{ @: h f @:function @: @:calc-describe-function@:}
  29672. @r{ @: h h @: @: @:calc-full-help@:}
  29673. @r{ @: h i @: @: @:calc-info@:}
  29674. @r{ @: h k @:key @: @:calc-describe-key@:}
  29675. @r{ @: h n @: @: @:calc-view-news@:}
  29676. @r{ @: h s @: @: @:calc-info-summary@:}
  29677. @r{ @: h t @: @: @:calc-tutorial@:}
  29678. @r{ @: h v @:var @: @:calc-describe-variable@:}
  29679. @c
  29680. @r{ @: j 1-9 @: @: @:calc-select-part@:}
  29681. @r{ @: j @key{RET} @: @: 27 @:calc-copy-selection@:}
  29682. @r{ @: j @key{DEL} @: @: 27 @:calc-del-selection@:}
  29683. @r{ @: j ' @:formula @: 27 @:calc-enter-selection@:}
  29684. @r{ @: j ` @:editing @: 27,30 @:calc-edit-selection@:}
  29685. @r{ @: j " @: @: 7,27 @:calc-sel-expand-formula@:}
  29686. @c
  29687. @r{ @: j + @:formula @: 27 @:calc-sel-add-both-sides@:}
  29688. @r{ @: j - @:formula @: 27 @:calc-sel-sub-both-sides@:}
  29689. @r{ @: j * @:formula @: 27 @:calc-sel-mul-both-sides@:}
  29690. @r{ @: j / @:formula @: 27 @:calc-sel-div-both-sides@:}
  29691. @r{ @: j & @: @: 27 @:calc-sel-invert@:}
  29692. @c
  29693. @r{ @: j a @: @: 27 @:calc-select-additional@:}
  29694. @r{ @: j b @: @: 12 @:calc-break-selections@:}
  29695. @r{ @: j c @: @: @:calc-clear-selections@:}
  29696. @r{ @: j d @: @: 12,50 @:calc-show-selections@:}
  29697. @r{ @: j e @: @: 12 @:calc-enable-selections@:}
  29698. @r{ @: j l @: @: 4,27 @:calc-select-less@:}
  29699. @r{ @: j m @: @: 4,27 @:calc-select-more@:}
  29700. @r{ @: j n @: @: 4 @:calc-select-next@:}
  29701. @r{ @: j o @: @: 4,27 @:calc-select-once@:}
  29702. @r{ @: j p @: @: 4 @:calc-select-previous@:}
  29703. @r{ @: j r @:rules @:4,8,27 @:calc-rewrite-selection@:}
  29704. @r{ @: j s @: @: 4,27 @:calc-select-here@:}
  29705. @r{ @: j u @: @: 27 @:calc-unselect@:}
  29706. @r{ @: j v @: @: 7,27 @:calc-sel-evaluate@:}
  29707. @c
  29708. @r{ @: j C @: @: 27 @:calc-sel-commute@:}
  29709. @r{ @: j D @: @: 4,27 @:calc-sel-distribute@:}
  29710. @r{ @: j E @: @: 27 @:calc-sel-jump-equals@:}
  29711. @r{ @: j I @: @: 27 @:calc-sel-isolate@:}
  29712. @r{ @: H j I @: @: 27 @:calc-sel-isolate@: (full)}
  29713. @r{ @: j L @: @: 4,27 @:calc-commute-left@:}
  29714. @r{ @: j M @: @: 27 @:calc-sel-merge@:}
  29715. @r{ @: j N @: @: 27 @:calc-sel-negate@:}
  29716. @r{ @: j O @: @: 4,27 @:calc-select-once-maybe@:}
  29717. @r{ @: j R @: @: 4,27 @:calc-commute-right@:}
  29718. @r{ @: j S @: @: 4,27 @:calc-select-here-maybe@:}
  29719. @r{ @: j U @: @: 27 @:calc-sel-unpack@:}
  29720. @c
  29721. @r{ @: k a @: @: @:calc-random-again@:}
  29722. @r{ n@: k b @: @: 1 @:bern@:(n)}
  29723. @r{ n x@: H k b @: @: 2 @:bern@:(n,x)}
  29724. @r{ n m@: k c @: @: 2 @:choose@:(n,m)}
  29725. @r{ n m@: H k c @: @: 2 @:perm@:(n,m)}
  29726. @r{ n@: k d @: @: 1 @:dfact@:(n) n!!}
  29727. @r{ n@: k e @: @: 1 @:euler@:(n)}
  29728. @r{ n x@: H k e @: @: 2 @:euler@:(n,x)}
  29729. @r{ n@: k f @: @: 4 @:prfac@:(n)}
  29730. @r{ n m@: k g @: @: 2 @:gcd@:(n,m)}
  29731. @r{ m n@: k h @: @: 14 @:shuffle@:(n,m)}
  29732. @r{ n m@: k l @: @: 2 @:lcm@:(n,m)}
  29733. @r{ n@: k m @: @: 1 @:moebius@:(n)}
  29734. @r{ n@: k n @: @: 4 @:nextprime@:(n)}
  29735. @r{ n@: I k n @: @: 4 @:prevprime@:(n)}
  29736. @r{ n@: k p @: @: 4,28 @:calc-prime-test@:}
  29737. @r{ m@: k r @: @: 14 @:random@:(m)}
  29738. @r{ n m@: k s @: @: 2 @:stir1@:(n,m)}
  29739. @r{ n m@: H k s @: @: 2 @:stir2@:(n,m)}
  29740. @r{ n@: k t @: @: 1 @:totient@:(n)}
  29741. @c
  29742. @r{ n p x@: k B @: @: @:utpb@:(x,n,p)}
  29743. @r{ n p x@: I k B @: @: @:ltpb@:(x,n,p)}
  29744. @r{ v x@: k C @: @: @:utpc@:(x,v)}
  29745. @r{ v x@: I k C @: @: @:ltpc@:(x,v)}
  29746. @r{ n m@: k E @: @: @:egcd@:(n,m)}
  29747. @r{v1 v2 x@: k F @: @: @:utpf@:(x,v1,v2)}
  29748. @r{v1 v2 x@: I k F @: @: @:ltpf@:(x,v1,v2)}
  29749. @r{ m s x@: k N @: @: @:utpn@:(x,m,s)}
  29750. @r{ m s x@: I k N @: @: @:ltpn@:(x,m,s)}
  29751. @r{ m x@: k P @: @: @:utpp@:(x,m)}
  29752. @r{ m x@: I k P @: @: @:ltpp@:(x,m)}
  29753. @r{ v x@: k T @: @: @:utpt@:(x,v)}
  29754. @r{ v x@: I k T @: @: @:ltpt@:(x,v)}
  29755. @c
  29756. @r{ @: m a @: @: 12,13 @:calc-algebraic-mode@:}
  29757. @r{ @: m d @: @: @:calc-degrees-mode@:}
  29758. @r{ @: m f @: @: 12 @:calc-frac-mode@:}
  29759. @r{ @: m g @: @: 52 @:calc-get-modes@:}
  29760. @r{ @: m h @: @: @:calc-hms-mode@:}
  29761. @r{ @: m i @: @: 12,13 @:calc-infinite-mode@:}
  29762. @r{ @: m m @: @: @:calc-save-modes@:}
  29763. @r{ @: m p @: @: 12 @:calc-polar-mode@:}
  29764. @r{ @: m r @: @: @:calc-radians-mode@:}
  29765. @r{ @: m s @: @: 12 @:calc-symbolic-mode@:}
  29766. @r{ @: m t @: @: 12 @:calc-total-algebraic-mode@:}
  29767. @r{ @: m v @: @: 12,13 @:calc-matrix-mode@:}
  29768. @r{ @: m w @: @: 13 @:calc-working@:}
  29769. @r{ @: m x @: @: @:calc-always-load-extensions@:}
  29770. @c
  29771. @r{ @: m A @: @: 12 @:calc-alg-simplify-mode@:}
  29772. @r{ @: m B @: @: 12 @:calc-bin-simplify-mode@:}
  29773. @r{ @: m C @: @: 12 @:calc-auto-recompute@:}
  29774. @r{ @: m D @: @: @:calc-default-simplify-mode@:}
  29775. @r{ @: m E @: @: 12 @:calc-ext-simplify-mode@:}
  29776. @r{ @: m F @:filename @: 13 @:calc-settings-file-name@:}
  29777. @r{ @: m N @: @: 12 @:calc-num-simplify-mode@:}
  29778. @r{ @: m O @: @: 12 @:calc-no-simplify-mode@:}
  29779. @r{ @: m R @: @: 12,13 @:calc-mode-record-mode@:}
  29780. @r{ @: m S @: @: 12 @:calc-shift-prefix@:}
  29781. @r{ @: m U @: @: 12 @:calc-units-simplify-mode@:}
  29782. @c
  29783. @r{ @: s c @:var1, var2 @: 29 @:calc-copy-variable@:}
  29784. @r{ @: s d @:var, decl @: @:calc-declare-variable@:}
  29785. @r{ @: s e @:var, editing @: 29,30 @:calc-edit-variable@:}
  29786. @r{ @: s i @:buffer @: @:calc-insert-variables@:}
  29787. @r{ a b@: s l @:var @: 29 @:@:a (letting var=b)}
  29788. @r{ a ...@: s m @:op, var @: 22,29 @:calc-store-map@:}
  29789. @r{ @: s n @:var @: 29,47 @:calc-store-neg@: (v/-1)}
  29790. @r{ @: s p @:var @: 29 @:calc-permanent-variable@:}
  29791. @r{ @: s r @:var @: 29 @:@:v (recalled value)}
  29792. @r{ @: r 0-9 @: @: @:calc-recall-quick@:}
  29793. @r{ a@: s s @:var @: 28,29 @:calc-store@:}
  29794. @r{ a@: s 0-9 @: @: @:calc-store-quick@:}
  29795. @r{ a@: s t @:var @: 29 @:calc-store-into@:}
  29796. @r{ a@: t 0-9 @: @: @:calc-store-into-quick@:}
  29797. @r{ @: s u @:var @: 29 @:calc-unstore@:}
  29798. @r{ a@: s x @:var @: 29 @:calc-store-exchange@:}
  29799. @c
  29800. @r{ @: s A @:editing @: 30 @:calc-edit-AlgSimpRules@:}
  29801. @r{ @: s D @:editing @: 30 @:calc-edit-Decls@:}
  29802. @r{ @: s E @:editing @: 30 @:calc-edit-EvalRules@:}
  29803. @r{ @: s F @:editing @: 30 @:calc-edit-FitRules@:}
  29804. @r{ @: s G @:editing @: 30 @:calc-edit-GenCount@:}
  29805. @r{ @: s H @:editing @: 30 @:calc-edit-Holidays@:}
  29806. @r{ @: s I @:editing @: 30 @:calc-edit-IntegLimit@:}
  29807. @r{ @: s L @:editing @: 30 @:calc-edit-LineStyles@:}
  29808. @r{ @: s P @:editing @: 30 @:calc-edit-PointStyles@:}
  29809. @r{ @: s R @:editing @: 30 @:calc-edit-PlotRejects@:}
  29810. @r{ @: s T @:editing @: 30 @:calc-edit-TimeZone@:}
  29811. @r{ @: s U @:editing @: 30 @:calc-edit-Units@:}
  29812. @r{ @: s X @:editing @: 30 @:calc-edit-ExtSimpRules@:}
  29813. @c
  29814. @r{ a@: s + @:var @: 29,47 @:calc-store-plus@: (v+a)}
  29815. @r{ a@: s - @:var @: 29,47 @:calc-store-minus@: (v-a)}
  29816. @r{ a@: s * @:var @: 29,47 @:calc-store-times@: (v*a)}
  29817. @r{ a@: s / @:var @: 29,47 @:calc-store-div@: (v/a)}
  29818. @r{ a@: s ^ @:var @: 29,47 @:calc-store-power@: (v^a)}
  29819. @r{ a@: s | @:var @: 29,47 @:calc-store-concat@: (v|a)}
  29820. @r{ @: s & @:var @: 29,47 @:calc-store-inv@: (v^-1)}
  29821. @r{ @: s [ @:var @: 29,47 @:calc-store-decr@: (v-1)}
  29822. @r{ @: s ] @:var @: 29,47 @:calc-store-incr@: (v-(-1))}
  29823. @r{ a b@: s : @: @: 2 @:assign@:(a,b) a @t{:=} b}
  29824. @r{ a@: s = @: @: 1 @:evalto@:(a,b) a @t{=>}}
  29825. @c
  29826. @r{ @: t [ @: @: 4 @:calc-trail-first@:}
  29827. @r{ @: t ] @: @: 4 @:calc-trail-last@:}
  29828. @r{ @: t < @: @: 4 @:calc-trail-scroll-left@:}
  29829. @r{ @: t > @: @: 4 @:calc-trail-scroll-right@:}
  29830. @r{ @: t . @: @: 12 @:calc-full-trail-vectors@:}
  29831. @c
  29832. @r{ @: t b @: @: 4 @:calc-trail-backward@:}
  29833. @r{ @: t d @: @: 12,50 @:calc-trail-display@:}
  29834. @r{ @: t f @: @: 4 @:calc-trail-forward@:}
  29835. @r{ @: t h @: @: @:calc-trail-here@:}
  29836. @r{ @: t i @: @: @:calc-trail-in@:}
  29837. @r{ @: t k @: @: 4 @:calc-trail-kill@:}
  29838. @r{ @: t m @:string @: @:calc-trail-marker@:}
  29839. @r{ @: t n @: @: 4 @:calc-trail-next@:}
  29840. @r{ @: t o @: @: @:calc-trail-out@:}
  29841. @r{ @: t p @: @: 4 @:calc-trail-previous@:}
  29842. @r{ @: t r @:string @: @:calc-trail-isearch-backward@:}
  29843. @r{ @: t s @:string @: @:calc-trail-isearch-forward@:}
  29844. @r{ @: t y @: @: 4 @:calc-trail-yank@:}
  29845. @c
  29846. @r{ d@: t C @:oz, nz @: @:tzconv@:(d,oz,nz)}
  29847. @r{d oz nz@: t C @:$ @: @:tzconv@:(d,oz,nz)}
  29848. @r{ d@: t D @: @: 15 @:date@:(d)}
  29849. @r{ d@: t I @: @: 4 @:incmonth@:(d,n)}
  29850. @r{ d@: t J @: @: 16 @:julian@:(d,z)}
  29851. @r{ d@: t M @: @: 17 @:newmonth@:(d,n)}
  29852. @r{ @: t N @: @: 16 @:now@:(z)}
  29853. @r{ d@: t P @:1 @: 31 @:year@:(d)}
  29854. @r{ d@: t P @:2 @: 31 @:month@:(d)}
  29855. @r{ d@: t P @:3 @: 31 @:day@:(d)}
  29856. @r{ d@: t P @:4 @: 31 @:hour@:(d)}
  29857. @r{ d@: t P @:5 @: 31 @:minute@:(d)}
  29858. @r{ d@: t P @:6 @: 31 @:second@:(d)}
  29859. @r{ d@: t P @:7 @: 31 @:weekday@:(d)}
  29860. @r{ d@: t P @:8 @: 31 @:yearday@:(d)}
  29861. @r{ d@: t P @:9 @: 31 @:time@:(d)}
  29862. @r{ d@: t U @: @: 16 @:unixtime@:(d,z)}
  29863. @r{ d@: t W @: @: 17 @:newweek@:(d,w)}
  29864. @r{ d@: t Y @: @: 17 @:newyear@:(d,n)}
  29865. @c
  29866. @r{ a b@: t + @: @: 2 @:badd@:(a,b)}
  29867. @r{ a b@: t - @: @: 2 @:bsub@:(a,b)}
  29868. @c
  29869. @r{ @: u a @: @: 12 @:calc-autorange-units@:}
  29870. @r{ a@: u b @: @: @:calc-base-units@:}
  29871. @r{ a@: u c @:units @: 18 @:calc-convert-units@:}
  29872. @r{ defn@: u d @:unit, descr @: @:calc-define-unit@:}
  29873. @r{ @: u e @: @: @:calc-explain-units@:}
  29874. @r{ @: u g @:unit @: @:calc-get-unit-definition@:}
  29875. @r{ @: u p @: @: @:calc-permanent-units@:}
  29876. @r{ a@: u r @: @: @:calc-remove-units@:}
  29877. @r{ a@: u s @: @: @:usimplify@:(a)}
  29878. @r{ a@: u t @:units @: 18 @:calc-convert-temperature@:}
  29879. @r{ @: u u @:unit @: @:calc-undefine-unit@:}
  29880. @r{ @: u v @: @: @:calc-enter-units-table@:}
  29881. @r{ a@: u x @: @: @:calc-extract-units@:}
  29882. @r{ a@: u 0-9 @: @: @:calc-quick-units@:}
  29883. @c
  29884. @r{ v1 v2@: u C @: @: 20 @:vcov@:(v1,v2)}
  29885. @r{ v1 v2@: I u C @: @: 20 @:vpcov@:(v1,v2)}
  29886. @r{ v1 v2@: H u C @: @: 20 @:vcorr@:(v1,v2)}
  29887. @r{ v@: u G @: @: 19 @:vgmean@:(v)}
  29888. @r{ a b@: H u G @: @: 2 @:agmean@:(a,b)}
  29889. @r{ v@: u M @: @: 19 @:vmean@:(v)}
  29890. @r{ v@: I u M @: @: 19 @:vmeane@:(v)}
  29891. @r{ v@: H u M @: @: 19 @:vmedian@:(v)}
  29892. @r{ v@: I H u M @: @: 19 @:vhmean@:(v)}
  29893. @r{ v@: u N @: @: 19 @:vmin@:(v)}
  29894. @r{ v@: u S @: @: 19 @:vsdev@:(v)}
  29895. @r{ v@: I u S @: @: 19 @:vpsdev@:(v)}
  29896. @r{ v@: H u S @: @: 19 @:vvar@:(v)}
  29897. @r{ v@: I H u S @: @: 19 @:vpvar@:(v)}
  29898. @r{ @: u V @: @: @:calc-view-units-table@:}
  29899. @r{ v@: u X @: @: 19 @:vmax@:(v)}
  29900. @c
  29901. @r{ v@: u + @: @: 19 @:vsum@:(v)}
  29902. @r{ v@: u * @: @: 19 @:vprod@:(v)}
  29903. @r{ v@: u # @: @: 19 @:vcount@:(v)}
  29904. @c
  29905. @r{ @: V ( @: @: 50 @:calc-vector-parens@:}
  29906. @r{ @: V @{ @: @: 50 @:calc-vector-braces@:}
  29907. @r{ @: V [ @: @: 50 @:calc-vector-brackets@:}
  29908. @r{ @: V ] @:ROCP @: 50 @:calc-matrix-brackets@:}
  29909. @r{ @: V , @: @: 50 @:calc-vector-commas@:}
  29910. @r{ @: V < @: @: 50 @:calc-matrix-left-justify@:}
  29911. @r{ @: V = @: @: 50 @:calc-matrix-center-justify@:}
  29912. @r{ @: V > @: @: 50 @:calc-matrix-right-justify@:}
  29913. @r{ @: V / @: @: 12,50 @:calc-break-vectors@:}
  29914. @r{ @: V . @: @: 12,50 @:calc-full-vectors@:}
  29915. @c
  29916. @r{ s t@: V ^ @: @: 2 @:vint@:(s,t)}
  29917. @r{ s t@: V - @: @: 2 @:vdiff@:(s,t)}
  29918. @r{ s@: V ~ @: @: 1 @:vcompl@:(s)}
  29919. @r{ s@: V # @: @: 1 @:vcard@:(s)}
  29920. @r{ s@: V : @: @: 1 @:vspan@:(s)}
  29921. @r{ s@: V + @: @: 1 @:rdup@:(s)}
  29922. @c
  29923. @r{ m@: V & @: @: 1 @:inv@:(m) 1/m}
  29924. @c
  29925. @r{ v@: v a @:n @: @:arrange@:(v,n)}
  29926. @r{ a@: v b @:n @: @:cvec@:(a,n)}
  29927. @r{ v@: v c @:n >0 @: 21,31 @:mcol@:(v,n)}
  29928. @r{ v@: v c @:n <0 @: 31 @:mrcol@:(v,-n)}
  29929. @r{ m@: v c @:0 @: 31 @:getdiag@:(m)}
  29930. @r{ v@: v d @: @: 25 @:diag@:(v,n)}
  29931. @r{ v m@: v e @: @: 2 @:vexp@:(v,m)}
  29932. @r{ v m f@: H v e @: @: 2 @:vexp@:(v,m,f)}
  29933. @r{ v a@: v f @: @: 26 @:find@:(v,a,n)}
  29934. @r{ v@: v h @: @: 1 @:head@:(v)}
  29935. @r{ v@: I v h @: @: 1 @:tail@:(v)}
  29936. @r{ v@: H v h @: @: 1 @:rhead@:(v)}
  29937. @r{ v@: I H v h @: @: 1 @:rtail@:(v)}
  29938. @r{ @: v i @:n @: 31 @:idn@:(1,n)}
  29939. @r{ @: v i @:0 @: 31 @:idn@:(1)}
  29940. @r{ h t@: v k @: @: 2 @:cons@:(h,t)}
  29941. @r{ h t@: H v k @: @: 2 @:rcons@:(h,t)}
  29942. @r{ v@: v l @: @: 1 @:vlen@:(v)}
  29943. @r{ v@: H v l @: @: 1 @:mdims@:(v)}
  29944. @r{ v m@: v m @: @: 2 @:vmask@:(v,m)}
  29945. @r{ v@: v n @: @: 1 @:rnorm@:(v)}
  29946. @r{ a b c@: v p @: @: 24 @:calc-pack@:}
  29947. @r{ v@: v r @:n >0 @: 21,31 @:mrow@:(v,n)}
  29948. @r{ v@: v r @:n <0 @: 31 @:mrrow@:(v,-n)}
  29949. @r{ m@: v r @:0 @: 31 @:getdiag@:(m)}
  29950. @r{ v i j@: v s @: @: @:subvec@:(v,i,j)}
  29951. @r{ v i j@: I v s @: @: @:rsubvec@:(v,i,j)}
  29952. @r{ m@: v t @: @: 1 @:trn@:(m)}
  29953. @r{ v@: v u @: @: 24 @:calc-unpack@:}
  29954. @r{ v@: v v @: @: 1 @:rev@:(v)}
  29955. @r{ @: v x @:n @: 31 @:index@:(n)}
  29956. @r{ n s i@: C-u v x @: @: @:index@:(n,s,i)}
  29957. @c
  29958. @r{ v@: V A @:op @: 22 @:apply@:(op,v)}
  29959. @r{ v1 v2@: V C @: @: 2 @:cross@:(v1,v2)}
  29960. @r{ m@: V D @: @: 1 @:det@:(m)}
  29961. @r{ s@: V E @: @: 1 @:venum@:(s)}
  29962. @r{ s@: V F @: @: 1 @:vfloor@:(s)}
  29963. @r{ v@: V G @: @: @:grade@:(v)}
  29964. @r{ v@: I V G @: @: @:rgrade@:(v)}
  29965. @r{ v@: V H @:n @: 31 @:histogram@:(v,n)}
  29966. @r{ v w@: H V H @:n @: 31 @:histogram@:(v,w,n)}
  29967. @r{ v1 v2@: V I @:mop aop @: 22 @:inner@:(mop,aop,v1,v2)}
  29968. @r{ m@: V J @: @: 1 @:ctrn@:(m)}
  29969. @r{ m@: V L @: @: 1 @:lud@:(m)}
  29970. @r{ v@: V M @:op @: 22,23 @:map@:(op,v)}
  29971. @r{ v@: V N @: @: 1 @:cnorm@:(v)}
  29972. @r{ v1 v2@: V O @:op @: 22 @:outer@:(op,v1,v2)}
  29973. @r{ v@: V R @:op @: 22,23 @:reduce@:(op,v)}
  29974. @r{ v@: I V R @:op @: 22,23 @:rreduce@:(op,v)}
  29975. @r{ a n@: H V R @:op @: 22 @:nest@:(op,a,n)}
  29976. @r{ a@: I H V R @:op @: 22 @:fixp@:(op,a)}
  29977. @r{ v@: V S @: @: @:sort@:(v)}
  29978. @r{ v@: I V S @: @: @:rsort@:(v)}
  29979. @r{ m@: V T @: @: 1 @:tr@:(m)}
  29980. @r{ v@: V U @:op @: 22 @:accum@:(op,v)}
  29981. @r{ v@: I V U @:op @: 22 @:raccum@:(op,v)}
  29982. @r{ a n@: H V U @:op @: 22 @:anest@:(op,a,n)}
  29983. @r{ a@: I H V U @:op @: 22 @:afixp@:(op,a)}
  29984. @r{ s t@: V V @: @: 2 @:vunion@:(s,t)}
  29985. @r{ s t@: V X @: @: 2 @:vxor@:(s,t)}
  29986. @c
  29987. @r{ @: Y @: @: @:@:user commands}
  29988. @c
  29989. @r{ @: z @: @: @:@:user commands}
  29990. @c
  29991. @r{ c@: Z [ @: @: 45 @:calc-kbd-if@:}
  29992. @r{ c@: Z | @: @: 45 @:calc-kbd-else-if@:}
  29993. @r{ @: Z : @: @: @:calc-kbd-else@:}
  29994. @r{ @: Z ] @: @: @:calc-kbd-end-if@:}
  29995. @c
  29996. @r{ @: Z @{ @: @: 4 @:calc-kbd-loop@:}
  29997. @r{ c@: Z / @: @: 45 @:calc-kbd-break@:}
  29998. @r{ @: Z @} @: @: @:calc-kbd-end-loop@:}
  29999. @r{ n@: Z < @: @: @:calc-kbd-repeat@:}
  30000. @r{ @: Z > @: @: @:calc-kbd-end-repeat@:}
  30001. @r{ n m@: Z ( @: @: @:calc-kbd-for@:}
  30002. @r{ s@: Z ) @: @: @:calc-kbd-end-for@:}
  30003. @c
  30004. @r{ @: Z C-g @: @: @:@:cancel if/loop command}
  30005. @c
  30006. @r{ @: Z ` @: @: @:calc-kbd-push@:}
  30007. @r{ @: Z ' @: @: @:calc-kbd-pop@:}
  30008. @r{ a@: Z = @:message @: 28 @:calc-kbd-report@:}
  30009. @r{ @: Z # @:prompt @: @:calc-kbd-query@:}
  30010. @c
  30011. @r{ comp@: Z C @:func, args @: 50 @:calc-user-define-composition@:}
  30012. @r{ @: Z D @:key, command @: @:calc-user-define@:}
  30013. @r{ @: Z E @:key, editing @: 30 @:calc-user-define-edit@:}
  30014. @r{ defn@: Z F @:k, c, f, a, n@: 28 @:calc-user-define-formula@:}
  30015. @r{ @: Z G @:key @: @:calc-get-user-defn@:}
  30016. @r{ @: Z I @: @: @:calc-user-define-invocation@:}
  30017. @r{ @: Z K @:key, command @: @:calc-user-define-kbd-macro@:}
  30018. @r{ @: Z P @:key @: @:calc-user-define-permanent@:}
  30019. @r{ @: Z S @: @: 30 @:calc-edit-user-syntax@:}
  30020. @r{ @: Z T @: @: 12 @:calc-timing@:}
  30021. @r{ @: Z U @:key @: @:calc-user-undefine@:}
  30022. @end format
  30023. @noindent
  30024. NOTES
  30025. @enumerate
  30026. @c 1
  30027. @item
  30028. Positive prefix arguments apply to @cite{n} stack entries.
  30029. Negative prefix arguments apply to the @cite{-n}th stack entry.
  30030. A prefix of zero applies to the entire stack. (For @key{LFD} and
  30031. @kbd{M-@key{DEL}}, the meaning of the sign is reversed.)
  30032. @c 2
  30033. @item
  30034. Positive prefix arguments apply to @cite{n} stack entries.
  30035. Negative prefix arguments apply to the top stack entry
  30036. and the next @cite{-n} stack entries.
  30037. @c 3
  30038. @item
  30039. Positive prefix arguments rotate top @cite{n} stack entries by one.
  30040. Negative prefix arguments rotate the entire stack by @cite{-n}.
  30041. A prefix of zero reverses the entire stack.
  30042. @c 4
  30043. @item
  30044. Prefix argument specifies a repeat count or distance.
  30045. @c 5
  30046. @item
  30047. Positive prefix arguments specify a precision @cite{p}.
  30048. Negative prefix arguments reduce the current precision by @cite{-p}.
  30049. @c 6
  30050. @item
  30051. A prefix argument is interpreted as an additional step-size parameter.
  30052. A plain @kbd{C-u} prefix means to prompt for the step size.
  30053. @c 7
  30054. @item
  30055. A prefix argument specifies simplification level and depth.
  30056. 1=Default, 2=like @kbd{a s}, 3=like @kbd{a e}.
  30057. @c 8
  30058. @item
  30059. A negative prefix operates only on the top level of the input formula.
  30060. @c 9
  30061. @item
  30062. Positive prefix arguments specify a word size of @cite{w} bits, unsigned.
  30063. Negative prefix arguments specify a word size of @cite{w} bits, signed.
  30064. @c 10
  30065. @item
  30066. Prefix arguments specify the shift amount @cite{n}. The @cite{w} argument
  30067. cannot be specified in the keyboard version of this command.
  30068. @c 11
  30069. @item
  30070. From the keyboard, @cite{d} is omitted and defaults to zero.
  30071. @c 12
  30072. @item
  30073. Mode is toggled; a positive prefix always sets the mode, and a negative
  30074. prefix always clears the mode.
  30075. @c 13
  30076. @item
  30077. Some prefix argument values provide special variations of the mode.
  30078. @c 14
  30079. @item
  30080. A prefix argument, if any, is used for @cite{m} instead of taking
  30081. @cite{m} from the stack. @cite{M} may take any of these values:
  30082. @iftex
  30083. {@advance@tableindent10pt
  30084. @end iftex
  30085. @table @asis
  30086. @item Integer
  30087. Random integer in the interval @cite{[0 .. m)}.
  30088. @item Float
  30089. Random floating-point number in the interval @cite{[0 .. m)}.
  30090. @item 0.0
  30091. Gaussian with mean 1 and standard deviation 0.
  30092. @item Error form
  30093. Gaussian with specified mean and standard deviation.
  30094. @item Interval
  30095. Random integer or floating-point number in that interval.
  30096. @item Vector
  30097. Random element from the vector.
  30098. @end table
  30099. @iftex
  30100. }
  30101. @end iftex
  30102. @c 15
  30103. @item
  30104. A prefix argument from 1 to 6 specifies number of date components
  30105. to remove from the stack. @xref{Date Conversions}.
  30106. @c 16
  30107. @item
  30108. A prefix argument specifies a time zone; @kbd{C-u} says to take the
  30109. time zone number or name from the top of the stack. @xref{Time Zones}.
  30110. @c 17
  30111. @item
  30112. A prefix argument specifies a day number (0-6, 0-31, or 0-366).
  30113. @c 18
  30114. @item
  30115. If the input has no units, you will be prompted for both the old and
  30116. the new units.
  30117. @c 19
  30118. @item
  30119. With a prefix argument, collect that many stack entries to form the
  30120. input data set. Each entry may be a single value or a vector of values.
  30121. @c 20
  30122. @item
  30123. With a prefix argument of 1, take a single @c{$@var{n}\times2$}
  30124. @i{@var{N}x2} matrix from the
  30125. stack instead of two separate data vectors.
  30126. @c 21
  30127. @item
  30128. The row or column number @cite{n} may be given as a numeric prefix
  30129. argument instead. A plain @kbd{C-u} prefix says to take @cite{n}
  30130. from the top of the stack. If @cite{n} is a vector or interval,
  30131. a subvector/submatrix of the input is created.
  30132. @c 22
  30133. @item
  30134. The @cite{op} prompt can be answered with the key sequence for the
  30135. desired function, or with @kbd{x} or @kbd{z} followed by a function name,
  30136. or with @kbd{$} to take a formula from the top of the stack, or with
  30137. @kbd{'} and a typed formula. In the last two cases, the formula may
  30138. be a nameless function like @samp{<#1+#2>} or @samp{<x, y : x+y>}, or it
  30139. may include @kbd{$}, @kbd{$$}, etc. (where @kbd{$} will correspond to the
  30140. last argument of the created function), or otherwise you will be
  30141. prompted for an argument list. The number of vectors popped from the
  30142. stack by @kbd{V M} depends on the number of arguments of the function.
  30143. @c 23
  30144. @item
  30145. One of the mapping direction keys @kbd{_} (horizontal, i.e., map
  30146. by rows or reduce across), @kbd{:} (vertical, i.e., map by columns or
  30147. reduce down), or @kbd{=} (map or reduce by rows) may be used before
  30148. entering @cite{op}; these modify the function name by adding the letter
  30149. @code{r} for ``rows,'' @code{c} for ``columns,'' @code{a} for ``across,''
  30150. or @code{d} for ``down.''
  30151. @c 24
  30152. @item
  30153. The prefix argument specifies a packing mode. A nonnegative mode
  30154. is the number of items (for @kbd{v p}) or the number of levels
  30155. (for @kbd{v u}). A negative mode is as described below. With no
  30156. prefix argument, the mode is taken from the top of the stack and
  30157. may be an integer or a vector of integers.
  30158. @iftex
  30159. {@advance@tableindent-20pt
  30160. @end iftex
  30161. @table @cite
  30162. @item -1
  30163. (@var{2}) Rectangular complex number.
  30164. @item -2
  30165. (@var{2}) Polar complex number.
  30166. @item -3
  30167. (@var{3}) HMS form.
  30168. @item -4
  30169. (@var{2}) Error form.
  30170. @item -5
  30171. (@var{2}) Modulo form.
  30172. @item -6
  30173. (@var{2}) Closed interval.
  30174. @item -7
  30175. (@var{2}) Closed .. open interval.
  30176. @item -8
  30177. (@var{2}) Open .. closed interval.
  30178. @item -9
  30179. (@var{2}) Open interval.
  30180. @item -10
  30181. (@var{2}) Fraction.
  30182. @item -11
  30183. (@var{2}) Float with integer mantissa.
  30184. @item -12
  30185. (@var{2}) Float with mantissa in @cite{[1 .. 10)}.
  30186. @item -13
  30187. (@var{1}) Date form (using date numbers).
  30188. @item -14
  30189. (@var{3}) Date form (using year, month, day).
  30190. @item -15
  30191. (@var{6}) Date form (using year, month, day, hour, minute, second).
  30192. @end table
  30193. @iftex
  30194. }
  30195. @end iftex
  30196. @c 25
  30197. @item
  30198. A prefix argument specifies the size @cite{n} of the matrix. With no
  30199. prefix argument, @cite{n} is omitted and the size is inferred from
  30200. the input vector.
  30201. @c 26
  30202. @item
  30203. The prefix argument specifies the starting position @cite{n} (default 1).
  30204. @c 27
  30205. @item
  30206. Cursor position within stack buffer affects this command.
  30207. @c 28
  30208. @item
  30209. Arguments are not actually removed from the stack by this command.
  30210. @c 29
  30211. @item
  30212. Variable name may be a single digit or a full name.
  30213. @c 30
  30214. @item
  30215. Editing occurs in a separate buffer. Press @kbd{M-# M-#} (or @kbd{C-c C-c},
  30216. @key{LFD}, or in some cases @key{RET}) to finish the edit, or press
  30217. @kbd{M-# x} to cancel the edit. The @key{LFD} key prevents evaluation
  30218. of the result of the edit.
  30219. @c 31
  30220. @item
  30221. The number prompted for can also be provided as a prefix argument.
  30222. @c 32
  30223. @item
  30224. Press this key a second time to cancel the prefix.
  30225. @c 33
  30226. @item
  30227. With a negative prefix, deactivate all formulas. With a positive
  30228. prefix, deactivate and then reactivate from scratch.
  30229. @c 34
  30230. @item
  30231. Default is to scan for nearest formula delimiter symbols. With a
  30232. prefix of zero, formula is delimited by mark and point. With a
  30233. non-zero prefix, formula is delimited by scanning forward or
  30234. backward by that many lines.
  30235. @c 35
  30236. @item
  30237. Parse the region between point and mark as a vector. A nonzero prefix
  30238. parses @var{n} lines before or after point as a vector. A zero prefix
  30239. parses the current line as a vector. A @kbd{C-u} prefix parses the
  30240. region between point and mark as a single formula.
  30241. @c 36
  30242. @item
  30243. Parse the rectangle defined by point and mark as a matrix. A positive
  30244. prefix @var{n} divides the rectangle into columns of width @var{n}.
  30245. A zero or @kbd{C-u} prefix parses each line as one formula. A negative
  30246. prefix suppresses special treatment of bracketed portions of a line.
  30247. @c 37
  30248. @item
  30249. A numeric prefix causes the current language mode to be ignored.
  30250. @c 38
  30251. @item
  30252. Responding to a prompt with a blank line answers that and all
  30253. later prompts by popping additional stack entries.
  30254. @c 39
  30255. @item
  30256. Answer for @cite{v} may also be of the form @cite{v = v_0} or
  30257. @cite{v - v_0}.
  30258. @c 40
  30259. @item
  30260. With a positive prefix argument, stack contains many @cite{y}'s and one
  30261. common @cite{x}. With a zero prefix, stack contains a vector of
  30262. @cite{y}s and a common @cite{x}. With a negative prefix, stack
  30263. contains many @cite{[x,y]} vectors. (For 3D plots, substitute
  30264. @cite{z} for @cite{y} and @cite{x,y} for @cite{x}.)
  30265. @c 41
  30266. @item
  30267. With any prefix argument, all curves in the graph are deleted.
  30268. @c 42
  30269. @item
  30270. With a positive prefix, refines an existing plot with more data points.
  30271. With a negative prefix, forces recomputation of the plot data.
  30272. @c 43
  30273. @item
  30274. With any prefix argument, set the default value instead of the
  30275. value for this graph.
  30276. @c 44
  30277. @item
  30278. With a negative prefix argument, set the value for the printer.
  30279. @c 45
  30280. @item
  30281. Condition is considered ``true'' if it is a nonzero real or complex
  30282. number, or a formula whose value is known to be nonzero; it is ``false''
  30283. otherwise.
  30284. @c 46
  30285. @item
  30286. Several formulas separated by commas are pushed as multiple stack
  30287. entries. Trailing @kbd{)}, @kbd{]}, @kbd{@}}, @kbd{>}, and @kbd{"}
  30288. delimiters may be omitted. The notation @kbd{$$$} refers to the value
  30289. in stack level three, and causes the formula to replace the top three
  30290. stack levels. The notation @kbd{$3} refers to stack level three without
  30291. causing that value to be removed from the stack. Use @key{LFD} in place
  30292. of @key{RET} to prevent evaluation; use @kbd{M-=} in place of @key{RET}
  30293. to evaluate variables.@refill
  30294. @c 47
  30295. @item
  30296. The variable is replaced by the formula shown on the right. The
  30297. Inverse flag reverses the order of the operands, e.g., @kbd{I s - x}
  30298. assigns @c{$x \coloneq a-x$}
  30299. @cite{x := a-x}.
  30300. @c 48
  30301. @item
  30302. Press @kbd{?} repeatedly to see how to choose a model. Answer the
  30303. variables prompt with @cite{iv} or @cite{iv;pv} to specify
  30304. independent and parameter variables. A positive prefix argument
  30305. takes @i{@var{n}+1} vectors from the stack; a zero prefix takes a matrix
  30306. and a vector from the stack.
  30307. @c 49
  30308. @item
  30309. With a plain @kbd{C-u} prefix, replace the current region of the
  30310. destination buffer with the yanked text instead of inserting.
  30311. @c 50
  30312. @item
  30313. All stack entries are reformatted; the @kbd{H} prefix inhibits this.
  30314. The @kbd{I} prefix sets the mode temporarily, redraws the top stack
  30315. entry, then restores the original setting of the mode.
  30316. @c 51
  30317. @item
  30318. A negative prefix sets the default 3D resolution instead of the
  30319. default 2D resolution.
  30320. @c 52
  30321. @item
  30322. This grabs a vector of the form [@var{prec}, @var{wsize}, @var{ssize},
  30323. @var{radix}, @var{flfmt}, @var{ang}, @var{frac}, @var{symb}, @var{polar},
  30324. @var{matrix}, @var{simp}, @var{inf}]. A prefix argument from 1 to 12
  30325. grabs the @var{n}th mode value only.
  30326. @end enumerate
  30327. @iftex
  30328. (Space is provided below for you to keep your own written notes.)
  30329. @page
  30330. @endgroup
  30331. @end iftex
  30332. @c [end-summary]
  30333. @node Key Index, Command Index, Summary, Top
  30334. @unnumbered Index of Key Sequences
  30335. @printindex ky
  30336. @node Command Index, Function Index, Key Index, Top
  30337. @unnumbered Index of Calculator Commands
  30338. Since all Calculator commands begin with the prefix @samp{calc-}, the
  30339. @kbd{x} key has been provided as a variant of @kbd{M-x} which automatically
  30340. types @samp{calc-} for you. Thus, @kbd{x last-args} is short for
  30341. @kbd{M-x calc-last-args}.
  30342. @printindex pg
  30343. @node Function Index, Concept Index, Command Index, Top
  30344. @unnumbered Index of Algebraic Functions
  30345. This is a list of built-in functions and operators usable in algebraic
  30346. expressions. Their full Lisp names are derived by adding the prefix
  30347. @samp{calcFunc-}, as in @code{calcFunc-sqrt}.
  30348. @iftex
  30349. All functions except those noted with ``*'' have corresponding
  30350. Calc keystrokes and can also be found in the Calc Summary.
  30351. @end iftex
  30352. @printindex tp
  30353. @node Concept Index, Variable Index, Function Index, Top
  30354. @unnumbered Concept Index
  30355. @printindex cp
  30356. @node Variable Index, Lisp Function Index, Concept Index, Top
  30357. @unnumbered Index of Variables
  30358. The variables in this list that do not contain dashes are accessible
  30359. as Calc variables. Add a @samp{var-} prefix to get the name of the
  30360. corresponding Lisp variable.
  30361. The remaining variables are Lisp variables suitable for @code{setq}ing
  30362. in your @file{.emacs} file.
  30363. @printindex vr
  30364. @node Lisp Function Index, , Variable Index, Top
  30365. @unnumbered Index of Lisp Math Functions
  30366. The following functions are meant to be used with @code{defmath}, not
  30367. @code{defun} definitions. For names that do not start with @samp{calc-},
  30368. the corresponding full Lisp name is derived by adding a prefix of
  30369. @samp{math-}.
  30370. @printindex fn
  30371. @summarycontents
  30372. @c [end]
  30373. @contents
  30374. @bye