calc-3 285 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820
  1. This is ../../info/calc, produced by makeinfo version 4.13 from
  2. calc.texi.
  3. This file documents Calc, the GNU Emacs calculator.
  4. Copyright (C) 1990-1991, 2001-2012 Free Software Foundation, Inc.
  5. Permission is granted to copy, distribute and/or modify this
  6. document under the terms of the GNU Free Documentation License,
  7. Version 1.3 or any later version published by the Free Software
  8. Foundation; with the Invariant Sections being just "GNU GENERAL
  9. PUBLIC LICENSE", with the Front-Cover texts being "A GNU Manual,"
  10. and with the Back-Cover Texts as in (a) below. A copy of the
  11. license is included in the section entitled "GNU Free
  12. Documentation License."
  13. (a) The FSF's Back-Cover Text is: "You have the freedom to copy and
  14. modify this GNU manual. Buying copies from the FSF supports it in
  15. developing GNU and promoting software freedom."
  16. INFO-DIR-SECTION Emacs misc features
  17. START-INFO-DIR-ENTRY
  18. * Calc: (calc). Advanced desk calculator and mathematical tool.
  19. END-INFO-DIR-ENTRY
  20. 
  21. File: calc, Node: Related Financial Functions, Next: Depreciation Functions, Prev: Present Value, Up: Financial Functions
  22. 9.6.4 Related Financial Functions
  23. ---------------------------------
  24. The functions in this section are basically inverses of the present
  25. value functions with respect to the various arguments.
  26. The `b M' (`calc-fin-pmt') [`pmt'] command computes the amount of
  27. periodic payment necessary to amortize a loan. Thus `pmt(RATE, N,
  28. AMOUNT)' equals the value of PAYMENT such that `pv(RATE, N, PAYMENT) =
  29. AMOUNT'.
  30. The `I b M' [`pmtb'] command does the same computation but using
  31. `pvb' instead of `pv'. Like `pv' and `pvb', these functions can also
  32. take a fourth argument which represents an initial lump-sum investment.
  33. The `H b M' key just invokes the `fvl' function, which is the
  34. inverse of `pvl'. There is no explicit `pmtl' function.
  35. The `b #' (`calc-fin-nper') [`nper'] command computes the number of
  36. regular payments necessary to amortize a loan. Thus `nper(RATE,
  37. PAYMENT, AMOUNT)' equals the value of N such that `pv(RATE, N, PAYMENT)
  38. = AMOUNT'. If PAYMENT is too small ever to amortize a loan for AMOUNT
  39. at interest rate RATE, the `nper' function is left in symbolic form.
  40. The `I b #' [`nperb'] command does the same computation but using
  41. `pvb' instead of `pv'. You can give a fourth lump-sum argument to
  42. these functions, but the computation will be rather slow in the
  43. four-argument case.
  44. The `H b #' [`nperl'] command does the same computation using `pvl'.
  45. By exchanging PAYMENT and AMOUNT you can also get the solution for
  46. `fvl'. For example, `nperl(8%, 2000, 1000) = 9.006', so if you place
  47. $1000 in a bank account earning 8%, it will take nine years to grow to
  48. $2000.
  49. The `b T' (`calc-fin-rate') [`rate'] command computes the rate of
  50. return on an investment. This is also an inverse of `pv': `rate(N,
  51. PAYMENT, AMOUNT)' computes the value of RATE such that `pv(RATE, N,
  52. PAYMENT) = AMOUNT'. The result is expressed as a formula like `6.3%'.
  53. The `I b T' [`rateb'] and `H b T' [`ratel'] commands solve the
  54. analogous equations with `pvb' or `pvl' in place of `pv'. Also, `rate'
  55. and `rateb' can accept an optional fourth argument just like `pv' and
  56. `pvb'. To redo the above example from a different perspective,
  57. `ratel(9, 2000, 1000) = 8.00597%', which says you will need an interest
  58. rate of 8% in order to double your account in nine years.
  59. The `b I' (`calc-fin-irr') [`irr'] command is the analogous function
  60. to `rate' but for net present value. Its argument is a vector of
  61. payments. Thus `irr(PAYMENTS)' computes the RATE such that `npv(RATE,
  62. PAYMENTS) = 0'; this rate is known as the "internal rate of return".
  63. The `I b I' [`irrb'] command computes the internal rate of return
  64. assuming payments occur at the beginning of each period.
  65. 
  66. File: calc, Node: Depreciation Functions, Next: Definitions of Financial Functions, Prev: Related Financial Functions, Up: Financial Functions
  67. 9.6.5 Depreciation Functions
  68. ----------------------------
  69. The functions in this section calculate "depreciation", which is the
  70. amount of value that a possession loses over time. These functions are
  71. characterized by three parameters: COST, the original cost of the
  72. asset; SALVAGE, the value the asset will have at the end of its
  73. expected "useful life"; and LIFE, the number of years (or other
  74. periods) of the expected useful life.
  75. There are several methods for calculating depreciation that differ in
  76. the way they spread the depreciation over the lifetime of the asset.
  77. The `b S' (`calc-fin-sln') [`sln'] command computes the
  78. "straight-line" depreciation. In this method, the asset depreciates by
  79. the same amount every year (or period). For example, `sln(12000, 2000,
  80. 5)' returns 2000. The asset costs $12000 initially and will be worth
  81. $2000 after five years; it loses $2000 per year.
  82. The `b Y' (`calc-fin-syd') [`syd'] command computes the accelerated
  83. "sum-of-years'-digits" depreciation. Here the depreciation is higher
  84. during the early years of the asset's life. Since the depreciation is
  85. different each year, `b Y' takes a fourth PERIOD parameter which
  86. specifies which year is requested, from 1 to LIFE. If PERIOD is
  87. outside this range, the `syd' function will return zero.
  88. The `b D' (`calc-fin-ddb') [`ddb'] command computes an accelerated
  89. depreciation using the double-declining balance method. It also takes
  90. a fourth PERIOD parameter.
  91. For symmetry, the `sln' function will accept a PERIOD parameter as
  92. well, although it will ignore its value except that the return value
  93. will as usual be zero if PERIOD is out of range.
  94. For example, pushing the vector `[1,2,3,4,5]' (perhaps with `v x 5')
  95. and then mapping `V M ' [sln(12000,2000,5,$), syd(12000,2000,5,$),
  96. ddb(12000,2000,5,$)] <RET>' produces a matrix that allows us to compare
  97. the three depreciation methods:
  98. [ [ 2000, 3333, 4800 ]
  99. [ 2000, 2667, 2880 ]
  100. [ 2000, 2000, 1728 ]
  101. [ 2000, 1333, 592 ]
  102. [ 2000, 667, 0 ] ]
  103. (Values have been rounded to nearest integers in this figure.) We see
  104. that `sln' depreciates by the same amount each year, `syd' depreciates
  105. more at the beginning and less at the end, and `ddb' weights the
  106. depreciation even more toward the beginning.
  107. Summing columns with `V R : +' yields `[10000, 10000, 10000]'; the
  108. total depreciation in any method is (by definition) the difference
  109. between the cost and the salvage value.
  110. 
  111. File: calc, Node: Definitions of Financial Functions, Prev: Depreciation Functions, Up: Financial Functions
  112. 9.6.6 Definitions
  113. -----------------
  114. For your reference, here are the actual formulas used to compute Calc's
  115. financial functions.
  116. Calc will not evaluate a financial function unless the RATE or N
  117. argument is known. However, PAYMENT or AMOUNT can be a variable. Calc
  118. expands these functions according to the formulas below for symbolic
  119. arguments only when you use the `a "' (`calc-expand-formula') command,
  120. or when taking derivatives or integrals or solving equations involving
  121. the functions.
  122. These formulas are shown using the conventions of Big display mode
  123. (`d B'); for example, the formula for `fv' written linearly is `pmt *
  124. ((1 + rate)^n) - 1) / rate'.
  125. n
  126. (1 + rate) - 1
  127. fv(rate, n, pmt) = pmt * ---------------
  128. rate
  129. n
  130. ((1 + rate) - 1) (1 + rate)
  131. fvb(rate, n, pmt) = pmt * ----------------------------
  132. rate
  133. n
  134. fvl(rate, n, pmt) = pmt * (1 + rate)
  135. -n
  136. 1 - (1 + rate)
  137. pv(rate, n, pmt) = pmt * ----------------
  138. rate
  139. -n
  140. (1 - (1 + rate) ) (1 + rate)
  141. pvb(rate, n, pmt) = pmt * -----------------------------
  142. rate
  143. -n
  144. pvl(rate, n, pmt) = pmt * (1 + rate)
  145. -1 -2 -3
  146. npv(rate, [a, b, c]) = a*(1 + rate) + b*(1 + rate) + c*(1 + rate)
  147. -1 -2
  148. npvb(rate, [a, b, c]) = a + b*(1 + rate) + c*(1 + rate)
  149. -n
  150. (amt - x * (1 + rate) ) * rate
  151. pmt(rate, n, amt, x) = -------------------------------
  152. -n
  153. 1 - (1 + rate)
  154. -n
  155. (amt - x * (1 + rate) ) * rate
  156. pmtb(rate, n, amt, x) = -------------------------------
  157. -n
  158. (1 - (1 + rate) ) (1 + rate)
  159. amt * rate
  160. nper(rate, pmt, amt) = - log(1 - ------------, 1 + rate)
  161. pmt
  162. amt * rate
  163. nperb(rate, pmt, amt) = - log(1 - ---------------, 1 + rate)
  164. pmt * (1 + rate)
  165. amt
  166. nperl(rate, pmt, amt) = - log(---, 1 + rate)
  167. pmt
  168. 1/n
  169. pmt
  170. ratel(n, pmt, amt) = ------ - 1
  171. 1/n
  172. amt
  173. cost - salv
  174. sln(cost, salv, life) = -----------
  175. life
  176. (cost - salv) * (life - per + 1)
  177. syd(cost, salv, life, per) = --------------------------------
  178. life * (life + 1) / 2
  179. book * 2
  180. ddb(cost, salv, life, per) = --------, book = cost - depreciation so far
  181. life
  182. In `pmt' and `pmtb', `x=0' if omitted.
  183. These functions accept any numeric objects, including error forms,
  184. intervals, and even (though not very usefully) complex numbers. The
  185. above formulas specify exactly the behavior of these functions with all
  186. sorts of inputs.
  187. Note that if the first argument to the `log' in `nper' is negative,
  188. `nper' leaves itself in symbolic form rather than returning a
  189. (financially meaningless) complex number.
  190. `rate(num, pmt, amt)' solves the equation `pv(rate, num, pmt) = amt'
  191. for `rate' using `H a R' (`calc-find-root'), with the interval `[.01%
  192. .. 100%]' for an initial guess. The `rateb' function is the same except
  193. that it uses `pvb'. Note that `ratel' can be solved directly; its
  194. formula is shown in the above list.
  195. Similarly, `irr(pmts)' solves the equation `npv(rate, pmts) = 0' for
  196. `rate'.
  197. If you give a fourth argument to `nper' or `nperb', Calc will also
  198. use `H a R' to solve the equation using an initial guess interval of
  199. `[0 .. 100]'.
  200. A fourth argument to `fv' simply sums the two components calculated
  201. from the above formulas for `fv' and `fvl'. The same is true of `fvb',
  202. `pv', and `pvb'.
  203. The `ddb' function is computed iteratively; the "book" value starts
  204. out equal to COST, and decreases according to the above formula for the
  205. specified number of periods. If the book value would decrease below
  206. SALVAGE, it only decreases to SALVAGE and the depreciation is zero for
  207. all subsequent periods. The `ddb' function returns the amount the book
  208. value decreased in the specified period.
  209. 
  210. File: calc, Node: Binary Functions, Prev: Financial Functions, Up: Arithmetic
  211. 9.7 Binary Number Functions
  212. ===========================
  213. The commands in this chapter all use two-letter sequences beginning with
  214. the `b' prefix.
  215. The "binary" operations actually work regardless of the currently
  216. displayed radix, although their results make the most sense in a radix
  217. like 2, 8, or 16 (as obtained by the `d 2', `d 8', or `d 6' commands,
  218. respectively). You may also wish to enable display of leading zeros
  219. with `d z'. *Note Radix Modes::.
  220. The Calculator maintains a current "word size" `w', an arbitrary
  221. positive or negative integer. For a positive word size, all of the
  222. binary operations described here operate modulo `2^w'. In particular,
  223. negative arguments are converted to positive integers modulo `2^w' by
  224. all binary functions.
  225. If the word size is negative, binary operations produce
  226. twos-complement integers from `-(2^(-w-1))' to `2^(-w-1)-1' inclusive.
  227. Either mode accepts inputs in any range; the sign of `w' affects only
  228. the results produced.
  229. The `b c' (`calc-clip') [`clip'] command can be used to clip a
  230. number by reducing it modulo `2^w'. The commands described in this
  231. chapter automatically clip their results to the current word size.
  232. Note that other operations like addition do not use the current word
  233. size, since integer addition generally is not "binary." (However,
  234. *note Simplification Modes::, `calc-bin-simplify-mode'.) For example,
  235. with a word size of 8 bits `b c' converts a number to the range 0 to
  236. 255; with a word size of -8 `b c' converts to the range -128 to 127.
  237. The default word size is 32 bits. All operations except the shifts
  238. and rotates allow you to specify a different word size for that one
  239. operation by giving a numeric prefix argument: `C-u 8 b c' clips the
  240. top of stack to the range 0 to 255 regardless of the current word size.
  241. To set the word size permanently, use `b w' (`calc-word-size'). This
  242. command displays a prompt with the current word size; press <RET>
  243. immediately to keep this word size, or type a new word size at the
  244. prompt.
  245. When the binary operations are written in symbolic form, they take an
  246. optional second (or third) word-size parameter. When a formula like
  247. `and(a,b)' is finally evaluated, the word size current at that time
  248. will be used, but when `and(a,b,-8)' is evaluated, a word size of -8
  249. will always be used. A symbolic binary function will be left in
  250. symbolic form unless the all of its argument(s) are integers or
  251. integer-valued floats.
  252. If either or both arguments are modulo forms for which `M' is a
  253. power of two, that power of two is taken as the word size unless a
  254. numeric prefix argument overrides it. The current word size is never
  255. consulted when modulo-power-of-two forms are involved.
  256. The `b a' (`calc-and') [`and'] command computes the bitwise AND of
  257. the two numbers on the top of the stack. In other words, for each of
  258. the `w' binary digits of the two numbers (pairwise), the corresponding
  259. bit of the result is 1 if and only if both input bits are 1:
  260. `and(2#1100, 2#1010) = 2#1000'.
  261. The `b o' (`calc-or') [`or'] command computes the bitwise inclusive
  262. OR of two numbers. A bit is 1 if either of the input bits, or both,
  263. are 1: `or(2#1100, 2#1010) = 2#1110'.
  264. The `b x' (`calc-xor') [`xor'] command computes the bitwise
  265. exclusive OR of two numbers. A bit is 1 if exactly one of the input
  266. bits is 1: `xor(2#1100, 2#1010) = 2#0110'.
  267. The `b d' (`calc-diff') [`diff'] command computes the bitwise
  268. difference of two numbers; this is defined by `diff(a,b) =
  269. and(a,not(b))', so that `diff(2#1100, 2#1010) = 2#0100'.
  270. The `b n' (`calc-not') [`not'] command computes the bitwise NOT of a
  271. number. A bit is 1 if the input bit is 0 and vice-versa.
  272. The `b l' (`calc-lshift-binary') [`lsh'] command shifts a number
  273. left by one bit, or by the number of bits specified in the numeric
  274. prefix argument. A negative prefix argument performs a logical right
  275. shift, in which zeros are shifted in on the left. In symbolic form,
  276. `lsh(a)' is short for `lsh(a,1)', which in turn is short for
  277. `lsh(a,n,w)'. Bits shifted "off the end," according to the current
  278. word size, are lost.
  279. The `H b l' command also does a left shift, but it takes two
  280. arguments from the stack (the value to shift, and, at top-of-stack, the
  281. number of bits to shift). This version interprets the prefix argument
  282. just like the regular binary operations, i.e., as a word size. The
  283. Hyperbolic flag has a similar effect on the rest of the binary shift
  284. and rotate commands.
  285. The `b r' (`calc-rshift-binary') [`rsh'] command shifts a number
  286. right by one bit, or by the number of bits specified in the numeric
  287. prefix argument: `rsh(a,n) = lsh(a,-n)'.
  288. The `b L' (`calc-lshift-arith') [`ash'] command shifts a number
  289. left. It is analogous to `lsh', except that if the shift is rightward
  290. (the prefix argument is negative), an arithmetic shift is performed as
  291. described below.
  292. The `b R' (`calc-rshift-arith') [`rash'] command performs an
  293. "arithmetic" shift to the right, in which the leftmost bit (according
  294. to the current word size) is duplicated rather than shifting in zeros.
  295. This corresponds to dividing by a power of two where the input is
  296. interpreted as a signed, twos-complement number. (The distinction
  297. between the `rsh' and `rash' operations is totally independent from
  298. whether the word size is positive or negative.) With a negative prefix
  299. argument, this performs a standard left shift.
  300. The `b t' (`calc-rotate-binary') [`rot'] command rotates a number
  301. one bit to the left. The leftmost bit (according to the current word
  302. size) is dropped off the left and shifted in on the right. With a
  303. numeric prefix argument, the number is rotated that many bits to the
  304. left or right.
  305. *Note Set Operations::, for the `b p' and `b u' commands that pack
  306. and unpack binary integers into sets. (For example, `b u' unpacks the
  307. number `2#11001' to the set of bit-numbers `[0, 3, 4]'.) Type `b u V
  308. #' to count the number of "1" bits in a binary integer.
  309. Another interesting use of the set representation of binary integers
  310. is to reverse the bits in, say, a 32-bit integer. Type `b u' to
  311. unpack; type `31 <TAB> -' to replace each bit-number in the set with 31
  312. minus that bit-number; type `b p' to pack the set back into a binary
  313. integer.
  314. 
  315. File: calc, Node: Scientific Functions, Next: Matrix Functions, Prev: Arithmetic, Up: Top
  316. 10 Scientific Functions
  317. ***********************
  318. The functions described here perform trigonometric and other
  319. transcendental calculations. They generally produce floating-point
  320. answers correct to the full current precision. The `H' (Hyperbolic)
  321. and `I' (Inverse) flag keys must be used to get some of these functions
  322. from the keyboard.
  323. One miscellaneous command is shift-`P' (`calc-pi'), which pushes the
  324. value of `pi' (at the current precision) onto the stack. With the
  325. Hyperbolic flag, it pushes the value `e', the base of natural
  326. logarithms. With the Inverse flag, it pushes Euler's constant `gamma'
  327. (about 0.5772). With both Inverse and Hyperbolic, it pushes the
  328. "golden ratio" `phi' (about 1.618). (At present, Euler's constant is
  329. not available to unlimited precision; Calc knows only the first 100
  330. digits.) In Symbolic mode, these commands push the actual variables
  331. `pi', `e', `gamma', and `phi', respectively, instead of their values;
  332. *note Symbolic Mode::.
  333. The `Q' (`calc-sqrt') [`sqrt'] function is described elsewhere;
  334. *note Basic Arithmetic::. With the Inverse flag [`sqr'], this command
  335. computes the square of the argument.
  336. *Note Prefix Arguments::, for a discussion of the effect of numeric
  337. prefix arguments on commands in this chapter which do not otherwise
  338. interpret a prefix argument.
  339. * Menu:
  340. * Logarithmic Functions::
  341. * Trigonometric and Hyperbolic Functions::
  342. * Advanced Math Functions::
  343. * Branch Cuts::
  344. * Random Numbers::
  345. * Combinatorial Functions::
  346. * Probability Distribution Functions::
  347. 
  348. File: calc, Node: Logarithmic Functions, Next: Trigonometric and Hyperbolic Functions, Prev: Scientific Functions, Up: Scientific Functions
  349. 10.1 Logarithmic Functions
  350. ==========================
  351. The shift-`L' (`calc-ln') [`ln'] command computes the natural logarithm
  352. of the real or complex number on the top of the stack. With the
  353. Inverse flag it computes the exponential function instead, although
  354. this is redundant with the `E' command.
  355. The shift-`E' (`calc-exp') [`exp'] command computes the exponential,
  356. i.e., `e' raised to the power of the number on the stack. The meanings
  357. of the Inverse and Hyperbolic flags follow from those for the `calc-ln'
  358. command.
  359. The `H L' (`calc-log10') [`log10'] command computes the common
  360. (base-10) logarithm of a number. (With the Inverse flag [`exp10'], it
  361. raises ten to a given power.) Note that the common logarithm of a
  362. complex number is computed by taking the natural logarithm and dividing
  363. by `ln(10)'.
  364. The `B' (`calc-log') [`log'] command computes a logarithm to any
  365. base. For example, `1024 <RET> 2 B' produces 10, since `2^10 = 1024'.
  366. In certain cases like `log(3,9)', the result will be either `1:2' or
  367. `0.5' depending on the current Fraction mode setting. With the Inverse
  368. flag [`alog'], this command is similar to `^' except that the order of
  369. the arguments is reversed.
  370. The `f I' (`calc-ilog') [`ilog'] command computes the integer
  371. logarithm of a number to any base. The number and the base must
  372. themselves be positive integers. This is the true logarithm, rounded
  373. down to an integer. Thus `ilog(x,10)' is 3 for all `x' in the range
  374. from 1000 to 9999. If both arguments are positive integers, exact
  375. integer arithmetic is used; otherwise, this is equivalent to
  376. `floor(log(x,b))'.
  377. The `f E' (`calc-expm1') [`expm1'] command computes `exp(x)-1', but
  378. using an algorithm that produces a more accurate answer when the result
  379. is close to zero, i.e., when `exp(x)' is close to one.
  380. The `f L' (`calc-lnp1') [`lnp1'] command computes `ln(x+1)',
  381. producing a more accurate answer when `x' is close to zero.
  382. 
  383. File: calc, Node: Trigonometric and Hyperbolic Functions, Next: Advanced Math Functions, Prev: Logarithmic Functions, Up: Scientific Functions
  384. 10.2 Trigonometric/Hyperbolic Functions
  385. =======================================
  386. The shift-`S' (`calc-sin') [`sin'] command computes the sine of an
  387. angle or complex number. If the input is an HMS form, it is interpreted
  388. as degrees-minutes-seconds; otherwise, the input is interpreted
  389. according to the current angular mode. It is best to use Radians mode
  390. when operating on complex numbers.
  391. Calc's "units" mechanism includes angular units like `deg', `rad',
  392. and `grad'. While `sin(45 deg)' is not evaluated all the time, the `u
  393. s' (`calc-simplify-units') command will simplify `sin(45 deg)' by
  394. taking the sine of 45 degrees, regardless of the current angular mode.
  395. *Note Basic Operations on Units::.
  396. Also, the symbolic variable `pi' is not ordinarily recognized in
  397. arguments to trigonometric functions, as in `sin(3 pi / 4)', but the `a
  398. s' (`calc-simplify') command recognizes many such formulas when the
  399. current angular mode is Radians _and_ Symbolic mode is enabled; this
  400. example would be replaced by `sqrt(2) / 2'. *Note Symbolic Mode::.
  401. Beware, this simplification occurs even if you have stored a different
  402. value in the variable `pi'; this is one reason why changing built-in
  403. variables is a bad idea. Arguments of the form `x' plus a multiple of
  404. `pi/2' are also simplified. Calc includes similar formulas for `cos'
  405. and `tan'.
  406. The `a s' command knows all angles which are integer multiples of
  407. `pi/12', `pi/10', or `pi/8' radians. In Degrees mode, analogous
  408. simplifications occur for integer multiples of 15 or 18 degrees, and
  409. for arguments plus multiples of 90 degrees.
  410. With the Inverse flag, `calc-sin' computes an arcsine. This is also
  411. available as the `calc-arcsin' command or `arcsin' algebraic function.
  412. The returned argument is converted to degrees, radians, or HMS notation
  413. depending on the current angular mode.
  414. With the Hyperbolic flag, `calc-sin' computes the hyperbolic sine,
  415. also available as `calc-sinh' [`sinh']. With the Hyperbolic and
  416. Inverse flags, it computes the hyperbolic arcsine (`calc-arcsinh')
  417. [`arcsinh'].
  418. The shift-`C' (`calc-cos') [`cos'] command computes the cosine of an
  419. angle or complex number, and shift-`T' (`calc-tan') [`tan'] computes
  420. the tangent, along with all the various inverse and hyperbolic variants
  421. of these functions.
  422. The `f T' (`calc-arctan2') [`arctan2'] command takes two numbers
  423. from the stack and computes the arc tangent of their ratio. The result
  424. is in the full range from -180 (exclusive) to +180 (inclusive) degrees,
  425. or the analogous range in radians. A similar result would be obtained
  426. with `/' followed by `I T', but the value would only be in the range
  427. from -90 to +90 degrees since the division loses information about the
  428. signs of the two components, and an error might result from an explicit
  429. division by zero which `arctan2' would avoid. By (arbitrary)
  430. definition, `arctan2(0,0)=0'.
  431. The `calc-sincos' [`sincos'] command computes the sine and cosine of
  432. a number, returning them as a vector of the form `[COS, SIN]'. With
  433. the Inverse flag [`arcsincos'], this command takes a two-element vector
  434. as an argument and computes `arctan2' of the elements. (This command
  435. does not accept the Hyperbolic flag.)
  436. The remaining trigonometric functions, `calc-sec' [`sec'],
  437. `calc-csc' [`csc'] and `calc-cot' [`cot'], are also available. With
  438. the Hyperbolic flag, these compute their hyperbolic counterparts, which
  439. are also available separately as `calc-sech' [`sech'], `calc-csch'
  440. [`csch'] and `calc-coth' [`coth']. (These commands do not accept the
  441. Inverse flag.)
  442. 
  443. File: calc, Node: Advanced Math Functions, Next: Branch Cuts, Prev: Trigonometric and Hyperbolic Functions, Up: Scientific Functions
  444. 10.3 Advanced Mathematical Functions
  445. ====================================
  446. Calc can compute a variety of less common functions that arise in
  447. various branches of mathematics. All of the functions described in
  448. this section allow arbitrary complex arguments and, except as noted,
  449. will work to arbitrarily large precision. They can not at present
  450. handle error forms or intervals as arguments.
  451. NOTE: These functions are still experimental. In particular, their
  452. accuracy is not guaranteed in all domains. It is advisable to set the
  453. current precision comfortably higher than you actually need when using
  454. these functions. Also, these functions may be impractically slow for
  455. some values of the arguments.
  456. The `f g' (`calc-gamma') [`gamma'] command computes the Euler gamma
  457. function. For positive integer arguments, this is related to the
  458. factorial function: `gamma(n+1) = fact(n)'. For general complex
  459. arguments the gamma function can be defined by the following definite
  460. integral: `gamma(a) = integ(t^(a-1) exp(t), t, 0, inf)'. (The actual
  461. implementation uses far more efficient computational methods.)
  462. The `f G' (`calc-inc-gamma') [`gammaP'] command computes the
  463. incomplete gamma function, denoted `P(a,x)'. This is defined by the
  464. integral, `gammaP(a,x) = integ(t^(a-1) exp(t), t, 0, x) / gamma(a)'.
  465. This implies that `gammaP(a,inf) = 1' for any `a' (see the definition
  466. of the normal gamma function).
  467. Several other varieties of incomplete gamma function are defined.
  468. The complement of `P(a,x)', called `Q(a,x) = 1-P(a,x)' by some authors,
  469. is computed by the `I f G' [`gammaQ'] command. You can think of this
  470. as taking the other half of the integral, from `x' to infinity.
  471. The functions corresponding to the integrals that define `P(a,x)'
  472. and `Q(a,x)' but without the normalizing `1/gamma(a)' factor are called
  473. `g(a,x)' and `G(a,x)', respectively (where `g' and `G' represent the
  474. lower- and upper-case Greek letter gamma). You can obtain these using
  475. the `H f G' [`gammag'] and `H I f G' [`gammaG'] commands.
  476. The `f b' (`calc-beta') [`beta'] command computes the Euler beta
  477. function, which is defined in terms of the gamma function as `beta(a,b)
  478. = gamma(a) gamma(b) / gamma(a+b)', or by `beta(a,b) = integ(t^(a-1)
  479. (1-t)^(b-1), t, 0, 1)'.
  480. The `f B' (`calc-inc-beta') [`betaI'] command computes the
  481. incomplete beta function `I(x,a,b)'. It is defined by `betaI(x,a,b) =
  482. integ(t^(a-1) (1-t)^(b-1), t, 0, x) / beta(a,b)'. Once again, the `H'
  483. (hyperbolic) prefix gives the corresponding un-normalized version
  484. [`betaB'].
  485. The `f e' (`calc-erf') [`erf'] command computes the error function
  486. `erf(x) = 2 integ(exp(-(t^2)), t, 0, x) / sqrt(pi)'. The complementary
  487. error function `I f e' (`calc-erfc') [`erfc'] is the corresponding
  488. integral from `x' to infinity; the sum `erf(x) + erfc(x) = 1'.
  489. The `f j' (`calc-bessel-J') [`besJ'] and `f y' (`calc-bessel-Y')
  490. [`besY'] commands compute the Bessel functions of the first and second
  491. kinds, respectively. In `besJ(n,x)' and `besY(n,x)' the "order"
  492. parameter `n' is often an integer, but is not required to be one.
  493. Calc's implementation of the Bessel functions currently limits the
  494. precision to 8 digits, and may not be exact even to that precision.
  495. Use with care!
  496. 
  497. File: calc, Node: Branch Cuts, Next: Random Numbers, Prev: Advanced Math Functions, Up: Scientific Functions
  498. 10.4 Branch Cuts and Principal Values
  499. =====================================
  500. All of the logarithmic, trigonometric, and other scientific functions
  501. are defined for complex numbers as well as for reals. This section
  502. describes the values returned in cases where the general result is a
  503. family of possible values. Calc follows section 12.5.3 of Steele's
  504. "Common Lisp, the Language", second edition, in these matters. This
  505. section will describe each function briefly; for a more detailed
  506. discussion (including some nifty diagrams), consult Steele's book.
  507. Note that the branch cuts for `arctan' and `arctanh' were changed
  508. between the first and second editions of Steele. Recent versions of
  509. Calc follow the second edition.
  510. The new branch cuts exactly match those of the HP-28/48 calculators.
  511. They also match those of Mathematica 1.2, except that Mathematica's
  512. `arctan' cut is always in the right half of the complex plane, and its
  513. `arctanh' cut is always in the top half of the plane. Calc's cuts are
  514. continuous with quadrants I and III for `arctan', or II and IV for
  515. `arctanh'.
  516. Note: The current implementations of these functions with complex
  517. arguments are designed with proper behavior around the branch cuts in
  518. mind, _not_ efficiency or accuracy. You may need to increase the
  519. floating precision and wait a while to get suitable answers from them.
  520. For `sqrt(a+bi)': When `a<0' and `b' is small but positive or zero,
  521. the result is close to the `+i' axis. For `b' small and negative, the
  522. result is close to the `-i' axis. The result always lies in the right
  523. half of the complex plane.
  524. For `ln(a+bi)': The real part is defined as `ln(abs(a+bi))'. The
  525. imaginary part is defined as `arg(a+bi) = arctan2(b,a)'. Thus the
  526. branch cuts for `sqrt' and `ln' both lie on the negative real axis.
  527. The following table describes these branch cuts in another way. If
  528. the real and imaginary parts of `z' are as shown, then the real and
  529. imaginary parts of `f(z)' will be as shown. Here `eps' stands for a
  530. small positive value; each occurrence of `eps' may stand for a
  531. different small value.
  532. z sqrt(z) ln(z)
  533. ----------------------------------------
  534. +, 0 +, 0 any, 0
  535. -, 0 0, + any, pi
  536. -, +eps +eps, + +eps, +
  537. -, -eps +eps, - +eps, -
  538. For `z1^z2': This is defined by `exp(ln(z1)*z2)'. One interesting
  539. consequence of this is that `(-8)^1:3' does not evaluate to -2 as you
  540. might expect, but to the complex number `(1., 1.732)'. Both of these
  541. are valid cube roots of -8 (as is `(1., -1.732)'); Calc chooses a
  542. perhaps less-obvious root for the sake of mathematical consistency.
  543. For `arcsin(z)': This is defined by `-i*ln(i*z + sqrt(1-z^2))'.
  544. The branch cuts are on the real axis, less than -1 and greater than 1.
  545. For `arccos(z)': This is defined by `-i*ln(z + i*sqrt(1-z^2))', or
  546. equivalently by `pi/2 - arcsin(z)'. The branch cuts are on the real
  547. axis, less than -1 and greater than 1.
  548. For `arctan(z)': This is defined by `(ln(1+i*z) - ln(1-i*z)) /
  549. (2*i)'. The branch cuts are on the imaginary axis, below `-i' and
  550. above `i'.
  551. For `arcsinh(z)': This is defined by `ln(z + sqrt(1+z^2))'. The
  552. branch cuts are on the imaginary axis, below `-i' and above `i'.
  553. For `arccosh(z)': This is defined by `ln(z +
  554. (z+1)*sqrt((z-1)/(z+1)))'. The branch cut is on the real axis less
  555. than 1.
  556. For `arctanh(z)': This is defined by `(ln(1+z) - ln(1-z)) / 2'.
  557. The branch cuts are on the real axis, less than -1 and greater than 1.
  558. The following tables for `arcsin', `arccos', and `arctan' assume the
  559. current angular mode is Radians. The hyperbolic functions operate
  560. independently of the angular mode.
  561. z arcsin(z) arccos(z)
  562. -------------------------------------------------------
  563. (-1..1), 0 (-pi/2..pi/2), 0 (0..pi), 0
  564. (-1..1), +eps (-pi/2..pi/2), +eps (0..pi), -eps
  565. (-1..1), -eps (-pi/2..pi/2), -eps (0..pi), +eps
  566. <-1, 0 -pi/2, + pi, -
  567. <-1, +eps -pi/2 + eps, + pi - eps, -
  568. <-1, -eps -pi/2 + eps, - pi - eps, +
  569. >1, 0 pi/2, - 0, +
  570. >1, +eps pi/2 - eps, + +eps, -
  571. >1, -eps pi/2 - eps, - +eps, +
  572. z arccosh(z) arctanh(z)
  573. -----------------------------------------------------
  574. (-1..1), 0 0, (0..pi) any, 0
  575. (-1..1), +eps +eps, (0..pi) any, +eps
  576. (-1..1), -eps +eps, (-pi..0) any, -eps
  577. <-1, 0 +, pi -, pi/2
  578. <-1, +eps +, pi - eps -, pi/2 - eps
  579. <-1, -eps +, -pi + eps -, -pi/2 + eps
  580. >1, 0 +, 0 +, -pi/2
  581. >1, +eps +, +eps +, pi/2 - eps
  582. >1, -eps +, -eps +, -pi/2 + eps
  583. z arcsinh(z) arctan(z)
  584. -----------------------------------------------------
  585. 0, (-1..1) 0, (-pi/2..pi/2) 0, any
  586. 0, <-1 -, -pi/2 -pi/2, -
  587. +eps, <-1 +, -pi/2 + eps pi/2 - eps, -
  588. -eps, <-1 -, -pi/2 + eps -pi/2 + eps, -
  589. 0, >1 +, pi/2 pi/2, +
  590. +eps, >1 +, pi/2 - eps pi/2 - eps, +
  591. -eps, >1 -, pi/2 - eps -pi/2 + eps, +
  592. Finally, the following identities help to illustrate the relationship
  593. between the complex trigonometric and hyperbolic functions. They are
  594. valid everywhere, including on the branch cuts.
  595. sin(i*z) = i*sinh(z) arcsin(i*z) = i*arcsinh(z)
  596. cos(i*z) = cosh(z) arcsinh(i*z) = i*arcsin(z)
  597. tan(i*z) = i*tanh(z) arctan(i*z) = i*arctanh(z)
  598. sinh(i*z) = i*sin(z) cosh(i*z) = cos(z)
  599. The "advanced math" functions (gamma, Bessel, etc.) are also defined
  600. for general complex arguments, but their branch cuts and principal
  601. values are not rigorously specified at present.
  602. 
  603. File: calc, Node: Random Numbers, Next: Combinatorial Functions, Prev: Branch Cuts, Up: Scientific Functions
  604. 10.5 Random Numbers
  605. ===================
  606. The `k r' (`calc-random') [`random'] command produces random numbers of
  607. various sorts.
  608. Given a positive numeric prefix argument `M', it produces a random
  609. integer `N' in the range `0 <= N < M'. Each possible value `N' appears
  610. with equal probability.
  611. With no numeric prefix argument, the `k r' command takes its argument
  612. from the stack instead. Once again, if this is a positive integer `M'
  613. the result is a random integer less than `M'. However, note that while
  614. numeric prefix arguments are limited to six digits or so, an `M' taken
  615. from the stack can be arbitrarily large. If `M' is negative, the
  616. result is a random integer in the range `M < N <= 0'.
  617. If the value on the stack is a floating-point number `M', the result
  618. is a random floating-point number `N' in the range `0 <= N < M' or `M <
  619. N <= 0', according to the sign of `M'.
  620. If `M' is zero, the result is a Gaussian-distributed random real
  621. number; the distribution has a mean of zero and a standard deviation of
  622. one. The algorithm used generates random numbers in pairs; thus, every
  623. other call to this function will be especially fast.
  624. If `M' is an error form `m +/- s' where M and S are both real
  625. numbers, the result uses a Gaussian distribution with mean M and
  626. standard deviation S.
  627. If `M' is an interval form, the lower and upper bounds specify the
  628. acceptable limits of the random numbers. If both bounds are integers,
  629. the result is a random integer in the specified range. If either bound
  630. is floating-point, the result is a random real number in the specified
  631. range. If the interval is open at either end, the result will be sure
  632. not to equal that end value. (This makes a big difference for integer
  633. intervals, but for floating-point intervals it's relatively minor: with
  634. a precision of 6, `random([1.0..2.0))' will return any of one million
  635. numbers from 1.00000 to 1.99999; `random([1.0..2.0])' may additionally
  636. return 2.00000, but the probability of this happening is extremely
  637. small.)
  638. If `M' is a vector, the result is one element taken at random from
  639. the vector. All elements of the vector are given equal probabilities.
  640. The sequence of numbers produced by `k r' is completely random by
  641. default, i.e., the sequence is seeded each time you start Calc using
  642. the current time and other information. You can get a reproducible
  643. sequence by storing a particular "seed value" in the Calc variable
  644. `RandSeed'. Any integer will do for a seed; integers of from 1 to 12
  645. digits are good. If you later store a different integer into
  646. `RandSeed', Calc will switch to a different pseudo-random sequence. If
  647. you "unstore" `RandSeed', Calc will re-seed itself from the current
  648. time. If you store the same integer that you used before back into
  649. `RandSeed', you will get the exact same sequence of random numbers as
  650. before.
  651. The `calc-rrandom' command (not on any key) produces a random real
  652. number between zero and one. It is equivalent to `random(1.0)'.
  653. The `k a' (`calc-random-again') command produces another random
  654. number, re-using the most recent value of `M'. With a numeric prefix
  655. argument N, it produces N more random numbers using that value of `M'.
  656. The `k h' (`calc-shuffle') command produces a vector of several
  657. random values with no duplicates. The value on the top of the stack
  658. specifies the set from which the random values are drawn, and may be any
  659. of the `M' formats described above. The numeric prefix argument gives
  660. the length of the desired list. (If you do not provide a numeric
  661. prefix argument, the length of the list is taken from the top of the
  662. stack, and `M' from second-to-top.)
  663. If `M' is a floating-point number, zero, or an error form (so that
  664. the random values are being drawn from the set of real numbers) there
  665. is little practical difference between using `k h' and using `k r'
  666. several times. But if the set of possible values consists of just a
  667. few integers, or the elements of a vector, then there is a very real
  668. chance that multiple `k r''s will produce the same number more than
  669. once. The `k h' command produces a vector whose elements are always
  670. distinct. (Actually, there is a slight exception: If `M' is a vector,
  671. no given vector element will be drawn more than once, but if several
  672. elements of `M' are equal, they may each make it into the result
  673. vector.)
  674. One use of `k h' is to rearrange a list at random. This happens if
  675. the prefix argument is equal to the number of values in the list: `[1,
  676. 1.5, 2, 2.5, 3] 5 k h' might produce the permuted list `[2.5, 1, 1.5,
  677. 3, 2]'. As a convenient feature, if the argument N is negative it is
  678. replaced by the size of the set represented by `M'. Naturally, this is
  679. allowed only when `M' specifies a small discrete set of possibilities.
  680. To do the equivalent of `k h' but with duplications allowed, given
  681. `M' on the stack and with N just entered as a numeric prefix, use `v b'
  682. to build a vector of copies of `M', then use `V M k r' to "map" the
  683. normal `k r' function over the elements of this vector. *Note Matrix
  684. Functions::.
  685. * Menu:
  686. * Random Number Generator:: (Complete description of Calc's algorithm)
  687. 
  688. File: calc, Node: Random Number Generator, Prev: Random Numbers, Up: Random Numbers
  689. 10.5.1 Random Number Generator
  690. ------------------------------
  691. Calc's random number generator uses several methods to ensure that the
  692. numbers it produces are highly random. Knuth's _Art of Computer
  693. Programming_, Volume II, contains a thorough description of the theory
  694. of random number generators and their measurement and characterization.
  695. If `RandSeed' has no stored value, Calc calls Emacs's built-in
  696. `random' function to get a stream of random numbers, which it then
  697. treats in various ways to avoid problems inherent in the simple random
  698. number generators that many systems use to implement `random'.
  699. When Calc's random number generator is first invoked, it "seeds" the
  700. low-level random sequence using the time of day, so that the random
  701. number sequence will be different every time you use Calc.
  702. Since Emacs Lisp doesn't specify the range of values that will be
  703. returned by its `random' function, Calc exercises the function several
  704. times to estimate the range. When Calc subsequently uses the `random'
  705. function, it takes only 10 bits of the result near the most-significant
  706. end. (It avoids at least the bottom four bits, preferably more, and
  707. also tries to avoid the top two bits.) This strategy works well with
  708. the linear congruential generators that are typically used to implement
  709. `random'.
  710. If `RandSeed' contains an integer, Calc uses this integer to seed an
  711. "additive congruential" method (Knuth's algorithm 3.2.2A, computing
  712. `X_n-55 - X_n-24'). This method expands the seed value into a large
  713. table which is maintained internally; the variable `RandSeed' is
  714. changed from, e.g., 42 to the vector `[42]' to indicate that the seed
  715. has been absorbed into this table. When `RandSeed' contains a vector,
  716. `k r' and related commands continue to use the same internal table as
  717. last time. There is no way to extract the complete state of the random
  718. number generator so that you can restart it from any point; you can
  719. only restart it from the same initial seed value. A simple way to
  720. restart from the same seed is to type `s r RandSeed' to get the seed
  721. vector, `v u' to unpack it back into a number, then `s t RandSeed' to
  722. reseed the generator with that number.
  723. Calc uses a "shuffling" method as described in algorithm 3.2.2B of
  724. Knuth. It fills a table with 13 random 10-bit numbers. Then, to
  725. generate a new random number, it uses the previous number to index into
  726. the table, picks the value it finds there as the new random number,
  727. then replaces that table entry with a new value obtained from a call to
  728. the base random number generator (either the additive congruential
  729. generator or the `random' function supplied by the system). If there
  730. are any flaws in the base generator, shuffling will tend to even them
  731. out. But if the system provides an excellent `random' function,
  732. shuffling will not damage its randomness.
  733. To create a random integer of a certain number of digits, Calc
  734. builds the integer three decimal digits at a time. For each group of
  735. three digits, Calc calls its 10-bit shuffling random number generator
  736. (which returns a value from 0 to 1023); if the random value is 1000 or
  737. more, Calc throws it out and tries again until it gets a suitable value.
  738. To create a random floating-point number with precision P, Calc
  739. simply creates a random P-digit integer and multiplies by `10^-p'. The
  740. resulting random numbers should be very clean, but note that relatively
  741. small numbers will have few significant random digits. In other words,
  742. with a precision of 12, you will occasionally get numbers on the order
  743. of `10^-9' or `10^-10', but those numbers will only have two or three
  744. random digits since they correspond to small integers times `10^-12'.
  745. To create a random integer in the interval `[0 .. M)', Calc counts
  746. the digits in M, creates a random integer with three additional digits,
  747. then reduces modulo M. Unless M is a power of ten the resulting values
  748. will be very slightly biased toward the lower numbers, but this bias
  749. will be less than 0.1%. (For example, if M is 42, Calc will reduce a
  750. random integer less than 100000 modulo 42 to get a result less than 42.
  751. It is easy to show that the numbers 40 and 41 will be only 2380/2381 as
  752. likely to result from this modulo operation as numbers 39 and below.)
  753. If M is a power of ten, however, the numbers should be completely
  754. unbiased.
  755. The Gaussian random numbers generated by `random(0.0)' use the
  756. "polar" method described in Knuth section 3.4.1C. This method
  757. generates a pair of Gaussian random numbers at a time, so only every
  758. other call to `random(0.0)' will require significant calculations.
  759. 
  760. File: calc, Node: Combinatorial Functions, Next: Probability Distribution Functions, Prev: Random Numbers, Up: Scientific Functions
  761. 10.6 Combinatorial Functions
  762. ============================
  763. Commands relating to combinatorics and number theory begin with the `k'
  764. key prefix.
  765. The `k g' (`calc-gcd') [`gcd'] command computes the Greatest Common
  766. Divisor of two integers. It also accepts fractions; the GCD of two
  767. fractions is defined by taking the GCD of the numerators, and the LCM
  768. of the denominators. This definition is consistent with the idea that
  769. `a / gcd(a,x)' should yield an integer for any `a' and `x'. For other
  770. types of arguments, the operation is left in symbolic form.
  771. The `k l' (`calc-lcm') [`lcm'] command computes the Least Common
  772. Multiple of two integers or fractions. The product of the LCM and GCD
  773. of two numbers is equal to the product of the numbers.
  774. The `k E' (`calc-extended-gcd') [`egcd'] command computes the GCD of
  775. two integers `x' and `y' and returns a vector `[g, a, b]' where `g =
  776. gcd(x,y) = a x + b y'.
  777. The `!' (`calc-factorial') [`fact'] command computes the factorial
  778. of the number at the top of the stack. If the number is an integer,
  779. the result is an exact integer. If the number is an integer-valued
  780. float, the result is a floating-point approximation. If the number is
  781. a non-integral real number, the generalized factorial is used, as
  782. defined by the Euler Gamma function. Please note that computation of
  783. large factorials can be slow; using floating-point format will help
  784. since fewer digits must be maintained. The same is true of many of the
  785. commands in this section.
  786. The `k d' (`calc-double-factorial') [`dfact'] command computes the
  787. "double factorial" of an integer. For an even integer, this is the
  788. product of even integers from 2 to `N'. For an odd integer, this is
  789. the product of odd integers from 3 to `N'. If the argument is an
  790. integer-valued float, the result is a floating-point approximation.
  791. This function is undefined for negative even integers. The notation
  792. `N!!' is also recognized for double factorials.
  793. The `k c' (`calc-choose') [`choose'] command computes the binomial
  794. coefficient `N'-choose-`M', where `M' is the number on the top of the
  795. stack and `N' is second-to-top. If both arguments are integers, the
  796. result is an exact integer. Otherwise, the result is a floating-point
  797. approximation. The binomial coefficient is defined for all real
  798. numbers by `N! / M! (N-M)!'.
  799. The `H k c' (`calc-perm') [`perm'] command computes the
  800. number-of-permutations function `N! / (N-M)!'.
  801. The `k b' (`calc-bernoulli-number') [`bern'] command computes a
  802. given Bernoulli number. The value at the top of the stack is a
  803. nonnegative integer `n' that specifies which Bernoulli number is
  804. desired. The `H k b' command computes a Bernoulli polynomial, taking
  805. `n' from the second-to-top position and `x' from the top of the stack.
  806. If `x' is a variable or formula the result is a polynomial in `x'; if
  807. `x' is a number the result is a number.
  808. The `k e' (`calc-euler-number') [`euler'] command similarly computes
  809. an Euler number, and `H k e' computes an Euler polynomial. Bernoulli
  810. and Euler numbers occur in the Taylor expansions of several functions.
  811. The `k s' (`calc-stirling-number') [`stir1'] command computes a
  812. Stirling number of the first kind, given two integers `n' and `m' on
  813. the stack. The `H k s' [`stir2'] command computes a Stirling number of
  814. the second kind. These are the number of `m'-cycle permutations of `n'
  815. objects, and the number of ways to partition `n' objects into `m'
  816. non-empty sets, respectively.
  817. The `k p' (`calc-prime-test') command checks if the integer on the
  818. top of the stack is prime. For integers less than eight million, the
  819. answer is always exact and reasonably fast. For larger integers, a
  820. probabilistic method is used (see Knuth vol. II, section 4.5.4,
  821. algorithm P). The number is first checked against small prime factors
  822. (up to 13). Then, any number of iterations of the algorithm are
  823. performed. Each step either discovers that the number is non-prime, or
  824. substantially increases the certainty that the number is prime. After
  825. a few steps, the chance that a number was mistakenly described as prime
  826. will be less than one percent. (Indeed, this is a worst-case estimate
  827. of the probability; in practice even a single iteration is quite
  828. reliable.) After the `k p' command, the number will be reported as
  829. definitely prime or non-prime if possible, or otherwise "probably"
  830. prime with a certain probability of error.
  831. The normal `k p' command performs one iteration of the primality
  832. test. Pressing `k p' repeatedly for the same integer will perform
  833. additional iterations. Also, `k p' with a numeric prefix performs the
  834. specified number of iterations. There is also an algebraic function
  835. `prime(n)' or `prime(n,iters)' which returns 1 if `n' is (probably)
  836. prime and 0 if not.
  837. The `k f' (`calc-prime-factors') [`prfac'] command attempts to
  838. decompose an integer into its prime factors. For numbers up to 25
  839. million, the answer is exact although it may take some time. The
  840. result is a vector of the prime factors in increasing order. For larger
  841. inputs, prime factors above 5000 may not be found, in which case the
  842. last number in the vector will be an unfactored integer greater than 25
  843. million (with a warning message). For negative integers, the first
  844. element of the list will be -1. For inputs -1, 0, and 1, the result is
  845. a list of the same number.
  846. The `k n' (`calc-next-prime') [`nextprime'] command finds the next
  847. prime above a given number. Essentially, it searches by calling
  848. `calc-prime-test' on successive integers until it finds one that passes
  849. the test. This is quite fast for integers less than eight million, but
  850. once the probabilistic test comes into play the search may be rather
  851. slow. Ordinarily this command stops for any prime that passes one
  852. iteration of the primality test. With a numeric prefix argument, a
  853. number must pass the specified number of iterations before the search
  854. stops. (This only matters when searching above eight million.) You
  855. can always use additional `k p' commands to increase your certainty
  856. that the number is indeed prime.
  857. The `I k n' (`calc-prev-prime') [`prevprime'] command analogously
  858. finds the next prime less than a given number.
  859. The `k t' (`calc-totient') [`totient'] command computes the Euler
  860. "totient" function, the number of integers less than `n' which are
  861. relatively prime to `n'.
  862. The `k m' (`calc-moebius') [`moebius'] command computes the Moebius
  863. "mu" function. If the input number is a product of `k' distinct
  864. factors, this is `(-1)^k'. If the input number has any duplicate
  865. factors (i.e., can be divided by the same prime more than once), the
  866. result is zero.
  867. 
  868. File: calc, Node: Probability Distribution Functions, Prev: Combinatorial Functions, Up: Scientific Functions
  869. 10.7 Probability Distribution Functions
  870. =======================================
  871. The functions in this section compute various probability distributions.
  872. For continuous distributions, this is the integral of the probability
  873. density function from `x' to infinity. (These are the "upper tail"
  874. distribution functions; there are also corresponding "lower tail"
  875. functions which integrate from minus infinity to `x'.) For discrete
  876. distributions, the upper tail function gives the sum from `x' to
  877. infinity; the lower tail function gives the sum from minus infinity up
  878. to, but not including, `x'.
  879. To integrate from `x' to `y', just use the distribution function
  880. twice and subtract. For example, the probability that a Gaussian
  881. random variable with mean 2 and standard deviation 1 will lie in the
  882. range from 2.5 to 2.8 is `utpn(2.5,2,1) - utpn(2.8,2,1)' ("the
  883. probability that it is greater than 2.5, but not greater than 2.8"), or
  884. equivalently `ltpn(2.8,2,1) - ltpn(2.5,2,1)'.
  885. The `k B' (`calc-utpb') [`utpb'] function uses the binomial
  886. distribution. Push the parameters N, P, and then X onto the stack; the
  887. result (`utpb(x,n,p)') is the probability that an event will occur X or
  888. more times out of N trials, if its probability of occurring in any given
  889. trial is P. The `I k B' [`ltpb'] function is the probability that the
  890. event will occur fewer than X times.
  891. The other probability distribution functions similarly take the form
  892. `k X' (`calc-utpX') [`utpX'] and `I k X' [`ltpX'], for various letters
  893. X. The arguments to the algebraic functions are the value of the
  894. random variable first, then whatever other parameters define the
  895. distribution. Note these are among the few Calc functions where the
  896. order of the arguments in algebraic form differs from the order of
  897. arguments as found on the stack. (The random variable comes last on
  898. the stack, so that you can type, e.g., `2 <RET> 1 <RET> 2.5 k N M-<RET>
  899. <DEL> 2.8 k N -', using `M-<RET> <DEL>' to recover the original
  900. arguments but substitute a new value for `x'.)
  901. The `utpc(x,v)' function uses the chi-square distribution with `v'
  902. degrees of freedom. It is the probability that a model is correct if
  903. its chi-square statistic is `x'.
  904. The `utpf(F,v1,v2)' function uses the F distribution, used in
  905. various statistical tests. The parameters `v1' and `v2' are the
  906. degrees of freedom in the numerator and denominator, respectively, used
  907. in computing the statistic `F'.
  908. The `utpn(x,m,s)' function uses a normal (Gaussian) distribution
  909. with mean `m' and standard deviation `s'. It is the probability that
  910. such a normal-distributed random variable would exceed `x'.
  911. The `utpp(n,x)' function uses a Poisson distribution with mean `x'.
  912. It is the probability that `n' or more such Poisson random events will
  913. occur.
  914. The `utpt(t,v)' function uses the Student's "t" distribution with `v'
  915. degrees of freedom. It is the probability that a t-distributed random
  916. variable will be greater than `t'. (Note: This computes the
  917. distribution function `A(t|v)' where `A(0|v) = 1' and `A(inf|v) -> 0'.
  918. The `UTPT' operation on the HP-48 uses a different definition which
  919. returns half of Calc's value: `UTPT(t,v) = .5*utpt(t,v)'.)
  920. While Calc does not provide inverses of the probability distribution
  921. functions, the `a R' command can be used to solve for the inverse.
  922. Since the distribution functions are monotonic, `a R' is guaranteed to
  923. be able to find a solution given any initial guess. *Note Numerical
  924. Solutions::.
  925. 
  926. File: calc, Node: Matrix Functions, Next: Algebra, Prev: Scientific Functions, Up: Top
  927. 11 Vector/Matrix Functions
  928. **************************
  929. Many of the commands described here begin with the `v' prefix. (For
  930. convenience, the shift-`V' prefix is equivalent to `v'.) The commands
  931. usually apply to both plain vectors and matrices; some apply only to
  932. matrices or only to square matrices. If the argument has the wrong
  933. dimensions the operation is left in symbolic form.
  934. Vectors are entered and displayed using `[a,b,c]' notation.
  935. Matrices are vectors of which all elements are vectors of equal length.
  936. (Though none of the standard Calc commands use this concept, a
  937. three-dimensional matrix or rank-3 tensor could be defined as a vector
  938. of matrices, and so on.)
  939. * Menu:
  940. * Packing and Unpacking::
  941. * Building Vectors::
  942. * Extracting Elements::
  943. * Manipulating Vectors::
  944. * Vector and Matrix Arithmetic::
  945. * Set Operations::
  946. * Statistical Operations::
  947. * Reducing and Mapping::
  948. * Vector and Matrix Formats::
  949. 
  950. File: calc, Node: Packing and Unpacking, Next: Building Vectors, Prev: Matrix Functions, Up: Matrix Functions
  951. 11.1 Packing and Unpacking
  952. ==========================
  953. Calc's "pack" and "unpack" commands collect stack entries to build
  954. composite objects such as vectors and complex numbers. They are
  955. described in this chapter because they are most often used to build
  956. vectors.
  957. The `v p' (`calc-pack') [`pack'] command collects several elements
  958. from the stack into a matrix, complex number, HMS form, error form,
  959. etc. It uses a numeric prefix argument to specify the kind of object
  960. to be built; this argument is referred to as the "packing mode." If
  961. the packing mode is a nonnegative integer, a vector of that length is
  962. created. For example, `C-u 5 v p' will pop the top five stack elements
  963. and push back a single vector of those five elements. (`C-u 0 v p'
  964. simply creates an empty vector.)
  965. The same effect can be had by pressing `[' to push an incomplete
  966. vector on the stack, using <TAB> (`calc-roll-down') to sneak the
  967. incomplete object up past a certain number of elements, and then
  968. pressing `]' to complete the vector.
  969. Negative packing modes create other kinds of composite objects:
  970. `-1'
  971. Two values are collected to build a complex number. For example,
  972. `5 <RET> 7 C-u -1 v p' creates the complex number `(5, 7)'. The
  973. result is always a rectangular complex number. The two input
  974. values must both be real numbers, i.e., integers, fractions, or
  975. floats. If they are not, Calc will instead build a formula like
  976. `a + (0, 1) b'. (The other packing modes also create a symbolic
  977. answer if the components are not suitable.)
  978. `-2'
  979. Two values are collected to build a polar complex number. The
  980. first is the magnitude; the second is the phase expressed in
  981. either degrees or radians according to the current angular mode.
  982. `-3'
  983. Three values are collected into an HMS form. The first two values
  984. (hours and minutes) must be integers or integer-valued floats.
  985. The third value may be any real number.
  986. `-4'
  987. Two values are collected into an error form. The inputs may be
  988. real numbers or formulas.
  989. `-5'
  990. Two values are collected into a modulo form. The inputs must be
  991. real numbers.
  992. `-6'
  993. Two values are collected into the interval `[a .. b]'. The inputs
  994. may be real numbers, HMS or date forms, or formulas.
  995. `-7'
  996. Two values are collected into the interval `[a .. b)'.
  997. `-8'
  998. Two values are collected into the interval `(a .. b]'.
  999. `-9'
  1000. Two values are collected into the interval `(a .. b)'.
  1001. `-10'
  1002. Two integer values are collected into a fraction.
  1003. `-11'
  1004. Two values are collected into a floating-point number. The first
  1005. is the mantissa; the second, which must be an integer, is the
  1006. exponent. The result is the mantissa times ten to the power of
  1007. the exponent.
  1008. `-12'
  1009. This is treated the same as -11 by the `v p' command. When
  1010. unpacking, -12 specifies that a floating-point mantissa is desired.
  1011. `-13'
  1012. A real number is converted into a date form.
  1013. `-14'
  1014. Three numbers (year, month, day) are packed into a pure date form.
  1015. `-15'
  1016. Six numbers are packed into a date/time form.
  1017. With any of the two-input negative packing modes, either or both of
  1018. the inputs may be vectors. If both are vectors of the same length, the
  1019. result is another vector made by packing corresponding elements of the
  1020. input vectors. If one input is a vector and the other is a plain
  1021. number, the number is packed along with each vector element to produce
  1022. a new vector. For example, `C-u -4 v p' could be used to convert a
  1023. vector of numbers and a vector of errors into a single vector of error
  1024. forms; `C-u -5 v p' could convert a vector of numbers and a single
  1025. number M into a vector of numbers modulo M.
  1026. If you don't give a prefix argument to `v p', it takes the packing
  1027. mode from the top of the stack. The elements to be packed then begin
  1028. at stack level 2. Thus `1 <RET> 2 <RET> 4 n v p' is another way to
  1029. enter the error form `1 +/- 2'.
  1030. If the packing mode taken from the stack is a vector, the result is a
  1031. matrix with the dimensions specified by the elements of the vector,
  1032. which must each be integers. For example, if the packing mode is `[2,
  1033. 3]', then six numbers will be taken from the stack and returned in the
  1034. form `[[a, b, c], [d, e, f]]'.
  1035. If any elements of the vector are negative, other kinds of packing
  1036. are done at that level as described above. For example, `[2, 3, -4]'
  1037. takes 12 objects and creates a 2x3 matrix of error forms: `[[a +/- b, c
  1038. +/- d ... ]]'. Also, `[-4, -10]' will convert four integers into an
  1039. error form consisting of two fractions: `a:b +/- c:d'.
  1040. There is an equivalent algebraic function, `pack(MODE, ITEMS)' where
  1041. MODE is a packing mode (an integer or a vector of integers) and ITEMS
  1042. is a vector of objects to be packed (re-packed, really) according to
  1043. that mode. For example, `pack([3, -4], [a,b,c,d,e,f])' yields `[a +/-
  1044. b, c +/- d, e +/- f]'. The function is left in symbolic form if the
  1045. packing mode is invalid, or if the number of data items does not match
  1046. the number of items required by the mode.
  1047. The `v u' (`calc-unpack') command takes the vector, complex number,
  1048. HMS form, or other composite object on the top of the stack and
  1049. "unpacks" it, pushing each of its elements onto the stack as separate
  1050. objects. Thus, it is the "inverse" of `v p'. If the value at the top
  1051. of the stack is a formula, `v u' unpacks it by pushing each of the
  1052. arguments of the top-level operator onto the stack.
  1053. You can optionally give a numeric prefix argument to `v u' to
  1054. specify an explicit (un)packing mode. If the packing mode is negative
  1055. and the input is actually a vector or matrix, the result will be two or
  1056. more similar vectors or matrices of the elements. For example, given
  1057. the vector `[a +/- b, c^2, d +/- 7]', the result of `C-u -4 v u' will
  1058. be the two vectors `[a, c^2, d]' and `[b, 0, 7]'.
  1059. Note that the prefix argument can have an effect even when the input
  1060. is not a vector. For example, if the input is the number -5, then `c-u
  1061. -1 v u' yields -5 and 0 (the components of -5 when viewed as a
  1062. rectangular complex number); `C-u -2 v u' yields 5 and 180 (assuming
  1063. Degrees mode); and `C-u -10 v u' yields -5 and 1 (the numerator and
  1064. denominator of -5, viewed as a rational number). Plain `v u' with this
  1065. input would complain that the input is not a composite object.
  1066. Unpacking mode -11 converts a float into an integer mantissa and an
  1067. integer exponent, where the mantissa is not divisible by 10 (except
  1068. that 0.0 is represented by a mantissa and exponent of 0). Unpacking
  1069. mode -12 converts a float into a floating-point mantissa and integer
  1070. exponent, where the mantissa (for non-zero numbers) is guaranteed to
  1071. lie in the range [1 .. 10). In both cases, the mantissa is shifted
  1072. left or right (and the exponent adjusted to compensate) in order to
  1073. satisfy these constraints.
  1074. Positive unpacking modes are treated differently than for `v p'. A
  1075. mode of 1 is much like plain `v u' with no prefix argument, except that
  1076. in addition to the components of the input object, a suitable packing
  1077. mode to re-pack the object is also pushed. Thus, `C-u 1 v u' followed
  1078. by `v p' will re-build the original object.
  1079. A mode of 2 unpacks two levels of the object; the resulting
  1080. re-packing mode will be a vector of length 2. This might be used to
  1081. unpack a matrix, say, or a vector of error forms. Higher unpacking
  1082. modes unpack the input even more deeply.
  1083. There are two algebraic functions analogous to `v u'. The
  1084. `unpack(MODE, ITEM)' function unpacks the ITEM using the given MODE,
  1085. returning the result as a vector of components. Here the MODE must be
  1086. an integer, not a vector. For example, `unpack(-4, a +/- b)' returns
  1087. `[a, b]', as does `unpack(1, a +/- b)'.
  1088. The `unpackt' function is like `unpack' but instead of returning a
  1089. simple vector of items, it returns a vector of two things: The mode,
  1090. and the vector of items. For example, `unpackt(1, 2:3 +/- 1:4)'
  1091. returns `[-4, [2:3, 1:4]]', and `unpackt(2, 2:3 +/- 1:4)' returns
  1092. `[[-4, -10], [2, 3, 1, 4]]'. The identity for re-building the original
  1093. object is `apply(pack, unpackt(N, X)) = X'. (The `apply' function
  1094. builds a function call given the function name and a vector of
  1095. arguments.)
  1096. Subscript notation is a useful way to extract a particular part of
  1097. an object. For example, to get the numerator of a rational number, you
  1098. can use `unpack(-10, X)_1'.
  1099. 
  1100. File: calc, Node: Building Vectors, Next: Extracting Elements, Prev: Packing and Unpacking, Up: Matrix Functions
  1101. 11.2 Building Vectors
  1102. =====================
  1103. Vectors and matrices can be added, subtracted, multiplied, and divided;
  1104. *note Basic Arithmetic::.
  1105. The `|' (`calc-concat') [`vconcat'] command "concatenates" two
  1106. vectors into one. For example, after `[ 1 , 2 ] [ 3 , 4 ] |', the stack
  1107. will contain the single vector `[1, 2, 3, 4]'. If the arguments are
  1108. matrices, the rows of the first matrix are concatenated with the rows
  1109. of the second. (In other words, two matrices are just two vectors of
  1110. row-vectors as far as `|' is concerned.)
  1111. If either argument to `|' is a scalar (a non-vector), it is treated
  1112. like a one-element vector for purposes of concatenation: `1 [ 2 , 3 ]
  1113. |' produces the vector `[1, 2, 3]'. Likewise, if one argument is a
  1114. matrix and the other is a plain vector, the vector is treated as a
  1115. one-row matrix.
  1116. The `H |' (`calc-append') [`append'] command concatenates two
  1117. vectors without any special cases. Both inputs must be vectors.
  1118. Whether or not they are matrices is not taken into account. If either
  1119. argument is a scalar, the `append' function is left in symbolic form.
  1120. See also `cons' and `rcons' below.
  1121. The `I |' and `H I |' commands are similar, but they use their two
  1122. stack arguments in the opposite order. Thus `I |' is equivalent to
  1123. `<TAB> |', but possibly more convenient and also a bit faster.
  1124. The `v d' (`calc-diag') [`diag'] function builds a diagonal square
  1125. matrix. The optional numeric prefix gives the number of rows and
  1126. columns in the matrix. If the value at the top of the stack is a
  1127. vector, the elements of the vector are used as the diagonal elements;
  1128. the prefix, if specified, must match the size of the vector. If the
  1129. value on the stack is a scalar, it is used for each element on the
  1130. diagonal, and the prefix argument is required.
  1131. To build a constant square matrix, e.g., a 3x3 matrix filled with
  1132. ones, use `0 M-3 v d 1 +', i.e., build a zero matrix first and then add
  1133. a constant value to that matrix. (Another alternative would be to use
  1134. `v b' and `v a'; see below.)
  1135. The `v i' (`calc-ident') [`idn'] function builds an identity matrix
  1136. of the specified size. It is a convenient form of `v d' where the
  1137. diagonal element is always one. If no prefix argument is given, this
  1138. command prompts for one.
  1139. In algebraic notation, `idn(a,n)' acts much like `diag(a,n)', except
  1140. that `a' is required to be a scalar (non-vector) quantity. If `n' is
  1141. omitted, `idn(a)' represents `a' times an identity matrix of unknown
  1142. size. Calc can operate algebraically on such generic identity
  1143. matrices, and if one is combined with a matrix whose size is known, it
  1144. is converted automatically to an identity matrix of a suitable matching
  1145. size. The `v i' command with an argument of zero creates a generic
  1146. identity matrix, `idn(1)'. Note that in dimensioned Matrix mode (*note
  1147. Matrix Mode::), generic identity matrices are immediately expanded to
  1148. the current default dimensions.
  1149. The `v x' (`calc-index') [`index'] function builds a vector of
  1150. consecutive integers from 1 to N, where N is the numeric prefix
  1151. argument. If you do not provide a prefix argument, you will be
  1152. prompted to enter a suitable number. If N is negative, the result is a
  1153. vector of negative integers from N to -1.
  1154. With a prefix argument of just `C-u', the `v x' command takes three
  1155. values from the stack: N, START, and INCR (with INCR at top-of-stack).
  1156. Counting starts at START and increases by INCR for successive vector
  1157. elements. If START or N is in floating-point format, the resulting
  1158. vector elements will also be floats. Note that START and INCR may in
  1159. fact be any kind of numbers or formulas.
  1160. When START and INCR are specified, a negative N has a different
  1161. interpretation: It causes a geometric instead of arithmetic sequence
  1162. to be generated. For example, `index(-3, a, b)' produces `[a, a b, a
  1163. b^2]'. If you omit INCR in the algebraic form, `index(N, START)', the
  1164. default value for INCR is one for positive N or two for negative N.
  1165. The `v b' (`calc-build-vector') [`cvec'] function builds a vector of
  1166. N copies of the value on the top of the stack, where N is the numeric
  1167. prefix argument. In algebraic formulas, `cvec(x,n,m)' can also be used
  1168. to build an N-by-M matrix of copies of X. (Interactively, just use `v
  1169. b' twice: once to build a row, then again to build a matrix of copies
  1170. of that row.)
  1171. The `v h' (`calc-head') [`head'] function returns the first element
  1172. of a vector. The `I v h' (`calc-tail') [`tail'] function returns the
  1173. vector with its first element removed. In both cases, the argument
  1174. must be a non-empty vector.
  1175. The `v k' (`calc-cons') [`cons'] function takes a value H and a
  1176. vector T from the stack, and produces the vector whose head is H and
  1177. whose tail is T. This is similar to `|', except if H is itself a
  1178. vector, `|' will concatenate the two vectors whereas `cons' will insert
  1179. H at the front of the vector T.
  1180. Each of these three functions also accepts the Hyperbolic flag
  1181. [`rhead', `rtail', `rcons'] in which case T instead represents the
  1182. _last_ single element of the vector, with H representing the remainder
  1183. of the vector. Thus the vector `[a, b, c, d] = cons(a, [b, c, d]) =
  1184. rcons([a, b, c], d)'. Also, `head([a, b, c, d]) = a', `tail([a, b, c,
  1185. d]) = [b, c, d]', `rhead([a, b, c, d]) = [a, b, c]', and `rtail([a, b,
  1186. c, d]) = d'.
  1187. 
  1188. File: calc, Node: Extracting Elements, Next: Manipulating Vectors, Prev: Building Vectors, Up: Matrix Functions
  1189. 11.3 Extracting Vector Elements
  1190. ===============================
  1191. The `v r' (`calc-mrow') [`mrow'] command extracts one row of the matrix
  1192. on the top of the stack, or one element of the plain vector on the top
  1193. of the stack. The row or element is specified by the numeric prefix
  1194. argument; the default is to prompt for the row or element number. The
  1195. matrix or vector is replaced by the specified row or element in the
  1196. form of a vector or scalar, respectively.
  1197. With a prefix argument of `C-u' only, `v r' takes the index of the
  1198. element or row from the top of the stack, and the vector or matrix from
  1199. the second-to-top position. If the index is itself a vector of
  1200. integers, the result is a vector of the corresponding elements of the
  1201. input vector, or a matrix of the corresponding rows of the input matrix.
  1202. This command can be used to obtain any permutation of a vector.
  1203. With `C-u', if the index is an interval form with integer components,
  1204. it is interpreted as a range of indices and the corresponding subvector
  1205. or submatrix is returned.
  1206. Subscript notation in algebraic formulas (`a_b') stands for the Calc
  1207. function `subscr', which is synonymous with `mrow'. Thus, `[x, y,
  1208. z]_k' produces `x', `y', or `z' if `k' is one, two, or three,
  1209. respectively. A double subscript (`M_i_j', equivalent to
  1210. `subscr(subscr(M, i), j)') will access the element at row `i', column
  1211. `j' of a matrix. The `a _' (`calc-subscript') command creates a
  1212. subscript formula `a_b' out of two stack entries. (It is on the `a'
  1213. "algebra" prefix because subscripted variables are often used purely as
  1214. an algebraic notation.)
  1215. Given a negative prefix argument, `v r' instead deletes one row or
  1216. element from the matrix or vector on the top of the stack. Thus `C-u 2
  1217. v r' replaces a matrix with its second row, but `C-u -2 v r' replaces
  1218. the matrix with the same matrix with its second row removed. In
  1219. algebraic form this function is called `mrrow'.
  1220. Given a prefix argument of zero, `v r' extracts the diagonal elements
  1221. of a square matrix in the form of a vector. In algebraic form this
  1222. function is called `getdiag'.
  1223. The `v c' (`calc-mcol') [`mcol' or `mrcol'] command is the analogous
  1224. operation on columns of a matrix. Given a plain vector it extracts (or
  1225. removes) one element, just like `v r'. If the index in `C-u v c' is an
  1226. interval or vector and the argument is a matrix, the result is a
  1227. submatrix with only the specified columns retained (and possibly
  1228. permuted in the case of a vector index).
  1229. To extract a matrix element at a given row and column, use `v r' to
  1230. extract the row as a vector, then `v c' to extract the column element
  1231. from that vector. In algebraic formulas, it is often more convenient to
  1232. use subscript notation: `m_i_j' gives row `i', column `j' of matrix
  1233. `m'.
  1234. The `v s' (`calc-subvector') [`subvec'] command extracts a subvector
  1235. of a vector. The arguments are the vector, the starting index, and the
  1236. ending index, with the ending index in the top-of-stack position. The
  1237. starting index indicates the first element of the vector to take. The
  1238. ending index indicates the first element _past_ the range to be taken.
  1239. Thus, `subvec([a, b, c, d, e], 2, 4)' produces the subvector `[b, c]'.
  1240. You could get the same result using `mrow([a, b, c, d, e], [2 .. 4))'.
  1241. If either the start or the end index is zero or negative, it is
  1242. interpreted as relative to the end of the vector. Thus `subvec([a, b,
  1243. c, d, e], 2, -2)' also produces `[b, c]'. In the algebraic form, the
  1244. end index can be omitted in which case it is taken as zero, i.e.,
  1245. elements from the starting element to the end of the vector are used.
  1246. The infinity symbol, `inf', also has this effect when used as the
  1247. ending index.
  1248. With the Inverse flag, `I v s' [`rsubvec'] removes a subvector from
  1249. a vector. The arguments are interpreted the same as for the normal `v
  1250. s' command. Thus, `rsubvec([a, b, c, d, e], 2, 4)' produces `[a, d,
  1251. e]'. It is always true that `subvec' and `rsubvec' return
  1252. complementary parts of the input vector.
  1253. *Note Selecting Subformulas::, for an alternative way to operate on
  1254. vectors one element at a time.
  1255. 
  1256. File: calc, Node: Manipulating Vectors, Next: Vector and Matrix Arithmetic, Prev: Extracting Elements, Up: Matrix Functions
  1257. 11.4 Manipulating Vectors
  1258. =========================
  1259. The `v l' (`calc-vlength') [`vlen'] command computes the length of a
  1260. vector. The length of a non-vector is considered to be zero. Note
  1261. that matrices are just vectors of vectors for the purposes of this
  1262. command.
  1263. With the Hyperbolic flag, `H v l' [`mdims'] computes a vector of the
  1264. dimensions of a vector, matrix, or higher-order object. For example,
  1265. `mdims([[a,b,c],[d,e,f]])' returns `[2, 3]' since its argument is a 2x3
  1266. matrix.
  1267. The `v f' (`calc-vector-find') [`find'] command searches along a
  1268. vector for the first element equal to a given target. The target is on
  1269. the top of the stack; the vector is in the second-to-top position. If
  1270. a match is found, the result is the index of the matching element.
  1271. Otherwise, the result is zero. The numeric prefix argument, if given,
  1272. allows you to select any starting index for the search.
  1273. The `v a' (`calc-arrange-vector') [`arrange'] command rearranges a
  1274. vector to have a certain number of columns and rows. The numeric
  1275. prefix argument specifies the number of columns; if you do not provide
  1276. an argument, you will be prompted for the number of columns. The
  1277. vector or matrix on the top of the stack is "flattened" into a plain
  1278. vector. If the number of columns is nonzero, this vector is then
  1279. formed into a matrix by taking successive groups of N elements. If the
  1280. number of columns does not evenly divide the number of elements in the
  1281. vector, the last row will be short and the result will not be suitable
  1282. for use as a matrix. For example, with the matrix `[[1, 2], [3, 4]]'
  1283. on the stack, `v a 4' produces `[[1, 2, 3, 4]]' (a 1x4 matrix), `v a 1'
  1284. produces `[[1], [2], [3], [4]]' (a 4x1 matrix), `v a 2' produces `[[1,
  1285. 2], [3, 4]]' (the original 2x2 matrix), `v a 3' produces `[[1, 2, 3],
  1286. [4]]' (not a matrix), and `v a 0' produces the flattened list `[1, 2,
  1287. 3, 4]'.
  1288. The `V S' (`calc-sort') [`sort'] command sorts the elements of a
  1289. vector into increasing order. Real numbers, real infinities, and
  1290. constant interval forms come first in this ordering; next come other
  1291. kinds of numbers, then variables (in alphabetical order), then finally
  1292. come formulas and other kinds of objects; these are sorted according to
  1293. a kind of lexicographic ordering with the useful property that one
  1294. vector is less or greater than another if the first corresponding
  1295. unequal elements are less or greater, respectively. Since quoted
  1296. strings are stored by Calc internally as vectors of ASCII character
  1297. codes (*note Strings::), this means vectors of strings are also sorted
  1298. into alphabetical order by this command.
  1299. The `I V S' [`rsort'] command sorts a vector into decreasing order.
  1300. The `V G' (`calc-grade') [`grade', `rgrade'] command produces an
  1301. index table or permutation vector which, if applied to the input vector
  1302. (as the index of `C-u v r', say), would sort the vector. A permutation
  1303. vector is just a vector of integers from 1 to N, where each integer
  1304. occurs exactly once. One application of this is to sort a matrix of
  1305. data rows using one column as the sort key; extract that column, grade
  1306. it with `V G', then use the result to reorder the original matrix with
  1307. `C-u v r'. Another interesting property of the `V G' command is that,
  1308. if the input is itself a permutation vector, the result will be the
  1309. inverse of the permutation. The inverse of an index table is a rank
  1310. table, whose Kth element says where the Kth original vector element
  1311. will rest when the vector is sorted. To get a rank table, just use `V
  1312. G V G'.
  1313. With the Inverse flag, `I V G' produces an index table that would
  1314. sort the input into decreasing order. Note that `V S' and `V G' use a
  1315. "stable" sorting algorithm, i.e., any two elements which are equal will
  1316. not be moved out of their original order. Generally there is no way to
  1317. tell with `V S', since two elements which are equal look the same, but
  1318. with `V G' this can be an important issue. In the matrix-of-rows
  1319. example, suppose you have names and telephone numbers as two columns and
  1320. you wish to sort by phone number primarily, and by name when the numbers
  1321. are equal. You can sort the data matrix by names first, and then again
  1322. by phone numbers. Because the sort is stable, any two rows with equal
  1323. phone numbers will remain sorted by name even after the second sort.
  1324. The `V H' (`calc-histogram') [`histogram'] command builds a
  1325. histogram of a vector of numbers. Vector elements are assumed to be
  1326. integers or real numbers in the range [0..N) for some "number of bins"
  1327. N, which is the numeric prefix argument given to the command. The
  1328. result is a vector of N counts of how many times each value appeared in
  1329. the original vector. Non-integers in the input are rounded down to
  1330. integers. Any vector elements outside the specified range are ignored.
  1331. (You can tell if elements have been ignored by noting that the counts
  1332. in the result vector don't add up to the length of the input vector.)
  1333. If no prefix is given, then you will be prompted for a vector which
  1334. will be used to determine the bins. (If a positive integer is given at
  1335. this prompt, it will be still treated as if it were given as a prefix.)
  1336. Each bin will consist of the interval of numbers closest to the
  1337. corresponding number of this new vector; if the vector `[a, b, c, ...]'
  1338. is entered at the prompt, the bins will be `(-inf, (a+b)/2]',
  1339. `((a+b)/2, (b+c)/2]', etc. The result of this command will be a vector
  1340. counting how many elements of the original vector are in each bin.
  1341. The result will then be a vector with the same length as this new
  1342. vector; each element of the new vector will be replaced by the number of
  1343. elements of the original vector which are closest to it.
  1344. With the Hyperbolic flag, `H V H' pulls two vectors from the stack.
  1345. The second-to-top vector is the list of numbers as before. The top
  1346. vector is an equal-sized list of "weights" to attach to the elements of
  1347. the data vector. For example, if the first data element is 4.2 and the
  1348. first weight is 10, then 10 will be added to bin 4 of the result
  1349. vector. Without the hyperbolic flag, every element has a weight of one.
  1350. The `v t' (`calc-transpose') [`trn'] command computes the transpose
  1351. of the matrix at the top of the stack. If the argument is a plain
  1352. vector, it is treated as a row vector and transposed into a one-column
  1353. matrix.
  1354. The `v v' (`calc-reverse-vector') [`rev'] command reverses a vector
  1355. end-for-end. Given a matrix, it reverses the order of the rows. (To
  1356. reverse the columns instead, just use `v t v v v t'. The same
  1357. principle can be used to apply other vector commands to the columns of
  1358. a matrix.)
  1359. The `v m' (`calc-mask-vector') [`vmask'] command uses one vector as
  1360. a mask to extract elements of another vector. The mask is in the
  1361. second-to-top position; the target vector is on the top of the stack.
  1362. These vectors must have the same length. The result is the same as the
  1363. target vector, but with all elements which correspond to zeros in the
  1364. mask vector deleted. Thus, for example, `vmask([1, 0, 1, 0, 1], [a, b,
  1365. c, d, e])' produces `[a, c, e]'. *Note Logical Operations::.
  1366. The `v e' (`calc-expand-vector') [`vexp'] command expands a vector
  1367. according to another mask vector. The result is a vector the same
  1368. length as the mask, but with nonzero elements replaced by successive
  1369. elements from the target vector. The length of the target vector is
  1370. normally the number of nonzero elements in the mask. If the target
  1371. vector is longer, its last few elements are lost. If the target vector
  1372. is shorter, the last few nonzero mask elements are left unreplaced in
  1373. the result. Thus `vexp([2, 0, 3, 0, 7], [a, b])' produces `[a, 0, b,
  1374. 0, 7]'.
  1375. With the Hyperbolic flag, `H v e' takes a filler value from the top
  1376. of the stack; the mask and target vectors come from the third and
  1377. second elements of the stack. This filler is used where the mask is
  1378. zero: `vexp([2, 0, 3, 0, 7], [a, b], z)' produces `[a, z, c, z, 7]'.
  1379. If the filler value is itself a vector, then successive values are
  1380. taken from it, so that the effect is to interleave two vectors
  1381. according to the mask: `vexp([2, 0, 3, 7, 0, 0], [a, b], [x, y])'
  1382. produces `[a, x, b, 7, y, 0]'.
  1383. Another variation on the masking idea is to combine `[a, b, c, d, e]'
  1384. with the mask `[1, 0, 1, 0, 1]' to produce `[a, 0, c, 0, e]'. You can
  1385. accomplish this with `V M a &', mapping the logical "and" operation
  1386. across the two vectors. *Note Logical Operations::. Note that the `?
  1387. :' operation also discussed there allows other types of masking using
  1388. vectors.
  1389. 
  1390. File: calc, Node: Vector and Matrix Arithmetic, Next: Set Operations, Prev: Manipulating Vectors, Up: Matrix Functions
  1391. 11.5 Vector and Matrix Arithmetic
  1392. =================================
  1393. Basic arithmetic operations like addition and multiplication are defined
  1394. for vectors and matrices as well as for numbers. Division of matrices,
  1395. in the sense of multiplying by the inverse, is supported. (Division by
  1396. a matrix actually uses LU-decomposition for greater accuracy and speed.)
  1397. *Note Basic Arithmetic::.
  1398. The following functions are applied element-wise if their arguments
  1399. are vectors or matrices: `change-sign', `conj', `arg', `re', `im',
  1400. `polar', `rect', `clean', `float', `frac'. *Note Function Index::.
  1401. The `V J' (`calc-conj-transpose') [`ctrn'] command computes the
  1402. conjugate transpose of its argument, i.e., `conj(trn(x))'.
  1403. The `A' (`calc-abs') [`abs'] command computes the Frobenius norm of
  1404. a vector or matrix argument. This is the square root of the sum of the
  1405. squares of the absolute values of the elements of the vector or matrix.
  1406. If the vector is interpreted as a point in two- or three-dimensional
  1407. space, this is the distance from that point to the origin.
  1408. The `v n' (`calc-rnorm') [`rnorm'] command computes the
  1409. infinity-norm of a vector, or the row norm of a matrix. For a plain
  1410. vector, this is the maximum of the absolute values of the elements. For
  1411. a matrix, this is the maximum of the row-absolute-value-sums, i.e., of
  1412. the sums of the absolute values of the elements along the various rows.
  1413. The `V N' (`calc-cnorm') [`cnorm'] command computes the one-norm of
  1414. a vector, or column norm of a matrix. For a plain vector, this is the
  1415. sum of the absolute values of the elements. For a matrix, this is the
  1416. maximum of the column-absolute-value-sums. General `k'-norms for `k'
  1417. other than one or infinity are not provided. However, the 2-norm (or
  1418. Frobenius norm) is provided for vectors by the `A' (`calc-abs') command.
  1419. The `V C' (`calc-cross') [`cross'] command computes the right-handed
  1420. cross product of two vectors, each of which must have exactly three
  1421. elements.
  1422. The `&' (`calc-inv') [`inv'] command computes the inverse of a
  1423. square matrix. If the matrix is singular, the inverse operation is
  1424. left in symbolic form. Matrix inverses are recorded so that once an
  1425. inverse (or determinant) of a particular matrix has been computed, the
  1426. inverse and determinant of the matrix can be recomputed quickly in the
  1427. future.
  1428. If the argument to `&' is a plain number `x', this command simply
  1429. computes `1/x'. This is okay, because the `/' operator also does a
  1430. matrix inversion when dividing one by a matrix.
  1431. The `V D' (`calc-mdet') [`det'] command computes the determinant of
  1432. a square matrix.
  1433. The `V L' (`calc-mlud') [`lud'] command computes the LU
  1434. decomposition of a matrix. The result is a list of three matrices
  1435. which, when multiplied together left-to-right, form the original matrix.
  1436. The first is a permutation matrix that arises from pivoting in the
  1437. algorithm, the second is lower-triangular with ones on the diagonal,
  1438. and the third is upper-triangular.
  1439. The `V T' (`calc-mtrace') [`tr'] command computes the trace of a
  1440. square matrix. This is defined as the sum of the diagonal elements of
  1441. the matrix.
  1442. The `V K' (`calc-kron') [`kron'] command computes the Kronecker
  1443. product of two matrices.
  1444. 
  1445. File: calc, Node: Set Operations, Next: Statistical Operations, Prev: Vector and Matrix Arithmetic, Up: Matrix Functions
  1446. 11.6 Set Operations using Vectors
  1447. =================================
  1448. Calc includes several commands which interpret vectors as "sets" of
  1449. objects. A set is a collection of objects; any given object can appear
  1450. only once in the set. Calc stores sets as vectors of objects in sorted
  1451. order. Objects in a Calc set can be any of the usual things, such as
  1452. numbers, variables, or formulas. Two set elements are considered equal
  1453. if they are identical, except that numerically equal numbers like the
  1454. integer 4 and the float 4.0 are considered equal even though they are
  1455. not "identical." Variables are treated like plain symbols without
  1456. attached values by the set operations; subtracting the set `[b]' from
  1457. `[a, b]' always yields the set `[a]' even though if the variables `a'
  1458. and `b' both equaled 17, you might expect the answer `[]'.
  1459. If a set contains interval forms, then it is assumed to be a set of
  1460. real numbers. In this case, all set operations require the elements of
  1461. the set to be only things that are allowed in intervals: Real numbers,
  1462. plus and minus infinity, HMS forms, and date forms. If there are
  1463. variables or other non-real objects present in a real set, all set
  1464. operations on it will be left in unevaluated form.
  1465. If the input to a set operation is a plain number or interval form
  1466. A, it is treated like the one-element vector `[A]'. The result is
  1467. always a vector, except that if the set consists of a single interval,
  1468. the interval itself is returned instead.
  1469. *Note Logical Operations::, for the `in' function which tests if a
  1470. certain value is a member of a given set. To test if the set `A' is a
  1471. subset of the set `B', use `vdiff(A, B) = []'.
  1472. The `V +' (`calc-remove-duplicates') [`rdup'] command converts an
  1473. arbitrary vector into set notation. It works by sorting the vector as
  1474. if by `V S', then removing duplicates. (For example, `[a, 5, 4, a,
  1475. 4.0]' is sorted to `[4, 4.0, 5, a, a]' and then reduced to `[4, 5,
  1476. a]'). Overlapping intervals are merged as necessary. You rarely need
  1477. to use `V +' explicitly, since all the other set-based commands apply
  1478. `V +' to their inputs before using them.
  1479. The `V V' (`calc-set-union') [`vunion'] command computes the union
  1480. of two sets. An object is in the union of two sets if and only if it
  1481. is in either (or both) of the input sets. (You could accomplish the
  1482. same thing by concatenating the sets with `|', then using `V +'.)
  1483. The `V ^' (`calc-set-intersect') [`vint'] command computes the
  1484. intersection of two sets. An object is in the intersection if and only
  1485. if it is in both of the input sets. Thus if the input sets are
  1486. disjoint, i.e., if they share no common elements, the result will be
  1487. the empty vector `[]'. Note that the characters `V' and `^' were
  1488. chosen to be close to the conventional mathematical notation for set
  1489. union and intersection.
  1490. The `V -' (`calc-set-difference') [`vdiff'] command computes the
  1491. difference between two sets. An object is in the difference `A - B' if
  1492. and only if it is in `A' but not in `B'. Thus subtracting `[y,z]' from
  1493. a set will remove the elements `y' and `z' if they are present. You
  1494. can also think of this as a general "set complement" operator; if `A'
  1495. is the set of all possible values, then `A - B' is the "complement" of
  1496. `B'. Obviously this is only practical if the set of all possible
  1497. values in your problem is small enough to list in a Calc vector (or
  1498. simple enough to express in a few intervals).
  1499. The `V X' (`calc-set-xor') [`vxor'] command computes the
  1500. "exclusive-or," or "symmetric difference" of two sets. An object is in
  1501. the symmetric difference of two sets if and only if it is in one, but
  1502. _not_ both, of the sets. Objects that occur in both sets "cancel out."
  1503. The `V ~' (`calc-set-complement') [`vcompl'] command computes the
  1504. complement of a set with respect to the real numbers. Thus `vcompl(x)'
  1505. is equivalent to `vdiff([-inf .. inf], x)'. For example, `vcompl([2,
  1506. (3 .. 4]])' evaluates to `[[-inf .. 2), (2 .. 3], (4 .. inf]]'.
  1507. The `V F' (`calc-set-floor') [`vfloor'] command reinterprets a set
  1508. as a set of integers. Any non-integer values, and intervals that do
  1509. not enclose any integers, are removed. Open intervals are converted to
  1510. equivalent closed intervals. Successive integers are converted into
  1511. intervals of integers. For example, the complement of the set `[2, 6,
  1512. 7, 8]' is messy, but if you wanted the complement with respect to the
  1513. set of integers you could type `V ~ V F' to get `[[-inf .. 1], [3 ..
  1514. 5], [9 .. inf]]'.
  1515. The `V E' (`calc-set-enumerate') [`venum'] command converts a set of
  1516. integers into an explicit vector. Intervals in the set are expanded
  1517. out to lists of all integers encompassed by the intervals. This only
  1518. works for finite sets (i.e., sets which do not involve `-inf' or `inf').
  1519. The `V :' (`calc-set-span') [`vspan'] command converts any set of
  1520. reals into an interval form that encompasses all its elements. The
  1521. lower limit will be the smallest element in the set; the upper limit
  1522. will be the largest element. For an empty set, `vspan([])' returns the
  1523. empty interval `[0 .. 0)'.
  1524. The `V #' (`calc-set-cardinality') [`vcard'] command counts the
  1525. number of integers in a set. The result is the length of the vector
  1526. that would be produced by `V E', although the computation is much more
  1527. efficient than actually producing that vector.
  1528. Another representation for sets that may be more appropriate in some
  1529. cases is binary numbers. If you are dealing with sets of integers in
  1530. the range 0 to 49, you can use a 50-bit binary number where a
  1531. particular bit is 1 if the corresponding element is in the set. *Note
  1532. Binary Functions::, for a list of commands that operate on binary
  1533. numbers. Note that many of the above set operations have direct
  1534. equivalents in binary arithmetic: `b o' (`calc-or'), `b a'
  1535. (`calc-and'), `b d' (`calc-diff'), `b x' (`calc-xor'), and `b n'
  1536. (`calc-not'), respectively. You can use whatever representation for
  1537. sets is most convenient to you.
  1538. The `b u' (`calc-unpack-bits') [`vunpack'] command converts an
  1539. integer that represents a set in binary into a set in vector/interval
  1540. notation. For example, `vunpack(67)' returns `[[0 .. 1], 6]'. If the
  1541. input is negative, the set it represents is semi-infinite: `vunpack(-4)
  1542. = [2 .. inf)'. Use `V E' afterwards to expand intervals to individual
  1543. values if you wish. Note that this command uses the `b' (binary)
  1544. prefix key.
  1545. The `b p' (`calc-pack-bits') [`vpack'] command converts the other
  1546. way, from a vector or interval representing a set of nonnegative
  1547. integers into a binary integer describing the same set. The set may
  1548. include positive infinity, but must not include any negative numbers.
  1549. The input is interpreted as a set of integers in the sense of `V F'
  1550. (`vfloor'). Beware that a simple input like `[100]' can result in a
  1551. huge integer representation (`2^100', a 31-digit integer, in this case).
  1552. 
  1553. File: calc, Node: Statistical Operations, Next: Reducing and Mapping, Prev: Set Operations, Up: Matrix Functions
  1554. 11.7 Statistical Operations on Vectors
  1555. ======================================
  1556. The commands in this section take vectors as arguments and compute
  1557. various statistical measures on the data stored in the vectors. The
  1558. references used in the definitions of these functions are Bevington's
  1559. _Data Reduction and Error Analysis for the Physical Sciences_, and
  1560. _Numerical Recipes_ by Press, Flannery, Teukolsky and Vetterling.
  1561. The statistical commands use the `u' prefix key followed by a
  1562. shifted letter or other character.
  1563. *Note Manipulating Vectors::, for a description of `V H'
  1564. (`calc-histogram').
  1565. *Note Curve Fitting::, for the `a F' command for doing least-squares
  1566. fits to statistical data.
  1567. *Note Probability Distribution Functions::, for several common
  1568. probability distribution functions.
  1569. * Menu:
  1570. * Single-Variable Statistics::
  1571. * Paired-Sample Statistics::
  1572. 
  1573. File: calc, Node: Single-Variable Statistics, Next: Paired-Sample Statistics, Prev: Statistical Operations, Up: Statistical Operations
  1574. 11.7.1 Single-Variable Statistics
  1575. ---------------------------------
  1576. These functions do various statistical computations on single vectors.
  1577. Given a numeric prefix argument, they actually pop N objects from the
  1578. stack and combine them into a data vector. Each object may be either a
  1579. number or a vector; if a vector, any sub-vectors inside it are
  1580. "flattened" as if by `v a 0'; *note Manipulating Vectors::. By default
  1581. one object is popped, which (in order to be useful) is usually a vector.
  1582. If an argument is a variable name, and the value stored in that
  1583. variable is a vector, then the stored vector is used. This method has
  1584. the advantage that if your data vector is large, you can avoid the slow
  1585. process of manipulating it directly on the stack.
  1586. These functions are left in symbolic form if any of their arguments
  1587. are not numbers or vectors, e.g., if an argument is a formula, or a
  1588. non-vector variable. However, formulas embedded within vector
  1589. arguments are accepted; the result is a symbolic representation of the
  1590. computation, based on the assumption that the formula does not itself
  1591. represent a vector. All varieties of numbers such as error forms and
  1592. interval forms are acceptable.
  1593. Some of the functions in this section also accept a single error form
  1594. or interval as an argument. They then describe a property of the
  1595. normal or uniform (respectively) statistical distribution described by
  1596. the argument. The arguments are interpreted in the same way as the M
  1597. argument of the random number function `k r'. In particular, an
  1598. interval with integer limits is considered an integer distribution, so
  1599. that `[2 .. 6)' is the same as `[2 .. 5]'. An interval with at least
  1600. one floating-point limit is a continuous distribution: `[2.0 .. 6.0)'
  1601. is _not_ the same as `[2.0 .. 5.0]'!
  1602. The `u #' (`calc-vector-count') [`vcount'] command computes the
  1603. number of data values represented by the inputs. For example,
  1604. `vcount(1, [2, 3], [[4, 5], [], x, y])' returns 7. If the argument is
  1605. a single vector with no sub-vectors, this simply computes the length of
  1606. the vector.
  1607. The `u +' (`calc-vector-sum') [`vsum'] command computes the sum of
  1608. the data values. The `u *' (`calc-vector-prod') [`vprod'] command
  1609. computes the product of the data values. If the input is a single flat
  1610. vector, these are the same as `V R +' and `V R *' (*note Reducing and
  1611. Mapping::).
  1612. The `u X' (`calc-vector-max') [`vmax'] command computes the maximum
  1613. of the data values, and the `u N' (`calc-vector-min') [`vmin'] command
  1614. computes the minimum. If the argument is an interval, this finds the
  1615. minimum or maximum value in the interval. (Note that `vmax([2..6)) =
  1616. 5' as described above.) If the argument is an error form, this returns
  1617. plus or minus infinity.
  1618. The `u M' (`calc-vector-mean') [`vmean'] command computes the
  1619. average (arithmetic mean) of the data values. If the inputs are error
  1620. forms `x +/- s', this is the weighted mean of the `x' values with
  1621. weights `1 / s^2'. If the inputs are not error forms, this is simply
  1622. the sum of the values divided by the count of the values.
  1623. Note that a plain number can be considered an error form with error
  1624. `s = 0'. If the input to `u M' is a mixture of plain numbers and error
  1625. forms, the result is the mean of the plain numbers, ignoring all values
  1626. with non-zero errors. (By the above definitions it's clear that a
  1627. plain number effectively has an infinite weight, next to which an error
  1628. form with a finite weight is completely negligible.)
  1629. This function also works for distributions (error forms or
  1630. intervals). The mean of an error form `A +/- B' is simply `a'. The
  1631. mean of an interval is the mean of the minimum and maximum values of
  1632. the interval.
  1633. The `I u M' (`calc-vector-mean-error') [`vmeane'] command computes
  1634. the mean of the data points expressed as an error form. This includes
  1635. the estimated error associated with the mean. If the inputs are error
  1636. forms, the error is the square root of the reciprocal of the sum of the
  1637. reciprocals of the squares of the input errors. (I.e., the variance is
  1638. the reciprocal of the sum of the reciprocals of the variances.) If the
  1639. inputs are plain numbers, the error is equal to the standard deviation
  1640. of the values divided by the square root of the number of values.
  1641. (This works out to be equivalent to calculating the standard deviation
  1642. and then assuming each value's error is equal to this standard
  1643. deviation.)
  1644. The `H u M' (`calc-vector-median') [`vmedian'] command computes the
  1645. median of the data values. The values are first sorted into numerical
  1646. order; the median is the middle value after sorting. (If the number of
  1647. data values is even, the median is taken to be the average of the two
  1648. middle values.) The median function is different from the other
  1649. functions in this section in that the arguments must all be real
  1650. numbers; variables are not accepted even when nested inside vectors.
  1651. (Otherwise it is not possible to sort the data values.) If any of the
  1652. input values are error forms, their error parts are ignored.
  1653. The median function also accepts distributions. For both normal
  1654. (error form) and uniform (interval) distributions, the median is the
  1655. same as the mean.
  1656. The `H I u M' (`calc-vector-harmonic-mean') [`vhmean'] command
  1657. computes the harmonic mean of the data values. This is defined as the
  1658. reciprocal of the arithmetic mean of the reciprocals of the values.
  1659. The `u G' (`calc-vector-geometric-mean') [`vgmean'] command computes
  1660. the geometric mean of the data values. This is the Nth root of the
  1661. product of the values. This is also equal to the `exp' of the
  1662. arithmetic mean of the logarithms of the data values.
  1663. The `H u G' [`agmean'] command computes the "arithmetic-geometric
  1664. mean" of two numbers taken from the stack. This is computed by
  1665. replacing the two numbers with their arithmetic mean and geometric
  1666. mean, then repeating until the two values converge.
  1667. Another commonly used mean, the RMS (root-mean-square), can be
  1668. computed for a vector of numbers simply by using the `A' command.
  1669. The `u S' (`calc-vector-sdev') [`vsdev'] command computes the
  1670. standard deviation of the data values. If the values are error forms,
  1671. the errors are used as weights just as for `u M'. This is the _sample_
  1672. standard deviation, whose value is the square root of the sum of the
  1673. squares of the differences between the values and the mean of the `N'
  1674. values, divided by `N-1'.
  1675. This function also applies to distributions. The standard deviation
  1676. of a single error form is simply the error part. The standard deviation
  1677. of a continuous interval happens to equal the difference between the
  1678. limits, divided by `sqrt(12)'. The standard deviation of an integer
  1679. interval is the same as the standard deviation of a vector of those
  1680. integers.
  1681. The `I u S' (`calc-vector-pop-sdev') [`vpsdev'] command computes the
  1682. _population_ standard deviation. It is defined by the same formula as
  1683. above but dividing by `N' instead of by `N-1'. The population standard
  1684. deviation is used when the input represents the entire set of data
  1685. values in the distribution; the sample standard deviation is used when
  1686. the input represents a sample of the set of all data values, so that
  1687. the mean computed from the input is itself only an estimate of the true
  1688. mean.
  1689. For error forms and continuous intervals, `vpsdev' works exactly
  1690. like `vsdev'. For integer intervals, it computes the population
  1691. standard deviation of the equivalent vector of integers.
  1692. The `H u S' (`calc-vector-variance') [`vvar'] and `H I u S'
  1693. (`calc-vector-pop-variance') [`vpvar'] commands compute the variance of
  1694. the data values. The variance is the square of the standard deviation,
  1695. i.e., the sum of the squares of the deviations of the data values from
  1696. the mean. (This definition also applies when the argument is a
  1697. distribution.)
  1698. The `vflat' algebraic function returns a vector of its arguments,
  1699. interpreted in the same way as the other functions in this section.
  1700. For example, `vflat(1, [2, [3, 4]], 5)' returns `[1, 2, 3, 4, 5]'.
  1701. 
  1702. File: calc, Node: Paired-Sample Statistics, Prev: Single-Variable Statistics, Up: Statistical Operations
  1703. 11.7.2 Paired-Sample Statistics
  1704. -------------------------------
  1705. The functions in this section take two arguments, which must be vectors
  1706. of equal size. The vectors are each flattened in the same way as by
  1707. the single-variable statistical functions. Given a numeric prefix
  1708. argument of 1, these functions instead take one object from the stack,
  1709. which must be an Nx2 matrix of data values. Once again, variable names
  1710. can be used in place of actual vectors and matrices.
  1711. The `u C' (`calc-vector-covariance') [`vcov'] command computes the
  1712. sample covariance of two vectors. The covariance of vectors X and Y is
  1713. the sum of the products of the differences between the elements of X
  1714. and the mean of X times the differences between the corresponding
  1715. elements of Y and the mean of Y, all divided by `N-1'. Note that the
  1716. variance of a vector is just the covariance of the vector with itself.
  1717. Once again, if the inputs are error forms the errors are used as weight
  1718. factors. If both X and Y are composed of error forms, the error for a
  1719. given data point is taken as the square root of the sum of the squares
  1720. of the two input errors.
  1721. The `I u C' (`calc-vector-pop-covariance') [`vpcov'] command
  1722. computes the population covariance, which is the same as the sample
  1723. covariance computed by `u C' except dividing by `N' instead of `N-1'.
  1724. The `H u C' (`calc-vector-correlation') [`vcorr'] command computes
  1725. the linear correlation coefficient of two vectors. This is defined by
  1726. the covariance of the vectors divided by the product of their standard
  1727. deviations. (There is no difference between sample or population
  1728. statistics here.)
  1729. 
  1730. File: calc, Node: Reducing and Mapping, Next: Vector and Matrix Formats, Prev: Statistical Operations, Up: Matrix Functions
  1731. 11.8 Reducing and Mapping Vectors
  1732. =================================
  1733. The commands in this section allow for more general operations on the
  1734. elements of vectors.
  1735. The simplest of these operations is `V A' (`calc-apply') [`apply'],
  1736. which applies a given operator to the elements of a vector. For
  1737. example, applying the hypothetical function `f' to the vector
  1738. `[1, 2, 3]' would produce the function call `f(1, 2, 3)'. Applying the
  1739. `+' function to the vector `[a, b]' gives `a + b'. Applying `+' to the
  1740. vector `[a, b, c]' is an error, since the `+' function expects exactly
  1741. two arguments.
  1742. While `V A' is useful in some cases, you will usually find that
  1743. either `V R' or `V M', described below, is closer to what you want.
  1744. * Menu:
  1745. * Specifying Operators::
  1746. * Mapping::
  1747. * Reducing::
  1748. * Nesting and Fixed Points::
  1749. * Generalized Products::
  1750. 
  1751. File: calc, Node: Specifying Operators, Next: Mapping, Prev: Reducing and Mapping, Up: Reducing and Mapping
  1752. 11.8.1 Specifying Operators
  1753. ---------------------------
  1754. Commands in this section (like `V A') prompt you to press the key
  1755. corresponding to the desired operator. Press `?' for a partial list of
  1756. the available operators. Generally, an operator is any key or sequence
  1757. of keys that would normally take one or more arguments from the stack
  1758. and replace them with a result. For example, `V A H C' uses the
  1759. hyperbolic cosine operator, `cosh'. (Since `cosh' expects one
  1760. argument, `V A H C' requires a vector with a single element as its
  1761. argument.)
  1762. You can press `x' at the operator prompt to select any algebraic
  1763. function by name to use as the operator. This includes functions you
  1764. have defined yourself using the `Z F' command. (*Note Algebraic
  1765. Definitions::.) If you give a name for which no function has been
  1766. defined, the result is left in symbolic form, as in `f(1, 2, 3)'. Calc
  1767. will prompt for the number of arguments the function takes if it can't
  1768. figure it out on its own (say, because you named a function that is
  1769. currently undefined). It is also possible to type a digit key before
  1770. the function name to specify the number of arguments, e.g., `V M 3 x f
  1771. <RET>' calls `f' with three arguments even if it looks like it ought to
  1772. have only two. This technique may be necessary if the function allows
  1773. a variable number of arguments. For example, the `v e' [`vexp']
  1774. function accepts two or three arguments; if you want to map with the
  1775. three-argument version, you will have to type `V M 3 v e'.
  1776. It is also possible to apply any formula to a vector by treating that
  1777. formula as a function. When prompted for the operator to use, press
  1778. `'' (the apostrophe) and type your formula as an algebraic entry. You
  1779. will then be prompted for the argument list, which defaults to a list
  1780. of all variables that appear in the formula, sorted into alphabetic
  1781. order. For example, suppose you enter the formula `x + 2y^x'. The
  1782. default argument list would be `(x y)', which means that if this
  1783. function is applied to the arguments `[3, 10]' the result will be `3 +
  1784. 2*10^3'. (If you plan to use a certain formula in this way often, you
  1785. might consider defining it as a function with `Z F'.)
  1786. Another way to specify the arguments to the formula you enter is with
  1787. `$', `$$', and so on. For example, `V A ' $$ + 2$^$$' has the same
  1788. effect as the previous example. The argument list is automatically
  1789. taken to be `($$ $)'. (The order of the arguments may seem backwards,
  1790. but it is analogous to the way normal algebraic entry interacts with
  1791. the stack.)
  1792. If you press `$' at the operator prompt, the effect is similar to
  1793. the apostrophe except that the relevant formula is taken from
  1794. top-of-stack instead. The actual vector arguments of the `V A $' or
  1795. related command then start at the second-to-top stack position. You
  1796. will still be prompted for an argument list.
  1797. A function can be written without a name using the notation `<#1 -
  1798. #2>', which means "a function of two arguments that computes the first
  1799. argument minus the second argument." The symbols `#1' and `#2' are
  1800. placeholders for the arguments. You can use any names for these
  1801. placeholders if you wish, by including an argument list followed by a
  1802. colon: `<x, y : x - y>'. When you type `V A ' $$ + 2$^$$ <RET>', Calc
  1803. builds the nameless function `<#1 + 2 #2^#1>' as the function to map
  1804. across the vectors. When you type `V A ' x + 2y^x <RET> <RET>', Calc
  1805. builds the nameless function `<x, y : x + 2 y^x>'. In both cases, Calc
  1806. also writes the nameless function to the Trail so that you can get it
  1807. back later if you wish.
  1808. If there is only one argument, you can write `#' in place of `#1'.
  1809. (Note that `< >' notation is also used for date forms. Calc tells that
  1810. `<STUFF>' is a nameless function by the presence of `#' signs inside
  1811. STUFF, or by the fact that STUFF begins with a list of variables
  1812. followed by a colon.)
  1813. You can type a nameless function directly to `V A '', or put one on
  1814. the stack and use it with `V A $'. Calc will not prompt for an
  1815. argument list in this case, since the nameless function specifies the
  1816. argument list as well as the function itself. In `V A '', you can omit
  1817. the `< >' marks if you use `#' notation for the arguments, so that `V A
  1818. ' #1+#2 <RET>' is the same as `V A ' <#1+#2> <RET>', which in turn is
  1819. the same as `V A ' $$+$ <RET>'.
  1820. The internal format for `<x, y : x + y>' is `lambda(x, y, x + y)'.
  1821. (The word `lambda' derives from Lisp notation and the theory of
  1822. functions.) The internal format for `<#1 + #2>' is `lambda(ArgA, ArgB,
  1823. ArgA + ArgB)'. Note that there is no actual Calc function called
  1824. `lambda'; the whole point is that the `lambda' expression is used in
  1825. its symbolic form, not evaluated for an answer until it is applied to
  1826. specific arguments by a command like `V A' or `V M'.
  1827. (Actually, `lambda' does have one special property: Its arguments
  1828. are never evaluated; for example, putting `<(2/3) #>' on the stack will
  1829. not simplify the `2/3' until the nameless function is actually called.)
  1830. As usual, commands like `V A' have algebraic function name
  1831. equivalents. For example, `V A k g' with an argument of `v' is
  1832. equivalent to `apply(gcd, v)'. The first argument specifies the
  1833. operator name, and is either a variable whose name is the same as the
  1834. function name, or a nameless function like `<#^3+1>'. Operators that
  1835. are normally written as algebraic symbols have the names `add', `sub',
  1836. `mul', `div', `pow', `neg', `mod', and `vconcat'.
  1837. The `call' function builds a function call out of several arguments:
  1838. `call(gcd, x, y)' is the same as `apply(gcd, [x, y])', which in turn is
  1839. the same as `gcd(x, y)'. The first argument of `call', like the other
  1840. functions described here, may be either a variable naming a function,
  1841. or a nameless function (`call(<#1+2#2>, x, y)' is the same as `x + 2y').
  1842. (Experts will notice that it's not quite proper to use a variable to
  1843. name a function, since the name `gcd' corresponds to the Lisp variable
  1844. `var-gcd' but to the Lisp function `calcFunc-gcd'. Calc automatically
  1845. makes this translation, so you don't have to worry about it.)
  1846. 
  1847. File: calc, Node: Mapping, Next: Reducing, Prev: Specifying Operators, Up: Reducing and Mapping
  1848. 11.8.2 Mapping
  1849. --------------
  1850. The `V M' (`calc-map') [`map'] command applies a given operator
  1851. elementwise to one or more vectors. For example, mapping `A' [`abs']
  1852. produces a vector of the absolute values of the elements in the input
  1853. vector. Mapping `+' pops two vectors from the stack, which must be of
  1854. equal length, and produces a vector of the pairwise sums of the
  1855. elements. If either argument is a non-vector, it is duplicated for
  1856. each element of the other vector. For example, `[1,2,3] 2 V M ^'
  1857. squares the elements of the specified vector. With the 2 listed first,
  1858. it would have computed a vector of powers of two. Mapping a
  1859. user-defined function pops as many arguments from the stack as the
  1860. function requires. If you give an undefined name, you will be prompted
  1861. for the number of arguments to use.
  1862. If any argument to `V M' is a matrix, the operator is normally mapped
  1863. across all elements of the matrix. For example, given the matrix `[[1,
  1864. -2, 3], [-4, 5, -6]]', `V M A' takes six absolute values to produce
  1865. another 3x2 matrix, `[[1, 2, 3], [4, 5, 6]]'.
  1866. The command `V M _' [`mapr'] (i.e., type an underscore at the
  1867. operator prompt) maps by rows instead. For example, `V M _ A' views
  1868. the above matrix as a vector of two 3-element row vectors. It produces
  1869. a new vector which contains the absolute values of those row vectors,
  1870. namely `[3.74, 8.77]'. (Recall, the absolute value of a vector is
  1871. defined as the square root of the sum of the squares of the elements.)
  1872. Some operators accept vectors and return new vectors; for example, `v
  1873. v' reverses a vector, so `V M _ v v' would reverse each row of the
  1874. matrix to get a new matrix, `[[3, -2, 1], [-6, 5, -4]]'.
  1875. Sometimes a vector of vectors (representing, say, strings, sets, or
  1876. lists) happens to look like a matrix. If so, remember to use `V M _'
  1877. if you want to map a function across the whole strings or sets rather
  1878. than across their individual elements.
  1879. The command `V M :' [`mapc'] maps by columns. Basically, it
  1880. transposes the input matrix, maps by rows, and then, if the result is a
  1881. matrix, transposes again. For example, `V M : A' takes the absolute
  1882. values of the three columns of the matrix, treating each as a 2-vector,
  1883. and `V M : v v' reverses the columns to get the matrix `[[-4, 5, -6],
  1884. [1, -2, 3]]'.
  1885. (The symbols `_' and `:' were chosen because they had row-like and
  1886. column-like appearances, and were not already taken by useful
  1887. operators. Also, they appear shifted on most keyboards so they are easy
  1888. to type after `V M'.)
  1889. The `_' and `:' modifiers have no effect on arguments that are not
  1890. matrices (so if none of the arguments are matrices, they have no effect
  1891. at all). If some of the arguments are matrices and others are plain
  1892. numbers, the plain numbers are held constant for all rows of the matrix
  1893. (so that `2 V M _ ^' squares every row of a matrix; squaring a vector
  1894. takes a dot product of the vector with itself).
  1895. If some of the arguments are vectors with the same lengths as the
  1896. rows (for `V M _') or columns (for `V M :') of the matrix arguments,
  1897. those vectors are also held constant for every row or column.
  1898. Sometimes it is useful to specify another mapping command as the
  1899. operator to use with `V M'. For example, `V M _ V A +' applies `V A +'
  1900. to each row of the input matrix, which in turn adds the two values on
  1901. that row. If you give another vector-operator command as the operator
  1902. for `V M', it automatically uses map-by-rows mode if you don't specify
  1903. otherwise; thus `V M V A +' is equivalent to `V M _ V A +'. (If you
  1904. really want to map-by-elements another mapping command, you can use a
  1905. triple-nested mapping command: `V M V M V A +' means to map `V M V A
  1906. +' over the rows of the matrix; in turn, `V A +' is mapped over the
  1907. elements of each row.)
  1908. Previous versions of Calc had "map across" and "map down" modes that
  1909. are now considered obsolete; the old "map across" is now simply `V M V
  1910. A', and "map down" is now `V M : V A'. The algebraic functions `mapa'
  1911. and `mapd' are still supported, though. Note also that, while the old
  1912. mapping modes were persistent (once you set the mode, it would apply to
  1913. later mapping commands until you reset it), the new `:' and `_'
  1914. modifiers apply only to the current mapping command. The default `V M'
  1915. always means map-by-elements.
  1916. *Note Algebraic Manipulation::, for the `a M' command, which is like
  1917. `V M' but for equations and inequalities instead of vectors. *Note
  1918. Storing Variables::, for the `s m' command which modifies a variable's
  1919. stored value using a `V M'-like operator.
  1920. 
  1921. File: calc, Node: Reducing, Next: Nesting and Fixed Points, Prev: Mapping, Up: Reducing and Mapping
  1922. 11.8.3 Reducing
  1923. ---------------
  1924. The `V R' (`calc-reduce') [`reduce'] command applies a given binary
  1925. operator across all the elements of a vector. A binary operator is a
  1926. function such as `+' or `max' which takes two arguments. For example,
  1927. reducing `+' over a vector computes the sum of the elements of the
  1928. vector. Reducing `-' computes the first element minus each of the
  1929. remaining elements. Reducing `max' computes the maximum element and so
  1930. on. In general, reducing `f' over the vector `[a, b, c, d]' produces
  1931. `f(f(f(a, b), c), d)'.
  1932. The `I V R' [`rreduce'] command is similar to `V R' except that
  1933. works from right to left through the vector. For example, plain `V R
  1934. -' on the vector `[a, b, c, d]' produces `a - b - c - d' but `I V R -'
  1935. on the same vector produces `a - (b - (c - d))', or `a - b + c - d'.
  1936. This "alternating sum" occurs frequently in power series expansions.
  1937. The `V U' (`calc-accumulate') [`accum'] command does an accumulation
  1938. operation. Here Calc does the corresponding reduction operation, but
  1939. instead of producing only the final result, it produces a vector of all
  1940. the intermediate results. Accumulating `+' over the vector `[a, b, c,
  1941. d]' produces the vector `[a, a + b, a + b + c, a + b + c + d]'.
  1942. The `I V U' [`raccum'] command does a right-to-left accumulation.
  1943. For example, `I V U -' on the vector `[a, b, c, d]' produces the vector
  1944. `[a - b + c - d, b - c + d, c - d, d]'.
  1945. As for `V M', `V R' normally reduces a matrix elementwise. For
  1946. example, given the matrix `[[a, b, c], [d, e, f]]', `V R +' will
  1947. compute `a + b + c + d + e + f'. You can type `V R _' or `V R :' to
  1948. modify this behavior. The `V R _' [`reducea'] command reduces "across"
  1949. the matrix; it reduces each row of the matrix as a vector, then
  1950. collects the results. Thus `V R _ +' of this matrix would produce `[a
  1951. + b + c, d + e + f]'. Similarly, `V R :' [`reduced'] reduces down; `V
  1952. R : +' would produce `[a + d, b + e, c + f]'.
  1953. There is a third "by rows" mode for reduction that is occasionally
  1954. useful; `V R =' [`reducer'] simply reduces the operator over the rows
  1955. of the matrix themselves. Thus `V R = +' on the above matrix would get
  1956. the same result as `V R : +', since adding two row vectors is
  1957. equivalent to adding their elements. But `V R = *' would multiply the
  1958. two rows (to get a single number, their dot product), while `V R : *'
  1959. would produce a vector of the products of the columns.
  1960. These three matrix reduction modes work with `V R' and `I V R', but
  1961. they are not currently supported with `V U' or `I V U'.
  1962. The obsolete reduce-by-columns function, `reducec', is still
  1963. supported but there is no way to get it through the `V R' command.
  1964. The commands `C-x * :' and `C-x * _' are equivalent to typing `C-x *
  1965. r' to grab a rectangle of data into Calc, and then typing `V R : +' or
  1966. `V R _ +', respectively, to sum the columns or rows of the matrix.
  1967. *Note Grabbing From Buffers::.
  1968. 
  1969. File: calc, Node: Nesting and Fixed Points, Next: Generalized Products, Prev: Reducing, Up: Reducing and Mapping
  1970. 11.8.4 Nesting and Fixed Points
  1971. -------------------------------
  1972. The `H V R' [`nest'] command applies a function to a given argument
  1973. repeatedly. It takes two values, `a' and `n', from the stack, where
  1974. `n' must be an integer. It then applies the function nested `n' times;
  1975. if the function is `f' and `n' is 3, the result is `f(f(f(a)))'. The
  1976. number `n' may be negative if Calc knows an inverse for the function
  1977. `f'; for example, `nest(sin, a, -2)' returns `arcsin(arcsin(a))'.
  1978. The `H V U' [`anest'] command is an accumulating version of `nest':
  1979. It returns a vector of `n+1' values, e.g., `[a, f(a), f(f(a)),
  1980. f(f(f(a)))]'. If `n' is negative and `F' is the inverse of `f', then
  1981. the result is of the form `[a, F(a), F(F(a)), F(F(F(a)))]'.
  1982. The `H I V R' [`fixp'] command is like `H V R', except that it takes
  1983. only an `a' value from the stack; the function is applied until it
  1984. reaches a "fixed point," i.e., until the result no longer changes.
  1985. The `H I V U' [`afixp'] command is an accumulating `fixp'. The
  1986. first element of the return vector will be the initial value `a'; the
  1987. last element will be the final result that would have been returned by
  1988. `fixp'.
  1989. For example, 0.739085 is a fixed point of the cosine function (in
  1990. radians): `cos(0.739085) = 0.739085'. You can find this value by
  1991. putting, say, 1.0 on the stack and typing `H I V U C'. (We use the
  1992. accumulating version so we can see the intermediate results: `[1,
  1993. 0.540302, 0.857553, 0.65329, ...]'. With a precision of six, this
  1994. command will take 36 steps to converge to 0.739085.)
  1995. Newton's method for finding roots is a classic example of iteration
  1996. to a fixed point. To find the square root of five starting with an
  1997. initial guess, Newton's method would look for a fixed point of the
  1998. function `(x + 5/x) / 2'. Putting a guess of 1 on the stack and typing
  1999. `H I V R ' ($ + 5/$)/2 <RET>' quickly yields the result 2.23607. This
  2000. is equivalent to using the `a R' (`calc-find-root') command to find a
  2001. root of the equation `x^2 = 5'.
  2002. These examples used numbers for `a' values. Calc keeps applying the
  2003. function until two successive results are equal to within the current
  2004. precision. For complex numbers, both the real parts and the imaginary
  2005. parts must be equal to within the current precision. If `a' is a
  2006. formula (say, a variable name), then the function is applied until two
  2007. successive results are exactly the same formula. It is up to you to
  2008. ensure that the function will eventually converge; if it doesn't, you
  2009. may have to press `C-g' to stop the Calculator.
  2010. The algebraic `fixp' function takes two optional arguments, `n' and
  2011. `tol'. The first is the maximum number of steps to be allowed, and
  2012. must be either an integer or the symbol `inf' (infinity, the default).
  2013. The second is a convergence tolerance. If a tolerance is specified,
  2014. all results during the calculation must be numbers, not formulas, and
  2015. the iteration stops when the magnitude of the difference between two
  2016. successive results is less than or equal to the tolerance. (This
  2017. implies that a tolerance of zero iterates until the results are exactly
  2018. equal.)
  2019. Putting it all together, `fixp(<(# + A/#)/2>, B, 20, 1e-10)'
  2020. computes the square root of `A' given the initial guess `B', stopping
  2021. when the result is correct within the specified tolerance, or when 20
  2022. steps have been taken, whichever is sooner.
  2023. 
  2024. File: calc, Node: Generalized Products, Prev: Nesting and Fixed Points, Up: Reducing and Mapping
  2025. 11.8.5 Generalized Products
  2026. ---------------------------
  2027. The `V O' (`calc-outer-product') [`outer'] command applies a given
  2028. binary operator to all possible pairs of elements from two vectors, to
  2029. produce a matrix. For example, `V O *' with `[a, b]' and `[x, y, z]'
  2030. on the stack produces a multiplication table: `[[a x, a y, a z], [b x,
  2031. b y, b z]]'. Element R,C of the result matrix is obtained by applying
  2032. the operator to element R of the lefthand vector and element C of the
  2033. righthand vector.
  2034. The `V I' (`calc-inner-product') [`inner'] command computes the
  2035. generalized inner product of two vectors or matrices, given a
  2036. "multiplicative" operator and an "additive" operator. These can each
  2037. actually be any binary operators; if they are `*' and `+',
  2038. respectively, the result is a standard matrix multiplication. Element
  2039. R,C of the result matrix is obtained by mapping the multiplicative
  2040. operator across row R of the lefthand matrix and column C of the
  2041. righthand matrix, and then reducing with the additive operator. Just
  2042. as for the standard `*' command, this can also do a vector-matrix or
  2043. matrix-vector inner product, or a vector-vector generalized dot product.
  2044. Since `V I' requires two operators, it prompts twice. In each case,
  2045. you can use any of the usual methods for entering the operator. If you
  2046. use `$' twice to take both operator formulas from the stack, the first
  2047. (multiplicative) operator is taken from the top of the stack and the
  2048. second (additive) operator is taken from second-to-top.
  2049. 
  2050. File: calc, Node: Vector and Matrix Formats, Prev: Reducing and Mapping, Up: Matrix Functions
  2051. 11.9 Vector and Matrix Display Formats
  2052. ======================================
  2053. Commands for controlling vector and matrix display use the `v' prefix
  2054. instead of the usual `d' prefix. But they are display modes; in
  2055. particular, they are influenced by the `I' and `H' prefix keys in the
  2056. same way (*note Display Modes::). Matrix display is also influenced by
  2057. the `d O' (`calc-flat-language') mode; *note Normal Language Modes::.
  2058. The commands `v <' (`calc-matrix-left-justify'), `v >'
  2059. (`calc-matrix-right-justify'), and `v =' (`calc-matrix-center-justify')
  2060. control whether matrix elements are justified to the left, right, or
  2061. center of their columns.
  2062. The `v [' (`calc-vector-brackets') command turns the square brackets
  2063. that surround vectors and matrices displayed in the stack on and off.
  2064. The `v {' (`calc-vector-braces') and `v (' (`calc-vector-parens')
  2065. commands use curly braces or parentheses, respectively, instead of
  2066. square brackets. For example, `v {' might be used in preparation for
  2067. yanking a matrix into a buffer running Mathematica. (In fact, the
  2068. Mathematica language mode uses this mode; *note Mathematica Language
  2069. Mode::.) Note that, regardless of the display mode, either brackets or
  2070. braces may be used to enter vectors, and parentheses may never be used
  2071. for this purpose.
  2072. The `v ]' (`calc-matrix-brackets') command controls the "big" style
  2073. display of matrices, for matrices which have more than one row. It
  2074. prompts for a string of code letters; currently implemented letters are
  2075. `R', which enables brackets on each row of the matrix; `O', which
  2076. enables outer brackets in opposite corners of the matrix; and `C',
  2077. which enables commas or semicolons at the ends of all rows but the
  2078. last. The default format is `RO'. (Before Calc 2.00, the format was
  2079. fixed at `ROC'.) Here are some example matrices:
  2080. [ [ 123, 0, 0 ] [ [ 123, 0, 0 ],
  2081. [ 0, 123, 0 ] [ 0, 123, 0 ],
  2082. [ 0, 0, 123 ] ] [ 0, 0, 123 ] ]
  2083. RO ROC
  2084. [ 123, 0, 0 [ 123, 0, 0 ;
  2085. 0, 123, 0 0, 123, 0 ;
  2086. 0, 0, 123 ] 0, 0, 123 ]
  2087. O OC
  2088. [ 123, 0, 0 ] 123, 0, 0
  2089. [ 0, 123, 0 ] 0, 123, 0
  2090. [ 0, 0, 123 ] 0, 0, 123
  2091. R blank
  2092. Note that of the formats shown here, `RO', `ROC', and `OC' are all
  2093. recognized as matrices during reading, while the others are useful for
  2094. display only.
  2095. The `v ,' (`calc-vector-commas') command turns commas on and off in
  2096. vector and matrix display.
  2097. In vectors of length one, and in all vectors when commas have been
  2098. turned off, Calc adds extra parentheses around formulas that might
  2099. otherwise be ambiguous. For example, `[a b]' could be a vector of the
  2100. one formula `a b', or it could be a vector of two variables with commas
  2101. turned off. Calc will display the former case as `[(a b)]'. You can
  2102. disable these extra parentheses (to make the output less cluttered at
  2103. the expense of allowing some ambiguity) by adding the letter `P' to the
  2104. control string you give to `v ]' (as described above).
  2105. The `v .' (`calc-full-vectors') command turns abbreviated display of
  2106. long vectors on and off. In this mode, vectors of six or more
  2107. elements, or matrices of six or more rows or columns, will be displayed
  2108. in an abbreviated form that displays only the first three elements and
  2109. the last element: `[a, b, c, ..., z]'. When very large vectors are
  2110. involved this will substantially improve Calc's display speed.
  2111. The `t .' (`calc-full-trail-vectors') command controls a similar
  2112. mode for recording vectors in the Trail. If you turn on this mode,
  2113. vectors of six or more elements and matrices of six or more rows or
  2114. columns will be abbreviated when they are put in the Trail. The `t y'
  2115. (`calc-trail-yank') command will be unable to recover those vectors.
  2116. If you are working with very large vectors, this mode will improve the
  2117. speed of all operations that involve the trail.
  2118. The `v /' (`calc-break-vectors') command turns multi-line vector
  2119. display on and off. Normally, matrices are displayed with one row per
  2120. line but all other types of vectors are displayed in a single line.
  2121. This mode causes all vectors, whether matrices or not, to be displayed
  2122. with a single element per line. Sub-vectors within the vectors will
  2123. still use the normal linear form.
  2124. 
  2125. File: calc, Node: Algebra, Next: Units, Prev: Matrix Functions, Up: Top
  2126. 12 Algebra
  2127. **********
  2128. This section covers the Calc features that help you work with algebraic
  2129. formulas. First, the general sub-formula selection mechanism is
  2130. described; this works in conjunction with any Calc commands. Then,
  2131. commands for specific algebraic operations are described. Finally, the
  2132. flexible "rewrite rule" mechanism is discussed.
  2133. The algebraic commands use the `a' key prefix; selection commands
  2134. use the `j' (for "just a letter that wasn't used for anything else")
  2135. prefix.
  2136. *Note Editing Stack Entries::, to see how to manipulate formulas
  2137. using regular Emacs editing commands.
  2138. When doing algebraic work, you may find several of the Calculator's
  2139. modes to be helpful, including Algebraic Simplification mode (`m A') or
  2140. No-Simplification mode (`m O'), Algebraic entry mode (`m a'), Fraction
  2141. mode (`m f'), and Symbolic mode (`m s'). *Note Mode Settings::, for
  2142. discussions of these modes. You may also wish to select Big display
  2143. mode (`d B'). *Note Normal Language Modes::.
  2144. * Menu:
  2145. * Selecting Subformulas::
  2146. * Algebraic Manipulation::
  2147. * Simplifying Formulas::
  2148. * Polynomials::
  2149. * Calculus::
  2150. * Solving Equations::
  2151. * Numerical Solutions::
  2152. * Curve Fitting::
  2153. * Summations::
  2154. * Logical Operations::
  2155. * Rewrite Rules::
  2156. 
  2157. File: calc, Node: Selecting Subformulas, Next: Algebraic Manipulation, Prev: Algebra, Up: Algebra
  2158. 12.1 Selecting Sub-Formulas
  2159. ===========================
  2160. When working with an algebraic formula it is often necessary to
  2161. manipulate a portion of the formula rather than the formula as a whole.
  2162. Calc allows you to "select" a portion of any formula on the stack.
  2163. Commands which would normally operate on that stack entry will now
  2164. operate only on the sub-formula, leaving the surrounding part of the
  2165. stack entry alone.
  2166. One common non-algebraic use for selection involves vectors. To work
  2167. on one element of a vector in-place, simply select that element as a
  2168. "sub-formula" of the vector.
  2169. * Menu:
  2170. * Making Selections::
  2171. * Changing Selections::
  2172. * Displaying Selections::
  2173. * Operating on Selections::
  2174. * Rearranging with Selections::
  2175. 
  2176. File: calc, Node: Making Selections, Next: Changing Selections, Prev: Selecting Subformulas, Up: Selecting Subformulas
  2177. 12.1.1 Making Selections
  2178. ------------------------
  2179. To select a sub-formula, move the Emacs cursor to any character in that
  2180. sub-formula, and press `j s' (`calc-select-here'). Calc will highlight
  2181. the smallest portion of the formula that contains that character. By
  2182. default the sub-formula is highlighted by blanking out all of the rest
  2183. of the formula with dots. Selection works in any display mode but is
  2184. perhaps easiest in Big mode (`d B'). Suppose you enter the following
  2185. formula:
  2186. 3 ___
  2187. (a + b) + V c
  2188. 1: ---------------
  2189. 2 x + 1
  2190. (by typing `' ((a+b)^3 + sqrt(c)) / (2x+1)'). If you move the cursor
  2191. to the letter `b' and press `j s', the display changes to
  2192. . ...
  2193. .. . b. . . .
  2194. 1* ...............
  2195. . . . .
  2196. Every character not part of the sub-formula `b' has been changed to a
  2197. dot. (If the customizable variable
  2198. `calc-highlight-selections-with-faces' is non-nil, then the characters
  2199. not part of the sub-formula are de-emphasized by using a less
  2200. noticeable face instead of using dots. *note Displaying Selections::.)
  2201. The `*' next to the line number is to remind you that the formula has a
  2202. portion of it selected. (In this case, it's very obvious, but it might
  2203. not always be. If Embedded mode is enabled, the word `Sel' also
  2204. appears in the mode line because the stack may not be visible. *note
  2205. Embedded Mode::.)
  2206. If you had instead placed the cursor on the parenthesis immediately
  2207. to the right of the `b', the selection would have been:
  2208. . ...
  2209. (a + b) . . .
  2210. 1* ...............
  2211. . . . .
  2212. The portion selected is always large enough to be considered a complete
  2213. formula all by itself, so selecting the parenthesis selects the whole
  2214. formula that it encloses. Putting the cursor on the `+' sign would
  2215. have had the same effect.
  2216. (Strictly speaking, the Emacs cursor is really the manifestation of
  2217. the Emacs "point," which is a position _between_ two characters in the
  2218. buffer. So purists would say that Calc selects the smallest
  2219. sub-formula which contains the character to the right of "point.")
  2220. If you supply a numeric prefix argument N, the selection is expanded
  2221. to the Nth enclosing sub-formula. Thus, positioning the cursor on the
  2222. `b' and typing `C-u 1 j s' will select `a + b'; typing `C-u 2 j s' will
  2223. select `(a + b)^3', and so on.
  2224. If the cursor is not on any part of the formula, or if you give a
  2225. numeric prefix that is too large, the entire formula is selected.
  2226. If the cursor is on the `.' line that marks the top of the stack
  2227. (i.e., its normal "rest position"), this command selects the entire
  2228. formula at stack level 1. Most selection commands similarly operate on
  2229. the formula at the top of the stack if you haven't positioned the
  2230. cursor on any stack entry.
  2231. The `j a' (`calc-select-additional') command enlarges the current
  2232. selection to encompass the cursor. To select the smallest sub-formula
  2233. defined by two different points, move to the first and press `j s',
  2234. then move to the other and press `j a'. This is roughly analogous to
  2235. using `C-@' (`set-mark-command') to select the two ends of a region of
  2236. text during normal Emacs editing.
  2237. The `j o' (`calc-select-once') command selects a formula in exactly
  2238. the same way as `j s', except that the selection will last only as long
  2239. as the next command that uses it. For example, `j o 1 +' is a handy
  2240. way to add one to the sub-formula indicated by the cursor.
  2241. (A somewhat more precise definition: The `j o' command sets a flag
  2242. such that the next command involving selected stack entries will clear
  2243. the selections on those stack entries afterwards. All other selection
  2244. commands except `j a' and `j O' clear this flag.)
  2245. The `j S' (`calc-select-here-maybe') and `j O'
  2246. (`calc-select-once-maybe') commands are equivalent to `j s' and `j o',
  2247. respectively, except that if the formula already has a selection they
  2248. have no effect. This is analogous to the behavior of some commands
  2249. such as `j r' (`calc-rewrite-selection'; *note Selections with Rewrite
  2250. Rules::) and is mainly intended to be used in keyboard macros that
  2251. implement your own selection-oriented commands.
  2252. Selection of sub-formulas normally treats associative terms like `a
  2253. + b - c + d' and `x * y * z' as single levels of the formula. If you
  2254. place the cursor anywhere inside `a + b - c + d' except on one of the
  2255. variable names and use `j s', you will select the entire four-term sum.
  2256. The `j b' (`calc-break-selections') command controls a mode in which
  2257. the "deep structure" of these associative formulas shows through. Calc
  2258. actually stores the above formulas as `((a + b) - c) + d' and `x * (y *
  2259. z)'. (Note that for certain obscure reasons, by default Calc treats
  2260. multiplication as right-associative.) Once you have enabled `j b'
  2261. mode, selecting with the cursor on the `-' sign would only select the
  2262. `a + b - c' portion, which makes sense when the deep structure of the
  2263. sum is considered. There is no way to select the `b - c + d' portion;
  2264. although this might initially look like just as legitimate a sub-formula
  2265. as `a + b - c', the deep structure shows that it isn't. The `d U'
  2266. command can be used to view the deep structure of any formula (*note
  2267. Normal Language Modes::).
  2268. When `j b' mode has not been enabled, the deep structure is
  2269. generally hidden by the selection commands--what you see is what you
  2270. get.
  2271. The `j u' (`calc-unselect') command unselects the formula that the
  2272. cursor is on. If there was no selection in the formula, this command
  2273. has no effect. With a numeric prefix argument, it unselects the Nth
  2274. stack element rather than using the cursor position.
  2275. The `j c' (`calc-clear-selections') command unselects all stack
  2276. elements.
  2277. 
  2278. File: calc, Node: Changing Selections, Next: Displaying Selections, Prev: Making Selections, Up: Selecting Subformulas
  2279. 12.1.2 Changing Selections
  2280. --------------------------
  2281. Once you have selected a sub-formula, you can expand it using the `j m'
  2282. (`calc-select-more') command. If `a + b' is selected, pressing `j m'
  2283. repeatedly works as follows:
  2284. 3 ... 3 ___ 3 ___
  2285. (a + b) . . . (a + b) + V c (a + b) + V c
  2286. 1* ............... 1* ............... 1* ---------------
  2287. . . . . . . . . 2 x + 1
  2288. In the last example, the entire formula is selected. This is roughly
  2289. the same as having no selection at all, but because there are subtle
  2290. differences the `*' character is still there on the line number.
  2291. With a numeric prefix argument N, `j m' expands N times (or until
  2292. the entire formula is selected). Note that `j s' with argument N is
  2293. equivalent to plain `j s' followed by `j m' with argument N. If `j m'
  2294. is used when there is no current selection, it is equivalent to `j s'.
  2295. Even though `j m' does not explicitly use the location of the cursor
  2296. within the formula, it nevertheless uses the cursor to determine which
  2297. stack element to operate on. As usual, `j m' when the cursor is not on
  2298. any stack element operates on the top stack element.
  2299. The `j l' (`calc-select-less') command reduces the current selection
  2300. around the cursor position. That is, it selects the immediate
  2301. sub-formula of the current selection which contains the cursor, the
  2302. opposite of `j m'. If the cursor is not inside the current selection,
  2303. the command de-selects the formula.
  2304. The `j 1' through `j 9' (`calc-select-part') commands select the Nth
  2305. sub-formula of the current selection. They are like `j l'
  2306. (`calc-select-less') except they use counting rather than the cursor
  2307. position to decide which sub-formula to select. For example, if the
  2308. current selection is `a + b + c' or `f(a, b, c)' or `[a, b, c]', then
  2309. `j 1' selects `a', `j 2' selects `b', and `j 3' selects `c'; in each of
  2310. these cases, `j 4' through `j 9' would be errors.
  2311. If there is no current selection, `j 1' through `j 9' select the Nth
  2312. top-level sub-formula. (In other words, they act as if the entire
  2313. stack entry were selected first.) To select the Nth sub-formula where
  2314. N is greater than nine, you must instead invoke `j 1' with N as a
  2315. numeric prefix argument.
  2316. The `j n' (`calc-select-next') and `j p' (`calc-select-previous')
  2317. commands change the current selection to the next or previous
  2318. sub-formula at the same level. For example, if `b' is selected in
  2319. `2 + a*b*c + x', then `j n' selects `c'. Further `j n' commands would
  2320. be in error because, even though there is something to the right of `c'
  2321. (namely, `x'), it is not at the same level; in this case, it is not a
  2322. term of the same product as `b' and `c'. However, `j m' (to select the
  2323. whole product `a*b*c' as a term of the sum) followed by `j n' would
  2324. successfully select the `x'.
  2325. Similarly, `j p' moves the selection from the `b' in this sample
  2326. formula to the `a'. Both commands accept numeric prefix arguments to
  2327. move several steps at a time.
  2328. It is interesting to compare Calc's selection commands with the
  2329. Emacs Info system's commands for navigating through hierarchically
  2330. organized documentation. Calc's `j n' command is completely analogous
  2331. to Info's `n' command. Likewise, `j p' maps to `p', `j 2' maps to `2',
  2332. and Info's `u' is like `j m'. (Note that `j u' stands for
  2333. `calc-unselect', not "up".) The Info `m' command is somewhat similar
  2334. to Calc's `j s' and `j l'; in each case, you can jump directly to a
  2335. sub-component of the hierarchy simply by pointing to it with the cursor.
  2336. 
  2337. File: calc, Node: Displaying Selections, Next: Operating on Selections, Prev: Changing Selections, Up: Selecting Subformulas
  2338. 12.1.3 Displaying Selections
  2339. ----------------------------
  2340. The `j d' (`calc-show-selections') command controls how selected
  2341. sub-formulas are displayed. One of the alternatives is illustrated in
  2342. the above examples; if we press `j d' we switch to the other style in
  2343. which the selected portion itself is obscured by `#' signs:
  2344. 3 ... # ___
  2345. (a + b) . . . ## # ## + V c
  2346. 1* ............... 1* ---------------
  2347. . . . . 2 x + 1
  2348. If the customizable variable `calc-highlight-selections-with-faces' is
  2349. non-nil, then the non-selected portion of the formula will be
  2350. de-emphasized by using a less noticeable face (`calc-nonselected-face')
  2351. instead of dots and the selected sub-formula will be highlighted by
  2352. using a more noticeable face (`calc-selected-face') instead of `#'
  2353. signs. (*note Customizing Calc::.)
  2354. 
  2355. File: calc, Node: Operating on Selections, Next: Rearranging with Selections, Prev: Displaying Selections, Up: Selecting Subformulas
  2356. 12.1.4 Operating on Selections
  2357. ------------------------------
  2358. Once a selection is made, all Calc commands that manipulate items on
  2359. the stack will operate on the selected portions of the items instead.
  2360. (Note that several stack elements may have selections at once, though
  2361. there can be only one selection at a time in any given stack element.)
  2362. The `j e' (`calc-enable-selections') command disables the effect
  2363. that selections have on Calc commands. The current selections still
  2364. exist, but Calc commands operate on whole stack elements anyway. This
  2365. mode can be identified by the fact that the `*' markers on the line
  2366. numbers are gone, even though selections are visible. To reactivate
  2367. the selections, press `j e' again.
  2368. To extract a sub-formula as a new formula, simply select the
  2369. sub-formula and press <RET>. This normally duplicates the top stack
  2370. element; here it duplicates only the selected portion of that element.
  2371. To replace a sub-formula with something different, you can enter the
  2372. new value onto the stack and press <TAB>. This normally exchanges the
  2373. top two stack elements; here it swaps the value you entered into the
  2374. selected portion of the formula, returning the old selected portion to
  2375. the top of the stack.
  2376. 3 ... ... ___
  2377. (a + b) . . . 17 x y . . . 17 x y + V c
  2378. 2* ............... 2* ............. 2: -------------
  2379. . . . . . . . . 2 x + 1
  2380. 3 3
  2381. 1: 17 x y 1: (a + b) 1: (a + b)
  2382. In this example we select a sub-formula of our original example,
  2383. enter a new formula, <TAB> it into place, then deselect to see the
  2384. complete, edited formula.
  2385. If you want to swap whole formulas around even though they contain
  2386. selections, just use `j e' before and after.
  2387. The `j '' (`calc-enter-selection') command is another way to replace
  2388. a selected sub-formula. This command does an algebraic entry just like
  2389. the regular `'' key. When you press <RET>, the formula you type
  2390. replaces the original selection. You can use the `$' symbol in the
  2391. formula to refer to the original selection. If there is no selection
  2392. in the formula under the cursor, the cursor is used to make a temporary
  2393. selection for the purposes of the command. Thus, to change a term of a
  2394. formula, all you have to do is move the Emacs cursor to that term and
  2395. press `j ''.
  2396. The `j `' (`calc-edit-selection') command is a similar analogue of
  2397. the ``' (`calc-edit') command. It edits the selected sub-formula in a
  2398. separate buffer. If there is no selection, it edits the sub-formula
  2399. indicated by the cursor.
  2400. To delete a sub-formula, press <DEL>. This generally replaces the
  2401. sub-formula with the constant zero, but in a few suitable contexts it
  2402. uses the constant one instead. The <DEL> key automatically deselects
  2403. and re-simplifies the entire formula afterwards. Thus:
  2404. ###
  2405. 17 x y + # # 17 x y 17 # y 17 y
  2406. 1* ------------- 1: ------- 1* ------- 1: -------
  2407. 2 x + 1 2 x + 1 2 x + 1 2 x + 1
  2408. In this example, we first delete the `sqrt(c)' term; Calc
  2409. accomplishes this by replacing `sqrt(c)' with zero and resimplifying.
  2410. We then delete the `x' in the numerator; since this is part of a
  2411. product, Calc replaces it with `1' and resimplifies.
  2412. If you select an element of a vector and press <DEL>, that element
  2413. is deleted from the vector. If you delete one side of an equation or
  2414. inequality, only the opposite side remains.
  2415. The `j <DEL>' (`calc-del-selection') command is like <DEL> but with
  2416. the auto-selecting behavior of `j '' and `j `'. It deletes the
  2417. selected portion of the formula indicated by the cursor, or, in the
  2418. absence of a selection, it deletes the sub-formula indicated by the
  2419. cursor position.
  2420. (There is also an auto-selecting `j <RET>' (`calc-copy-selection')
  2421. command.)
  2422. Normal arithmetic operations also apply to sub-formulas. Here we
  2423. select the denominator, press `5 -' to subtract five from the
  2424. denominator, press `n' to negate the denominator, then press `Q' to
  2425. take the square root.
  2426. .. . .. . .. . .. .
  2427. 1* ....... 1* ....... 1* ....... 1* ..........
  2428. 2 x + 1 2 x - 4 4 - 2 x _________
  2429. V 4 - 2 x
  2430. Certain types of operations on selections are not allowed. For
  2431. example, for an arithmetic function like `-' no more than one of the
  2432. arguments may be a selected sub-formula. (As the above example shows,
  2433. the result of the subtraction is spliced back into the argument which
  2434. had the selection; if there were more than one selection involved, this
  2435. would not be well-defined.) If you try to subtract two selections, the
  2436. command will abort with an error message.
  2437. Operations on sub-formulas sometimes leave the formula as a whole in
  2438. an "un-natural" state. Consider negating the `2 x' term of our sample
  2439. formula by selecting it and pressing `n' (`calc-change-sign').
  2440. .. . .. .
  2441. 1* .......... 1* ...........
  2442. ......... ..........
  2443. . . . 2 x . . . -2 x
  2444. Unselecting the sub-formula reveals that the minus sign, which would
  2445. normally have canceled out with the subtraction automatically, has not
  2446. been able to do so because the subtraction was not part of the selected
  2447. portion. Pressing `=' (`calc-evaluate') or doing any other
  2448. mathematical operation on the whole formula will cause it to be
  2449. simplified.
  2450. 17 y 17 y
  2451. 1: ----------- 1: ----------
  2452. __________ _________
  2453. V 4 - -2 x V 4 + 2 x
  2454. 
  2455. File: calc, Node: Rearranging with Selections, Prev: Operating on Selections, Up: Selecting Subformulas
  2456. 12.1.5 Rearranging Formulas using Selections
  2457. --------------------------------------------
  2458. The `j R' (`calc-commute-right') command moves the selected sub-formula
  2459. to the right in its surrounding formula. Generally the selection is
  2460. one term of a sum or product; the sum or product is rearranged
  2461. according to the commutative laws of algebra.
  2462. As with `j '' and `j <DEL>', the term under the cursor is used if
  2463. there is no selection in the current formula. All commands described
  2464. in this section share this property. In this example, we place the
  2465. cursor on the `a' and type `j R', then repeat.
  2466. 1: a + b - c 1: b + a - c 1: b - c + a
  2467. Note that in the final step above, the `a' is switched with the `c' but
  2468. the signs are adjusted accordingly. When moving terms of sums and
  2469. products, `j R' will never change the mathematical meaning of the
  2470. formula.
  2471. The selected term may also be an element of a vector or an argument
  2472. of a function. The term is exchanged with the one to its right. In
  2473. this case, the "meaning" of the vector or function may of course be
  2474. drastically changed.
  2475. 1: [a, b, c] 1: [b, a, c] 1: [b, c, a]
  2476. 1: f(a, b, c) 1: f(b, a, c) 1: f(b, c, a)
  2477. The `j L' (`calc-commute-left') command is like `j R' except that it
  2478. swaps the selected term with the one to its left.
  2479. With numeric prefix arguments, these commands move the selected term
  2480. several steps at a time. It is an error to try to move a term left or
  2481. right past the end of its enclosing formula. With numeric prefix
  2482. arguments of zero, these commands move the selected term as far as
  2483. possible in the given direction.
  2484. The `j D' (`calc-sel-distribute') command mixes the selected sum or
  2485. product into the surrounding formula using the distributive law. For
  2486. example, in `a * (b - c)' with the `b - c' selected, the result is `a b
  2487. - a c'. This also distributes products or quotients into surrounding
  2488. powers, and can also do transformations like `exp(a + b)' to `exp(a)
  2489. exp(b)', where `a + b' is the selected term, and `ln(a ^ b)' to `ln(a)
  2490. b', where `a ^ b' is the selected term.
  2491. For multiple-term sums or products, `j D' takes off one term at a
  2492. time: `a * (b + c - d)' goes to `a * (c - d) + a b' with the `c - d'
  2493. selected so that you can type `j D' repeatedly to expand completely.
  2494. The `j D' command allows a numeric prefix argument which specifies the
  2495. maximum number of times to expand at once; the default is one time only.
  2496. The `j D' command is implemented using rewrite rules. *Note
  2497. Selections with Rewrite Rules::. The rules are stored in the Calc
  2498. variable `DistribRules'. A convenient way to view these rules is to
  2499. use `s e' (`calc-edit-variable') which displays and edits the stored
  2500. value of a variable. Press `C-c C-c' to return from editing mode; be
  2501. careful not to make any actual changes or else you will affect the
  2502. behavior of future `j D' commands!
  2503. To extend `j D' to handle new cases, just edit `DistribRules' as
  2504. described above. You can then use the `s p' command to save this
  2505. variable's value permanently for future Calc sessions. *Note
  2506. Operations on Variables::.
  2507. The `j M' (`calc-sel-merge') command is the complement of `j D';
  2508. given `a b - a c' with either `a b' or `a c' selected, the result is `a
  2509. * (b - c)'. Once again, `j M' can also merge calls to functions like
  2510. `exp' and `ln'; examine the variable `MergeRules' to see all the
  2511. relevant rules.
  2512. The `j C' (`calc-sel-commute') command swaps the arguments of the
  2513. selected sum, product, or equation. It always behaves as if `j b' mode
  2514. were in effect, i.e., the sum `a + b + c' is treated as the nested sums
  2515. `(a + b) + c' by this command. If you put the cursor on the first `+',
  2516. the result is `(b + a) + c'; if you put the cursor on the second `+',
  2517. the result is `c + (a + b)' (which the default simplifications will
  2518. rearrange to `(c + a) + b'). The relevant rules are stored in the
  2519. variable `CommuteRules'.
  2520. You may need to turn default simplifications off (with the `m O'
  2521. command) in order to get the full benefit of `j C'. For example,
  2522. commuting `a - b' produces `-b + a', but the default simplifications
  2523. will "simplify" this right back to `a - b' if you don't turn them off.
  2524. The same is true of some of the other manipulations described in this
  2525. section.
  2526. The `j N' (`calc-sel-negate') command replaces the selected term
  2527. with the negative of that term, then adjusts the surrounding formula in
  2528. order to preserve the meaning. For example, given `exp(a - b)' where
  2529. `a - b' is selected, the result is `1 / exp(b - a)'. By contrast,
  2530. selecting a term and using the regular `n' (`calc-change-sign') command
  2531. negates the term without adjusting the surroundings, thus changing the
  2532. meaning of the formula as a whole. The rules variable is `NegateRules'.
  2533. The `j &' (`calc-sel-invert') command is similar to `j N' except it
  2534. takes the reciprocal of the selected term. For example, given `a -
  2535. ln(b)' with `b' selected, the result is `a + ln(1/b)'. The rules
  2536. variable is `InvertRules'.
  2537. The `j E' (`calc-sel-jump-equals') command moves the selected term
  2538. from one side of an equation to the other. Given `a + b = c + d' with
  2539. `c' selected, the result is `a + b - c = d'. This command also works
  2540. if the selected term is part of a `*', `/', or `^' formula. The
  2541. relevant rules variable is `JumpRules'.
  2542. The `j I' (`calc-sel-isolate') command isolates the selected term on
  2543. its side of an equation. It uses the `a S' (`calc-solve-for') command
  2544. to solve the equation, and the Hyperbolic flag affects it in the same
  2545. way. *Note Solving Equations::. When it applies, `j I' is often
  2546. easier to use than `j E'. It understands more rules of algebra, and
  2547. works for inequalities as well as equations.
  2548. The `j *' (`calc-sel-mult-both-sides') command prompts for a formula
  2549. using algebraic entry, then multiplies both sides of the selected
  2550. quotient or equation by that formula. It simplifies each side with `a
  2551. s' (`calc-simplify') before re-forming the quotient or equation. You
  2552. can suppress this simplification by providing a prefix argument: `C-u j
  2553. *'. There is also a `j /' (`calc-sel-div-both-sides') which is similar
  2554. to `j *' but dividing instead of multiplying by the factor you enter.
  2555. If the selection is a quotient with numerator 1, then Calc's default
  2556. simplifications would normally cancel the new factors. To prevent
  2557. this, when the `j *' command is used on a selection whose numerator is
  2558. 1 or -1, the denominator is expanded at the top level using the
  2559. distributive law (as if using the `C-u 1 a x' command). Suppose the
  2560. formula on the stack is `1 / (a + 1)' and you wish to multiplying the
  2561. top and bottom by `a - 1'. Calc's default simplifications would
  2562. normally change the result `(a - 1) /(a + 1) (a - 1)' back to the
  2563. original form by cancellation; when `j *' is used, Calc expands the
  2564. denominator to `a (a - 1) + a - 1' to prevent this.
  2565. If you wish the `j *' command to completely expand the denominator
  2566. of a quotient you can call it with a zero prefix: `C-u 0 j *'. For
  2567. example, if the formula on the stack is `1 / (sqrt(a) + 1)', you may
  2568. wish to eliminate the square root in the denominator by multiplying the
  2569. top and bottom by `sqrt(a) - 1'. If you did this simply by using a
  2570. simple `j *' command, you would get `(sqrt(a)-1)/ (sqrt(a) (sqrt(a) -
  2571. 1) + sqrt(a) - 1)'. Instead, you would probably want to use `C-u 0 j
  2572. *', which would expand the bottom and give you the desired result
  2573. `(sqrt(a)-1)/(a-1)'. More generally, if `j *' is called with an
  2574. argument of a positive integer N, then the denominator of the
  2575. expression will be expanded N times (as if with the `C-u N a x'
  2576. command).
  2577. If the selection is an inequality, `j *' and `j /' will accept any
  2578. factor, but will warn unless they can prove the factor is either
  2579. positive or negative. (In the latter case the direction of the
  2580. inequality will be switched appropriately.) *Note Declarations::, for
  2581. ways to inform Calc that a given variable is positive or negative. If
  2582. Calc can't tell for sure what the sign of the factor will be, it will
  2583. assume it is positive and display a warning message.
  2584. For selections that are not quotients, equations, or inequalities,
  2585. these commands pull out a multiplicative factor: They divide (or
  2586. multiply) by the entered formula, simplify, then multiply (or divide)
  2587. back by the formula.
  2588. The `j +' (`calc-sel-add-both-sides') and `j -'
  2589. (`calc-sel-sub-both-sides') commands analogously add to or subtract
  2590. from both sides of an equation or inequality. For other types of
  2591. selections, they extract an additive factor. A numeric prefix argument
  2592. suppresses simplification of the intermediate results.
  2593. The `j U' (`calc-sel-unpack') command replaces the selected function
  2594. call with its argument. For example, given `a + sin(x^2)' with
  2595. `sin(x^2)' selected, the result is `a + x^2'. (The `x^2' will remain
  2596. selected; if you wanted to change the `sin' to `cos', just press `C'
  2597. now to take the cosine of the selected part.)
  2598. The `j v' (`calc-sel-evaluate') command performs the normal default
  2599. simplifications on the selected sub-formula. These are the
  2600. simplifications that are normally done automatically on all results,
  2601. but which may have been partially inhibited by previous
  2602. selection-related operations, or turned off altogether by the `m O'
  2603. command. This command is just an auto-selecting version of the `a v'
  2604. command (*note Algebraic Manipulation::).
  2605. With a numeric prefix argument of 2, `C-u 2 j v' applies the `a s'
  2606. (`calc-simplify') command to the selected sub-formula. With a prefix
  2607. argument of 3 or more, e.g., `C-u j v' applies the `a e'
  2608. (`calc-simplify-extended') command. *Note Simplifying Formulas::.
  2609. With a negative prefix argument it simplifies at the top level only,
  2610. just as with `a v'. Here the "top" level refers to the top level of
  2611. the selected sub-formula.
  2612. The `j "' (`calc-sel-expand-formula') command is to `a "' (*note
  2613. Algebraic Manipulation::) what `j v' is to `a v'.
  2614. You can use the `j r' (`calc-rewrite-selection') command to define
  2615. other algebraic operations on sub-formulas. *Note Rewrite Rules::.
  2616. 
  2617. File: calc, Node: Algebraic Manipulation, Next: Simplifying Formulas, Prev: Selecting Subformulas, Up: Algebra
  2618. 12.2 Algebraic Manipulation
  2619. ===========================
  2620. The commands in this section perform general-purpose algebraic
  2621. manipulations. They work on the whole formula at the top of the stack
  2622. (unless, of course, you have made a selection in that formula).
  2623. Many algebra commands prompt for a variable name or formula. If you
  2624. answer the prompt with a blank line, the variable or formula is taken
  2625. from top-of-stack, and the normal argument for the command is taken
  2626. from the second-to-top stack level.
  2627. The `a v' (`calc-alg-evaluate') command performs the normal default
  2628. simplifications on a formula; for example, `a - -b' is changed to `a +
  2629. b'. These simplifications are normally done automatically on all Calc
  2630. results, so this command is useful only if you have turned default
  2631. simplifications off with an `m O' command. *Note Simplification
  2632. Modes::.
  2633. It is often more convenient to type `=', which is like `a v' but
  2634. which also substitutes stored values for variables in the formula. Use
  2635. `a v' if you want the variables to ignore their stored values.
  2636. If you give a numeric prefix argument of 2 to `a v', it simplifies
  2637. as if in Algebraic Simplification mode. This is equivalent to typing
  2638. `a s'; *note Simplifying Formulas::. If you give a numeric prefix of 3
  2639. or more, it uses Extended Simplification mode (`a e').
  2640. If you give a negative prefix argument -1, -2, or -3, it simplifies
  2641. in the corresponding mode but only works on the top-level function call
  2642. of the formula. For example, `(2 + 3) * (2 + 3)' will simplify to `(2
  2643. + 3)^2', without simplifying the sub-formulas `2 + 3'. As another
  2644. example, typing `V R +' to sum the vector `[1, 2, 3, 4]' produces the
  2645. formula `reduce(add, [1, 2, 3, 4])' in No-Simplify mode. Using `a v'
  2646. will evaluate this all the way to 10; using `C-u - a v' will evaluate
  2647. it only to `1 + 2 + 3 + 4'. (*Note Reducing and Mapping::.)
  2648. The `=' command corresponds to the `evalv' function, and the related
  2649. `N' command, which is like `=' but temporarily disables Symbolic mode
  2650. (`m s') during the evaluation, corresponds to the `evalvn' function.
  2651. (These commands interpret their prefix arguments differently than `a
  2652. v'; `=' treats the prefix as the number of stack elements to evaluate
  2653. at once, and `N' treats it as a temporary different working precision.)
  2654. The `evalvn' function can take an alternate working precision as an
  2655. optional second argument. This argument can be either an integer, to
  2656. set the precision absolutely, or a vector containing a single integer,
  2657. to adjust the precision relative to the current precision. Note that
  2658. `evalvn' with a larger than current precision will do the calculation
  2659. at this higher precision, but the result will as usual be rounded back
  2660. down to the current precision afterward. For example, `evalvn(pi -
  2661. 3.1415)' at a precision of 12 will return `9.265359e-5'; `evalvn(pi -
  2662. 3.1415, 30)' will return `9.26535897932e-5' (computing a 25-digit
  2663. result which is then rounded down to 12); and `evalvn(pi - 3.1415,
  2664. [-2])' will return `9.2654e-5'.
  2665. The `a "' (`calc-expand-formula') command expands functions into
  2666. their defining formulas wherever possible. For example, `deg(x^2)' is
  2667. changed to `180 x^2 / pi'. Most functions, like `sin' and `gcd', are
  2668. not defined by simple formulas and so are unaffected by this command.
  2669. One important class of functions which _can_ be expanded is the
  2670. user-defined functions created by the `Z F' command. *Note Algebraic
  2671. Definitions::. Other functions which `a "' can expand include the
  2672. probability distribution functions, most of the financial functions,
  2673. and the hyperbolic and inverse hyperbolic functions. A numeric prefix
  2674. argument affects `a "' in the same way as it does `a v': A positive
  2675. argument expands all functions in the formula and then simplifies in
  2676. various ways; a negative argument expands and simplifies only the
  2677. top-level function call.
  2678. The `a M' (`calc-map-equation') [`mapeq'] command applies a given
  2679. function or operator to one or more equations. It is analogous to `V
  2680. M', which operates on vectors instead of equations. *note Reducing and
  2681. Mapping::. For example, `a M S' changes `x = y+1' to `sin(x) =
  2682. sin(y+1)', and `a M +' with `x = y+1' and `6' on the stack produces
  2683. `x+6 = y+7'. With two equations on the stack, `a M +' would add the
  2684. lefthand sides together and the righthand sides together to get the two
  2685. respective sides of a new equation.
  2686. Mapping also works on inequalities. Mapping two similar inequalities
  2687. produces another inequality of the same type. Mapping an inequality
  2688. with an equation produces an inequality of the same type. Mapping a
  2689. `<=' with a `<' or `!=' (not-equal) produces a `<'. If inequalities
  2690. with opposite direction (e.g., `<' and `>') are mapped, the direction
  2691. of the second inequality is reversed to match the first: Using `a M +'
  2692. on `a < b' and `a > 2' reverses the latter to get `2 < a', which then
  2693. allows the combination `a + 2 < b + a', which the `a s' command can
  2694. then simplify to get `2 < b'.
  2695. Using `a M *', `a M /', `a M n', or `a M &' to negate or invert an
  2696. inequality will reverse the direction of the inequality. Other
  2697. adjustments to inequalities are _not_ done automatically; `a M S' will
  2698. change `x < y' to `sin(x) < sin(y)' even though this is not true for
  2699. all values of the variables.
  2700. With the Hyperbolic flag, `H a M' [`mapeqp'] does a plain mapping
  2701. operation without reversing the direction of any inequalities. Thus,
  2702. `H a M &' would change `x > 2' to `1/x > 0.5'. (This change is
  2703. mathematically incorrect, but perhaps you were fixing an inequality
  2704. which was already incorrect.)
  2705. With the Inverse flag, `I a M' [`mapeqr'] always reverses the
  2706. direction of the inequality. You might use `I a M C' to change `x < y'
  2707. to `cos(x) > cos(y)' if you know you are working with small positive
  2708. angles.
  2709. The `a b' (`calc-substitute') [`subst'] command substitutes all
  2710. occurrences of some variable or sub-expression of an expression with a
  2711. new sub-expression. For example, substituting `sin(x)' with `cos(y)'
  2712. in `2 sin(x)^2 + x sin(x) + sin(2 x)' produces `2 cos(y)^2 + x cos(y) +
  2713. sin(2 x)'. Note that this is a purely structural substitution; the
  2714. lone `x' and the `sin(2 x)' stayed the same because they did not look
  2715. like `sin(x)'. *Note Rewrite Rules::, for a more general method for
  2716. doing substitutions.
  2717. The `a b' command normally prompts for two formulas, the old one and
  2718. the new one. If you enter a blank line for the first prompt, all three
  2719. arguments are taken from the stack (new, then old, then target
  2720. expression). If you type an old formula but then enter a blank line
  2721. for the new one, the new formula is taken from top-of-stack and the
  2722. target from second-to-top. If you answer both prompts, the target is
  2723. taken from top-of-stack as usual.
  2724. Note that `a b' has no understanding of commutativity or
  2725. associativity. The pattern `x+y' will not match the formula `y+x'.
  2726. Also, `y+z' will not match inside the formula `x+y+z' because the `+'
  2727. operator is left-associative, so the "deep structure" of that formula
  2728. is `(x+y) + z'. Use `d U' (`calc-unformatted-language') mode to see
  2729. the true structure of a formula. The rewrite rule mechanism, discussed
  2730. later, does not have these limitations.
  2731. As an algebraic function, `subst' takes three arguments: Target
  2732. expression, old, new. Note that `subst' is always evaluated
  2733. immediately, even if its arguments are variables, so if you wish to put
  2734. a call to `subst' onto the stack you must turn the default
  2735. simplifications off first (with `m O').
  2736. 
  2737. File: calc, Node: Simplifying Formulas, Next: Polynomials, Prev: Algebraic Manipulation, Up: Algebra
  2738. 12.3 Simplifying Formulas
  2739. =========================
  2740. The `a s' (`calc-simplify') [`simplify'] command applies various
  2741. algebraic rules to simplify a formula. This includes rules which are
  2742. not part of the default simplifications because they may be too slow to
  2743. apply all the time, or may not be desirable all of the time. For
  2744. example, non-adjacent terms of sums are combined, as in `a + b + 2 a'
  2745. to `b + 3 a', and some formulas like `sin(arcsin(x))' are simplified to
  2746. `x'.
  2747. The sections below describe all the various kinds of algebraic
  2748. simplifications Calc provides in full detail. None of Calc's
  2749. simplification commands are designed to pull rabbits out of hats; they
  2750. simply apply certain specific rules to put formulas into less redundant
  2751. or more pleasing forms. Serious algebra in Calc must be done manually,
  2752. usually with a combination of selections and rewrite rules. *Note
  2753. Rearranging with Selections::. *Note Rewrite Rules::.
  2754. *Note Simplification Modes::, for commands to control what level of
  2755. simplification occurs automatically. Normally only the "default
  2756. simplifications" occur.
  2757. There are some simplifications that, while sometimes useful, are
  2758. never done automatically. For example, the `I' prefix can be given to
  2759. `a s'; the `I a s' command will change any trigonometric function to
  2760. the appropriate combination of `sin's and `cos's before simplifying.
  2761. This can be useful in simplifying even mildly complicated trigonometric
  2762. expressions. For example, while `a s' can reduce `sin(x) csc(x)' to
  2763. `1', it will not simplify `sin(x)^2 csc(x)'. The command `I a s' can
  2764. be used to simplify this latter expression; it will transform `sin(x)^2
  2765. csc(x)' into `sin(x)'. However, `I a s' will also perform some
  2766. "simplifications" which may not be desired; for example, it will
  2767. transform `tan(x)^2' into `sin(x)^2 / cos(x)^2'. The Hyperbolic prefix
  2768. `H' can be used similarly; the `H a s' will replace any hyperbolic
  2769. functions in the formula with the appropriate combinations of `sinh's
  2770. and `cosh's before simplifying.
  2771. * Menu:
  2772. * Default Simplifications::
  2773. * Algebraic Simplifications::
  2774. * Unsafe Simplifications::
  2775. * Simplification of Units::
  2776. 
  2777. File: calc, Node: Default Simplifications, Next: Algebraic Simplifications, Prev: Simplifying Formulas, Up: Simplifying Formulas
  2778. 12.3.1 Default Simplifications
  2779. ------------------------------
  2780. This section describes the "default simplifications," those which are
  2781. normally applied to all results. For example, if you enter the variable
  2782. `x' on the stack twice and push `+', Calc's default simplifications
  2783. automatically change `x + x' to `2 x'.
  2784. The `m O' command turns off the default simplifications, so that `x
  2785. + x' will remain in this form unless you give an explicit "simplify"
  2786. command like `=' or `a v'. *Note Algebraic Manipulation::. The `m D'
  2787. command turns the default simplifications back on.
  2788. The most basic default simplification is the evaluation of functions.
  2789. For example, `2 + 3' is evaluated to `5', and `sqrt(9)' is evaluated to
  2790. `3'. Evaluation does not occur if the arguments to a function are
  2791. somehow of the wrong type `tan([2,3,4])'), range (`tan(90)'), or number
  2792. (`tan(3,5)'), or if the function name is not recognized (`f(5)'), or if
  2793. Symbolic mode (*note Symbolic Mode::) prevents evaluation (`sqrt(2)').
  2794. Calc simplifies (evaluates) the arguments to a function before it
  2795. simplifies the function itself. Thus `sqrt(5+4)' is simplified to
  2796. `sqrt(9)' before the `sqrt' function itself is applied. There are very
  2797. few exceptions to this rule: `quote', `lambda', and `condition' (the
  2798. `::' operator) do not evaluate their arguments, `if' (the `? :'
  2799. operator) does not evaluate all of its arguments, and `evalto' does not
  2800. evaluate its lefthand argument.
  2801. Most commands apply the default simplifications to all arguments they
  2802. take from the stack, perform a particular operation, then simplify the
  2803. result before pushing it back on the stack. In the common special case
  2804. of regular arithmetic commands like `+' and `Q' [`sqrt'], the arguments
  2805. are simply popped from the stack and collected into a suitable function
  2806. call, which is then simplified (the arguments being simplified first as
  2807. part of the process, as described above).
  2808. The default simplifications are too numerous to describe completely
  2809. here, but this section will describe the ones that apply to the major
  2810. arithmetic operators. This list will be rather technical in nature,
  2811. and will probably be interesting to you only if you are a serious user
  2812. of Calc's algebra facilities.
  2813. As well as the simplifications described here, if you have stored
  2814. any rewrite rules in the variable `EvalRules' then these rules will
  2815. also be applied before any built-in default simplifications. *Note
  2816. Automatic Rewrites::, for details.
  2817. And now, on with the default simplifications:
  2818. Arithmetic operators like `+' and `*' always take two arguments in
  2819. Calc's internal form. Sums and products of three or more terms are
  2820. arranged by the associative law of algebra into a left-associative form
  2821. for sums, `((a + b) + c) + d', and (by default) a right-associative
  2822. form for products, `a * (b * (c * d))'. Formulas like `(a + b) + (c +
  2823. d)' are rearranged to left-associative form, though this rarely matters
  2824. since Calc's algebra commands are designed to hide the inner structure
  2825. of sums and products as much as possible. Sums and products in their
  2826. proper associative form will be written without parentheses in the
  2827. examples below.
  2828. Sums and products are _not_ rearranged according to the commutative
  2829. law (`a + b' to `b + a') except in a few special cases described below.
  2830. Some algebra programs always rearrange terms into a canonical order,
  2831. which enables them to see that `a b + b a' can be simplified to `2 a b'.
  2832. Calc assumes you have put the terms into the order you want and
  2833. generally leaves that order alone, with the consequence that formulas
  2834. like the above will only be simplified if you explicitly give the `a s'
  2835. command. *Note Algebraic Simplifications::.
  2836. Differences `a - b' are treated like sums `a + (-b)' for purposes of
  2837. simplification; one of the default simplifications is to rewrite `a +
  2838. (-b)' or `(-b) + a', where `-b' represents a "negative-looking" term,
  2839. into `a - b' form. "Negative-looking" means negative numbers, negated
  2840. formulas like `-x', and products or quotients in which either term is
  2841. negative-looking.
  2842. Other simplifications involving negation are `-(-x)' to `x'; `-(a
  2843. b)' or `-(a/b)' where either `a' or `b' is negative-looking, simplified
  2844. by negating that term, or else where `a' or `b' is any number, by
  2845. negating that number; `-(a + b)' to `-a - b', and `-(b - a)' to `a - b'.
  2846. (This, and rewriting `(-b) + a' to `a - b', are the only cases where
  2847. the order of terms in a sum is changed by the default simplifications.)
  2848. The distributive law is used to simplify sums in some cases: `a x +
  2849. b x' to `(a + b) x', where `a' represents a number or an implicit 1 or
  2850. -1 (as in `x' or `-x') and similarly for `b'. Use the `a c', `a f', or
  2851. `j M' commands to merge sums with non-numeric coefficients using the
  2852. distributive law.
  2853. The distributive law is only used for sums of two terms, or for
  2854. adjacent terms in a larger sum. Thus `a + b + b + c' is simplified to
  2855. `a + 2 b + c', but `a + b + c + b' is not simplified. The reason is
  2856. that comparing all terms of a sum with one another would require time
  2857. proportional to the square of the number of terms; Calc relegates
  2858. potentially slow operations like this to commands that have to be
  2859. invoked explicitly, like `a s'.
  2860. Finally, `a + 0' and `0 + a' are simplified to `a'. A consequence
  2861. of the above rules is that `0 - a' is simplified to `-a'.
  2862. The products `1 a' and `a 1' are simplified to `a'; `(-1) a' and `a
  2863. (-1)' are simplified to `-a'; `0 a' and `a 0' are simplified to `0',
  2864. except that in Matrix mode where `a' is not provably scalar the result
  2865. is the generic zero matrix `idn(0)', and that if `a' is infinite the
  2866. result is `nan'.
  2867. Also, `(-a) b' and `a (-b)' are simplified to `-(a b)', where this
  2868. occurs for negated formulas but not for regular negative numbers.
  2869. Products are commuted only to move numbers to the front: `a b 2' is
  2870. commuted to `2 a b'.
  2871. The product `a (b + c)' is distributed over the sum only if `a' and
  2872. at least one of `b' and `c' are numbers: `2 (x + 3)' goes to `2 x + 6'.
  2873. The formula `(-a) (b - c)', where `-a' is a negative number, is
  2874. rewritten to `a (c - b)'.
  2875. The distributive law of products and powers is used for adjacent
  2876. terms of the product: `x^a x^b' goes to `x^(a+b)' where `a' is a
  2877. number, or an implicit 1 (as in `x'), or the implicit one-half of
  2878. `sqrt(x)', and similarly for `b'. The result is written using `sqrt'
  2879. or `1/sqrt' if the sum of the powers is `1/2' or `-1/2', respectively.
  2880. If the sum of the powers is zero, the product is simplified to `1' or
  2881. to `idn(1)' if Matrix mode is enabled.
  2882. The product of a negative power times anything but another negative
  2883. power is changed to use division: `x^(-2) y' goes to `y / x^2' unless
  2884. Matrix mode is in effect and neither `x' nor `y' are scalar (in which
  2885. case it is considered unsafe to rearrange the order of the terms).
  2886. Finally, `a (b/c)' is rewritten to `(a b)/c', and also `(a/b) c' is
  2887. changed to `(a c)/b' unless in Matrix mode.
  2888. Simplifications for quotients are analogous to those for products.
  2889. The quotient `0 / x' is simplified to `0', with the same exceptions
  2890. that were noted for `0 x'. Likewise, `x / 1' and `x / (-1)' are
  2891. simplified to `x' and `-x', respectively.
  2892. The quotient `x / 0' is left unsimplified or changed to an infinite
  2893. quantity, as directed by the current infinite mode. *Note Infinite
  2894. Mode::.
  2895. The expression `a / b^(-c)' is changed to `a b^c', where `-c' is any
  2896. negative-looking power. Also, `1 / b^c' is changed to `b^(-c)' for any
  2897. power `c'.
  2898. Also, `(-a) / b' and `a / (-b)' go to `-(a/b)'; `(a/b) / c' goes to
  2899. `a / (b c)'; and `a / (b/c)' goes to `(a c) / b' unless Matrix mode
  2900. prevents this rearrangement. Similarly, `a / (b:c)' is simplified to
  2901. `(c:b) a' for any fraction `b:c'.
  2902. The distributive law is applied to `(a + b) / c' only if `c' and at
  2903. least one of `a' and `b' are numbers. Quotients of powers and square
  2904. roots are distributed just as described for multiplication.
  2905. Quotients of products cancel only in the leading terms of the
  2906. numerator and denominator. In other words, `a x b / a y b' is canceled
  2907. to `x b / y b' but not to `x / y'. Once again this is because full
  2908. cancellation can be slow; use `a s' to cancel all terms of the quotient.
  2909. Quotients of negative-looking values are simplified according to
  2910. `(-a) / (-b)' to `a / b', `(-a) / (b - c)' to `a / (c - b)', and `(a -
  2911. b) / (-c)' to `(b - a) / c'.
  2912. The formula `x^0' is simplified to `1', or to `idn(1)' in Matrix
  2913. mode. The formula `0^x' is simplified to `0' unless `x' is a negative
  2914. number, complex number or zero. If `x' is negative, complex or `0.0',
  2915. `0^x' is an infinity or an unsimplified formula according to the
  2916. current infinite mode. The expression `0^0' is simplified to `1'.
  2917. Powers of products or quotients `(a b)^c', `(a/b)^c' are distributed
  2918. to `a^c b^c', `a^c / b^c' only if `c' is an integer, or if either `a'
  2919. or `b' are nonnegative real numbers. Powers of powers `(a^b)^c' are
  2920. simplified to `a^(b c)' only when `c' is an integer and `b c' also
  2921. evaluates to an integer. Without these restrictions these
  2922. simplifications would not be safe because of problems with principal
  2923. values. (In other words, `((-3)^1:2)^2' is safe to simplify, but
  2924. `((-3)^2)^1:2' is not.) *Note Declarations::, for ways to inform Calc
  2925. that your variables satisfy these requirements.
  2926. As a special case of this rule, `sqrt(x)^n' is simplified to
  2927. `x^(n/2)' only for even integers `n'.
  2928. If `a' is known to be real, `b' is an even integer, and `c' is a
  2929. half- or quarter-integer, then `(a^b)^c' is simplified to `abs(a^(b
  2930. c))'.
  2931. Also, `(-a)^b' is simplified to `a^b' if `b' is an even integer, or
  2932. to `-(a^b)' if `b' is an odd integer, for any negative-looking
  2933. expression `-a'.
  2934. Square roots `sqrt(x)' generally act like one-half powers `x^1:2'
  2935. for the purposes of the above-listed simplifications.
  2936. Also, note that `1 / x^1:2' is changed to `x^(-1:2)', but `1 /
  2937. sqrt(x)' is left alone.
  2938. Generic identity matrices (*note Matrix Mode::) are simplified by the
  2939. following rules: `idn(a) + b' to `a + b' if `b' is provably scalar, or
  2940. expanded out if `b' is a matrix; `idn(a) + idn(b)' to `idn(a + b)';
  2941. `-idn(a)' to `idn(-a)'; `a idn(b)' to `idn(a b)' if `a' is provably
  2942. scalar, or to `a b' if `a' is provably non-scalar; `idn(a) idn(b)' to
  2943. `idn(a b)'; analogous simplifications for quotients involving `idn';
  2944. and `idn(a)^n' to `idn(a^n)' where `n' is an integer.
  2945. The `floor' function and other integer truncation functions vanish
  2946. if the argument is provably integer-valued, so that `floor(round(x))'
  2947. simplifies to `round(x)'. Also, combinations of `float', `floor' and
  2948. its friends, and `ffloor' and its friends, are simplified in appropriate
  2949. ways. *Note Integer Truncation::.
  2950. The expression `abs(-x)' changes to `abs(x)'. The expression
  2951. `abs(abs(x))' changes to `abs(x)'; in fact, `abs(x)' changes to `x' or
  2952. `-x' if `x' is provably nonnegative or nonpositive (*note
  2953. Declarations::).
  2954. While most functions do not recognize the variable `i' as an
  2955. imaginary number, the `arg' function does handle the two cases `arg(i)'
  2956. and `arg(-i)' just for convenience.
  2957. The expression `conj(conj(x))' simplifies to `x'. Various other
  2958. expressions involving `conj', `re', and `im' are simplified, especially
  2959. if some of the arguments are provably real or involve the constant `i'.
  2960. For example, `conj(a + b i)' is changed to `conj(a) - conj(b) i', or
  2961. to `a - b i' if `a' and `b' are known to be real.
  2962. Functions like `sin' and `arctan' generally don't have any default
  2963. simplifications beyond simply evaluating the functions for suitable
  2964. numeric arguments and infinity. The `a s' command described in the
  2965. next section does provide some simplifications for these functions,
  2966. though.
  2967. One important simplification that does occur is that `ln(e)' is
  2968. simplified to 1, and `ln(e^x)' is simplified to `x' for any `x'. This
  2969. occurs even if you have stored a different value in the Calc variable
  2970. `e'; but this would be a bad idea in any case if you were also using
  2971. natural logarithms!
  2972. Among the logical functions, !(A <= B) changes to A > B and so on.
  2973. Equations and inequalities where both sides are either negative-looking
  2974. or zero are simplified by negating both sides and reversing the
  2975. inequality. While it might seem reasonable to simplify `!!x' to `x',
  2976. this would not be valid in general because `!!2' is 1, not 2.
  2977. Most other Calc functions have few if any default simplifications
  2978. defined, aside of course from evaluation when the arguments are
  2979. suitable numbers.
  2980. 
  2981. File: calc, Node: Algebraic Simplifications, Next: Unsafe Simplifications, Prev: Default Simplifications, Up: Simplifying Formulas
  2982. 12.3.2 Algebraic Simplifications
  2983. --------------------------------
  2984. The `a s' command makes simplifications that may be too slow to do all
  2985. the time, or that may not be desirable all of the time. If you find
  2986. these simplifications are worthwhile, you can type `m A' to have Calc
  2987. apply them automatically.
  2988. This section describes all simplifications that are performed by the
  2989. `a s' command. Note that these occur in addition to the default
  2990. simplifications; even if the default simplifications have been turned
  2991. off by an `m O' command, `a s' will turn them back on temporarily while
  2992. it simplifies the formula.
  2993. There is a variable, `AlgSimpRules', in which you can put rewrites
  2994. to be applied by `a s'. Its use is analogous to `EvalRules', but
  2995. without the special restrictions. Basically, the simplifier does `a r
  2996. AlgSimpRules' with an infinite repeat count on the whole expression
  2997. being simplified, then it traverses the expression applying the
  2998. built-in rules described below. If the result is different from the
  2999. original expression, the process repeats with the default
  3000. simplifications (including `EvalRules'), then `AlgSimpRules', then the
  3001. built-in simplifications, and so on.
  3002. Sums are simplified in two ways. Constant terms are commuted to the
  3003. end of the sum, so that `a + 2 + b' changes to `a + b + 2'. The only
  3004. exception is that a constant will not be commuted away from the first
  3005. position of a difference, i.e., `2 - x' is not commuted to `-x + 2'.
  3006. Also, terms of sums are combined by the distributive law, as in `x +
  3007. y + 2 x' to `y + 3 x'. This always occurs for adjacent terms, but `a
  3008. s' compares all pairs of terms including non-adjacent ones.
  3009. Products are sorted into a canonical order using the commutative
  3010. law. For example, `b c a' is commuted to `a b c'. This allows easier
  3011. comparison of products; for example, the default simplifications will
  3012. not change `x y + y x' to `2 x y', but `a s' will; it first rewrites
  3013. the sum to `x y + x y', and then the default simplifications are able
  3014. to recognize a sum of identical terms.
  3015. The canonical ordering used to sort terms of products has the
  3016. property that real-valued numbers, interval forms and infinities come
  3017. first, and are sorted into increasing order. The `V S' command uses
  3018. the same ordering when sorting a vector.
  3019. Sorting of terms of products is inhibited when Matrix mode is turned
  3020. on; in this case, Calc will never exchange the order of two terms
  3021. unless it knows at least one of the terms is a scalar.
  3022. Products of powers are distributed by comparing all pairs of terms,
  3023. using the same method that the default simplifications use for adjacent
  3024. terms of products.
  3025. Even though sums are not sorted, the commutative law is still taken
  3026. into account when terms of a product are being compared. Thus `(x + y)
  3027. (y + x)' will be simplified to `(x + y)^2'. A subtle point is that `(x
  3028. - y) (y - x)' will _not_ be simplified to `-(x - y)^2'; Calc does not
  3029. notice that one term can be written as a constant times the other, even
  3030. if that constant is -1.
  3031. A fraction times any expression, `(a:b) x', is changed to a quotient
  3032. involving integers: `a x / b'. This is not done for floating-point
  3033. numbers like `0.5', however. This is one reason why you may find it
  3034. convenient to turn Fraction mode on while doing algebra; *note Fraction
  3035. Mode::.
  3036. Quotients are simplified by comparing all terms in the numerator
  3037. with all terms in the denominator for possible cancellation using the
  3038. distributive law. For example, `a x^2 b / c x^3 d' will cancel `x^2'
  3039. from the top and bottom to get `a b / c x d'. (The terms in the
  3040. denominator will then be rearranged to `c d x' as described above.) If
  3041. there is any common integer or fractional factor in the numerator and
  3042. denominator, it is canceled out; for example, `(4 x + 6) / 8 x'
  3043. simplifies to `(2 x + 3) / 4 x'.
  3044. Non-constant common factors are not found even by `a s'. To cancel
  3045. the factor `a' in `(a x + a) / a^2' you could first use `j M' on the
  3046. product `a x' to Merge the numerator to `a (1+x)', which can then be
  3047. simplified successfully.
  3048. Integer powers of the variable `i' are simplified according to the
  3049. identity `i^2 = -1'. If you store a new value other than the complex
  3050. number `(0,1)' in `i', this simplification will no longer occur. This
  3051. is done by `a s' instead of by default in case someone (unwisely) uses
  3052. the name `i' for a variable unrelated to complex numbers; it would be
  3053. unfortunate if Calc quietly and automatically changed this formula for
  3054. reasons the user might not have been thinking of.
  3055. Square roots of integer or rational arguments are simplified in
  3056. several ways. (Note that these will be left unevaluated only in
  3057. Symbolic mode.) First, square integer or rational factors are pulled
  3058. out so that `sqrt(8)' is rewritten as `2 sqrt(2)'. Conceptually
  3059. speaking this implies factoring the argument into primes and moving
  3060. pairs of primes out of the square root, but for reasons of efficiency
  3061. Calc only looks for primes up to 29.
  3062. Square roots in the denominator of a quotient are moved to the
  3063. numerator: `1 / sqrt(3)' changes to `sqrt(3) / 3'. The same effect
  3064. occurs for the square root of a fraction: `sqrt(2:3)' changes to
  3065. `sqrt(6) / 3'.
  3066. The `%' (modulo) operator is simplified in several ways when the
  3067. modulus `M' is a positive real number. First, if the argument is of
  3068. the form `x + n' for some real number `n', then `n' is itself reduced
  3069. modulo `M'. For example, `(x - 23) % 10' is simplified to `(x + 7) %
  3070. 10'.
  3071. If the argument is multiplied by a constant, and this constant has a
  3072. common integer divisor with the modulus, then this factor is canceled
  3073. out. For example, `12 x % 15' is changed to `3 (4 x % 5)' by factoring
  3074. out 3. Also, `(12 x + 1) % 15' is changed to `3 ((4 x + 1:3) % 5)'.
  3075. While these forms may not seem "simpler," they allow Calc to discover
  3076. useful information about modulo forms in the presence of declarations.
  3077. If the modulus is 1, then Calc can use `int' declarations to
  3078. evaluate the expression. For example, the idiom `x % 2' is often used
  3079. to check whether a number is odd or even. As described above,
  3080. `2 n % 2' and `(2 n + 1) % 2' are simplified to `2 (n % 1)' and `2 ((n
  3081. + 1:2) % 1)', respectively; Calc can simplify these to 0 and 1
  3082. (respectively) if `n' has been declared to be an integer.
  3083. Trigonometric functions are simplified in several ways. Whenever a
  3084. products of two trigonometric functions can be replaced by a single
  3085. function, the replacement is made; for example, `tan(x) cos(x)' is
  3086. simplified to `sin(x)'. Reciprocals of trigonometric functions are
  3087. replaced by their reciprocal function; for example, `1/sec(x)' is
  3088. simplified to `cos(x)'. The corresponding simplifications for the
  3089. hyperbolic functions are also handled.
  3090. Trigonometric functions of their inverse functions are simplified.
  3091. The expression `sin(arcsin(x))' is simplified to `x', and similarly for
  3092. `cos' and `tan'. Trigonometric functions of inverses of different
  3093. trigonometric functions can also be simplified, as in `sin(arccos(x))'
  3094. to `sqrt(1 - x^2)'.
  3095. If the argument to `sin' is negative-looking, it is simplified to
  3096. `-sin(x)', and similarly for `cos' and `tan'. Finally, certain special
  3097. values of the argument are recognized; *note Trigonometric and
  3098. Hyperbolic Functions::.
  3099. Hyperbolic functions of their inverses and of negative-looking
  3100. arguments are also handled, as are exponentials of inverse hyperbolic
  3101. functions.
  3102. No simplifications for inverse trigonometric and hyperbolic
  3103. functions are known, except for negative arguments of `arcsin',
  3104. `arctan', `arcsinh', and `arctanh'. Note that `arcsin(sin(x))' can
  3105. _not_ safely change to `x', since this only correct within an integer
  3106. multiple of `2 pi' radians or 360 degrees. However, `arcsinh(sinh(x))'
  3107. is simplified to `x' if `x' is known to be real.
  3108. Several simplifications that apply to logarithms and exponentials
  3109. are that `exp(ln(x))', `e^ln(x)', and `10^log10(x)' all reduce to `x'.
  3110. Also, `ln(exp(x))', etc., can reduce to `x' if `x' is provably real.
  3111. The form `exp(x)^y' is simplified to `exp(x y)'. If `x' is a suitable
  3112. multiple of `pi i' (as described above for the trigonometric
  3113. functions), then `exp(x)' or `e^x' will be expanded. Finally, `ln(x)'
  3114. is simplified to a form involving `pi' and `i' where `x' is provably
  3115. negative, positive imaginary, or negative imaginary.
  3116. The error functions `erf' and `erfc' are simplified when their
  3117. arguments are negative-looking or are calls to the `conj' function.
  3118. Equations and inequalities are simplified by canceling factors of
  3119. products, quotients, or sums on both sides. Inequalities change sign
  3120. if a negative multiplicative factor is canceled. Non-constant
  3121. multiplicative factors as in `a b = a c' are canceled from equations
  3122. only if they are provably nonzero (generally because they were declared
  3123. so; *note Declarations::). Factors are canceled from inequalities only
  3124. if they are nonzero and their sign is known.
  3125. Simplification also replaces an equation or inequality with 1 or 0
  3126. ("true" or "false") if it can through the use of declarations. If `x'
  3127. is declared to be an integer greater than 5, then `x < 3', `x = 3', and
  3128. `x = 7.5' are all simplified to 0, but `x > 3' is simplified to 1. By
  3129. a similar analysis, `abs(x) >= 0' is simplified to 1, as is `x^2 >= 0'
  3130. if `x' is known to be real.
  3131. 
  3132. File: calc, Node: Unsafe Simplifications, Next: Simplification of Units, Prev: Algebraic Simplifications, Up: Simplifying Formulas
  3133. 12.3.3 "Unsafe" Simplifications
  3134. -------------------------------
  3135. The `a e' (`calc-simplify-extended') [`esimplify'] command is like `a s'
  3136. except that it applies some additional simplifications which are not
  3137. "safe" in all cases. Use this only if you know the values in your
  3138. formula lie in the restricted ranges for which these simplifications
  3139. are valid. The symbolic integrator uses `a e'; one effect of this is
  3140. that the integrator's results must be used with caution. Where an
  3141. integral table will often attach conditions like "for positive `a'
  3142. only," Calc (like most other symbolic integration programs) will simply
  3143. produce an unqualified result.
  3144. Because `a e''s simplifications are unsafe, it is sometimes better
  3145. to type `C-u -3 a v', which does extended simplification only on the
  3146. top level of the formula without affecting the sub-formulas. In fact,
  3147. `C-u -3 j v' allows you to target extended simplification to any
  3148. specific part of a formula.
  3149. The variable `ExtSimpRules' contains rewrites to be applied by the
  3150. `a e' command. These are applied in addition to `EvalRules' and
  3151. `AlgSimpRules'. (The `a r AlgSimpRules' step described above is simply
  3152. followed by an `a r ExtSimpRules' step.)
  3153. Following is a complete list of "unsafe" simplifications performed
  3154. by `a e'.
  3155. Inverse trigonometric or hyperbolic functions, called with their
  3156. corresponding non-inverse functions as arguments, are simplified by `a
  3157. e'. For example, `arcsin(sin(x))' changes to `x'. Also,
  3158. `arcsin(cos(x))' and `arccos(sin(x))' both change to `pi/2 - x'. These
  3159. simplifications are unsafe because they are valid only for values of
  3160. `x' in a certain range; outside that range, values are folded down to
  3161. the 360-degree range that the inverse trigonometric functions always
  3162. produce.
  3163. Powers of powers `(x^a)^b' are simplified to `x^(a b)' for all `a'
  3164. and `b'. These results will be valid only in a restricted range of
  3165. `x'; for example, in `(x^2)^1:2' the powers cancel to get `x', which is
  3166. valid for positive values of `x' but not for negative or complex values.
  3167. Similarly, `sqrt(x^a)' and `sqrt(x)^a' are both simplified (possibly
  3168. unsafely) to `x^(a/2)'.
  3169. Forms like `sqrt(1 - sin(x)^2)' are simplified to, e.g., `cos(x)'.
  3170. Calc has identities of this sort for `sin', `cos', `tan', `sinh', and
  3171. `cosh'.
  3172. Arguments of square roots are partially factored to look for squared
  3173. terms that can be extracted. For example, `sqrt(a^2 b^3 + a^3 b^2)'
  3174. simplifies to `a b sqrt(a+b)'.
  3175. The simplifications of `ln(exp(x))', `ln(e^x)', and `log10(10^x)' to
  3176. `x' are also unsafe because of problems with principal values (although
  3177. these simplifications are safe if `x' is known to be real).
  3178. Common factors are canceled from products on both sides of an
  3179. equation, even if those factors may be zero: `a x / b x' to `a / b'.
  3180. Such factors are never canceled from inequalities: Even `a e' is not
  3181. bold enough to reduce `a x < b x' to `a < b' (or `a > b', depending on
  3182. whether you believe `x' is positive or negative). The `a M /' command
  3183. can be used to divide a factor out of both sides of an inequality.
  3184. 
  3185. File: calc, Node: Simplification of Units, Prev: Unsafe Simplifications, Up: Simplifying Formulas
  3186. 12.3.4 Simplification of Units
  3187. ------------------------------
  3188. The simplifications described in this section are applied by the `u s'
  3189. (`calc-simplify-units') command. These are in addition to the regular
  3190. `a s' (but not `a e') simplifications described earlier. *Note Basic
  3191. Operations on Units::.
  3192. The variable `UnitSimpRules' contains rewrites to be applied by the
  3193. `u s' command. These are applied in addition to `EvalRules' and
  3194. `AlgSimpRules'.
  3195. Scalar mode is automatically put into effect when simplifying units.
  3196. *Note Matrix Mode::.
  3197. Sums `a + b' involving units are simplified by extracting the units
  3198. of `a' as if by the `u x' command (call the result `u_a'), then
  3199. simplifying the expression `b / u_a' using `u b' and `u s'. If the
  3200. result has units then the sum is inconsistent and is left alone.
  3201. Otherwise, it is rewritten in terms of the units `u_a'.
  3202. If units auto-ranging mode is enabled, products or quotients in
  3203. which the first argument is a number which is out of range for the
  3204. leading unit are modified accordingly.
  3205. When canceling and combining units in products and quotients, Calc
  3206. accounts for unit names that differ only in the prefix letter. For
  3207. example, `2 km m' is simplified to `2000 m^2'. However, compatible but
  3208. different units like `ft' and `in' are not combined in this way.
  3209. Quotients `a / b' are simplified in three additional ways. First,
  3210. if `b' is a number or a product beginning with a number, Calc computes
  3211. the reciprocal of this number and moves it to the numerator.
  3212. Second, for each pair of unit names from the numerator and
  3213. denominator of a quotient, if the units are compatible (e.g., they are
  3214. both units of area) then they are replaced by the ratio between those
  3215. units. For example, in `3 s in N / kg cm' the units `in / cm' will be
  3216. replaced by `2.54'.
  3217. Third, if the units in the quotient exactly cancel out, so that a `u
  3218. b' command on the quotient would produce a dimensionless number for an
  3219. answer, then the quotient simplifies to that number.
  3220. For powers and square roots, the "unsafe" simplifications `(a b)^c'
  3221. to `a^c b^c', `(a/b)^c' to `a^c / b^c', and `(a^b)^c' to `a^(b c)' are
  3222. done if the powers are real numbers. (These are safe in the context of
  3223. units because all numbers involved can reasonably be assumed to be
  3224. real.)
  3225. Also, if a unit name is raised to a fractional power, and the base
  3226. units in that unit name all occur to powers which are a multiple of the
  3227. denominator of the power, then the unit name is expanded out into its
  3228. base units, which can then be simplified according to the previous
  3229. paragraph. For example, `acre^1.5' is simplified by noting that `1.5 =
  3230. 3:2', that `acre' is defined in terms of `m^2', and that the 2 in the
  3231. power of `m' is a multiple of 2 in `3:2'. Thus, `acre^1.5' is replaced
  3232. by approximately `(4046 m^2)^1.5', which is then changed to `4046^1.5
  3233. (m^2)^1.5', then to `257440 m^3'.
  3234. The functions `float', `frac', `clean', `abs', as well as `floor'
  3235. and the other integer truncation functions, applied to unit names or
  3236. products or quotients involving units, are simplified. For example,
  3237. `round(1.6 in)' is changed to `round(1.6) round(in)'; the lefthand term
  3238. evaluates to 2, and the righthand term simplifies to `in'.
  3239. The functions `sin', `cos', and `tan' with arguments that have
  3240. angular units like `rad' or `arcmin' are simplified by converting to
  3241. base units (radians), then evaluating with the angular mode temporarily
  3242. set to radians.
  3243. 
  3244. File: calc, Node: Polynomials, Next: Calculus, Prev: Simplifying Formulas, Up: Algebra
  3245. 12.4 Polynomials
  3246. ================
  3247. A "polynomial" is a sum of terms which are coefficients times various
  3248. powers of a "base" variable. For example, `2 x^2 + 3 x - 4' is a
  3249. polynomial in `x'. Some formulas can be considered polynomials in
  3250. several different variables: `1 + 2 x + 3 y + 4 x y^2' is a polynomial
  3251. in both `x' and `y'. Polynomial coefficients are often numbers, but
  3252. they may in general be any formulas not involving the base variable.
  3253. The `a f' (`calc-factor') [`factor'] command factors a polynomial
  3254. into a product of terms. For example, the polynomial `x^3 + 2 x^2 + x'
  3255. is factored into `x*(x+1)^2'. As another example, `a c + b d + b c + a
  3256. d' is factored into the product `(a + b) (c + d)'.
  3257. Calc currently has three algorithms for factoring. Formulas which
  3258. are linear in several variables, such as the second example above, are
  3259. merged according to the distributive law. Formulas which are
  3260. polynomials in a single variable, with constant integer or fractional
  3261. coefficients, are factored into irreducible linear and/or quadratic
  3262. terms. The first example above factors into three linear terms (`x',
  3263. `x+1', and `x+1' again). Finally, formulas which do not fit the above
  3264. criteria are handled by the algebraic rewrite mechanism.
  3265. Calc's polynomial factorization algorithm works by using the general
  3266. root-finding command (`a P') to solve for the roots of the polynomial.
  3267. It then looks for roots which are rational numbers or complex-conjugate
  3268. pairs, and converts these into linear and quadratic terms,
  3269. respectively. Because it uses floating-point arithmetic, it may be
  3270. unable to find terms that involve large integers (whose number of
  3271. digits approaches the current precision). Also, irreducible factors of
  3272. degree higher than quadratic are not found, and polynomials in more
  3273. than one variable are not treated. (A more robust factorization
  3274. algorithm may be included in a future version of Calc.)
  3275. The rewrite-based factorization method uses rules stored in the
  3276. variable `FactorRules'. *Note Rewrite Rules::, for a discussion of the
  3277. operation of rewrite rules. The default `FactorRules' are able to
  3278. factor quadratic forms symbolically into two linear terms, `(a x + b)
  3279. (c x + d)'. You can edit these rules to include other cases if you
  3280. wish. To use the rules, Calc builds the formula `thecoefs(x, [a, b, c,
  3281. ...])' where `x' is the polynomial base variable and `a', `b', etc.,
  3282. are polynomial coefficients (which may be numbers or formulas). The
  3283. constant term is written first, i.e., in the `a' position. When the
  3284. rules complete, they should have changed the formula into the form
  3285. `thefactors(x, [f1, f2, f3, ...])' where each `fi' should be a factored
  3286. term, e.g., `x - ai'. Calc then multiplies these terms together to get
  3287. the complete factored form of the polynomial. If the rules do not
  3288. change the `thecoefs' call to a `thefactors' call, `a f' leaves the
  3289. polynomial alone on the assumption that it is unfactorable. (Note that
  3290. the function names `thecoefs' and `thefactors' are used only as
  3291. placeholders; there are no actual Calc functions by those names.)
  3292. The `H a f' [`factors'] command also factors a polynomial, but it
  3293. returns a list of factors instead of an expression which is the product
  3294. of the factors. Each factor is represented by a sub-vector of the
  3295. factor, and the power with which it appears. For example, `x^5 + x^4 -
  3296. 33 x^3 + 63 x^2' factors to `(x + 7) x^2 (x - 3)^2' in `a f', or to `[
  3297. [x, 2], [x+7, 1], [x-3, 2] ]' in `H a f'. If there is an overall
  3298. numeric factor, it always comes first in the list. The functions
  3299. `factor' and `factors' allow a second argument when written in
  3300. algebraic form; `factor(x,v)' factors `x' with respect to the specific
  3301. variable `v'. The default is to factor with respect to all the
  3302. variables that appear in `x'.
  3303. The `a c' (`calc-collect') [`collect'] command rearranges a formula
  3304. as a polynomial in a given variable, ordered in decreasing powers of
  3305. that variable. For example, given `1 + 2 x + 3 y + 4 x y^2' on the
  3306. stack, `a c x' would produce `(2 + 4 y^2) x + (1 + 3 y)', and `a c y'
  3307. would produce `(4 x) y^2 + 3 y + (1 + 2 x)'. The polynomial will be
  3308. expanded out using the distributive law as necessary: Collecting `x'
  3309. in `(x - 1)^3' produces `x^3 - 3 x^2 + 3 x - 1'. Terms not involving
  3310. `x' will not be expanded.
  3311. The "variable" you specify at the prompt can actually be any
  3312. expression: `a c ln(x+1)' will collect together all terms multiplied by
  3313. `ln(x+1)' or integer powers thereof. If `x' also appears in the
  3314. formula in a context other than `ln(x+1)', `a c' will treat those
  3315. occurrences as unrelated to `ln(x+1)', i.e., as constants.
  3316. The `a x' (`calc-expand') [`expand'] command expands an expression
  3317. by applying the distributive law everywhere. It applies to products,
  3318. quotients, and powers involving sums. By default, it fully distributes
  3319. all parts of the expression. With a numeric prefix argument, the
  3320. distributive law is applied only the specified number of times, then
  3321. the partially expanded expression is left on the stack.
  3322. The `a x' and `j D' commands are somewhat redundant. Use `a x' if
  3323. you want to expand all products of sums in your formula. Use `j D' if
  3324. you want to expand a particular specified term of the formula. There
  3325. is an exactly analogous correspondence between `a f' and `j M'. (The
  3326. `j D' and `j M' commands also know many other kinds of expansions, such
  3327. as `exp(a + b) = exp(a) exp(b)', which `a x' and `a f' do not do.)
  3328. Calc's automatic simplifications will sometimes reverse a partial
  3329. expansion. For example, the first step in expanding `(x+1)^3' is to
  3330. write `(x+1) (x+1)^2'. If `a x' stops there and tries to put this
  3331. formula onto the stack, though, Calc will automatically simplify it
  3332. back to `(x+1)^3' form. The solution is to turn simplification off
  3333. first (*note Simplification Modes::), or to run `a x' without a numeric
  3334. prefix argument so that it expands all the way in one step.
  3335. The `a a' (`calc-apart') [`apart'] command expands a rational
  3336. function by partial fractions. A rational function is the quotient of
  3337. two polynomials; `apart' pulls this apart into a sum of rational
  3338. functions with simple denominators. In algebraic notation, the `apart'
  3339. function allows a second argument that specifies which variable to use
  3340. as the "base"; by default, Calc chooses the base variable automatically.
  3341. The `a n' (`calc-normalize-rat') [`nrat'] command attempts to
  3342. arrange a formula into a quotient of two polynomials. For example,
  3343. given `1 + (a + b/c) / d', the result would be `(b + a c + c d) / c d'.
  3344. The quotient is reduced, so that `a n' will simplify `(x^2 + 2x + 1) /
  3345. (x^2 - 1)' by dividing out the common factor `x + 1', yielding `(x + 1)
  3346. / (x - 1)'.
  3347. The `a \' (`calc-poly-div') [`pdiv'] command divides two polynomials
  3348. `u' and `v', yielding a new polynomial `q'. If several variables occur
  3349. in the inputs, the inputs are considered multivariate polynomials.
  3350. (Calc divides by the variable with the largest power in `u' first, or,
  3351. in the case of equal powers, chooses the variables in alphabetical
  3352. order.) For example, dividing `x^2 + 3 x + 2' by `x + 2' yields `x +
  3353. 1'. The remainder from the division, if any, is reported at the bottom
  3354. of the screen and is also placed in the Trail along with the quotient.
  3355. Using `pdiv' in algebraic notation, you can specify the particular
  3356. variable to be used as the base: `pdiv(A,B,X)'. If `pdiv' is given
  3357. only two arguments (as is always the case with the `a \' command), then
  3358. it does a multivariate division as outlined above.
  3359. The `a %' (`calc-poly-rem') [`prem'] command divides two polynomials
  3360. and keeps the remainder `r'. The quotient `q' is discarded. For any
  3361. formulas `a' and `b', the results of `a \' and `a %' satisfy `a = q b +
  3362. r'. (This is analogous to plain `\' and `%', which compute the integer
  3363. quotient and remainder from dividing two numbers.)
  3364. The `a /' (`calc-poly-div-rem') [`pdivrem'] command divides two
  3365. polynomials and reports both the quotient and the remainder as a vector
  3366. `[q, r]'. The `H a /' [`pdivide'] command divides two polynomials and
  3367. constructs the formula `q + r/b' on the stack. (Naturally if the
  3368. remainder is zero, this will immediately simplify to `q'.)
  3369. The `a g' (`calc-poly-gcd') [`pgcd'] command computes the greatest
  3370. common divisor of two polynomials. (The GCD actually is unique only to
  3371. within a constant multiplier; Calc attempts to choose a GCD which will
  3372. be unsurprising.) For example, the `a n' command uses `a g' to take
  3373. the GCD of the numerator and denominator of a quotient, then divides
  3374. each by the result using `a \'. (The definition of GCD ensures that
  3375. this division can take place without leaving a remainder.)
  3376. While the polynomials used in operations like `a /' and `a g' often
  3377. have integer coefficients, this is not required. Calc can also deal
  3378. with polynomials over the rationals or floating-point reals.
  3379. Polynomials with modulo-form coefficients are also useful in many
  3380. applications; if you enter `(x^2 + 3 x - 1) mod 5', Calc automatically
  3381. transforms this into a polynomial over the field of integers mod 5:
  3382. `(1 mod 5) x^2 + (3 mod 5) x + (4 mod 5)'.
  3383. Congratulations and thanks go to Ove Ewerlid
  3384. (`ewerlid@mizar.DoCS.UU.SE'), who contributed many of the polynomial
  3385. routines used in the above commands.
  3386. *Note Decomposing Polynomials::, for several useful functions for
  3387. extracting the individual coefficients of a polynomial.
  3388. 
  3389. File: calc, Node: Calculus, Next: Solving Equations, Prev: Polynomials, Up: Algebra
  3390. 12.5 Calculus
  3391. =============
  3392. The following calculus commands do not automatically simplify their
  3393. inputs or outputs using `calc-simplify'. You may find it helps to do
  3394. this by hand by typing `a s' or `a e'. It may also help to use `a x'
  3395. and/or `a c' to arrange a result in the most readable way.
  3396. * Menu:
  3397. * Differentiation::
  3398. * Integration::
  3399. * Customizing the Integrator::
  3400. * Numerical Integration::
  3401. * Taylor Series::
  3402. 
  3403. File: calc, Node: Differentiation, Next: Integration, Prev: Calculus, Up: Calculus
  3404. 12.5.1 Differentiation
  3405. ----------------------
  3406. The `a d' (`calc-derivative') [`deriv'] command computes the derivative
  3407. of the expression on the top of the stack with respect to some
  3408. variable, which it will prompt you to enter. Normally, variables in
  3409. the formula other than the specified differentiation variable are
  3410. considered constant, i.e., `deriv(y,x)' is reduced to zero. With the
  3411. Hyperbolic flag, the `tderiv' (total derivative) operation is used
  3412. instead, in which derivatives of variables are not reduced to zero
  3413. unless those variables are known to be "constant," i.e., independent of
  3414. any other variables. (The built-in special variables like `pi' are
  3415. considered constant, as are variables that have been declared `const';
  3416. *note Declarations::.)
  3417. With a numeric prefix argument N, this command computes the Nth
  3418. derivative.
  3419. When working with trigonometric functions, it is best to switch to
  3420. Radians mode first (with `m r'). The derivative of `sin(x)' in degrees
  3421. is `(pi/180) cos(x)', probably not the expected answer!
  3422. If you use the `deriv' function directly in an algebraic formula,
  3423. you can write `deriv(f,x,x0)' which represents the derivative of `f'
  3424. with respect to `x', evaluated at the point `x=x0'.
  3425. If the formula being differentiated contains functions which Calc
  3426. does not know, the derivatives of those functions are produced by adding
  3427. primes (apostrophe characters). For example, `deriv(f(2x), x)'
  3428. produces `2 f'(2 x)', where the function `f'' represents the derivative
  3429. of `f'.
  3430. For functions you have defined with the `Z F' command, Calc expands
  3431. the functions according to their defining formulas unless you have also
  3432. defined `f'' suitably. For example, suppose we define `sinc(x) =
  3433. sin(x)/x' using `Z F'. If we then differentiate the formula `sinc(2
  3434. x)', the formula will be expanded to `sin(2 x) / (2 x)' and
  3435. differentiated. However, if we also define `sinc'(x) = dsinc(x)', say,
  3436. then Calc will write the result as `2 dsinc(2 x)'. *Note Algebraic
  3437. Definitions::.
  3438. For multi-argument functions `f(x,y,z)', the derivative with respect
  3439. to the first argument is written `f'(x,y,z)'; derivatives with respect
  3440. to the other arguments are `f'2(x,y,z)' and `f'3(x,y,z)'. Various
  3441. higher-order derivatives can be formed in the obvious way, e.g.,
  3442. `f''(x)' (the second derivative of `f') or `f''2'3(x,y,z)' (`f'
  3443. differentiated with respect to each argument once).
  3444. 
  3445. File: calc, Node: Integration, Next: Customizing the Integrator, Prev: Differentiation, Up: Calculus
  3446. 12.5.2 Integration
  3447. ------------------
  3448. The `a i' (`calc-integral') [`integ'] command computes the indefinite
  3449. integral of the expression on the top of the stack with respect to a
  3450. prompted-for variable. The integrator is not guaranteed to work for
  3451. all integrable functions, but it is able to integrate several large
  3452. classes of formulas. In particular, any polynomial or rational
  3453. function (a polynomial divided by a polynomial) is acceptable.
  3454. (Rational functions don't have to be in explicit quotient form, however;
  3455. `x/(1+x^-2)' is not strictly a quotient of polynomials, but it is
  3456. equivalent to `x^3/(x^2+1)', which is.) Also, square roots of terms
  3457. involving `x' and `x^2' may appear in rational functions being
  3458. integrated. Finally, rational functions involving trigonometric or
  3459. hyperbolic functions can be integrated.
  3460. With an argument (`C-u a i'), this command will compute the definite
  3461. integral of the expression on top of the stack. In this case, the
  3462. command will again prompt for an integration variable, then prompt for a
  3463. lower limit and an upper limit.
  3464. If you use the `integ' function directly in an algebraic formula,
  3465. you can also write `integ(f,x,v)' which expresses the resulting
  3466. indefinite integral in terms of variable `v' instead of `x'. With four
  3467. arguments, `integ(f(x),x,a,b)' represents a definite integral from `a'
  3468. to `b'.
  3469. Please note that the current implementation of Calc's integrator
  3470. sometimes produces results that are significantly more complex than
  3471. they need to be. For example, the integral Calc finds for
  3472. `1/(x+sqrt(x^2+1))' is several times more complicated than the answer
  3473. Mathematica returns for the same input, although the two forms are
  3474. numerically equivalent. Also, any indefinite integral should be
  3475. considered to have an arbitrary constant of integration added to it,
  3476. although Calc does not write an explicit constant of integration in its
  3477. result. For example, Calc's solution for `1/(1+tan(x))' differs from
  3478. the solution given in the _CRC Math Tables_ by a constant factor of `pi
  3479. i / 2', due to a different choice of constant of integration.
  3480. The Calculator remembers all the integrals it has done. If
  3481. conditions change in a way that would invalidate the old integrals,
  3482. say, a switch from Degrees to Radians mode, then they will be thrown
  3483. out. If you suspect this is not happening when it should, use the
  3484. `calc-flush-caches' command; *note Caches::.
  3485. Calc normally will pursue integration by substitution or integration
  3486. by parts up to 3 nested times before abandoning an approach as
  3487. fruitless. If the integrator is taking too long, you can lower this
  3488. limit by storing a number (like 2) in the variable `IntegLimit'. (The
  3489. `s I' command is a convenient way to edit `IntegLimit'.) If this
  3490. variable has no stored value or does not contain a nonnegative integer,
  3491. a limit of 3 is used. The lower this limit is, the greater the chance
  3492. that Calc will be unable to integrate a function it could otherwise
  3493. handle. Raising this limit allows the Calculator to solve more
  3494. integrals, though the time it takes may grow exponentially. You can
  3495. monitor the integrator's actions by creating an Emacs buffer called
  3496. `*Trace*'. If such a buffer exists, the `a i' command will write a log
  3497. of its actions there.
  3498. If you want to manipulate integrals in a purely symbolic way, you can
  3499. set the integration nesting limit to 0 to prevent all but fast
  3500. table-lookup solutions of integrals. You might then wish to define
  3501. rewrite rules for integration by parts, various kinds of substitutions,
  3502. and so on. *Note Rewrite Rules::.
  3503. 
  3504. File: calc, Node: Customizing the Integrator, Next: Numerical Integration, Prev: Integration, Up: Calculus
  3505. 12.5.3 Customizing the Integrator
  3506. ---------------------------------
  3507. Calc has two built-in rewrite rules called `IntegRules' and
  3508. `IntegAfterRules' which you can edit to define new integration methods.
  3509. *Note Rewrite Rules::. At each step of the integration process, Calc
  3510. wraps the current integrand in a call to the fictitious function
  3511. `integtry(EXPR,VAR)', where EXPR is the integrand and VAR is the
  3512. integration variable. If your rules rewrite this to be a plain formula
  3513. (not a call to `integtry'), then Calc will use this formula as the
  3514. integral of EXPR. For example, the rule `integtry(mysin(x),x) :=
  3515. -mycos(x)' would define a rule to integrate a function `mysin' that
  3516. acts like the sine function. Then, putting `4 mysin(2y+1)' on the
  3517. stack and typing `a i y' will produce the integral `-2 mycos(2y+1)'.
  3518. Note that Calc has automatically made various transformations on the
  3519. integral to allow it to use your rule; integral tables generally give
  3520. rules for `mysin(a x + b)', but you don't need to use this much
  3521. generality in your `IntegRules'.
  3522. As a more serious example, the expression `exp(x)/x' cannot be
  3523. integrated in terms of the standard functions, so the "exponential
  3524. integral" function `Ei(x)' was invented to describe it. We can get
  3525. Calc to do this integral in terms of a made-up `Ei' function by adding
  3526. the rule `[integtry(exp(x)/x, x) := Ei(x)]' to `IntegRules'. Now
  3527. entering `exp(2x)/x' on the stack and typing `a i x' yields `Ei(2 x)'.
  3528. This new rule will work with Calc's various built-in integration
  3529. methods (such as integration by substitution) to solve a variety of
  3530. other problems involving `Ei': For example, now Calc will also be able
  3531. to integrate `exp(exp(x))' and `ln(ln(x))' (to get `Ei(exp(x))' and `x
  3532. ln(ln(x)) - Ei(ln(x))', respectively).
  3533. Your rule may do further integration by calling `integ'. For
  3534. example, `integtry(twice(u),x) := twice(integ(u))' allows Calc to
  3535. integrate `twice(sin(x))' to get `twice(-cos(x))'. Note that `integ'
  3536. was called with only one argument. This notation is allowed only
  3537. within `IntegRules'; it means "integrate this with respect to the same
  3538. integration variable." If Calc is unable to integrate `u', the
  3539. integration that invoked `IntegRules' also fails. Thus integrating
  3540. `twice(f(x))' fails, returning the unevaluated integral
  3541. `integ(twice(f(x)), x)'. It is still valid to call `integ' with two or
  3542. more arguments, however; in this case, if `u' is not integrable,
  3543. `twice' itself will still be integrated: If the above rule is changed
  3544. to `... := twice(integ(u,x))', then integrating `twice(f(x))' will
  3545. yield `twice(integ(f(x),x))'.
  3546. If a rule instead produces the formula `integsubst(SEXPR, SVAR)',
  3547. either replacing the top-level `integtry' call or nested anywhere
  3548. inside the expression, then Calc will apply the substitution `U =
  3549. SEXPR(SVAR)' to try to integrate the original EXPR. For example, the
  3550. rule `sqrt(a) := integsubst(sqrt(x),x)' says that if Calc ever finds a
  3551. square root in the integrand, it should attempt the substitution `u =
  3552. sqrt(x)'. (This particular rule is unnecessary because Calc always
  3553. tries "obvious" substitutions where SEXPR actually appears in the
  3554. integrand.) The variable SVAR may be the same as the VAR that appeared
  3555. in the call to `integtry', but it need not be.
  3556. When integrating according to an `integsubst', Calc uses the
  3557. equation solver to find the inverse of SEXPR (if the integrand refers
  3558. to VAR anywhere except in subexpressions that exactly match SEXPR). It
  3559. uses the differentiator to find the derivative of SEXPR and/or its
  3560. inverse (it has two methods that use one derivative or the other). You
  3561. can also specify these items by adding extra arguments to the
  3562. `integsubst' your rules construct; the general form is
  3563. `integsubst(SEXPR, SVAR, SINV, SPRIME)', where SINV is the inverse of
  3564. SEXPR (still written as a function of SVAR), and SPRIME is the
  3565. derivative of SEXPR with respect to SVAR. If you don't specify these
  3566. things, and Calc is not able to work them out on its own with the
  3567. information it knows, then your substitution rule will work only in
  3568. very specific, simple cases.
  3569. Calc applies `IntegRules' as if by `C-u 1 a r IntegRules'; in other
  3570. words, Calc stops rewriting as soon as any rule in your rule set
  3571. succeeds. (If it weren't for this, the `integsubst(sqrt(x),x)' example
  3572. above would keep on adding layers of `integsubst' calls forever!)
  3573. Another set of rules, stored in `IntegSimpRules', are applied every
  3574. time the integrator uses `a s' to simplify an intermediate result. For
  3575. example, putting the rule `twice(x) := 2 x' into `IntegSimpRules' would
  3576. tell Calc to convert the `twice' function into a form it knows whenever
  3577. integration is attempted.
  3578. One more way to influence the integrator is to define a function with
  3579. the `Z F' command (*note Algebraic Definitions::). Calc's integrator
  3580. automatically expands such functions according to their defining
  3581. formulas, even if you originally asked for the function to be left
  3582. unevaluated for symbolic arguments. (Certain other Calc systems, such
  3583. as the differentiator and the equation solver, also do this.)
  3584. Sometimes Calc is able to find a solution to your integral, but it
  3585. expresses the result in a way that is unnecessarily complicated. If
  3586. this happens, you can either use `integsubst' as described above to try
  3587. to hint at a more direct path to the desired result, or you can use
  3588. `IntegAfterRules'. This is an extra rule set that runs after the main
  3589. integrator returns its result; basically, Calc does an `a r
  3590. IntegAfterRules' on the result before showing it to you. (It also does
  3591. an `a s', without `IntegSimpRules', after that to further simplify the
  3592. result.) For example, Calc's integrator sometimes produces expressions
  3593. of the form `ln(1+x) - ln(1-x)'; the default `IntegAfterRules' rewrite
  3594. this into the more readable form `2 arctanh(x)'. Note that, unlike
  3595. `IntegRules', `IntegSimpRules' and `IntegAfterRules' are applied any
  3596. number of times until no further changes are possible. Rewriting by
  3597. `IntegAfterRules' occurs only after the main integrator has finished,
  3598. not at every step as for `IntegRules' and `IntegSimpRules'.
  3599. 
  3600. File: calc, Node: Numerical Integration, Next: Taylor Series, Prev: Customizing the Integrator, Up: Calculus
  3601. 12.5.4 Numerical Integration
  3602. ----------------------------
  3603. If you want a purely numerical answer to an integration problem, you can
  3604. use the `a I' (`calc-num-integral') [`ninteg'] command. This command
  3605. prompts for an integration variable, a lower limit, and an upper limit.
  3606. Except for the integration variable, all other variables that appear in
  3607. the integrand formula must have stored values. (A stored value, if
  3608. any, for the integration variable itself is ignored.)
  3609. Numerical integration works by evaluating your formula at many
  3610. points in the specified interval. Calc uses an "open Romberg" method;
  3611. this means that it does not evaluate the formula actually at the
  3612. endpoints (so that it is safe to integrate `sin(x)/x' from zero, for
  3613. example). Also, the Romberg method works especially well when the
  3614. function being integrated is fairly smooth. If the function is not
  3615. smooth, Calc will have to evaluate it at quite a few points before it
  3616. can accurately determine the value of the integral.
  3617. Integration is much faster when the current precision is small. It
  3618. is best to set the precision to the smallest acceptable number of digits
  3619. before you use `a I'. If Calc appears to be taking too long, press
  3620. `C-g' to halt it and try a lower precision. If Calc still appears to
  3621. need hundreds of evaluations, check to make sure your function is
  3622. well-behaved in the specified interval.
  3623. It is possible for the lower integration limit to be `-inf' (minus
  3624. infinity). Likewise, the upper limit may be plus infinity. Calc
  3625. internally transforms the integral into an equivalent one with finite
  3626. limits. However, integration to or across singularities is not
  3627. supported: The integral of `1/sqrt(x)' from 0 to 1 exists (it can be
  3628. found by Calc's symbolic integrator, for example), but `a I' will fail
  3629. because the integrand goes to infinity at one of the endpoints.
  3630. 
  3631. File: calc, Node: Taylor Series, Prev: Numerical Integration, Up: Calculus
  3632. 12.5.5 Taylor Series
  3633. --------------------
  3634. The `a t' (`calc-taylor') [`taylor'] command computes a power series
  3635. expansion or Taylor series of a function. You specify the variable and
  3636. the desired number of terms. You may give an expression of the form
  3637. `VAR = A' or `VAR - A' instead of just a variable to produce a Taylor
  3638. expansion about the point A. You may specify the number of terms with
  3639. a numeric prefix argument; otherwise the command will prompt you for
  3640. the number of terms. Note that many series expansions have
  3641. coefficients of zero for some terms, so you may appear to get fewer
  3642. terms than you asked for.
  3643. If the `a i' command is unable to find a symbolic integral for a
  3644. function, you can get an approximation by integrating the function's
  3645. Taylor series.
  3646. 
  3647. File: calc, Node: Solving Equations, Next: Numerical Solutions, Prev: Calculus, Up: Algebra
  3648. 12.6 Solving Equations
  3649. ======================
  3650. The `a S' (`calc-solve-for') [`solve'] command rearranges an equation
  3651. to solve for a specific variable. An equation is an expression of the
  3652. form `L = R'. For example, the command `a S x' will rearrange `y = 3x
  3653. + 6' to the form, `x = y/3 - 2'. If the input is not an equation, it
  3654. is treated like an equation of the form `X = 0'.
  3655. This command also works for inequalities, as in `y < 3x + 6'. Some
  3656. inequalities cannot be solved where the analogous equation could be;
  3657. for example, solving `a < b c' for `b' is impossible without knowing
  3658. the sign of `c'. In this case, `a S' will produce the result `b != a/c'
  3659. (using the not-equal-to operator) to signify that the direction of the
  3660. inequality is now unknown. The inequality `a <= b c' is not even
  3661. partially solved. *Note Declarations::, for a way to tell Calc that
  3662. the signs of the variables in a formula are in fact known.
  3663. Two useful commands for working with the result of `a S' are `a .'
  3664. (*note Logical Operations::), which converts `x = y/3 - 2' to `y/3 -
  3665. 2', and `s l' (*note Let Command::) which evaluates another formula
  3666. with `x' set equal to `y/3 - 2'.
  3667. * Menu:
  3668. * Multiple Solutions::
  3669. * Solving Systems of Equations::
  3670. * Decomposing Polynomials::
  3671. 
  3672. File: calc, Node: Multiple Solutions, Next: Solving Systems of Equations, Prev: Solving Equations, Up: Solving Equations
  3673. 12.6.1 Multiple Solutions
  3674. -------------------------
  3675. Some equations have more than one solution. The Hyperbolic flag (`H a
  3676. S') [`fsolve'] tells the solver to report the fully general family of
  3677. solutions. It will invent variables `n1', `n2', ..., which represent
  3678. independent arbitrary integers, and `s1', `s2', ..., which represent
  3679. independent arbitrary signs (either +1 or -1). If you don't use the
  3680. Hyperbolic flag, Calc will use zero in place of all arbitrary integers,
  3681. and plus one in place of all arbitrary signs. Note that variables like
  3682. `n1' and `s1' are not given any special interpretation in Calc except by
  3683. the equation solver itself. As usual, you can use the `s l'
  3684. (`calc-let') command to obtain solutions for various actual values of
  3685. these variables.
  3686. For example, `' x^2 = y <RET> H a S x <RET>' solves to get `x = s1
  3687. sqrt(y)', indicating that the two solutions to the equation are
  3688. `sqrt(y)' and `-sqrt(y)'. Another way to think about it is that the
  3689. square-root operation is really a two-valued function; since every Calc
  3690. function must return a single result, `sqrt' chooses to return the
  3691. positive result. Then `H a S' doctors this result using `s1' to
  3692. indicate the full set of possible values of the mathematical
  3693. square-root.
  3694. There is a similar phenomenon going the other direction: Suppose we
  3695. solve `sqrt(y) = x' for `y'. Calc squares both sides to get `y = x^2'.
  3696. This is correct, except that it introduces some dubious solutions.
  3697. Consider solving `sqrt(y) = -3': Calc will report `y = 9' as a valid
  3698. solution, which is true in the mathematical sense of square-root, but
  3699. false (there is no solution) for the actual Calc positive-valued
  3700. `sqrt'. This happens for both `a S' and `H a S'.
  3701. If you store a positive integer in the Calc variable `GenCount',
  3702. then Calc will generate formulas of the form `as(N)' for arbitrary
  3703. signs, and `an(N)' for arbitrary integers, where N represents
  3704. successive values taken by incrementing `GenCount' by one. While the
  3705. normal arbitrary sign and integer symbols start over at `s1' and `n1'
  3706. with each new Calc command, the `GenCount' approach will give each
  3707. arbitrary value a name that is unique throughout the entire Calc
  3708. session. Also, the arbitrary values are function calls instead of
  3709. variables, which is advantageous in some cases. For example, you can
  3710. make a rewrite rule that recognizes all arbitrary signs using a pattern
  3711. like `as(n)'. The `s l' command only works on variables, but you can
  3712. use the `a b' (`calc-substitute') command to substitute actual values
  3713. for function calls like `as(3)'.
  3714. The `s G' (`calc-edit-GenCount') command is a convenient way to
  3715. create or edit this variable. Press `C-c C-c' to finish.
  3716. If you have not stored a value in `GenCount', or if the value in
  3717. that variable is not a positive integer, the regular `s1'/`n1' notation
  3718. is used.
  3719. With the Inverse flag, `I a S' [`finv'] treats the expression on top
  3720. of the stack as a function of the specified variable and solves to find
  3721. the inverse function, written in terms of the same variable. For
  3722. example, `I a S x' inverts `2x + 6' to `x/2 - 3'. You can use both
  3723. Inverse and Hyperbolic [`ffinv'] to obtain a fully general inverse, as
  3724. described above.
  3725. Some equations, specifically polynomials, have a known, finite number
  3726. of solutions. The `a P' (`calc-poly-roots') [`roots'] command uses `H
  3727. a S' to solve an equation in general form, then, for all arbitrary-sign
  3728. variables like `s1', and all arbitrary-integer variables like `n1' for
  3729. which `n1' only usefully varies over a finite range, it expands these
  3730. variables out to all their possible values. The results are collected
  3731. into a vector, which is returned. For example, `roots(x^4 = 1, x)'
  3732. returns the four solutions `[1, -1, (0, 1), (0, -1)]'. Generally an
  3733. Nth degree polynomial will always have N roots on the complex plane.
  3734. (If you have given a `real' declaration for the solution variable, then
  3735. only the real-valued solutions, if any, will be reported; *note
  3736. Declarations::.)
  3737. Note that because `a P' uses `H a S', it is able to deliver symbolic
  3738. solutions if the polynomial has symbolic coefficients. Also note that
  3739. Calc's solver is not able to get exact symbolic solutions to all
  3740. polynomials. Polynomials containing powers up to `x^4' can always be
  3741. solved exactly; polynomials of higher degree sometimes can be: `x^6 +
  3742. x^3 + 1' is converted to `(x^3)^2 + (x^3) + 1', which can be solved for
  3743. `x^3' using the quadratic equation, and then for `x' by taking cube
  3744. roots. But in many cases, like `x^6 + x + 1', Calc does not know how
  3745. to rewrite the polynomial into a form it can solve. The `a P' command
  3746. can still deliver a list of numerical roots, however, provided that
  3747. Symbolic mode (`m s') is not turned on. (If you work with Symbolic
  3748. mode on, recall that the `N' (`calc-eval-num') key is a handy way to
  3749. reevaluate the formula on the stack with Symbolic mode temporarily
  3750. off.) Naturally, `a P' can only provide numerical roots if the
  3751. polynomial coefficients are all numbers (real or complex).
  3752. 
  3753. File: calc, Node: Solving Systems of Equations, Next: Decomposing Polynomials, Prev: Multiple Solutions, Up: Solving Equations
  3754. 12.6.2 Solving Systems of Equations
  3755. -----------------------------------
  3756. You can also use the commands described above to solve systems of
  3757. simultaneous equations. Just create a vector of equations, then
  3758. specify a vector of variables for which to solve. (You can omit the
  3759. surrounding brackets when entering the vector of variables at the
  3760. prompt.)
  3761. For example, putting `[x + y = a, x - y = b]' on the stack and
  3762. typing `a S x,y <RET>' produces the vector of solutions `[x = a -
  3763. (a-b)/2, y = (a-b)/2]'. The result vector will have the same length as
  3764. the variables vector, and the variables will be listed in the same
  3765. order there. Note that the solutions are not always simplified as far
  3766. as possible; the solution for `x' here could be improved by an
  3767. application of the `a n' command.
  3768. Calc's algorithm works by trying to eliminate one variable at a time
  3769. by solving one of the equations for that variable and then substituting
  3770. into the other equations. Calc will try all the possibilities, but you
  3771. can speed things up by noting that Calc first tries to eliminate the
  3772. first variable with the first equation, then the second variable with
  3773. the second equation, and so on. It also helps to put the simpler
  3774. (e.g., more linear) equations toward the front of the list. Calc's
  3775. algorithm will solve any system of linear equations, and also many
  3776. kinds of nonlinear systems.
  3777. Normally there will be as many variables as equations. If you give
  3778. fewer variables than equations (an "over-determined" system of
  3779. equations), Calc will find a partial solution. For example, typing `a
  3780. S y <RET>' with the above system of equations would produce `[y = a -
  3781. x]'. There are now several ways to express this solution in terms of
  3782. the original variables; Calc uses the first one that it finds. You can
  3783. control the choice by adding variable specifiers of the form `elim(V)'
  3784. to the variables list. This says that V should be eliminated from the
  3785. equations; the variable will not appear at all in the solution. For
  3786. example, typing `a S y,elim(x)' would yield `[y = a - (b+a)/2]'.
  3787. If the variables list contains only `elim' specifiers, Calc simply
  3788. eliminates those variables from the equations and then returns the
  3789. resulting set of equations. For example, `a S elim(x)' produces `[a -
  3790. 2 y = b]'. Every variable eliminated will reduce the number of
  3791. equations in the system by one.
  3792. Again, `a S' gives you one solution to the system of equations. If
  3793. there are several solutions, you can use `H a S' to get a general
  3794. family of solutions, or, if there is a finite number of solutions, you
  3795. can use `a P' to get a list. (In the latter case, the result will take
  3796. the form of a matrix where the rows are different solutions and the
  3797. columns correspond to the variables you requested.)
  3798. Another way to deal with certain kinds of overdetermined systems of
  3799. equations is the `a F' command, which does least-squares fitting to
  3800. satisfy the equations. *Note Curve Fitting::.
  3801. 
  3802. File: calc, Node: Decomposing Polynomials, Prev: Solving Systems of Equations, Up: Solving Equations
  3803. 12.6.3 Decomposing Polynomials
  3804. ------------------------------
  3805. The `poly' function takes a polynomial and a variable as arguments, and
  3806. returns a vector of polynomial coefficients (constant coefficient
  3807. first). For example, `poly(x^3 + 2 x, x)' returns `[0, 2, 0, 1]'. If
  3808. the input is not a polynomial in `x', the call to `poly' is left in
  3809. symbolic form. If the input does not involve the variable `x', the
  3810. input is returned in a list of length one, representing a polynomial
  3811. with only a constant coefficient. The call `poly(x, x)' returns the
  3812. vector `[0, 1]'. The last element of the returned vector is guaranteed
  3813. to be nonzero; note that `poly(0, x)' returns the empty vector `[]'.
  3814. Note also that `x' may actually be any formula; for example,
  3815. `poly(sin(x)^2 - sin(x) + 3, sin(x))' returns `[3, -1, 1]'.
  3816. To get the `x^k' coefficient of polynomial `p', use `poly(p,
  3817. x)_(k+1)'. To get the degree of polynomial `p', use `vlen(poly(p, x))
  3818. - 1'. For example, `poly((x+1)^4, x)' returns `[1, 4, 6, 4, 1]', so
  3819. `poly((x+1)^4, x)_(2+1)' gives the `x^2' coefficient of this
  3820. polynomial, 6.
  3821. One important feature of the solver is its ability to recognize
  3822. formulas which are "essentially" polynomials. This ability is made
  3823. available to the user through the `gpoly' function, which is used just
  3824. like `poly': `gpoly(EXPR, VAR)'. If EXPR is a polynomial in some term
  3825. which includes VAR, then this function will return a vector `[X, C, A]'
  3826. where X is the term that depends on VAR, C is a vector of polynomial
  3827. coefficients (like the one returned by `poly'), and A is a multiplier
  3828. which is usually 1. Basically, `EXPR = A*(C_1 + C_2 X + C_3 X^2 +
  3829. ...)'. The last element of C is guaranteed to be non-zero, and C will
  3830. not equal `[1]' (i.e., the trivial decomposition EXPR = X is not
  3831. considered a polynomial). One side effect is that `gpoly(x, x)' and
  3832. `gpoly(6, x)', both of which might be expected to recognize their
  3833. arguments as polynomials, will not because the decomposition is
  3834. considered trivial.
  3835. For example, `gpoly((x-2)^2, x)' returns `[x, [4, -4, 1], 1]', since
  3836. the expanded form of this polynomial is `4 - 4 x + x^2'.
  3837. The term X may itself be a polynomial in VAR. This is done to
  3838. reduce the size of the C vector. For example, `gpoly(x^4 + x^2 - 1,
  3839. x)' returns `[x^2, [-1, 1, 1], 1]', since a quadratic polynomial in
  3840. `x^2' is easier to solve than a quartic polynomial in `x'.
  3841. A few more examples of the kinds of polynomials `gpoly' can discover:
  3842. sin(x) - 1 [sin(x), [-1, 1], 1]
  3843. x + 1/x - 1 [x, [1, -1, 1], 1/x]
  3844. x + 1/x [x^2, [1, 1], 1/x]
  3845. x^3 + 2 x [x^2, [2, 1], x]
  3846. x + x^2:3 + sqrt(x) [x^1:6, [1, 1, 0, 1], x^1:2]
  3847. x^(2a) + 2 x^a + 5 [x^a, [5, 2, 1], 1]
  3848. (exp(-x) + exp(x)) / 2 [e^(2 x), [0.5, 0.5], e^-x]
  3849. The `poly' and `gpoly' functions accept a third integer argument
  3850. which specifies the largest degree of polynomial that is acceptable.
  3851. If this is `n', then only C vectors of length `n+1' or less will be
  3852. returned. Otherwise, the `poly' or `gpoly' call will remain in
  3853. symbolic form. For example, the equation solver can handle quartics
  3854. and smaller polynomials, so it calls `gpoly(EXPR, VAR, 4)' to discover
  3855. whether EXPR can be treated by its linear, quadratic, cubic, or quartic
  3856. formulas.
  3857. The `pdeg' function computes the degree of a polynomial; `pdeg(p,x)'
  3858. is the highest power of `x' that appears in `p'. This is the same as
  3859. `vlen(poly(p,x))-1', but is much more efficient. If `p' is constant
  3860. with respect to `x', then `pdeg(p,x) = 0'. If `p' is not a polynomial
  3861. in `x' (e.g., `pdeg(2 cos(x), x)', the function remains unevaluated.
  3862. It is possible to omit the second argument `x', in which case `pdeg(p)'
  3863. returns the highest total degree of any term of the polynomial,
  3864. counting all variables that appear in `p'. Note that `pdeg(c) =
  3865. pdeg(c,x) = 0' for any nonzero constant `c'; the degree of the constant
  3866. zero is considered to be `-inf' (minus infinity).
  3867. The `plead' function finds the leading term of a polynomial. Thus
  3868. `plead(p,x)' is equivalent to `poly(p,x)_vlen(poly(p,x))', though again
  3869. more efficient. In particular, `plead((2x+1)^10, x)' returns 1024
  3870. without expanding out the list of coefficients. The value of
  3871. `plead(p,x)' will be zero only if `p = 0'.
  3872. The `pcont' function finds the "content" of a polynomial. This is
  3873. the greatest common divisor of all the coefficients of the polynomial.
  3874. With two arguments, `pcont(p,x)' effectively uses `poly(p,x)' to get a
  3875. list of coefficients, then uses `pgcd' (the polynomial GCD function) to
  3876. combine these into an answer. For example, `pcont(4 x y^2 + 6 x^2 y,
  3877. x)' is `2 y'. The content is basically the "biggest" polynomial that
  3878. can be divided into `p' exactly. The sign of the content is the same
  3879. as the sign of the leading coefficient.
  3880. With only one argument, `pcont(p)' computes the numerical content of
  3881. the polynomial, i.e., the `gcd' of the numerical coefficients of all
  3882. the terms in the formula. Note that `gcd' is defined on rational
  3883. numbers as well as integers; it computes the `gcd' of the numerators
  3884. and the `lcm' of the denominators. Thus `pcont(4:3 x y^2 + 6 x^2 y)'
  3885. returns 2:3. Dividing the polynomial by this number will clear all the
  3886. denominators, as well as dividing by any common content in the
  3887. numerators. The numerical content of a polynomial is negative only if
  3888. all the coefficients in the polynomial are negative.
  3889. The `pprim' function finds the "primitive part" of a polynomial,
  3890. which is simply the polynomial divided (using `pdiv' if necessary) by
  3891. its content. If the input polynomial has rational coefficients, the
  3892. result will have integer coefficients in simplest terms.
  3893. 
  3894. File: calc, Node: Numerical Solutions, Next: Curve Fitting, Prev: Solving Equations, Up: Algebra
  3895. 12.7 Numerical Solutions
  3896. ========================
  3897. Not all equations can be solved symbolically. The commands in this
  3898. section use numerical algorithms that can find a solution to a specific
  3899. instance of an equation to any desired accuracy. Note that the
  3900. numerical commands are slower than their algebraic cousins; it is a
  3901. good idea to try `a S' before resorting to these commands.
  3902. (*Note Curve Fitting::, for some other, more specialized, operations
  3903. on numerical data.)
  3904. * Menu:
  3905. * Root Finding::
  3906. * Minimization::
  3907. * Numerical Systems of Equations::
  3908. 
  3909. File: calc, Node: Root Finding, Next: Minimization, Prev: Numerical Solutions, Up: Numerical Solutions
  3910. 12.7.1 Root Finding
  3911. -------------------
  3912. The `a R' (`calc-find-root') [`root'] command finds a numerical
  3913. solution (or "root") of an equation. (This command treats inequalities
  3914. the same as equations. If the input is any other kind of formula, it
  3915. is interpreted as an equation of the form `X = 0'.)
  3916. The `a R' command requires an initial guess on the top of the stack,
  3917. and a formula in the second-to-top position. It prompts for a solution
  3918. variable, which must appear in the formula. All other variables that
  3919. appear in the formula must have assigned values, i.e., when a value is
  3920. assigned to the solution variable and the formula is evaluated with
  3921. `=', it should evaluate to a number. Any assigned value for the
  3922. solution variable itself is ignored and unaffected by this command.
  3923. When the command completes, the initial guess is replaced on the
  3924. stack by a vector of two numbers: The value of the solution variable
  3925. that solves the equation, and the difference between the lefthand and
  3926. righthand sides of the equation at that value. Ordinarily, the second
  3927. number will be zero or very nearly zero. (Note that Calc uses a
  3928. slightly higher precision while finding the root, and thus the second
  3929. number may be slightly different from the value you would compute from
  3930. the equation yourself.)
  3931. The `v h' (`calc-head') command is a handy way to extract the first
  3932. element of the result vector, discarding the error term.
  3933. The initial guess can be a real number, in which case Calc searches
  3934. for a real solution near that number, or a complex number, in which
  3935. case Calc searches the whole complex plane near that number for a
  3936. solution, or it can be an interval form which restricts the search to
  3937. real numbers inside that interval.
  3938. Calc tries to use `a d' to take the derivative of the equation. If
  3939. this succeeds, it uses Newton's method. If the equation is not
  3940. differentiable Calc uses a bisection method. (If Newton's method
  3941. appears to be going astray, Calc switches over to bisection if it can,
  3942. or otherwise gives up. In this case it may help to try again with a
  3943. slightly different initial guess.) If the initial guess is a complex
  3944. number, the function must be differentiable.
  3945. If the formula (or the difference between the sides of an equation)
  3946. is negative at one end of the interval you specify and positive at the
  3947. other end, the root finder is guaranteed to find a root. Otherwise,
  3948. Calc subdivides the interval into small parts looking for positive and
  3949. negative values to bracket the root. When your guess is an interval,
  3950. Calc will not look outside that interval for a root.
  3951. The `H a R' [`wroot'] command is similar to `a R', except that if
  3952. the initial guess is an interval for which the function has the same
  3953. sign at both ends, then rather than subdividing the interval Calc
  3954. attempts to widen it to enclose a root. Use this mode if you are not
  3955. sure if the function has a root in your interval.
  3956. If the function is not differentiable, and you give a simple number
  3957. instead of an interval as your initial guess, Calc uses this widening
  3958. process even if you did not type the Hyperbolic flag. (If the function
  3959. _is_ differentiable, Calc uses Newton's method which does not require a
  3960. bounding interval in order to work.)
  3961. If Calc leaves the `root' or `wroot' function in symbolic form on
  3962. the stack, it will normally display an explanation for why no root was
  3963. found. If you miss this explanation, press `w' (`calc-why') to get it
  3964. back.
  3965. 
  3966. File: calc, Node: Minimization, Next: Numerical Systems of Equations, Prev: Root Finding, Up: Numerical Solutions
  3967. 12.7.2 Minimization
  3968. -------------------
  3969. The `a N' (`calc-find-minimum') [`minimize'] command finds a minimum
  3970. value for a formula. It is very similar in operation to `a R'
  3971. (`calc-find-root'): You give the formula and an initial guess on the
  3972. stack, and are prompted for the name of a variable. The guess may be
  3973. either a number near the desired minimum, or an interval enclosing the
  3974. desired minimum. The function returns a vector containing the value of
  3975. the variable which minimizes the formula's value, along with the
  3976. minimum value itself.
  3977. Note that this command looks for a _local_ minimum. Many functions
  3978. have more than one minimum; some, like `x sin(x)', have infinitely
  3979. many. In fact, there is no easy way to define the "global" minimum of
  3980. `x sin(x)' but Calc can still locate any particular local minimum for
  3981. you. Calc basically goes downhill from the initial guess until it
  3982. finds a point at which the function's value is greater both to the left
  3983. and to the right. Calc does not use derivatives when minimizing a
  3984. function.
  3985. If your initial guess is an interval and it looks like the minimum
  3986. occurs at one or the other endpoint of the interval, Calc will return
  3987. that endpoint only if that endpoint is closed; thus, minimizing `17 x'
  3988. over `[2..3]' will return `[2, 38]', but minimizing over `(2..3]' would
  3989. report no minimum found. In general, you should use closed intervals
  3990. to find literally the minimum value in that range of `x', or open
  3991. intervals to find the local minimum, if any, that happens to lie in
  3992. that range.
  3993. Most functions are smooth and flat near their minimum values.
  3994. Because of this flatness, if the current precision is, say, 12 digits,
  3995. the variable can only be determined meaningfully to about six digits.
  3996. Thus you should set the precision to twice as many digits as you need
  3997. in your answer.
  3998. The `H a N' [`wminimize'] command, analogously to `H a R', expands
  3999. the guess interval to enclose a minimum rather than requiring that the
  4000. minimum lie inside the interval you supply.
  4001. The `a X' (`calc-find-maximum') [`maximize'] and `H a X'
  4002. [`wmaximize'] commands effectively minimize the negative of the formula
  4003. you supply.
  4004. The formula must evaluate to a real number at all points inside the
  4005. interval (or near the initial guess if the guess is a number). If the
  4006. initial guess is a complex number the variable will be minimized over
  4007. the complex numbers; if it is real or an interval it will be minimized
  4008. over the reals.
  4009. 
  4010. File: calc, Node: Numerical Systems of Equations, Prev: Minimization, Up: Numerical Solutions
  4011. 12.7.3 Systems of Equations
  4012. ---------------------------
  4013. The `a R' command can also solve systems of equations. In this case,
  4014. the equation should instead be a vector of equations, the guess should
  4015. instead be a vector of numbers (intervals are not supported), and the
  4016. variable should be a vector of variables. You can omit the brackets
  4017. while entering the list of variables. Each equation must be
  4018. differentiable by each variable for this mode to work. The result will
  4019. be a vector of two vectors: The variable values that solved the system
  4020. of equations, and the differences between the sides of the equations
  4021. with those variable values. There must be the same number of equations
  4022. as variables. Since only plain numbers are allowed as guesses, the
  4023. Hyperbolic flag has no effect when solving a system of equations.
  4024. It is also possible to minimize over many variables with `a N' (or
  4025. maximize with `a X'). Once again the variable name should be replaced
  4026. by a vector of variables, and the initial guess should be an
  4027. equal-sized vector of initial guesses. But, unlike the case of
  4028. multidimensional `a R', the formula being minimized should still be a
  4029. single formula, _not_ a vector. Beware that multidimensional
  4030. minimization is currently _very_ slow.
  4031. 
  4032. File: calc, Node: Curve Fitting, Next: Summations, Prev: Numerical Solutions, Up: Algebra
  4033. 12.8 Curve Fitting
  4034. ==================
  4035. The `a F' command fits a set of data to a "model formula", such as `y =
  4036. m x + b' where `m' and `b' are parameters to be determined. For a
  4037. typical set of measured data there will be no single `m' and `b' that
  4038. exactly fit the data; in this case, Calc chooses values of the
  4039. parameters that provide the closest possible fit. The model formula
  4040. can be entered in various ways after the key sequence `a F' is pressed.
  4041. If the letter `P' is pressed after `a F' but before the model
  4042. description is entered, the data as well as the model formula will be
  4043. plotted after the formula is determined. This will be indicated by a
  4044. "P" in the minibuffer after the help message.
  4045. * Menu:
  4046. * Linear Fits::
  4047. * Polynomial and Multilinear Fits::
  4048. * Error Estimates for Fits::
  4049. * Standard Nonlinear Models::
  4050. * Curve Fitting Details::
  4051. * Interpolation::
  4052. 
  4053. File: calc, Node: Linear Fits, Next: Polynomial and Multilinear Fits, Prev: Curve Fitting, Up: Curve Fitting
  4054. 12.8.1 Linear Fits
  4055. ------------------
  4056. The `a F' (`calc-curve-fit') [`fit'] command attempts to fit a set of
  4057. data (`x' and `y' vectors of numbers) to a straight line, polynomial,
  4058. or other function of `x'. For the moment we will consider only the
  4059. case of fitting to a line, and we will ignore the issue of whether or
  4060. not the model was in fact a good fit for the data.
  4061. In a standard linear least-squares fit, we have a set of `(x,y)'
  4062. data points that we wish to fit to the model `y = m x + b' by adjusting
  4063. the parameters `m' and `b' to make the `y' values calculated from the
  4064. formula be as close as possible to the actual `y' values in the data
  4065. set. (In a polynomial fit, the model is instead, say, `y = a x^3 + b
  4066. x^2 + c x + d'. In a multilinear fit, we have data points of the form
  4067. `(x_1,x_2,x_3,y)' and our model is `y = a x_1 + b x_2 + c x_3 + d'.
  4068. These will be discussed later.)
  4069. In the model formula, variables like `x' and `x_2' are called the
  4070. "independent variables", and `y' is the "dependent variable".
  4071. Variables like `m', `a', and `b' are called the "parameters" of the
  4072. model.
  4073. The `a F' command takes the data set to be fitted from the stack.
  4074. By default, it expects the data in the form of a matrix. For example,
  4075. for a linear or polynomial fit, this would be a 2xN matrix where the
  4076. first row is a list of `x' values and the second row has the
  4077. corresponding `y' values. For the multilinear fit shown above, the
  4078. matrix would have four rows (`x_1', `x_2', `x_3', and `y',
  4079. respectively).
  4080. If you happen to have an Nx2 matrix instead of a 2xN matrix, just
  4081. press `v t' first to transpose the matrix.
  4082. After you type `a F', Calc prompts you to select a model. For a
  4083. linear fit, press the digit `1'.
  4084. Calc then prompts for you to name the variables. By default it
  4085. chooses high letters like `x' and `y' for independent variables and low
  4086. letters like `a' and `b' for parameters. (The dependent variable
  4087. doesn't need a name.) The two kinds of variables are separated by a
  4088. semicolon. Since you generally care more about the names of the
  4089. independent variables than of the parameters, Calc also allows you to
  4090. name only those and let the parameters use default names.
  4091. For example, suppose the data matrix
  4092. [ [ 1, 2, 3, 4, 5 ]
  4093. [ 5, 7, 9, 11, 13 ] ]
  4094. is on the stack and we wish to do a simple linear fit. Type `a F',
  4095. then `1' for the model, then <RET> to use the default names. The
  4096. result will be the formula `3. + 2. x' on the stack. Calc has created
  4097. the model expression `a + b x', then found the optimal values of `a'
  4098. and `b' to fit the data. (In this case, it was able to find an exact
  4099. fit.) Calc then substituted those values for `a' and `b' in the model
  4100. formula.
  4101. The `a F' command puts two entries in the trail. One is, as always,
  4102. a copy of the result that went to the stack; the other is a vector of
  4103. the actual parameter values, written as equations: `[a = 3, b = 2]', in
  4104. case you'd rather read them in a list than pick them out of the
  4105. formula. (You can type `t y' to move this vector to the stack; see
  4106. *note Trail Commands::.
  4107. Specifying a different independent variable name will affect the
  4108. resulting formula: `a F 1 k <RET>' produces `3 + 2 k'. Changing the
  4109. parameter names (say, `a F 1 k;b,m <RET>') will affect the equations
  4110. that go into the trail.
  4111. To see what happens when the fit is not exact, we could change the
  4112. number 13 in the data matrix to 14 and try the fit again. The result
  4113. is:
  4114. 2.6 + 2.2 x
  4115. Evaluating this formula, say with `v x 5 <RET> <TAB> V M $ <RET>',
  4116. shows a reasonably close match to the y-values in the data.
  4117. [4.8, 7., 9.2, 11.4, 13.6]
  4118. Since there is no line which passes through all the N data points,
  4119. Calc has chosen a line that best approximates the data points using the
  4120. method of least squares. The idea is to define the "chi-square" error
  4121. measure
  4122. chi^2 = sum((y_i - (a + b x_i))^2, i, 1, N)
  4123. which is clearly zero if `a + b x' exactly fits all data points, and
  4124. increases as various `a + b x_i' values fail to match the corresponding
  4125. `y_i' values. There are several reasons why the summand is squared,
  4126. one of them being to ensure that `chi^2 >= 0'. Least-squares fitting
  4127. simply chooses the values of `a' and `b' for which the error `chi^2' is
  4128. as small as possible.
  4129. Other kinds of models do the same thing but with a different model
  4130. formula in place of `a + b x_i'.
  4131. A numeric prefix argument causes the `a F' command to take the data
  4132. in some other form than one big matrix. A positive argument N will
  4133. take N items from the stack, corresponding to the N rows of a data
  4134. matrix. In the linear case, N must be 2 since there is always one
  4135. independent variable and one dependent variable.
  4136. A prefix of zero or plain `C-u' is a compromise; Calc takes two
  4137. items from the stack, an N-row matrix of `x' values, and a vector of
  4138. `y' values. If there is only one independent variable, the `x' values
  4139. can be either a one-row matrix or a plain vector, in which case the
  4140. `C-u' prefix is the same as a `C-u 2' prefix.
  4141. 
  4142. File: calc, Node: Polynomial and Multilinear Fits, Next: Error Estimates for Fits, Prev: Linear Fits, Up: Curve Fitting
  4143. 12.8.2 Polynomial and Multilinear Fits
  4144. --------------------------------------
  4145. To fit the data to higher-order polynomials, just type one of the
  4146. digits `2' through `9' when prompted for a model. For example, we
  4147. could fit the original data matrix from the previous section (with 13,
  4148. not 14) to a parabola instead of a line by typing `a F 2 <RET>'.
  4149. 2.00000000001 x - 1.5e-12 x^2 + 2.99999999999
  4150. Note that since the constant and linear terms are enough to fit the
  4151. data exactly, it's no surprise that Calc chose a tiny contribution for
  4152. `x^2'. (The fact that it's not exactly zero is due only to roundoff
  4153. error. Since our data are exact integers, we could get an exact answer
  4154. by typing `m f' first to get Fraction mode. Then the `x^2' term would
  4155. vanish altogether. Usually, though, the data being fitted will be
  4156. approximate floats so Fraction mode won't help.)
  4157. Doing the `a F 2' fit on the data set with 14 instead of 13 gives a
  4158. much larger `x^2' contribution, as Calc bends the line slightly to
  4159. improve the fit.
  4160. 0.142857142855 x^2 + 1.34285714287 x + 3.59999999998
  4161. An important result from the theory of polynomial fitting is that it
  4162. is always possible to fit N data points exactly using a polynomial of
  4163. degree N-1, sometimes called an "interpolating polynomial". Using the
  4164. modified (14) data matrix, a model number of 4 gives a polynomial that
  4165. exactly matches all five data points:
  4166. 0.04167 x^4 - 0.4167 x^3 + 1.458 x^2 - 0.08333 x + 4.
  4167. The actual coefficients we get with a precision of 12, like
  4168. `0.0416666663588', clearly suffer from loss of precision. It is a good
  4169. idea to increase the working precision to several digits beyond what
  4170. you need when you do a fitting operation. Or, if your data are exact,
  4171. use Fraction mode to get exact results.
  4172. You can type `i' instead of a digit at the model prompt to fit the
  4173. data exactly to a polynomial. This just counts the number of columns
  4174. of the data matrix to choose the degree of the polynomial automatically.
  4175. Fitting data "exactly" to high-degree polynomials is not always a
  4176. good idea, though. High-degree polynomials have a tendency to wiggle
  4177. uncontrollably in between the fitting data points. Also, if the
  4178. exact-fit polynomial is going to be used to interpolate or extrapolate
  4179. the data, it is numerically better to use the `a p' command described
  4180. below. *Note Interpolation::.
  4181. Another generalization of the linear model is to assume the `y'
  4182. values are a sum of linear contributions from several `x' values. This
  4183. is a "multilinear" fit, and it is also selected by the `1' digit key.
  4184. (Calc decides whether the fit is linear or multilinear by counting the
  4185. rows in the data matrix.)
  4186. Given the data matrix,
  4187. [ [ 1, 2, 3, 4, 5 ]
  4188. [ 7, 2, 3, 5, 2 ]
  4189. [ 14.5, 15, 18.5, 22.5, 24 ] ]
  4190. the command `a F 1 <RET>' will call the first row `x' and the second
  4191. row `y', and will fit the values in the third row to the model `a + b x
  4192. + c y'.
  4193. 8. + 3. x + 0.5 y
  4194. Calc can do multilinear fits with any number of independent variables
  4195. (i.e., with any number of data rows).
  4196. Yet another variation is "homogeneous" linear models, in which the
  4197. constant term is known to be zero. In the linear case, this means the
  4198. model formula is simply `a x'; in the multilinear case, the model might
  4199. be `a x + b y + c z'; and in the polynomial case, the model could be `a
  4200. x + b x^2 + c x^3'. You can get a homogeneous linear or multilinear
  4201. model by pressing the letter `h' followed by a regular model key, like
  4202. `1' or `2'. This will be indicated by an "h" in the minibuffer after
  4203. the help message.
  4204. It is certainly possible to have other constrained linear models,
  4205. like `2.3 + a x' or `a - 4 x'. While there is no single key to select
  4206. models like these, a later section shows how to enter any desired model
  4207. by hand. In the first case, for example, you would enter `a F ' 2.3 +
  4208. a x'.
  4209. Another class of models that will work but must be entered by hand
  4210. are multinomial fits, e.g., `a + b x + c y + d x^2 + e y^2 + f x y'.
  4211. 
  4212. File: calc, Node: Error Estimates for Fits, Next: Standard Nonlinear Models, Prev: Polynomial and Multilinear Fits, Up: Curve Fitting
  4213. 12.8.3 Error Estimates for Fits
  4214. -------------------------------
  4215. With the Hyperbolic flag, `H a F' [`efit'] performs the same fitting
  4216. operation as `a F', but reports the coefficients as error forms instead
  4217. of plain numbers. Fitting our two data matrices (first with 13, then
  4218. with 14) to a line with `H a F' gives the results,
  4219. 3. + 2. x
  4220. 2.6 +/- 0.382970843103 + 2.2 +/- 0.115470053838 x
  4221. In the first case the estimated errors are zero because the linear
  4222. fit is perfect. In the second case, the errors are nonzero but
  4223. moderately small, because the data are still very close to linear.
  4224. It is also possible for the _input_ to a fitting operation to
  4225. contain error forms. The data values must either all include errors or
  4226. all be plain numbers. Error forms can go anywhere but generally go on
  4227. the numbers in the last row of the data matrix. If the last row
  4228. contains error forms `Y_I +/- SIGMA_I', then the `chi^2' statistic is
  4229. now,
  4230. chi^2 = sum(((y_i - (a + b x_i)) / sigma_i)^2, i, 1, N)
  4231. so that data points with larger error estimates contribute less to the
  4232. fitting operation.
  4233. If there are error forms on other rows of the data matrix, all the
  4234. errors for a given data point are combined; the square root of the sum
  4235. of the squares of the errors forms the `sigma_i' used for the data
  4236. point.
  4237. Both `a F' and `H a F' can accept error forms in the input matrix,
  4238. although if you are concerned about error analysis you will probably
  4239. use `H a F' so that the output also contains error estimates.
  4240. If the input contains error forms but all the `sigma_i' values are
  4241. the same, it is easy to see that the resulting fitted model will be the
  4242. same as if the input did not have error forms at all (`chi^2' is simply
  4243. scaled uniformly by `1 / sigma^2', which doesn't affect where it has a
  4244. minimum). But there _will_ be a difference in the estimated errors of
  4245. the coefficients reported by `H a F'.
  4246. Consult any text on statistical modeling of data for a discussion of
  4247. where these error estimates come from and how they should be
  4248. interpreted.
  4249. With the Inverse flag, `I a F' [`xfit'] produces even more
  4250. information. The result is a vector of six items:
  4251. 1. The model formula with error forms for its coefficients or
  4252. parameters. This is the result that `H a F' would have produced.
  4253. 2. A vector of "raw" parameter values for the model. These are the
  4254. polynomial coefficients or other parameters as plain numbers, in
  4255. the same order as the parameters appeared in the final prompt of
  4256. the `I a F' command. For polynomials of degree `d', this vector
  4257. will have length `M = d+1' with the constant term first.
  4258. 3. The covariance matrix `C' computed from the fit. This is an MxM
  4259. symmetric matrix; the diagonal elements `C_j_j' are the variances
  4260. `sigma_j^2' of the parameters. The other elements are covariances
  4261. `sigma_i_j^2' that describe the correlation between pairs of
  4262. parameters. (A related set of numbers, the "linear correlation
  4263. coefficients" `r_i_j', are defined as `sigma_i_j^2 / sigma_i
  4264. sigma_j'.)
  4265. 4. A vector of `M' "parameter filter" functions whose meanings are
  4266. described below. If no filters are necessary this will instead be
  4267. an empty vector; this is always the case for the polynomial and
  4268. multilinear fits described so far.
  4269. 5. The value of `chi^2' for the fit, calculated by the formulas shown
  4270. above. This gives a measure of the quality of the fit;
  4271. statisticians consider `chi^2 = N - M' to indicate a moderately
  4272. good fit (where again `N' is the number of data points and `M' is
  4273. the number of parameters).
  4274. 6. A measure of goodness of fit expressed as a probability `Q'. This
  4275. is computed from the `utpc' probability distribution function using
  4276. `chi^2' with `N - M' degrees of freedom. A value of 0.5 implies a
  4277. good fit; some texts recommend that often `Q = 0.1' or even 0.001
  4278. can signify an acceptable fit. In particular, `chi^2' statistics
  4279. assume the errors in your inputs follow a normal (Gaussian)
  4280. distribution; if they don't, you may have to accept smaller values
  4281. of `Q'.
  4282. The `Q' value is computed only if the input included error
  4283. estimates. Otherwise, Calc will report the symbol `nan' for `Q'.
  4284. The reason is that in this case the `chi^2' value has effectively
  4285. been used to estimate the original errors in the input, and thus
  4286. there is no redundant information left over to use for a
  4287. confidence test.
  4288. 
  4289. File: calc, Node: Standard Nonlinear Models, Next: Curve Fitting Details, Prev: Error Estimates for Fits, Up: Curve Fitting
  4290. 12.8.4 Standard Nonlinear Models
  4291. --------------------------------
  4292. The `a F' command also accepts other kinds of models besides lines and
  4293. polynomials. Some common models have quick single-key abbreviations;
  4294. others must be entered by hand as algebraic formulas.
  4295. Here is a complete list of the standard models recognized by `a F':
  4296. `1'
  4297. Linear or multilinear. a + b x + c y + d z.
  4298. `2-9'
  4299. Polynomials. a + b x + c x^2 + d x^3.
  4300. `e'
  4301. Exponential. a exp(b x) exp(c y).
  4302. `E'
  4303. Base-10 exponential. a 10^(b x) 10^(c y).
  4304. `x'
  4305. Exponential (alternate notation). exp(a + b x + c y).
  4306. `X'
  4307. Base-10 exponential (alternate). 10^(a + b x + c y).
  4308. `l'
  4309. Logarithmic. a + b ln(x) + c ln(y).
  4310. `L'
  4311. Base-10 logarithmic. a + b log10(x) + c log10(y).
  4312. `^'
  4313. General exponential. a b^x c^y.
  4314. `p'
  4315. Power law. a x^b y^c.
  4316. `q'
  4317. Quadratic. a + b (x-c)^2 + d (x-e)^2.
  4318. `g'
  4319. Gaussian. (a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2).
  4320. `s'
  4321. Logistic _s_ curve. a/(1 + exp(b (x - c))).
  4322. `b'
  4323. Logistic bell curve. a exp(b (x - c))/(1 + exp(b (x - c)))^2.
  4324. `o'
  4325. Hubbert linearization. (y/x) = a (1 - x/b).
  4326. All of these models are used in the usual way; just press the
  4327. appropriate letter at the model prompt, and choose variable names if
  4328. you wish. The result will be a formula as shown in the above table,
  4329. with the best-fit values of the parameters substituted. (You may find
  4330. it easier to read the parameter values from the vector that is placed
  4331. in the trail.)
  4332. All models except Gaussian, logistics, Hubbert and polynomials can
  4333. generalize as shown to any number of independent variables. Also, all
  4334. the built-in models except for the logistic and Hubbert curves have an
  4335. additive or multiplicative parameter shown as `a' in the above table
  4336. which can be replaced by zero or one, as appropriate, by typing `h'
  4337. before the model key.
  4338. Note that many of these models are essentially equivalent, but
  4339. express the parameters slightly differently. For example, `a b^x' and
  4340. the other two exponential models are all algebraic rearrangements of
  4341. each other. Also, the "quadratic" model is just a degree-2 polynomial
  4342. with the parameters expressed differently. Use whichever form best
  4343. matches the problem.
  4344. The HP-28/48 calculators support four different models for curve
  4345. fitting, called `LIN', `LOG', `EXP', and `PWR'. These correspond to
  4346. Calc models `a + b x', `a + b ln(x)', `a exp(b x)', and `a x^b',
  4347. respectively. In each case, `a' is what the HP-48 identifies as the
  4348. "intercept," and `b' is what it calls the "slope."
  4349. If the model you want doesn't appear on this list, press `'' (the
  4350. apostrophe key) at the model prompt to enter any algebraic formula,
  4351. such as `m x - b', as the model. (Not all models will work,
  4352. though--see the next section for details.)
  4353. The model can also be an equation like `y = m x + b'. In this case,
  4354. Calc thinks of all the rows of the data matrix on equal terms; this
  4355. model effectively has two parameters (`m' and `b') and two independent
  4356. variables (`x' and `y'), with no "dependent" variables. Model equations
  4357. do not need to take this `y =' form. For example, the implicit line
  4358. equation `a x + b y = 1' works fine as a model.
  4359. When you enter a model, Calc makes an alphabetical list of all the
  4360. variables that appear in the model. These are used for the default
  4361. parameters, independent variables, and dependent variable (in that
  4362. order). If you enter a plain formula (not an equation), Calc assumes
  4363. the dependent variable does not appear in the formula and thus does not
  4364. need a name.
  4365. For example, if the model formula has the variables `a,mu,sigma,t,x',
  4366. and the data matrix has three rows (meaning two independent variables),
  4367. Calc will use `a,mu,sigma' as the default parameters, and the data rows
  4368. will be named `t' and `x', respectively. If you enter an equation
  4369. instead of a plain formula, Calc will use `a,mu' as the parameters, and
  4370. `sigma,t,x' as the three independent variables.
  4371. You can, of course, override these choices by entering something
  4372. different at the prompt. If you leave some variables out of the list,
  4373. those variables must have stored values and those stored values will be
  4374. used as constants in the model. (Stored values for the parameters and
  4375. independent variables are ignored by the `a F' command.) If you list
  4376. only independent variables, all the remaining variables in the model
  4377. formula will become parameters.
  4378. If there are `$' signs in the model you type, they will stand for
  4379. parameters and all other variables (in alphabetical order) will be
  4380. independent. Use `$' for one parameter, `$$' for another, and so on.
  4381. Thus `$ x + $$' is another way to describe a linear model.
  4382. If you type a `$' instead of `'' at the model prompt itself, Calc
  4383. will take the model formula from the stack. (The data must then appear
  4384. at the second stack level.) The same conventions are used to choose
  4385. which variables in the formula are independent by default and which are
  4386. parameters.
  4387. Models taken from the stack can also be expressed as vectors of two
  4388. or three elements, `[MODEL, VARS]' or `[MODEL, VARS, PARAMS]'. Each of
  4389. VARS and PARAMS may be either a variable or a vector of variables. (If
  4390. PARAMS is omitted, all variables in MODEL except those listed as VARS
  4391. are parameters.)
  4392. When you enter a model manually with `'', Calc puts a 3-vector
  4393. describing the model in the trail so you can get it back if you wish.
  4394. Finally, you can store a model in one of the Calc variables `Model1'
  4395. or `Model2', then use this model by typing `a F u' or `a F U'
  4396. (respectively). The value stored in the variable can be any of the
  4397. formats that `a F $' would accept for a model on the stack.
  4398. Calc uses the principal values of inverse functions like `ln' and
  4399. `arcsin' when doing fits. For example, when you enter the model `y =
  4400. sin(a t + b)' Calc actually uses the easier form `arcsin(y) = a t + b'.
  4401. The `arcsin' function always returns results in the range from -90 to
  4402. 90 degrees (or the equivalent range in radians). Suppose you had data
  4403. that you believed to represent roughly three oscillations of a sine
  4404. wave, so that the argument of the sine might go from zero to 3*360
  4405. degrees. The above model would appear to be a good way to determine the
  4406. true frequency and phase of the sine wave, but in practice it would
  4407. fail utterly. The righthand side of the actual model `arcsin(y) = a t
  4408. + b' will grow smoothly with `t', but the lefthand side will bounce
  4409. back and forth between -90 and 90. No values of `a' and `b' can make
  4410. the two sides match, even approximately.
  4411. There is no good solution to this problem at present. You could
  4412. restrict your data to small enough ranges so that the above problem
  4413. doesn't occur (i.e., not straddling any peaks in the sine wave). Or,
  4414. in this case, you could use a totally different method such as Fourier
  4415. analysis, which is beyond the scope of the `a F' command.
  4416. (Unfortunately, Calc does not currently have any facilities for taking
  4417. Fourier and related transforms.)
  4418. 
  4419. File: calc, Node: Curve Fitting Details, Next: Interpolation, Prev: Standard Nonlinear Models, Up: Curve Fitting
  4420. 12.8.5 Curve Fitting Details
  4421. ----------------------------
  4422. Calc's internal least-squares fitter can only handle multilinear
  4423. models. More precisely, it can handle any model of the form `a
  4424. f(x,y,z) + b g(x,y,z) + c h(x,y,z)', where `a,b,c' are the parameters
  4425. and `x,y,z' are the independent variables (of course there can be any
  4426. number of each, not just three).
  4427. In a simple multilinear or polynomial fit, it is easy to see how to
  4428. convert the model into this form. For example, if the model is `a + b
  4429. x + c x^2', then `f(x) = 1', `g(x) = x', and `h(x) = x^2' are suitable
  4430. functions.
  4431. For most other models, Calc uses a variety of algebraic manipulations
  4432. to try to put the problem into the form
  4433. 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)
  4434. where `Y,A,B,C,F,G,H' are arbitrary functions. It computes `Y', `F',
  4435. `G', and `H' for all the data points, does a standard linear fit to
  4436. find the values of `A', `B', and `C', then uses the equation solver to
  4437. solve for `a,b,c' in terms of `A,B,C'.
  4438. A remarkable number of models can be cast into this general form.
  4439. We'll look at two examples here to see how it works. The power-law
  4440. model `y = a x^b' with two independent variables and two parameters can
  4441. be rewritten as follows:
  4442. y = a x^b
  4443. y = a exp(b ln(x))
  4444. y = exp(ln(a) + b ln(x))
  4445. ln(y) = ln(a) + b ln(x)
  4446. which matches the desired form with `Y = ln(y)', `A = ln(a)', `F = 1',
  4447. `B = b', and `G = ln(x)'. Calc thus computes the logarithms of your
  4448. `y' and `x' values, does a linear fit for `A' and `B', then solves to
  4449. get `a = exp(A)' and `b = B'.
  4450. Another interesting example is the "quadratic" model, which can be
  4451. handled by expanding according to the distributive law.
  4452. y = a + b*(x - c)^2
  4453. y = a + b c^2 - 2 b c x + b x^2
  4454. which matches with `Y = y', `A = a + b c^2', `F = 1', `B = -2 b c', `G
  4455. = x' (the -2 factor could just as easily have been put into `G' instead
  4456. of `B'), `C = b', and `H = x^2'.
  4457. The Gaussian model looks quite complicated, but a closer examination
  4458. shows that it's actually similar to the quadratic model but with an
  4459. exponential that can be brought to the top and moved into `Y'.
  4460. The logistic models cannot be put into general linear form. For
  4461. these models, and the Hubbert linearization, Calc computes a rough
  4462. approximation for the parameters, then uses the Levenberg-Marquardt
  4463. iterative method to refine the approximations.
  4464. Another model that cannot be put into general linear form is a
  4465. Gaussian with a constant background added on, i.e., `d' + the regular
  4466. Gaussian formula. If you have a model like this, your best bet is to
  4467. replace enough of your parameters with constants to make the model
  4468. linearizable, then adjust the constants manually by doing a series of
  4469. fits. You can compare the fits by graphing them, by examining the
  4470. goodness-of-fit measures returned by `I a F', or by some other method
  4471. suitable to your application. Note that some models can be linearized
  4472. in several ways. The Gaussian-plus-D model can be linearized by
  4473. setting `d' (the background) to a constant, or by setting `b' (the
  4474. standard deviation) and `c' (the mean) to constants.
  4475. To fit a model with constants substituted for some parameters, just
  4476. store suitable values in those parameter variables, then omit them from
  4477. the list of parameters when you answer the variables prompt.
  4478. A last desperate step would be to use the general-purpose `minimize'
  4479. function rather than `fit'. After all, both functions solve the
  4480. problem of minimizing an expression (the `chi^2' sum) by adjusting
  4481. certain parameters in the expression. The `a F' command is able to use
  4482. a vastly more efficient algorithm due to its special knowledge about
  4483. linear chi-square sums, but the `a N' command can do the same thing by
  4484. brute force.
  4485. A compromise would be to pick out a few parameters without which the
  4486. fit is linearizable, and use `minimize' on a call to `fit' which
  4487. efficiently takes care of the rest of the parameters. The thing to be
  4488. minimized would be the value of `chi^2' returned as the fifth result of
  4489. the `xfit' function:
  4490. minimize(xfit(gaus(a,b,c,d,x), x, [a,b,c], data)_5, d, guess)
  4491. where `gaus' represents the Gaussian model with background, `data'
  4492. represents the data matrix, and `guess' represents the initial guess
  4493. for `d' that `minimize' requires. This operation will only be, shall
  4494. we say, extraordinarily slow rather than astronomically slow (as would
  4495. be the case if `minimize' were used by itself to solve the problem).
  4496. The `I a F' [`xfit'] command is somewhat trickier when nonlinear
  4497. models are used. The second item in the result is the vector of "raw"
  4498. parameters `A', `B', `C'. The covariance matrix is written in terms of
  4499. those raw parameters. The fifth item is a vector of "filter"
  4500. expressions. This is the empty vector `[]' if the raw parameters were
  4501. the same as the requested parameters, i.e., if `A = a', `B = b', and so
  4502. on (which is always true if the model is already linear in the
  4503. parameters as written, e.g., for polynomial fits). If the parameters
  4504. had to be rearranged, the fifth item is instead a vector of one formula
  4505. per parameter in the original model. The raw parameters are expressed
  4506. in these "filter" formulas as `fitdummy(1)' for `A', `fitdummy(2)' for
  4507. `B', and so on.
  4508. When Calc needs to modify the model to return the result, it replaces
  4509. `fitdummy(1)' in all the filters with the first item in the raw
  4510. parameters list, and so on for the other raw parameters, then evaluates
  4511. the resulting filter formulas to get the actual parameter values to be
  4512. substituted into the original model. In the case of `H a F' and `I a
  4513. F' where the parameters must be error forms, Calc uses the square roots
  4514. of the diagonal entries of the covariance matrix as error values for
  4515. the raw parameters, then lets Calc's standard error-form arithmetic
  4516. take it from there.
  4517. If you use `I a F' with a nonlinear model, be sure to remember that
  4518. the covariance matrix is in terms of the raw parameters, _not_ the
  4519. actual requested parameters. It's up to you to figure out how to
  4520. interpret the covariances in the presence of nontrivial filter
  4521. functions.
  4522. Things are also complicated when the input contains error forms.
  4523. Suppose there are three independent and dependent variables, `x', `y',
  4524. and `z', one or more of which are error forms in the data. Calc
  4525. combines all the error values by taking the square root of the sum of
  4526. the squares of the errors. It then changes `x' and `y' to be plain
  4527. numbers, and makes `z' into an error form with this combined error.
  4528. The `Y(x,y,z)' part of the linearized model is evaluated, and the
  4529. result should be an error form. The error part of that result is used
  4530. for `sigma_i' for the data point. If for some reason `Y(x,y,z)' does
  4531. not return an error form, the combined error from `z' is used directly
  4532. for `sigma_i'. Finally, `z' is also stripped of its error for use in
  4533. computing `F(x,y,z)', `G(x,y,z)' and so on; the righthand side of the
  4534. linearized model is computed in regular arithmetic with no error forms.
  4535. (While these rules may seem complicated, they are designed to do the
  4536. most reasonable thing in the typical case that `Y(x,y,z)' depends only
  4537. on the dependent variable `z', and in fact is often simply equal to
  4538. `z'. For common cases like polynomials and multilinear models, the
  4539. combined error is simply used as the `sigma' for the data point with no
  4540. further ado.)
  4541. It may be the case that the model you wish to use is linearizable,
  4542. but Calc's built-in rules are unable to figure it out. Calc uses its
  4543. algebraic rewrite mechanism to linearize a model. The rewrite rules
  4544. are kept in the variable `FitRules'. You can edit this variable using
  4545. the `s e FitRules' command; in fact, there is a special `s F' command
  4546. just for editing `FitRules'. *Note Operations on Variables::.
  4547. *Note Rewrite Rules::, for a discussion of rewrite rules.
  4548. Calc uses `FitRules' as follows. First, it converts the model to an
  4549. equation if necessary and encloses the model equation in a call to the
  4550. function `fitmodel' (which is not actually a defined function in Calc;
  4551. it is only used as a placeholder by the rewrite rules). Parameter
  4552. variables are renamed to function calls `fitparam(1)', `fitparam(2)',
  4553. and so on, and independent variables are renamed to `fitvar(1)',
  4554. `fitvar(2)', etc. The dependent variable is the highest-numbered
  4555. `fitvar'. For example, the power law model `a x^b' is converted to `y
  4556. = a x^b', then to
  4557. fitmodel(fitvar(2) = fitparam(1) fitvar(1)^fitparam(2))
  4558. Calc then applies the rewrites as if by `C-u 0 a r FitRules'. (The
  4559. zero prefix means that rewriting should continue until no further
  4560. changes are possible.)
  4561. When rewriting is complete, the `fitmodel' call should have been
  4562. replaced by a `fitsystem' call that looks like this:
  4563. fitsystem(Y, FGH, ABC)
  4564. where Y is a formula that describes the function `Y(x,y,z)', FGH is the
  4565. vector of formulas `[F(x,y,z), G(x,y,z), H(x,y,z)]', and ABC is the
  4566. vector of parameter filters which refer to the raw parameters as
  4567. `fitdummy(1)' for `A', `fitdummy(2)' for `B', etc. While the number of
  4568. raw parameters (the length of the FGH vector) is usually the same as
  4569. the number of original parameters (the length of the ABC vector), this
  4570. is not required.
  4571. The power law model eventually boils down to
  4572. fitsystem(ln(fitvar(2)),
  4573. [1, ln(fitvar(1))],
  4574. [exp(fitdummy(1)), fitdummy(2)])
  4575. The actual implementation of `FitRules' is complicated; it proceeds
  4576. in four phases. First, common rearrangements are done to try to bring
  4577. linear terms together and to isolate functions like `exp' and `ln'
  4578. either all the way "out" (so that they can be put into Y) or all the
  4579. way "in" (so that they can be put into ABC or FGH). In particular, all
  4580. non-constant powers are converted to logs-and-exponentials form, and
  4581. the distributive law is used to expand products of sums. Quotients are
  4582. rewritten to use the `fitinv' function, where `fitinv(x)' represents
  4583. `1/x' while the `FitRules' are operating. (The use of `fitinv' makes
  4584. recognition of linear-looking forms easier.) If you modify `FitRules',
  4585. you will probably only need to modify the rules for this phase.
  4586. Phase two, whose rules can actually also apply during phases one and
  4587. three, first rewrites `fitmodel' to a two-argument form `fitmodel(Y,
  4588. MODEL)', where Y is initially zero and MODEL has been changed from `a=b'
  4589. to `a-b' form. It then tries to peel off invertible functions from the
  4590. outside of MODEL and put them into Y instead, calling the equation
  4591. solver to invert the functions. Finally, when this is no longer
  4592. possible, the `fitmodel' is changed to a four-argument `fitsystem',
  4593. where the fourth argument is MODEL and the FGH and ABC vectors are
  4594. initially empty. (The last vector is really ABC, corresponding to raw
  4595. parameters, for now.)
  4596. Phase three converts a sum of items in the MODEL to a sum of
  4597. `fitpart(A, B, C)' terms which represent terms `A*B*C' of the sum,
  4598. where A is all factors that do not involve any variables, B is all
  4599. factors that involve only parameters, and C is the factors that involve
  4600. only independent variables. (If this decomposition is not possible,
  4601. the rule set will not complete and Calc will complain that the model is
  4602. too complex.) Then `fitpart's with equal B or C components are merged
  4603. back together using the distributive law in order to minimize the
  4604. number of raw parameters needed.
  4605. Phase four moves the `fitpart' terms into the FGH and ABC vectors.
  4606. Also, some of the algebraic expansions that were done in phase 1 are
  4607. undone now to make the formulas more computationally efficient.
  4608. Finally, it calls the solver one more time to convert the ABC vector to
  4609. an ABC vector, and removes the fourth MODEL argument (which by now will
  4610. be zero) to obtain the three-argument `fitsystem' that the linear
  4611. least-squares solver wants to see.
  4612. Two functions which are useful in connection with `FitRules' are
  4613. `hasfitparams(x)' and `hasfitvars(x)', which check whether `x' refers
  4614. to any parameters or independent variables, respectively.
  4615. Specifically, these functions return "true" if the argument contains
  4616. any `fitparam' (or `fitvar') function calls, and "false" otherwise.
  4617. (Recall that "true" means a nonzero number, and "false" means zero.
  4618. The actual nonzero number returned is the largest N from all the
  4619. `fitparam(N)'s or `fitvar(N)'s, respectively, that appear in the
  4620. formula.)
  4621. The `fit' function in algebraic notation normally takes four
  4622. arguments, `fit(MODEL, VARS, PARAMS, DATA)', where MODEL is the model
  4623. formula as it would be typed after `a F '', VARS is the independent
  4624. variable or a vector of independent variables, PARAMS likewise gives
  4625. the parameter(s), and DATA is the data matrix. Note that the length of
  4626. VARS must be equal to the number of rows in DATA if MODEL is an
  4627. equation, or one less than the number of rows if MODEL is a plain
  4628. formula. (Actually, a name for the dependent variable is allowed but
  4629. will be ignored in the plain-formula case.)
  4630. If PARAMS is omitted, the parameters are all variables in MODEL
  4631. except those that appear in VARS. If VARS is also omitted, Calc sorts
  4632. all the variables that appear in MODEL alphabetically and uses the
  4633. higher ones for VARS and the lower ones for PARAMS.
  4634. Alternatively, `fit(MODELVEC, DATA)' is allowed where MODELVEC is a
  4635. 2- or 3-vector describing the model and variables, as discussed
  4636. previously.
  4637. If Calc is unable to do the fit, the `fit' function is left in
  4638. symbolic form, ordinarily with an explanatory message. The message
  4639. will be "Model expression is too complex" if the linearizer was unable
  4640. to put the model into the required form.
  4641. The `efit' (corresponding to `H a F') and `xfit' (for `I a F')
  4642. functions are completely analogous.
  4643. 
  4644. File: calc, Node: Interpolation, Prev: Curve Fitting Details, Up: Curve Fitting
  4645. 12.8.6 Polynomial Interpolation
  4646. -------------------------------
  4647. The `a p' (`calc-poly-interp') [`polint'] command does a polynomial
  4648. interpolation at a particular `x' value. It takes two arguments from
  4649. the stack: A data matrix of the sort used by `a F', and a single
  4650. number which represents the desired `x' value. Calc effectively does
  4651. an exact polynomial fit as if by `a F i', then substitutes the `x'
  4652. value into the result in order to get an approximate `y' value based on
  4653. the fit. (Calc does not actually use `a F i', however; it uses a
  4654. direct method which is both more efficient and more numerically stable.)
  4655. The result of `a p' is actually a vector of two values: The `y'
  4656. value approximation, and an error measure `dy' that reflects Calc's
  4657. estimation of the probable error of the approximation at that value of
  4658. `x'. If the input `x' is equal to any of the `x' values in the data
  4659. matrix, the output `y' will be the corresponding `y' value from the
  4660. matrix, and the output `dy' will be exactly zero.
  4661. A prefix argument of 2 causes `a p' to take separate x- and
  4662. y-vectors from the stack instead of one data matrix.
  4663. If `x' is a vector of numbers, `a p' will return a matrix of
  4664. interpolated results for each of those `x' values. (The matrix will
  4665. have two columns, the `y' values and the `dy' values.) If `x' is a
  4666. formula instead of a number, the `polint' function remains in symbolic
  4667. form; use the `a "' command to expand it out to a formula that
  4668. describes the fit in symbolic terms.
  4669. In all cases, the `a p' command leaves the data vectors or matrix on
  4670. the stack. Only the `x' value is replaced by the result.
  4671. The `H a p' [`ratint'] command does a rational function
  4672. interpolation. It is used exactly like `a p', except that it uses as
  4673. its model the quotient of two polynomials. If there are `N' data
  4674. points, the numerator and denominator polynomials will each have degree
  4675. `N/2' (if `N' is odd, the denominator will have degree one higher than
  4676. the numerator).
  4677. Rational approximations have the advantage that they can accurately
  4678. describe functions that have poles (points at which the function's value
  4679. goes to infinity, so that the denominator polynomial of the
  4680. approximation goes to zero). If `x' corresponds to a pole of the
  4681. fitted rational function, then the result will be a division by zero.
  4682. If Infinite mode is enabled, the result will be `[uinf, uinf]'.
  4683. There is no way to get the actual coefficients of the rational
  4684. function used by `H a p'. (The algorithm never generates these
  4685. coefficients explicitly, and quotients of polynomials are beyond `a F''s
  4686. capabilities to fit.)
  4687. 
  4688. File: calc, Node: Summations, Next: Logical Operations, Prev: Curve Fitting, Up: Algebra
  4689. 12.9 Summations
  4690. ===============
  4691. The `a +' (`calc-summation') [`sum'] command computes the sum of a
  4692. formula over a certain range of index values. The formula is taken
  4693. from the top of the stack; the command prompts for the name of the
  4694. summation index variable, the lower limit of the sum (any formula), and
  4695. the upper limit of the sum. If you enter a blank line at any of these
  4696. prompts, that prompt and any later ones are answered by reading
  4697. additional elements from the stack. Thus, `' k^2 <RET> ' k <RET> 1
  4698. <RET> 5 <RET> a + <RET>' produces the result 55.
  4699. The choice of index variable is arbitrary, but it's best not to use
  4700. a variable with a stored value. In particular, while `i' is often a
  4701. favorite index variable, it should be avoided in Calc because `i' has
  4702. the imaginary constant `(0, 1)' as a value. If you pressed `=' on a
  4703. sum over `i', it would be changed to a nonsensical sum over the
  4704. "variable" `(0, 1)'! If you really want to use `i' as an index
  4705. variable, use `s u i <RET>' first to "unstore" this variable. (*Note
  4706. Storing Variables::.)
  4707. A numeric prefix argument steps the index by that amount rather than
  4708. by one. Thus `' a_k <RET> C-u -2 a + k <RET> 10 <RET> 0 <RET>' yields
  4709. `a_10 + a_8 + a_6 + a_4 + a_2 + a_0'. A prefix argument of plain `C-u'
  4710. causes `a +' to prompt for the step value, in which case you can enter
  4711. any formula or enter a blank line to take the step value from the
  4712. stack. With the `C-u' prefix, `a +' can take up to five arguments from
  4713. the stack: The formula, the variable, the lower limit, the upper
  4714. limit, and (at the top of the stack), the step value.
  4715. Calc knows how to do certain sums in closed form. For example,
  4716. `sum(6 k^2, k, 1, n) = 2 n^3 + 3 n^2 + n'. In particular, this is
  4717. possible if the formula being summed is polynomial or exponential in
  4718. the index variable. Sums of logarithms are transformed into logarithms
  4719. of products. Sums of trigonometric and hyperbolic functions are
  4720. transformed to sums of exponentials and then done in closed form.
  4721. Also, of course, sums in which the lower and upper limits are both
  4722. numbers can always be evaluated just by grinding them out, although
  4723. Calc will use closed forms whenever it can for the sake of efficiency.
  4724. The notation for sums in algebraic formulas is `sum(EXPR, VAR, LOW,
  4725. HIGH, STEP)'. If STEP is omitted, it defaults to one. If HIGH is
  4726. omitted, LOW is actually the upper limit and the lower limit is one.
  4727. If LOW is also omitted, the limits are `-inf' and `inf', respectively.
  4728. Infinite sums can sometimes be evaluated: `sum(.5^k, k, 1, inf)'
  4729. returns `1'. This is done by evaluating the sum in closed form (to `1.
  4730. - 0.5^n' in this case), then evaluating this formula with `n' set to
  4731. `inf'. Calc's usual rules for "infinite" arithmetic can find the
  4732. answer from there. If infinite arithmetic yields a `nan', or if the
  4733. sum cannot be solved in closed form, Calc leaves the `sum' function in
  4734. symbolic form. *Note Infinities::.
  4735. As a special feature, if the limits are infinite (or omitted, as
  4736. described above) but the formula includes vectors subscripted by
  4737. expressions that involve the iteration variable, Calc narrows the
  4738. limits to include only the range of integers which result in valid
  4739. subscripts for the vector. For example, the sum `sum(k
  4740. [a,b,c,d,e,f,g]_(2k),k)' evaluates to `b + 2 d + 3 f'.
  4741. The limits of a sum do not need to be integers. For example,
  4742. `sum(a_k, k, 0, 2 n, n)' produces `a_0 + a_n + a_(2 n)'. Calc computes
  4743. the number of iterations using the formula `1 + (HIGH - LOW) / STEP',
  4744. which must, after simplification as if by `a s', evaluate to an integer.
  4745. If the number of iterations according to the above formula does not
  4746. come out to an integer, the sum is invalid and will be left in symbolic
  4747. form. However, closed forms are still supplied, and you are on your
  4748. honor not to misuse the resulting formulas by substituting mismatched
  4749. bounds into them. For example, `sum(k, k, 1, 10, 2)' is invalid, but
  4750. Calc will go ahead and evaluate the closed form solution for the limits
  4751. 1 and 10 to get the rather dubious answer, 29.25.
  4752. If the lower limit is greater than the upper limit (assuming a
  4753. positive step size), the result is generally zero. However, Calc only
  4754. guarantees a zero result when the upper limit is exactly one step less
  4755. than the lower limit, i.e., if the number of iterations is -1. Thus
  4756. `sum(f(k), k, n, n-1)' is zero but the sum from `n' to `n-2' may report
  4757. a nonzero value if Calc used a closed form solution.
  4758. Calc's logical predicates like `a < b' return 1 for "true" and 0 for
  4759. "false." *Note Logical Operations::. This can be used to advantage
  4760. for building conditional sums. For example, `sum(prime(k)*k^2, k, 1,
  4761. 20)' is the sum of the squares of all prime numbers from 1 to 20; the
  4762. `prime' predicate returns 1 if its argument is prime and 0 otherwise.
  4763. You can read this expression as "the sum of `k^2', where `k' is prime."
  4764. Indeed, `sum(prime(k)*k^2, k)' would represent the sum of _all_ primes
  4765. squared, since the limits default to plus and minus infinity, but there
  4766. are no such sums that Calc's built-in rules can do in closed form.
  4767. As another example, `sum((k != k_0) * f(k), k, 1, n)' is the sum of
  4768. `f(k)' for all `k' from 1 to `n', excluding one value `k_0'. Slightly
  4769. more tricky is the summand `(k != k_0) / (k - k_0)', which is an
  4770. attempt to describe the sum of all `1/(k-k_0)' except at `k = k_0',
  4771. where this would be a division by zero. But at `k = k_0', this formula
  4772. works out to the indeterminate form `0 / 0', which Calc will not assume
  4773. is zero. Better would be to use `(k != k_0) ? 1/(k-k_0) : 0'; the `?
  4774. :' operator does an "if-then-else" test: This expression says, "if `k
  4775. != k_0', then `1/(k-k_0)', else zero." Now the formula `1/(k-k_0)'
  4776. will not even be evaluated by Calc when `k = k_0'.
  4777. The `a -' (`calc-alt-summation') [`asum'] command computes an
  4778. alternating sum. Successive terms of the sequence are given
  4779. alternating signs, with the first term (corresponding to the lower
  4780. index value) being positive. Alternating sums are converted to normal
  4781. sums with an extra term of the form `(-1)^(k-LOW)'. This formula is
  4782. adjusted appropriately if the step value is other than one. For
  4783. example, the Taylor series for the sine function is `asum(x^k / k!, k,
  4784. 1, inf, 2)'. (Calc cannot evaluate this infinite series, but it can
  4785. approximate it if you replace `inf' with any particular odd number.)
  4786. Calc converts this series to a regular sum with a step of one, namely
  4787. `sum((-1)^k x^(2k+1) / (2k+1)!, k, 0, inf)'.
  4788. The `a *' (`calc-product') [`prod'] command is the analogous way to
  4789. take a product of many terms. Calc also knows some closed forms for
  4790. products, such as `prod(k, k, 1, n) = n!'. Conditional products can be
  4791. written `prod(k^prime(k), k, 1, n)' or `prod(prime(k) ? k : 1, k, 1,
  4792. n)'.
  4793. The `a T' (`calc-tabulate') [`table'] command evaluates a formula at
  4794. a series of iterated index values, just like `sum' and `prod', but its
  4795. result is simply a vector of the results. For example, `table(a_i, i,
  4796. 1, 7, 2)' produces `[a_1, a_3, a_5, a_7]'.