calc-4 293 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311
  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: Logical Operations, Next: Rewrite Rules, Prev: Summations, Up: Algebra
  22. 12.10 Logical Operations
  23. ========================
  24. The following commands and algebraic functions return true/false values,
  25. where 1 represents "true" and 0 represents "false." In cases where a
  26. truth value is required (such as for the condition part of a rewrite
  27. rule, or as the condition for a `Z [ Z ]' control structure), any
  28. nonzero value is accepted to mean "true." (Specifically, anything for
  29. which `dnonzero' returns 1 is "true," and anything for which `dnonzero'
  30. returns 0 or cannot decide is assumed "false." Note that this means
  31. that `Z [ Z ]' will execute the "then" portion if its condition is
  32. provably true, but it will execute the "else" portion for any condition
  33. like `a = b' that is not provably true, even if it might be true.
  34. Algebraic functions that have conditions as arguments, like `? :' and
  35. `&&', remain unevaluated if the condition is neither provably true nor
  36. provably false. *Note Declarations::.)
  37. The `a =' (`calc-equal-to') command, or `eq(a,b)' function (which
  38. can also be written `a = b' or `a == b' in an algebraic formula) is
  39. true if `a' and `b' are equal, either because they are identical
  40. expressions, or because they are numbers which are numerically equal.
  41. (Thus the integer 1 is considered equal to the float 1.0.) If the
  42. equality of `a' and `b' cannot be determined, the comparison is left in
  43. symbolic form. Note that as a command, this operation pops two values
  44. from the stack and pushes back either a 1 or a 0, or a formula `a = b'
  45. if the values' equality cannot be determined.
  46. Many Calc commands use `=' formulas to represent "equations". For
  47. example, the `a S' (`calc-solve-for') command rearranges an equation to
  48. solve for a given variable. The `a M' (`calc-map-equation') command
  49. can be used to apply any function to both sides of an equation; for
  50. example, `2 a M *' multiplies both sides of the equation by two. Note
  51. that just `2 *' would not do the same thing; it would produce the
  52. formula `2 (a = b)' which represents 2 if the equality is true or zero
  53. if not.
  54. The `eq' function with more than two arguments (e.g., `C-u 3 a =' or
  55. `a = b = c') tests if all of its arguments are equal. In algebraic
  56. notation, the `=' operator is unusual in that it is neither left- nor
  57. right-associative: `a = b = c' is not the same as `(a = b) = c' or `a
  58. = (b = c)' (which each compare one variable with the 1 or 0 that
  59. results from comparing two other variables).
  60. The `a #' (`calc-not-equal-to') command, or `neq(a,b)' or `a != b'
  61. function, is true if `a' and `b' are not equal. This also works with
  62. more than two arguments; `a != b != c != d' tests that all four of `a',
  63. `b', `c', and `d' are distinct numbers.
  64. The `a <' (`calc-less-than') [`lt(a,b)' or `a < b'] operation is
  65. true if `a' is less than `b'. Similar functions are `a >'
  66. (`calc-greater-than') [`gt(a,b)' or `a > b'], `a [' (`calc-less-equal')
  67. [`leq(a,b)' or `a <= b'], and `a ]' (`calc-greater-equal') [`geq(a,b)'
  68. or `a >= b'].
  69. While the inequality functions like `lt' do not accept more than two
  70. arguments, the syntax `a <= b < c' is translated to an equivalent
  71. expression involving intervals: `b in [a .. c)'. (See the description
  72. of `in' below.) All four combinations of `<' and `<=' are allowed, or
  73. any of the four combinations of `>' and `>='. Four-argument
  74. constructions like `a < b < c < d', and mixtures like `a < b = c' that
  75. involve both equations and inequalities, are not allowed.
  76. The `a .' (`calc-remove-equal') [`rmeq'] command extracts the
  77. righthand side of the equation or inequality on the top of the stack.
  78. It also works elementwise on vectors. For example, if `[x = 2.34, y =
  79. z / 2]' is on the stack, then `a .' produces `[2.34, z / 2]'. As a
  80. special case, if the righthand side is a variable and the lefthand side
  81. is a number (as in `2.34 = x'), then Calc keeps the lefthand side
  82. instead. Finally, this command works with assignments `x := 2.34' as
  83. well as equations, always taking the righthand side, and for `=>'
  84. (evaluates-to) operators, always taking the lefthand side.
  85. The `a &' (`calc-logical-and') [`land(a,b)' or `a && b'] function is
  86. true if both of its arguments are true, i.e., are non-zero numbers. In
  87. this case, the result will be either `a' or `b', chosen arbitrarily.
  88. If either argument is zero, the result is zero. Otherwise, the formula
  89. is left in symbolic form.
  90. The `a |' (`calc-logical-or') [`lor(a,b)' or `a || b'] function is
  91. true if either or both of its arguments are true (nonzero). The result
  92. is whichever argument was nonzero, choosing arbitrarily if both are
  93. nonzero. If both `a' and `b' are zero, the result is zero.
  94. The `a !' (`calc-logical-not') [`lnot(a)' or `! a'] function is true
  95. if `a' is false (zero), or false if `a' is true (nonzero). It is left
  96. in symbolic form if `a' is not a number.
  97. The `a :' (`calc-logical-if') [`if(a,b,c)' or `a ? b : c'] function
  98. is equal to either `b' or `c' if `a' is a nonzero number or zero,
  99. respectively. If `a' is not a number, the test is left in symbolic
  100. form and neither `b' nor `c' is evaluated in any way. In algebraic
  101. formulas, this is one of the few Calc functions whose arguments are not
  102. automatically evaluated when the function itself is evaluated. The
  103. others are `lambda', `quote', and `condition'.
  104. One minor surprise to watch out for is that the formula `a?3:4' will
  105. not work because the `3:4' is parsed as a fraction instead of as three
  106. separate symbols. Type something like `a ? 3 : 4' or `a?(3):4' instead.
  107. As a special case, if `a' evaluates to a vector, then both `b' and
  108. `c' are evaluated; the result is a vector of the same length as `a'
  109. whose elements are chosen from corresponding elements of `b' and `c'
  110. according to whether each element of `a' is zero or nonzero. Each of
  111. `b' and `c' must be either a vector of the same length as `a', or a
  112. non-vector which is matched with all elements of `a'.
  113. The `a {' (`calc-in-set') [`in(a,b)'] function is true if the number
  114. `a' is in the set of numbers represented by `b'. If `b' is an interval
  115. form, `a' must be one of the values encompassed by the interval. If
  116. `b' is a vector, `a' must be equal to one of the elements of the
  117. vector. (If any vector elements are intervals, `a' must be in any of
  118. the intervals.) If `b' is a plain number, `a' must be numerically
  119. equal to `b'. *Note Set Operations::, for a group of commands that
  120. manipulate sets of this sort.
  121. The `typeof(a)' function produces an integer or variable which
  122. characterizes `a'. If `a' is a number, vector, or variable, the result
  123. will be one of the following numbers:
  124. 1 Integer
  125. 2 Fraction
  126. 3 Floating-point number
  127. 4 HMS form
  128. 5 Rectangular complex number
  129. 6 Polar complex number
  130. 7 Error form
  131. 8 Interval form
  132. 9 Modulo form
  133. 10 Date-only form
  134. 11 Date/time form
  135. 12 Infinity (inf, uinf, or nan)
  136. 100 Variable
  137. 101 Vector (but not a matrix)
  138. 102 Matrix
  139. Otherwise, `a' is a formula, and the result is a variable which
  140. represents the name of the top-level function call.
  141. The `integer(a)' function returns true if `a' is an integer. The
  142. `real(a)' function is true if `a' is a real number, either integer,
  143. fraction, or float. The `constant(a)' function returns true if `a' is
  144. any of the objects for which `typeof' would produce an integer code
  145. result except for variables, and provided that the components of an
  146. object like a vector or error form are themselves constant. Note that
  147. infinities do not satisfy any of these tests, nor do special constants
  148. like `pi' and `e'.
  149. *Note Declarations::, for a set of similar functions that recognize
  150. formulas as well as actual numbers. For example, `dint(floor(x))' is
  151. true because `floor(x)' is provably integer-valued, but
  152. `integer(floor(x))' does not because `floor(x)' is not literally an
  153. integer constant.
  154. The `refers(a,b)' function is true if the variable (or
  155. sub-expression) `b' appears in `a', or false otherwise. Unlike the
  156. other tests described here, this function returns a definite "no" answer
  157. even if its arguments are still in symbolic form. The only case where
  158. `refers' will be left unevaluated is if `a' is a plain variable
  159. (different from `b').
  160. The `negative(a)' function returns true if `a' "looks" negative,
  161. because it is a negative number, because it is of the form `-x', or
  162. because it is a product or quotient with a term that looks negative.
  163. This is most useful in rewrite rules. Beware that `negative(a)'
  164. evaluates to 1 or 0 for _any_ argument `a', so it can only be stored in
  165. a formula if the default simplifications are turned off first with `m
  166. O' (or if it appears in an unevaluated context such as a rewrite rule
  167. condition).
  168. The `variable(a)' function is true if `a' is a variable, or false if
  169. not. If `a' is a function call, this test is left in symbolic form.
  170. Built-in variables like `pi' and `inf' are considered variables like
  171. any others by this test.
  172. The `nonvar(a)' function is true if `a' is a non-variable. If its
  173. argument is a variable it is left unsimplified; it never actually
  174. returns zero. However, since Calc's condition-testing commands
  175. consider "false" anything not provably true, this is often good enough.
  176. The functions `lin', `linnt', `islin', and `islinnt' check if an
  177. expression is "linear," i.e., can be written in the form `a + b x' for
  178. some constants `a' and `b', and some variable or subformula `x'. The
  179. function `islin(f,x)' checks if formula `f' is linear in `x', returning
  180. 1 if so. For example, `islin(x,x)', `islin(-x,x)', `islin(3,x)', and
  181. `islin(x y / 3 - 2, x)' all return 1. The `lin(f,x)' function is
  182. similar, except that instead of returning 1 it returns the vector `[a,
  183. b, x]'. For the above examples, this vector would be `[0, 1, x]', `[0,
  184. -1, x]', `[3, 0, x]', and `[-2, y/3, x]', respectively. Both `lin' and
  185. `islin' generally remain unevaluated for expressions which are not
  186. linear, e.g., `lin(2 x^2, x)' and `lin(sin(x), x)'. The second
  187. argument can also be a formula; `islin(2 + 3 sin(x), sin(x))' returns
  188. true.
  189. The `linnt' and `islinnt' functions perform a similar check, but
  190. require a "non-trivial" linear form, which means that the `b'
  191. coefficient must be non-zero. For example, `lin(2,x)' returns `[2, 0,
  192. x]' and `lin(y,x)' returns `[y, 0, x]', but `linnt(2,x)' and
  193. `linnt(y,x)' are left unevaluated (in other words, these formulas are
  194. considered to be only "trivially" linear in `x').
  195. All four linearity-testing functions allow you to omit the second
  196. argument, in which case the input may be linear in any non-constant
  197. formula. Here, the `a=0', `b=1' case is also considered trivial, and
  198. only constant values for `a' and `b' are recognized. Thus, `lin(2 x
  199. y)' returns `[0, 2, x y]', `lin(2 - x y)' returns `[2, -1, x y]', and
  200. `lin(x y)' returns `[0, 1, x y]'. The `linnt' function would allow the
  201. first two cases but not the third. Also, neither `lin' nor `linnt'
  202. accept plain constants as linear in the one-argument case: `islin(2,x)'
  203. is true, but `islin(2)' is false.
  204. The `istrue(a)' function returns 1 if `a' is a nonzero number or
  205. provably nonzero formula, or 0 if `a' is anything else. Calls to
  206. `istrue' can only be manipulated if `m O' mode is used to make sure
  207. they are not evaluated prematurely. (Note that declarations are used
  208. when deciding whether a formula is true; `istrue' returns 1 when
  209. `dnonzero' would return 1, and it returns 0 when `dnonzero' would
  210. return 0 or leave itself in symbolic form.)
  211. 
  212. File: calc, Node: Rewrite Rules, Prev: Logical Operations, Up: Algebra
  213. 12.11 Rewrite Rules
  214. ===================
  215. The `a r' (`calc-rewrite') [`rewrite'] command makes substitutions in a
  216. formula according to a specified pattern or patterns known as "rewrite
  217. rules". Whereas `a b' (`calc-substitute') matches literally, so that
  218. substituting `sin(x)' with `cos(x)' matches only the `sin' function
  219. applied to the variable `x', rewrite rules match general kinds of
  220. formulas; rewriting using the rule `sin(x) := cos(x)' matches `sin' of
  221. any argument and replaces it with `cos' of that same argument. The
  222. only significance of the name `x' is that the same name is used on both
  223. sides of the rule.
  224. Rewrite rules rearrange formulas already in Calc's memory. *Note
  225. Syntax Tables::, to read about "syntax rules", which are similar to
  226. algebraic rewrite rules but operate when new algebraic entries are
  227. being parsed, converting strings of characters into Calc formulas.
  228. * Menu:
  229. * Entering Rewrite Rules::
  230. * Basic Rewrite Rules::
  231. * Conditional Rewrite Rules::
  232. * Algebraic Properties of Rewrite Rules::
  233. * Other Features of Rewrite Rules::
  234. * Composing Patterns in Rewrite Rules::
  235. * Nested Formulas with Rewrite Rules::
  236. * Multi-Phase Rewrite Rules::
  237. * Selections with Rewrite Rules::
  238. * Matching Commands::
  239. * Automatic Rewrites::
  240. * Debugging Rewrites::
  241. * Examples of Rewrite Rules::
  242. 
  243. File: calc, Node: Entering Rewrite Rules, Next: Basic Rewrite Rules, Prev: Rewrite Rules, Up: Rewrite Rules
  244. 12.11.1 Entering Rewrite Rules
  245. ------------------------------
  246. Rewrite rules normally use the "assignment" operator `OLD := NEW'.
  247. This operator is equivalent to the function call `assign(old, new)'.
  248. The `assign' function is undefined by itself in Calc, so an assignment
  249. formula such as a rewrite rule will be left alone by ordinary Calc
  250. commands. But certain commands, like the rewrite system, interpret
  251. assignments in special ways.
  252. For example, the rule `sin(x)^2 := 1-cos(x)^2' says to replace every
  253. occurrence of the sine of something, squared, with one minus the square
  254. of the cosine of that same thing. All by itself as a formula on the
  255. stack it does nothing, but when given to the `a r' command it turns
  256. that command into a sine-squared-to-cosine-squared converter.
  257. To specify a set of rules to be applied all at once, make a vector of
  258. rules.
  259. When `a r' prompts you to enter the rewrite rules, you can answer in
  260. several ways:
  261. 1. With a rule: `f(x) := g(x) <RET>'.
  262. 2. With a vector of rules: `[f1(x) := g1(x), f2(x) := g2(x)] <RET>'.
  263. (You can omit the enclosing square brackets if you wish.)
  264. 3. With the name of a variable that contains the rule or rules vector:
  265. `myrules <RET>'.
  266. 4. With any formula except a rule, a vector, or a variable name; this
  267. will be interpreted as the OLD half of a rewrite rule, and you
  268. will be prompted a second time for the NEW half: `f(x) <RET> g(x)
  269. <RET>'.
  270. 5. With a blank line, in which case the rule, rules vector, or
  271. variable will be taken from the top of the stack (and the formula
  272. to be rewritten will come from the second-to-top position).
  273. If you enter the rules directly (as opposed to using rules stored in
  274. a variable), those rules will be put into the Trail so that you can
  275. retrieve them later. *Note Trail Commands::.
  276. It is most convenient to store rules you use often in a variable and
  277. invoke them by giving the variable name. The `s e'
  278. (`calc-edit-variable') command is an easy way to create or edit a rule
  279. set stored in a variable. You may also wish to use `s p'
  280. (`calc-permanent-variable') to save your rules permanently; *note
  281. Operations on Variables::.
  282. Rewrite rules are compiled into a special internal form for faster
  283. matching. If you enter a rule set directly it must be recompiled every
  284. time. If you store the rules in a variable and refer to them through
  285. that variable, they will be compiled once and saved away along with the
  286. variable for later reference. This is another good reason to store
  287. your rules in a variable.
  288. Calc also accepts an obsolete notation for rules, as vectors `[OLD,
  289. NEW]'. But because it is easily confused with a vector of two rules,
  290. the use of this notation is no longer recommended.
  291. 
  292. File: calc, Node: Basic Rewrite Rules, Next: Conditional Rewrite Rules, Prev: Entering Rewrite Rules, Up: Rewrite Rules
  293. 12.11.2 Basic Rewrite Rules
  294. ---------------------------
  295. To match a particular formula `x' with a particular rewrite rule `OLD
  296. := NEW', Calc compares the structure of `x' with the structure of OLD.
  297. Variables that appear in OLD are treated as "meta-variables"; the
  298. corresponding positions in `x' may contain any sub-formulas. For
  299. example, the pattern `f(x,y)' would match the expression `f(12, a+1)'
  300. with the meta-variable `x' corresponding to 12 and with `y'
  301. corresponding to `a+1'. However, this pattern would not match `f(12)'
  302. or `g(12, a+1)', since there is no assignment of the meta-variables
  303. that will make the pattern match these expressions. Notice that if the
  304. pattern is a single meta-variable, it will match any expression.
  305. If a given meta-variable appears more than once in OLD, the
  306. corresponding sub-formulas of `x' must be identical. Thus the pattern
  307. `f(x,x)' would match `f(12, 12)' and `f(a+1, a+1)' but not `f(12, a+1)'
  308. or `f(a+b, b+a)'. (*Note Conditional Rewrite Rules::, for a way to
  309. match the latter.)
  310. Things other than variables must match exactly between the pattern
  311. and the target formula. To match a particular variable exactly, use
  312. the pseudo-function `quote(v)' in the pattern. For example, the
  313. pattern `x+quote(y)' matches `x+y', `2+y', or `sin(a)+y'.
  314. The special variable names `e', `pi', `i', `phi', `gamma', `inf',
  315. `uinf', and `nan' always match literally. Thus the pattern `sin(d + e
  316. + f)' acts exactly like `sin(d + quote(e) + f)'.
  317. If the OLD pattern is found to match a given formula, that formula
  318. is replaced by NEW, where any occurrences in NEW of meta-variables from
  319. the pattern are replaced with the sub-formulas that they matched.
  320. Thus, applying the rule `f(x,y) := g(y+x,x)' to `f(12, a+1)' would
  321. produce `g(a+13, 12)'.
  322. The normal `a r' command applies rewrite rules over and over
  323. throughout the target formula until no further changes are possible (up
  324. to a limit of 100 times). Use `C-u 1 a r' to make only one change at a
  325. time.
  326. 
  327. File: calc, Node: Conditional Rewrite Rules, Next: Algebraic Properties of Rewrite Rules, Prev: Basic Rewrite Rules, Up: Rewrite Rules
  328. 12.11.3 Conditional Rewrite Rules
  329. ---------------------------------
  330. A rewrite rule can also be "conditional", written in the form `OLD :=
  331. NEW :: COND'. (There is also the obsolete form `[OLD, NEW, COND]'.)
  332. If a COND part is present in the rule, this is an additional condition
  333. that must be satisfied before the rule is accepted. Once OLD has been
  334. successfully matched to the target expression, COND is evaluated (with
  335. all the meta-variables substituted for the values they matched) and
  336. simplified with `a s' (`calc-simplify'). If the result is a nonzero
  337. number or any other object known to be nonzero (*note Declarations::),
  338. the rule is accepted. If the result is zero or if it is a symbolic
  339. formula that is not known to be nonzero, the rule is rejected. *Note
  340. Logical Operations::, for a number of functions that return 1 or 0
  341. according to the results of various tests.
  342. For example, the formula `n > 0' simplifies to 1 or 0 if `n' is
  343. replaced by a positive or nonpositive number, respectively (or if `n'
  344. has been declared to be positive or nonpositive). Thus, the rule
  345. `f(x,y) := g(y+x,x) :: x+y > 0' would apply to `f(0, 4)' but not to
  346. `f(-3, 2)' or `f(12, a+1)' (assuming no outstanding declarations for
  347. `a'). In the case of `f(-3, 2)', the condition can be shown not to be
  348. satisfied; in the case of `f(12, a+1)', the condition merely cannot be
  349. shown to be satisfied, but that is enough to reject the rule.
  350. While Calc will use declarations to reason about variables in the
  351. formula being rewritten, declarations do not apply to meta-variables.
  352. For example, the rule `f(a) := g(a+1)' will match for any values of
  353. `a', such as complex numbers, vectors, or formulas, even if `a' has
  354. been declared to be real or scalar. If you want the meta-variable `a'
  355. to match only literal real numbers, use `f(a) := g(a+1) :: real(a)'.
  356. If you want `a' to match only reals and formulas which are provably
  357. real, use `dreal(a)' as the condition.
  358. The `::' operator is a shorthand for the `condition' function; `OLD
  359. := NEW :: COND' is equivalent to the formula `condition(assign(OLD,
  360. NEW), COND)'.
  361. If you have several conditions, you can use `... :: c1 :: c2 :: c3'
  362. or `... :: c1 && c2 && c3'. The two are entirely equivalent.
  363. It is also possible to embed conditions inside the pattern: `f(x ::
  364. x>0, y) := g(y+x, x)'. This is purely a notational convenience,
  365. though; where a condition appears in a rule has no effect on when it is
  366. tested. The rewrite-rule compiler automatically decides when it is
  367. best to test each condition while a rule is being matched.
  368. Certain conditions are handled as special cases by the rewrite rule
  369. system and are tested very efficiently: Where `x' is any
  370. meta-variable, these conditions are `integer(x)', `real(x)',
  371. `constant(x)', `negative(x)', `x >= y' where `y' is either a constant
  372. or another meta-variable and `>=' may be replaced by any of the six
  373. relational operators, and `x % a = b' where `a' and `b' are constants.
  374. Other conditions, like `x >= y+1' or `dreal(x)', will be less efficient
  375. to check since Calc must bring the whole evaluator and simplifier into
  376. play.
  377. An interesting property of `::' is that neither of its arguments
  378. will be touched by Calc's default simplifications. This is important
  379. because conditions often are expressions that cannot safely be
  380. evaluated early. For example, the `typeof' function never remains in
  381. symbolic form; entering `typeof(a)' will put the number 100 (the type
  382. code for variables like `a') on the stack. But putting the condition
  383. `... :: typeof(a) = 6' on the stack is safe since `::' prevents the
  384. `typeof' from being evaluated until the condition is actually used by
  385. the rewrite system.
  386. Since `::' protects its lefthand side, too, you can use a dummy
  387. condition to protect a rule that must itself not evaluate early. For
  388. example, it's not safe to put `a(f,x) := apply(f, [x])' on the stack
  389. because it will immediately evaluate to `a(f,x) := f(x)', where the
  390. meta-variable-ness of `f' on the righthand side has been lost. But
  391. `a(f,x) := apply(f, [x]) :: 1' is safe, and of course the condition `1'
  392. is always true (nonzero) so it has no effect on the functioning of the
  393. rule. (The rewrite compiler will ensure that it doesn't even impact
  394. the speed of matching the rule.)
  395. 
  396. File: calc, Node: Algebraic Properties of Rewrite Rules, Next: Other Features of Rewrite Rules, Prev: Conditional Rewrite Rules, Up: Rewrite Rules
  397. 12.11.4 Algebraic Properties of Rewrite Rules
  398. ---------------------------------------------
  399. The rewrite mechanism understands the algebraic properties of functions
  400. like `+' and `*'. In particular, pattern matching takes the
  401. associativity and commutativity of the following functions into account:
  402. + - * = != && || and or xor vint vunion vxor gcd lcm max min beta
  403. For example, the rewrite rule:
  404. a x + b x := (a + b) x
  405. will match formulas of the form,
  406. a x + b x, x a + x b, a x + x b, x a + b x
  407. Rewrites also understand the relationship between the `+' and `-'
  408. operators. The above rewrite rule will also match the formulas,
  409. a x - b x, x a - x b, a x - x b, x a - b x
  410. by matching `b' in the pattern to `-b' from the formula.
  411. Applied to a sum of many terms like `r + a x + s + b x + t', this
  412. pattern will check all pairs of terms for possible matches. The rewrite
  413. will take whichever suitable pair it discovers first.
  414. In general, a pattern using an associative operator like `a + b'
  415. will try 2 N different ways to match a sum of N terms like `x + y + z -
  416. w'. First, `a' is matched against each of `x', `y', `z', and `-w' in
  417. turn, with `b' being matched to the remainders `y + z - w', `x + z -
  418. w', etc. If none of these succeed, then `b' is matched against each of
  419. the four terms with `a' matching the remainder. Half-and-half matches,
  420. like `(x + y) + (z - w)', are not tried.
  421. Note that `*' is not commutative when applied to matrices, but
  422. rewrite rules pretend that it is. If you type `m v' to enable Matrix
  423. mode (*note Matrix Mode::), rewrite rules will match `*' literally,
  424. ignoring its usual commutativity property. (In the current
  425. implementation, the associativity also vanishes--it is as if the
  426. pattern had been enclosed in a `plain' marker; see below.) If you are
  427. applying rewrites to formulas with matrices, it's best to enable Matrix
  428. mode first to prevent algebraically incorrect rewrites from occurring.
  429. The pattern `-x' will actually match any expression. For example,
  430. the rule
  431. f(-x) := -f(x)
  432. will rewrite `f(a)' to `-f(-a)'. To avoid this, either use a `plain'
  433. marker as described below, or add a `negative(x)' condition. The
  434. `negative' function is true if its argument "looks" negative, for
  435. example, because it is a negative number or because it is a formula
  436. like `-x'. The new rule using this condition is:
  437. f(x) := -f(-x) :: negative(x) or, equivalently,
  438. f(-x) := -f(x) :: negative(-x)
  439. In the same way, the pattern `x - y' will match the sum `a + b' by
  440. matching `y' to `-b'.
  441. The pattern `a b' will also match the formula `x/y' if `y' is a
  442. number. Thus the rule `a x + b x := (a+b) x' will also convert `a x +
  443. x / 2' to `(a + 0.5) x' (or `(a + 1:2) x', depending on the current
  444. fraction mode).
  445. Calc will _not_ take other liberties with `*', `/', and `^'. For
  446. example, the pattern `f(a b)' will not match `f(x^2)', and `f(a + b)'
  447. will not match `f(2 x)', even though conceivably these patterns could
  448. match with `a = b = x'. Nor will `f(a b)' match `f(x / y)' if `y' is
  449. not a constant, even though it could be considered to match with `a = x'
  450. and `b = 1/y'. The reasons are partly for efficiency, and partly
  451. because while few mathematical operations are substantively different
  452. for addition and subtraction, often it is preferable to treat the cases
  453. of multiplication, division, and integer powers separately.
  454. Even more subtle is the rule set
  455. [ f(a) + f(b) := f(a + b), -f(a) := f(-a) ]
  456. attempting to match `f(x) - f(y)'. You might think that Calc will view
  457. this subtraction as `f(x) + (-f(y))' and then apply the above two rules
  458. in turn, but actually this will not work because Calc only does this
  459. when considering rules for `+' (like the first rule in this set). So
  460. it will see first that `f(x) + (-f(y))' does not match `f(a) + f(b)'
  461. for any assignments of the meta-variables, and then it will see that
  462. `f(x) - f(y)' does not match `-f(a)' for any assignment of `a'.
  463. Because Calc tries only one rule at a time, it will not be able to
  464. rewrite `f(x) - f(y)' with this rule set. An explicit `f(a) - f(b)'
  465. rule will have to be added.
  466. Another thing patterns will _not_ do is break up complex numbers.
  467. The pattern `myconj(a + b i) := a - b i' will work for formulas
  468. involving the special constant `i' (such as `3 - 4 i'), but it will not
  469. match actual complex numbers like `(3, -4)'. A version of the above
  470. rule for complex numbers would be
  471. myconj(a) := re(a) - im(a) (0,1) :: im(a) != 0
  472. (Because the `re' and `im' functions understand the properties of the
  473. special constant `i', this rule will also work for `3 - 4 i'. In fact,
  474. this particular rule would probably be better without the `im(a) != 0'
  475. condition, since if `im(a) = 0' the righthand side of the rule will
  476. still give the correct answer for the conjugate of a real number.)
  477. It is also possible to specify optional arguments in patterns. The
  478. rule
  479. opt(a) x + opt(b) (x^opt(c) + opt(d)) := f(a, b, c, d)
  480. will match the formula
  481. 5 (x^2 - 4) + 3 x
  482. in a fairly straightforward manner, but it will also match reduced
  483. formulas like
  484. x + x^2, 2(x + 1) - x, x + x
  485. producing, respectively,
  486. f(1, 1, 2, 0), f(-1, 2, 1, 1), f(1, 1, 1, 0)
  487. (The latter two formulas can be entered only if default
  488. simplifications have been turned off with `m O'.)
  489. The default value for a term of a sum is zero. The default value
  490. for a part of a product, for a power, or for the denominator of a
  491. quotient, is one. Also, `-x' matches the pattern `opt(a) b' with `a =
  492. -1'.
  493. In particular, the distributive-law rule can be refined to
  494. opt(a) x + opt(b) x := (a + b) x
  495. so that it will convert, e.g., `a x - x', to `(a - 1) x'.
  496. The pattern `opt(a) + opt(b) x' matches almost any formulas which
  497. are linear in `x'. You can also use the `lin' and `islin' functions
  498. with rewrite conditions to test for this; *note Logical Operations::.
  499. These functions are not as convenient to use in rewrite rules, but they
  500. recognize more kinds of formulas as linear: `x/z' is considered linear
  501. with `b = 1/z' by `lin', but it will not match the above pattern
  502. because that pattern calls for a multiplication, not a division.
  503. As another example, the obvious rule to replace `sin(x)^2 + cos(x)^2'
  504. by 1,
  505. sin(x)^2 + cos(x)^2 := 1
  506. misses many cases because the sine and cosine may both be multiplied by
  507. an equal factor. Here's a more successful rule:
  508. opt(a) sin(x)^2 + opt(a) cos(x)^2 := a
  509. Note that this rule will _not_ match `sin(x)^2 + 6 cos(x)^2' because
  510. one `a' would have "matched" 1 while the other matched 6.
  511. Calc automatically converts a rule like
  512. f(x-1, x) := g(x)
  513. into the form
  514. f(temp, x) := g(x) :: temp = x-1
  515. (where `temp' stands for a new, invented meta-variable that doesn't
  516. actually have a name). This modified rule will successfully match
  517. `f(6, 7)', binding `temp' and `x' to 6 and 7, respectively, then
  518. verifying that they differ by one even though `6' does not
  519. superficially look like `x-1'.
  520. However, Calc does not solve equations to interpret a rule. The
  521. following rule,
  522. f(x-1, x+1) := g(x)
  523. will not work. That is, it will match `f(a - 1 + b, a + 1 + b)' but
  524. not `f(6, 8)'. Calc always interprets at least one occurrence of a
  525. variable by literal matching. If the variable appears "isolated" then
  526. Calc is smart enough to use it for literal matching. But in this last
  527. example, Calc is forced to rewrite the rule to `f(x-1, temp) := g(x) ::
  528. temp = x+1' where the `x-1' term must correspond to an actual
  529. "something-minus-one" in the target formula.
  530. A successful way to write this would be `f(x, x+2) := g(x+1)'. You
  531. could make this resemble the original form more closely by using `let'
  532. notation, which is described in the next section:
  533. f(xm1, x+1) := g(x) :: let(x := xm1+1)
  534. Calc does this rewriting or "conditionalizing" for any sub-pattern
  535. which involves only the functions in the following list, operating only
  536. on constants and meta-variables which have already been matched
  537. elsewhere in the pattern. When matching a function call, Calc is
  538. careful to match arguments which are plain variables before arguments
  539. which are calls to any of the functions below, so that a pattern like
  540. `f(x-1, x)' can be conditionalized even though the isolated `x' comes
  541. after the `x-1'.
  542. + - * / \ % ^ abs sign round rounde roundu trunc floor ceil
  543. max min re im conj arg
  544. You can suppress all of the special treatments described in this
  545. section by surrounding a function call with a `plain' marker. This
  546. marker causes the function call which is its argument to be matched
  547. literally, without regard to commutativity, associativity, negation, or
  548. conditionalization. When you use `plain', the "deep structure" of the
  549. formula being matched can show through. For example,
  550. plain(a - a b) := f(a, b)
  551. will match only literal subtractions. However, the `plain' marker does
  552. not affect its arguments' arguments. In this case, commutativity and
  553. associativity is still considered while matching the `a b' sub-pattern,
  554. so the whole pattern will match `x - y x' as well as `x - x y'. We
  555. could go still further and use
  556. plain(a - plain(a b)) := f(a, b)
  557. which would do a completely strict match for the pattern.
  558. By contrast, the `quote' marker means that not only the function
  559. name but also the arguments must be literally the same. The above
  560. pattern will match `x - x y' but
  561. quote(a - a b) := f(a, b)
  562. will match only the single formula `a - a b'. Also,
  563. quote(a - quote(a b)) := f(a, b)
  564. will match only `a - quote(a b)'--probably not the desired effect!
  565. A certain amount of algebra is also done when substituting the
  566. meta-variables on the righthand side of a rule. For example, in the
  567. rule
  568. a + f(b) := f(a + b)
  569. matching `f(x) - y' would produce `f((-y) + x)' if taken literally, but
  570. the rewrite mechanism will simplify the righthand side to `f(x - y)'
  571. automatically. (Of course, the default simplifications would do this
  572. anyway, so this special simplification is only noticeable if you have
  573. turned the default simplifications off.) This rewriting is done only
  574. when a meta-variable expands to a "negative-looking" expression. If
  575. this simplification is not desirable, you can use a `plain' marker on
  576. the righthand side:
  577. a + f(b) := f(plain(a + b))
  578. In this example, we are still allowing the pattern-matcher to use all
  579. the algebra it can muster, but the righthand side will always simplify
  580. to a literal addition like `f((-y) + x)'.
  581. 
  582. File: calc, Node: Other Features of Rewrite Rules, Next: Composing Patterns in Rewrite Rules, Prev: Algebraic Properties of Rewrite Rules, Up: Rewrite Rules
  583. 12.11.5 Other Features of Rewrite Rules
  584. ---------------------------------------
  585. Certain "function names" serve as markers in rewrite rules. Here is a
  586. complete list of these markers. First are listed the markers that work
  587. inside a pattern; then come the markers that work in the righthand side
  588. of a rule.
  589. One kind of marker, `import(x)', takes the place of a whole rule.
  590. Here `x' is the name of a variable containing another rule set; those
  591. rules are "spliced into" the rule set that imports them. For example,
  592. if `[f(a+b) := f(a) + f(b), f(a b) := a f(b) :: real(a)]' is stored in
  593. variable `linearF', then the rule set `[f(0) := 0, import(linearF)]'
  594. will apply all three rules. It is possible to modify the imported rules
  595. slightly: `import(x, v1, x1, v2, x2, ...)' imports the rule set `x'
  596. with all occurrences of `v1', as either a variable name or a function
  597. name, replaced with `x1' and so on. (If `v1' is used as a function
  598. name, then `x1' must be either a function name itself or a `< >'
  599. nameless function; *note Specifying Operators::.) For example, `[g(0)
  600. := 0, import(linearF, f, g)]' applies the linearity rules to the
  601. function `g' instead of `f'. Imports can be nested, but the
  602. import-with-renaming feature may fail to rename sub-imports properly.
  603. The special functions allowed in patterns are:
  604. `quote(x)'
  605. This pattern matches exactly `x'; variable names in `x' are not
  606. interpreted as meta-variables. The only flexibility is that
  607. numbers are compared for numeric equality, so that the pattern
  608. `f(quote(12))' will match both `f(12)' and `f(12.0)'. (Numbers
  609. are always treated this way by the rewrite mechanism: The rule
  610. `f(x,x) := g(x)' will match `f(12, 12.0)'. The rewrite may
  611. produce either `g(12)' or `g(12.0)' as a result in this case.)
  612. `plain(x)'
  613. Here `x' must be a function call `f(x1,x2,...)'. This pattern
  614. matches a call to function `f' with the specified argument
  615. patterns. No special knowledge of the properties of the function
  616. `f' is used in this case; `+' is not commutative or associative.
  617. Unlike `quote', the arguments `x1,x2,...' are treated as patterns.
  618. If you wish them to be treated "plainly" as well, you must enclose
  619. them with more `plain' markers: `plain(plain(-a) + plain(b c))'.
  620. `opt(x,def)'
  621. Here `x' must be a variable name. This must appear as an argument
  622. to a function or an element of a vector; it specifies that the
  623. argument or element is optional. As an argument to `+', `-', `*',
  624. `&&', or `||', or as the second argument to `/' or `^', the value
  625. DEF may be omitted. The pattern `x + opt(y)' matches a sum by
  626. binding one summand to `x' and the other to `y', and it matches
  627. anything else by binding the whole expression to `x' and zero to
  628. `y'. The other operators above work similarly.
  629. For general miscellaneous functions, the default value `def' must
  630. be specified. Optional arguments are dropped starting with the
  631. rightmost one during matching. For example, the pattern
  632. `f(opt(a,0), b, opt(c,b))' will match `f(b)', `f(a,b)', or
  633. `f(a,b,c)'. Default values of zero and `b' are supplied in this
  634. example for the omitted arguments. Note that the literal variable
  635. `b' will be the default in the latter case, _not_ the value that
  636. matched the meta-variable `b'. In other words, the default DEF is
  637. effectively quoted.
  638. `condition(x,c)'
  639. This matches the pattern `x', with the attached condition `c'. It
  640. is the same as `x :: c'.
  641. `pand(x,y)'
  642. This matches anything that matches both pattern `x' and pattern
  643. `y'. It is the same as `x &&& y'. *note Composing Patterns in
  644. Rewrite Rules::.
  645. `por(x,y)'
  646. This matches anything that matches either pattern `x' or pattern
  647. `y'. It is the same as `x ||| y'.
  648. `pnot(x)'
  649. This matches anything that does not match pattern `x'. It is the
  650. same as `!!! x'.
  651. `cons(h,t)'
  652. This matches any vector of one or more elements. The first
  653. element is matched to `h'; a vector of the remaining elements is
  654. matched to `t'. Note that vectors of fixed length can also be
  655. matched as actual vectors: The rule `cons(a,cons(b,[])) :=
  656. cons(a+b,[])' is equivalent to the rule `[a,b] := [a+b]'.
  657. `rcons(t,h)'
  658. This is like `cons', except that the _last_ element is matched to
  659. `h', with the remaining elements matched to `t'.
  660. `apply(f,args)'
  661. This matches any function call. The name of the function, in the
  662. form of a variable, is matched to `f'. The arguments of the
  663. function, as a vector of zero or more objects, are matched to
  664. `args'. Constants, variables, and vectors do _not_ match an
  665. `apply' pattern. For example, `apply(f,x)' matches any function
  666. call, `apply(quote(f),x)' matches any call to the function `f',
  667. `apply(f,[a,b])' matches any function call with exactly two
  668. arguments, and `apply(quote(f), cons(a,cons(b,x)))' matches any
  669. call to the function `f' with two or more arguments. Another way
  670. to implement the latter, if the rest of the rule does not need to
  671. refer to the first two arguments of `f' by name, would be
  672. `apply(quote(f), x :: vlen(x) >= 2)'. Here's a more interesting
  673. sample use of `apply':
  674. apply(f,[x+n]) := n + apply(f,[x])
  675. :: in(f, [floor,ceil,round,trunc]) :: integer(n)
  676. Note, however, that this will be slower to match than a rule set
  677. with four separate rules. The reason is that Calc sorts the rules
  678. of a rule set according to top-level function name; if the
  679. top-level function is `apply', Calc must try the rule for every
  680. single formula and sub-formula. If the top-level function in the
  681. pattern is, say, `floor', then Calc invokes the rule only for
  682. sub-formulas which are calls to `floor'.
  683. Formulas normally written with operators like `+' are still
  684. considered function calls: `apply(f,x)' matches `a+b' with `f =
  685. add', `x = [a,b]'.
  686. You must use `apply' for meta-variables with function names on
  687. both sides of a rewrite rule: `apply(f, [x]) := f(x+1)' is _not_
  688. correct, because it rewrites `spam(6)' into `f(7)'. The righthand
  689. side should be `apply(f, [x+1])'. Also note that you will have to
  690. use No-Simplify mode (`m O') when entering this rule so that the
  691. `apply' isn't evaluated immediately to get the new rule `f(x) :=
  692. f(x+1)'. Or, use `s e' to enter the rule without going through
  693. the stack, or enter the rule as `apply(f, [x]) := apply(f, [x+1])
  694. :: 1'. *Note Conditional Rewrite Rules::.
  695. `select(x)'
  696. This is used for applying rules to formulas with selections; *note
  697. Selections with Rewrite Rules::.
  698. Special functions for the righthand sides of rules are:
  699. `quote(x)'
  700. The notation `quote(x)' is changed to `x' when the righthand side
  701. is used. As far as the rewrite rule is concerned, `quote' is
  702. invisible. However, `quote' has the special property in Calc that
  703. its argument is not evaluated. Thus, while it will not work to
  704. put the rule `t(a) := typeof(a)' on the stack because `typeof(a)'
  705. is evaluated immediately to produce `t(a) := 100', you can use
  706. `quote' to protect the righthand side: `t(a) := quote(typeof(a))'.
  707. (*Note Conditional Rewrite Rules::, for another trick for
  708. protecting rules from evaluation.)
  709. `plain(x)'
  710. Special properties of and simplifications for the function call
  711. `x' are not used. One interesting case where `plain' is useful is
  712. the rule, `q(x) := quote(x)', trying to expand a shorthand
  713. notation for the `quote' function. This rule will not work as
  714. shown; instead of replacing `q(foo)' with `quote(foo)', it will
  715. replace it with `foo'! The correct rule would be `q(x) :=
  716. plain(quote(x))'.
  717. `cons(h,t)'
  718. Where `t' is a vector, this is converted into an expanded vector
  719. during rewrite processing. Note that `cons' is a regular Calc
  720. function which normally does this anyway; the only way `cons' is
  721. treated specially by rewrites is that `cons' on the righthand side
  722. of a rule will be evaluated even if default simplifications have
  723. been turned off.
  724. `rcons(t,h)'
  725. Analogous to `cons' except putting `h' at the _end_ of the vector
  726. `t'.
  727. `apply(f,args)'
  728. Where `f' is a variable and ARGS is a vector, this is converted to
  729. a function call. Once again, note that `apply' is also a regular
  730. Calc function.
  731. `eval(x)'
  732. The formula `x' is handled in the usual way, then the default
  733. simplifications are applied to it even if they have been turned
  734. off normally. This allows you to treat any function similarly to
  735. the way `cons' and `apply' are always treated. However, there is
  736. a slight difference: `cons(2+3, [])' with default simplifications
  737. off will be converted to `[2+3]', whereas `eval(cons(2+3, []))'
  738. will be converted to `[5]'.
  739. `evalsimp(x)'
  740. The formula `x' has meta-variables substituted in the usual way,
  741. then algebraically simplified as if by the `a s' command.
  742. `evalextsimp(x)'
  743. The formula `x' has meta-variables substituted in the normal way,
  744. then "extendedly" simplified as if by the `a e' command.
  745. `select(x)'
  746. *Note Selections with Rewrite Rules::.
  747. There are also some special functions you can use in conditions.
  748. `let(v := x)'
  749. The expression `x' is evaluated with meta-variables substituted.
  750. The `a s' command's simplifications are _not_ applied by default,
  751. but `x' can include calls to `evalsimp' or `evalextsimp' as
  752. described above to invoke higher levels of simplification. The
  753. result of `x' is then bound to the meta-variable `v'. As usual,
  754. if this meta-variable has already been matched to something else
  755. the two values must be equal; if the meta-variable is new then it
  756. is bound to the result of the expression. This variable can then
  757. appear in later conditions, and on the righthand side of the rule.
  758. In fact, `v' may be any pattern in which case the result of
  759. evaluating `x' is matched to that pattern, binding any
  760. meta-variables that appear in that pattern. Note that `let' can
  761. only appear by itself as a condition, or as one term of an `&&'
  762. which is a whole condition: It cannot be inside an `||' term or
  763. otherwise buried.
  764. The alternate, equivalent form `let(v, x)' is also recognized.
  765. Note that the use of `:=' by `let', while still being
  766. assignment-like in character, is unrelated to the use of `:=' in
  767. the main part of a rewrite rule.
  768. As an example, `f(a) := g(ia) :: let(ia := 1/a) :: constant(ia)'
  769. replaces `f(a)' with `g' of the inverse of `a', if that inverse
  770. exists and is constant. For example, if `a' is a singular matrix
  771. the operation `1/a' is left unsimplified and `constant(ia)' fails,
  772. but if `a' is an invertible matrix then the rule succeeds.
  773. Without `let' there would be no way to express this rule that
  774. didn't have to invert the matrix twice. Note that, because the
  775. meta-variable `ia' is otherwise unbound in this rule, the `let'
  776. condition itself always "succeeds" because no matter what `1/a'
  777. evaluates to, it can successfully be bound to `ia'.
  778. Here's another example, for integrating cosines of linear terms:
  779. `myint(cos(y),x) := sin(y)/b :: let([a,b,x] := lin(y,x))'. The
  780. `lin' function returns a 3-vector if its argument is linear, or
  781. leaves itself unevaluated if not. But an unevaluated `lin' call
  782. will not match the 3-vector on the lefthand side of the `let', so
  783. this `let' both verifies that `y' is linear, and binds the
  784. coefficients `a' and `b' for use elsewhere in the rule. (It would
  785. have been possible to use `sin(a x + b)/b' for the righthand side
  786. instead, but using `sin(y)/b' avoids gratuitous rearrangement of
  787. the argument of the sine.)
  788. Similarly, here is a rule that implements an inverse-`erf'
  789. function. It uses `root' to search for a solution. If `root'
  790. succeeds, it will return a vector of two numbers where the first
  791. number is the desired solution. If no solution is found, `root'
  792. remains in symbolic form. So we use `let' to check that the
  793. result was indeed a vector.
  794. ierf(x) := y :: let([y,z] := root(erf(a) = x, a, .5))
  795. `matches(v,p)'
  796. The meta-variable V, which must already have been matched to
  797. something elsewhere in the rule, is compared against pattern P.
  798. Since `matches' is a standard Calc function, it can appear
  799. anywhere in a condition. But if it appears alone or as a term of
  800. a top-level `&&', then you get the special extra feature that
  801. meta-variables which are bound to things inside P can be used
  802. elsewhere in the surrounding rewrite rule.
  803. The only real difference between `let(p := v)' and `matches(v, p)'
  804. is that the former evaluates `v' using the default
  805. simplifications, while the latter does not.
  806. `remember'
  807. This is actually a variable, not a function. If `remember'
  808. appears as a condition in a rule, then when that rule succeeds the
  809. original expression and rewritten expression are added to the
  810. front of the rule set that contained the rule. If the rule set
  811. was not stored in a variable, `remember' is ignored. The lefthand
  812. side is enclosed in `quote' in the added rule if it contains any
  813. variables.
  814. For example, the rule `f(n) := n f(n-1) :: remember' applied to
  815. `f(7)' will add the rule `f(7) := 7 f(6)' to the front of the rule
  816. set. The rule set `EvalRules' works slightly differently: There,
  817. the evaluation of `f(6)' will complete before the result is added
  818. to the rule set, in this case as `f(7) := 5040'. Thus `remember'
  819. is most useful inside `EvalRules'.
  820. It is up to you to ensure that the optimization performed by
  821. `remember' is safe. For example, the rule `foo(n) := n ::
  822. evalv(eatfoo) > 0 :: remember' is a bad idea (`evalv' is the
  823. function equivalent of the `=' command); if the variable `eatfoo'
  824. ever contains 1, rules like `foo(7) := 7' will be added to the
  825. rule set and will continue to operate even if `eatfoo' is later
  826. changed to 0.
  827. `remember(c)'
  828. Remember the match as described above, but only if condition `c'
  829. is true. For example, `remember(n % 4 = 0)' in the above factorial
  830. rule remembers only every fourth result. Note that `remember(1)'
  831. is equivalent to `remember', and `remember(0)' has no effect.
  832. 
  833. File: calc, Node: Composing Patterns in Rewrite Rules, Next: Nested Formulas with Rewrite Rules, Prev: Other Features of Rewrite Rules, Up: Rewrite Rules
  834. 12.11.6 Composing Patterns in Rewrite Rules
  835. -------------------------------------------
  836. There are three operators, `&&&', `|||', and `!!!', that combine
  837. rewrite patterns to make larger patterns. The combinations are "and,"
  838. "or," and "not," respectively, and these operators are the pattern
  839. equivalents of `&&', `||' and `!' (which operate on zero-or-nonzero
  840. logical values).
  841. Note that `&&&', `|||', and `!!!' are left in symbolic form by all
  842. regular Calc features; they have special meaning only in the context of
  843. rewrite rule patterns.
  844. The pattern `P1 &&& P2' matches anything that matches both P1 and
  845. P2. One especially useful case is when one of P1 or P2 is a
  846. meta-variable. For example, here is a rule that operates on error
  847. forms:
  848. f(x &&& a +/- b, x) := g(x)
  849. This does the same thing, but is arguably simpler than, the rule
  850. f(a +/- b, a +/- b) := g(a +/- b)
  851. Here's another interesting example:
  852. ends(cons(a, x) &&& rcons(y, b)) := [a, b]
  853. which effectively clips out the middle of a vector leaving just the
  854. first and last elements. This rule will change a one-element vector
  855. `[a]' to `[a, a]'. The similar rule
  856. ends(cons(a, rcons(y, b))) := [a, b]
  857. would do the same thing except that it would fail to match a
  858. one-element vector.
  859. The pattern `P1 ||| P2' matches anything that matches either P1 or
  860. P2. Calc first tries matching against P1; if that fails, it goes on to
  861. try P2.
  862. A simple example of `|||' is
  863. curve(inf ||| -inf) := 0
  864. which converts both `curve(inf)' and `curve(-inf)' to zero.
  865. Here is a larger example:
  866. log(a, b) ||| (ln(a) :: let(b := e)) := mylog(a, b)
  867. This matches both generalized and natural logarithms in a single
  868. rule. Note that the `::' term must be enclosed in parentheses because
  869. that operator has lower precedence than `|||' or `:='.
  870. (In practice this rule would probably include a third alternative,
  871. omitted here for brevity, to take care of `log10'.)
  872. While Calc generally treats interior conditions exactly the same as
  873. conditions on the outside of a rule, it does guarantee that if all the
  874. variables in the condition are special names like `e', or already bound
  875. in the pattern to which the condition is attached (say, if `a' had
  876. appeared in this condition), then Calc will process this condition
  877. right after matching the pattern to the left of the `::'. Thus, we
  878. know that `b' will be bound to `e' only if the `ln' branch of the `|||'
  879. was taken.
  880. Note that this rule was careful to bind the same set of
  881. meta-variables on both sides of the `|||'. Calc does not check this,
  882. but if you bind a certain meta-variable only in one branch and then use
  883. that meta-variable elsewhere in the rule, results are unpredictable:
  884. f(a,b) ||| g(b) := h(a,b)
  885. Here if the pattern matches `g(17)', Calc makes no promises about
  886. the value that will be substituted for `a' on the righthand side.
  887. The pattern `!!! PAT' matches anything that does not match PAT. Any
  888. meta-variables that are bound while matching PAT remain unbound outside
  889. of PAT.
  890. For example,
  891. f(x &&& !!! a +/- b, !!![]) := g(x)
  892. converts `f' whose first argument is anything _except_ an error form,
  893. and whose second argument is not the empty vector, into a similar call
  894. to `g' (but without the second argument).
  895. If we know that the second argument will be a vector (empty or not),
  896. then an equivalent rule would be:
  897. f(x, y) := g(x) :: typeof(x) != 7 :: vlen(y) > 0
  898. where of course 7 is the `typeof' code for error forms. Another final
  899. condition, that works for any kind of `y', would be `!istrue(y == [])'.
  900. (The `istrue' function returns an explicit 0 if its argument was left
  901. in symbolic form; plain `!(y == [])' or `y != []' would not work to
  902. replace `!!![]' since these would be left unsimplified, and thus cause
  903. the rule to fail, if `y' was something like a variable name.)
  904. It is possible for a `!!!' to refer to meta-variables bound
  905. elsewhere in the pattern. For example,
  906. f(a, !!!a) := g(a)
  907. matches any call to `f' with different arguments, changing this to `g'
  908. with only the first argument.
  909. If a function call is to be matched and one of the argument patterns
  910. contains a `!!!' somewhere inside it, that argument will be matched
  911. last. Thus
  912. f(!!!a, a) := g(a)
  913. will be careful to bind `a' to the second argument of `f' before
  914. testing the first argument. If Calc had tried to match the first
  915. argument of `f' first, the results would have been disastrous: since
  916. `a' was unbound so far, the pattern `a' would have matched anything at
  917. all, and the pattern `!!!a' therefore would _not_ have matched anything
  918. at all!
  919. 
  920. File: calc, Node: Nested Formulas with Rewrite Rules, Next: Multi-Phase Rewrite Rules, Prev: Composing Patterns in Rewrite Rules, Up: Rewrite Rules
  921. 12.11.7 Nested Formulas with Rewrite Rules
  922. ------------------------------------------
  923. When `a r' (`calc-rewrite') is used, it takes an expression from the
  924. top of the stack and attempts to match any of the specified rules to
  925. any part of the expression, starting with the whole expression and
  926. then, if that fails, trying deeper and deeper sub-expressions. For
  927. each part of the expression, the rules are tried in the order they
  928. appear in the rules vector. The first rule to match the first
  929. sub-expression wins; it replaces the matched sub-expression according
  930. to the NEW part of the rule.
  931. Often, the rule set will match and change the formula several times.
  932. The top-level formula is first matched and substituted repeatedly until
  933. it no longer matches the pattern; then, sub-formulas are tried, and so
  934. on. Once every part of the formula has gotten its chance, the rewrite
  935. mechanism starts over again with the top-level formula (in case a
  936. substitution of one of its arguments has caused it again to match).
  937. This continues until no further matches can be made anywhere in the
  938. formula.
  939. It is possible for a rule set to get into an infinite loop. The
  940. most obvious case, replacing a formula with itself, is not a problem
  941. because a rule is not considered to "succeed" unless the righthand side
  942. actually comes out to something different than the original formula or
  943. sub-formula that was matched. But if you accidentally had both `ln(a
  944. b) := ln(a) + ln(b)' and the reverse `ln(a) + ln(b) := ln(a b)' in your
  945. rule set, Calc would run forever switching a formula back and forth
  946. between the two forms.
  947. To avoid disaster, Calc normally stops after 100 changes have been
  948. made to the formula. This will be enough for most multiple rewrites,
  949. but it will keep an endless loop of rewrites from locking up the
  950. computer forever. (On most systems, you can also type `C-g' to halt
  951. any Emacs command prematurely.)
  952. To change this limit, give a positive numeric prefix argument. In
  953. particular, `M-1 a r' applies only one rewrite at a time, useful when
  954. you are first testing your rule (or just if repeated rewriting is not
  955. what is called for by your application).
  956. You can also put a "function call" `iterations(N)' in place of a
  957. rule anywhere in your rules vector (but usually at the top). Then, N
  958. will be used instead of 100 as the default number of iterations for
  959. this rule set. You can use `iterations(inf)' if you want no iteration
  960. limit by default. A prefix argument will override the `iterations'
  961. limit in the rule set.
  962. [ iterations(1),
  963. f(x) := f(x+1) ]
  964. More precisely, the limit controls the number of "iterations," where
  965. each iteration is a successful matching of a rule pattern whose
  966. righthand side, after substituting meta-variables and applying the
  967. default simplifications, is different from the original sub-formula
  968. that was matched.
  969. A prefix argument of zero sets the limit to infinity. Use with
  970. caution!
  971. Given a negative numeric prefix argument, `a r' will match and
  972. substitute the top-level expression up to that many times, but will not
  973. attempt to match the rules to any sub-expressions.
  974. In a formula, `rewrite(EXPR, RULES, N)' does a rewriting operation.
  975. Here EXPR is the expression being rewritten, RULES is the rule, vector
  976. of rules, or variable containing the rules, and N is the optional
  977. iteration limit, which may be a positive integer, a negative integer,
  978. or `inf' or `-inf'. If N is omitted the `iterations' value from the
  979. rule set is used; if both are omitted, 100 is used.
  980. 
  981. File: calc, Node: Multi-Phase Rewrite Rules, Next: Selections with Rewrite Rules, Prev: Nested Formulas with Rewrite Rules, Up: Rewrite Rules
  982. 12.11.8 Multi-Phase Rewrite Rules
  983. ---------------------------------
  984. It is possible to separate a rewrite rule set into several "phases".
  985. During each phase, certain rules will be enabled while certain others
  986. will be disabled. A "phase schedule" controls the order in which
  987. phases occur during the rewriting process.
  988. If a call to the marker function `phase' appears in the rules vector
  989. in place of a rule, all rules following that point will be members of
  990. the phase(s) identified in the arguments to `phase'. Phases are given
  991. integer numbers. The markers `phase()' and `phase(all)' both mean the
  992. following rules belong to all phases; this is the default at the start
  993. of the rule set.
  994. If you do not explicitly schedule the phases, Calc sorts all phase
  995. numbers that appear in the rule set and executes the phases in
  996. ascending order. For example, the rule set
  997. [ f0(x) := g0(x),
  998. phase(1),
  999. f1(x) := g1(x),
  1000. phase(2),
  1001. f2(x) := g2(x),
  1002. phase(3),
  1003. f3(x) := g3(x),
  1004. phase(1,2),
  1005. f4(x) := g4(x) ]
  1006. has three phases, 1 through 3. Phase 1 consists of the `f0', `f1', and
  1007. `f4' rules (in that order). Phase 2 consists of `f0', `f2', and `f4'.
  1008. Phase 3 consists of `f0' and `f3'.
  1009. When Calc rewrites a formula using this rule set, it first rewrites
  1010. the formula using only the phase 1 rules until no further changes are
  1011. possible. Then it switches to the phase 2 rule set and continues until
  1012. no further changes occur, then finally rewrites with phase 3. When no
  1013. more phase 3 rules apply, rewriting finishes. (This is assuming `a r'
  1014. with a large enough prefix argument to allow the rewriting to run to
  1015. completion; the sequence just described stops early if the number of
  1016. iterations specified in the prefix argument, 100 by default, is
  1017. reached.)
  1018. During each phase, Calc descends through the nested levels of the
  1019. formula as described previously. (*Note Nested Formulas with Rewrite
  1020. Rules::.) Rewriting starts at the top of the formula, then works its
  1021. way down to the parts, then goes back to the top and works down again.
  1022. The phase 2 rules do not begin until no phase 1 rules apply anywhere in
  1023. the formula.
  1024. A `schedule' marker appearing in the rule set (anywhere, but
  1025. conventionally at the top) changes the default schedule of phases. In
  1026. the simplest case, `schedule' has a sequence of phase numbers for
  1027. arguments; each phase number is invoked in turn until the arguments to
  1028. `schedule' are exhausted. Thus adding `schedule(3,2,1)' at the top of
  1029. the above rule set would reverse the order of the phases;
  1030. `schedule(1,2,3)' would have no effect since this is the default
  1031. schedule; and `schedule(1,2,1,3)' would give phase 1 a second chance
  1032. after phase 2 has completed, before moving on to phase 3.
  1033. Any argument to `schedule' can instead be a vector of phase numbers
  1034. (or even of sub-vectors). Then the sub-sequence of phases described by
  1035. the vector are tried repeatedly until no change occurs in any phase in
  1036. the sequence. For example, `schedule([1, 2], 3)' tries phase 1, then
  1037. phase 2, then, if either phase made any changes to the formula, repeats
  1038. these two phases until they can make no further progress. Finally, it
  1039. goes on to phase 3 for finishing touches.
  1040. Also, items in `schedule' can be variable names as well as numbers.
  1041. A variable name is interpreted as the name of a function to call on the
  1042. whole formula. For example, `schedule(1, simplify)' says to apply the
  1043. phase-1 rules (presumably, all of them), then to call `simplify' which
  1044. is the function name equivalent of `a s'. Likewise, `schedule([1,
  1045. simplify])' says to alternate between phase 1 and `a s' until no
  1046. further changes occur.
  1047. Phases can be used purely to improve efficiency; if it is known that
  1048. a certain group of rules will apply only at the beginning of rewriting,
  1049. and a certain other group will apply only at the end, then rewriting
  1050. will be faster if these groups are identified as separate phases. Once
  1051. the phase 1 rules are done, Calc can put them aside and no longer spend
  1052. any time on them while it works on phase 2.
  1053. There are also some problems that can only be solved with several
  1054. rewrite phases. For a real-world example of a multi-phase rule set,
  1055. examine the set `FitRules', which is used by the curve-fitting command
  1056. to convert a model expression to linear form. *Note Curve Fitting
  1057. Details::. This set is divided into four phases. The first phase
  1058. rewrites certain kinds of expressions to be more easily linearizable,
  1059. but less computationally efficient. After the linear components have
  1060. been picked out, the final phase includes the opposite rewrites to put
  1061. each component back into an efficient form. If both sets of rules were
  1062. included in one big phase, Calc could get into an infinite loop going
  1063. back and forth between the two forms.
  1064. Elsewhere in `FitRules', the components are first isolated, then
  1065. recombined where possible to reduce the complexity of the linear fit,
  1066. then finally packaged one component at a time into vectors. If the
  1067. packaging rules were allowed to begin before the recombining rules were
  1068. finished, some components might be put away into vectors before they
  1069. had a chance to recombine. By putting these rules in two separate
  1070. phases, this problem is neatly avoided.
  1071. 
  1072. File: calc, Node: Selections with Rewrite Rules, Next: Matching Commands, Prev: Multi-Phase Rewrite Rules, Up: Rewrite Rules
  1073. 12.11.9 Selections with Rewrite Rules
  1074. -------------------------------------
  1075. If a sub-formula of the current formula is selected (as by `j s'; *note
  1076. Selecting Subformulas::), the `a r' (`calc-rewrite') command applies
  1077. only to that sub-formula. Together with a negative prefix argument,
  1078. you can use this fact to apply a rewrite to one specific part of a
  1079. formula without affecting any other parts.
  1080. The `j r' (`calc-rewrite-selection') command allows more
  1081. sophisticated operations on selections. This command prompts for the
  1082. rules in the same way as `a r', but it then applies those rules to the
  1083. whole formula in question even though a sub-formula of it has been
  1084. selected. However, the selected sub-formula will first have been
  1085. surrounded by a `select( )' function call. (Calc's evaluator does not
  1086. understand the function name `select'; this is only a tag used by the
  1087. `j r' command.)
  1088. For example, suppose the formula on the stack is `2 (a + b)^2' and
  1089. the sub-formula `a + b' is selected. This formula will be rewritten to
  1090. `2 select(a + b)^2' and then the rewrite rules will be applied in the
  1091. usual way. The rewrite rules can include references to `select' to
  1092. tell where in the pattern the selected sub-formula should appear.
  1093. If there is still exactly one `select( )' function call in the
  1094. formula after rewriting is done, it indicates which part of the formula
  1095. should be selected afterwards. Otherwise, the formula will be
  1096. unselected.
  1097. You can make `j r' act much like `a r' by enclosing both parts of
  1098. the rewrite rule with `select()'. However, `j r' allows you to use the
  1099. current selection in more flexible ways. Suppose you wished to make a
  1100. rule which removed the exponent from the selected term; the rule
  1101. `select(a)^x := select(a)' would work. In the above example, it would
  1102. rewrite `2 select(a + b)^2' to `2 select(a + b)'. This would then be
  1103. returned to the stack as `2 (a + b)' with the `a + b' selected.
  1104. The `j r' command uses one iteration by default, unlike `a r' which
  1105. defaults to 100 iterations. A numeric prefix argument affects `j r' in
  1106. the same way as `a r'. *Note Nested Formulas with Rewrite Rules::.
  1107. As with other selection commands, `j r' operates on the stack entry
  1108. that contains the cursor. (If the cursor is on the top-of-stack `.'
  1109. marker, it works as if the cursor were on the formula at stack level 1.)
  1110. If you don't specify a set of rules, the rules are taken from the
  1111. top of the stack, just as with `a r'. In this case, the cursor must
  1112. indicate stack entry 2 or above as the formula to be rewritten
  1113. (otherwise the same formula would be used as both the target and the
  1114. rewrite rules).
  1115. If the indicated formula has no selection, the cursor position within
  1116. the formula temporarily selects a sub-formula for the purposes of this
  1117. command. If the cursor is not on any sub-formula (e.g., it is in the
  1118. line-number area to the left of the formula), the `select( )' markers
  1119. are ignored by the rewrite mechanism and the rules are allowed to apply
  1120. anywhere in the formula.
  1121. As a special feature, the normal `a r' command also ignores `select(
  1122. )' calls in rewrite rules. For example, if you used the above rule
  1123. `select(a)^x := select(a)' with `a r', it would apply the rule as if it
  1124. were `a^x := a'. Thus, you can write general purpose rules with
  1125. `select( )' hints inside them so that they will "do the right thing" in
  1126. both `a r' and `j r', both with and without selections.
  1127. 
  1128. File: calc, Node: Matching Commands, Next: Automatic Rewrites, Prev: Selections with Rewrite Rules, Up: Rewrite Rules
  1129. 12.11.10 Matching Commands
  1130. --------------------------
  1131. The `a m' (`calc-match') [`match'] function takes a vector of formulas
  1132. and a rewrite-rule-style pattern, and produces a vector of all formulas
  1133. which match the pattern. The command prompts you to enter the pattern;
  1134. as for `a r', you can enter a single pattern (i.e., a formula with
  1135. meta-variables), or a vector of patterns, or a variable which contains
  1136. patterns, or you can give a blank response in which case the patterns
  1137. are taken from the top of the stack. The pattern set will be compiled
  1138. once and saved if it is stored in a variable. If there are several
  1139. patterns in the set, vector elements are kept if they match any of the
  1140. patterns.
  1141. For example, `match(a+b, [x, x+y, x-y, 7, x+y+z])' will return
  1142. `[x+y, x-y, x+y+z]'.
  1143. The `import' mechanism is not available for pattern sets.
  1144. The `a m' command can also be used to extract all vector elements
  1145. which satisfy any condition: The pattern `x :: x>0' will select all
  1146. the positive vector elements.
  1147. With the Inverse flag [`matchnot'], this command extracts all vector
  1148. elements which do _not_ match the given pattern.
  1149. There is also a function `matches(X, P)' which evaluates to 1 if
  1150. expression X matches pattern P, or to 0 otherwise. This is sometimes
  1151. useful for including into the conditional clauses of other rewrite
  1152. rules.
  1153. The function `vmatches' is just like `matches', except that if the
  1154. match succeeds it returns a vector of assignments to the meta-variables
  1155. instead of the number 1. For example, `vmatches(f(1,2), f(a,b))'
  1156. returns `[a := 1, b := 2]'. If the match fails, the function returns
  1157. the number 0.
  1158. 
  1159. File: calc, Node: Automatic Rewrites, Next: Debugging Rewrites, Prev: Matching Commands, Up: Rewrite Rules
  1160. 12.11.11 Automatic Rewrites
  1161. ---------------------------
  1162. It is possible to get Calc to apply a set of rewrite rules on all
  1163. results, effectively adding to the built-in set of default
  1164. simplifications. To do this, simply store your rule set in the
  1165. variable `EvalRules'. There is a convenient `s E' command for editing
  1166. `EvalRules'; *note Operations on Variables::.
  1167. For example, suppose you want `sin(a + b)' to be expanded out to
  1168. `sin(b) cos(a) + cos(b) sin(a)' wherever it appears, and similarly for
  1169. `cos(a + b)'. The corresponding rewrite rule set would be,
  1170. [ sin(a + b) := cos(a) sin(b) + sin(a) cos(b),
  1171. cos(a + b) := cos(a) cos(b) - sin(a) sin(b) ]
  1172. To apply these manually, you could put them in a variable called
  1173. `trigexp' and then use `a r trigexp' every time you wanted to expand
  1174. trig functions. But if instead you store them in the variable
  1175. `EvalRules', they will automatically be applied to all sines and
  1176. cosines of sums. Then, with `2 x' and `45' on the stack, typing `+ S'
  1177. will (assuming Degrees mode) result in `0.7071 sin(2 x) + 0.7071 cos(2
  1178. x)' automatically.
  1179. As each level of a formula is evaluated, the rules from `EvalRules'
  1180. are applied before the default simplifications. Rewriting continues
  1181. until no further `EvalRules' apply. Note that this is different from
  1182. the usual order of application of rewrite rules: `EvalRules' works
  1183. from the bottom up, simplifying the arguments to a function before the
  1184. function itself, while `a r' applies rules from the top down.
  1185. Because the `EvalRules' are tried first, you can use them to
  1186. override the normal behavior of any built-in Calc function.
  1187. It is important not to write a rule that will get into an infinite
  1188. loop. For example, the rule set `[f(0) := 1, f(n) := n f(n-1)]'
  1189. appears to be a good definition of a factorial function, but it is
  1190. unsafe. Imagine what happens if `f(2.5)' is simplified. Calc will
  1191. continue to subtract 1 from this argument forever without reaching
  1192. zero. A safer second rule would be `f(n) := n f(n-1) :: n>0'. Another
  1193. dangerous rule is `g(x, y) := g(y, x)'. Rewriting `g(2, 4)', this
  1194. would bounce back and forth between that and `g(4, 2)' forever. If an
  1195. infinite loop in `EvalRules' occurs, Emacs will eventually stop with a
  1196. "Computation got stuck or ran too long" message.
  1197. Another subtle difference between `EvalRules' and regular rewrites
  1198. concerns rules that rewrite a formula into an identical formula. For
  1199. example, `f(n) := f(floor(n))' "fails to match" when `n' is already an
  1200. integer. But in `EvalRules' this case is detected only if the
  1201. righthand side literally becomes the original formula before any
  1202. further simplification. This means that `f(n) := f(floor(n))' will get
  1203. into an infinite loop if it occurs in `EvalRules'. Calc will replace
  1204. `f(6)' with `f(floor(6))', which is different from `f(6)', so it will
  1205. consider the rule to have matched and will continue simplifying that
  1206. formula; first the argument is simplified to get `f(6)', then the rule
  1207. matches again to get `f(floor(6))' again, ad infinitum. A much safer
  1208. rule would check its argument first, say, with `f(n) := f(floor(n)) ::
  1209. !dint(n)'.
  1210. (What really happens is that the rewrite mechanism substitutes the
  1211. meta-variables in the righthand side of a rule, compares to see if the
  1212. result is the same as the original formula and fails if so, then uses
  1213. the default simplifications to simplify the result and compares again
  1214. (and again fails if the formula has simplified back to its original
  1215. form). The only special wrinkle for the `EvalRules' is that the same
  1216. rules will come back into play when the default simplifications are
  1217. used. What Calc wants to do is build `f(floor(6))', see that this is
  1218. different from the original formula, simplify to `f(6)', see that this
  1219. is the same as the original formula, and thus halt the rewriting. But
  1220. while simplifying, `f(6)' will again trigger the same `EvalRules' rule
  1221. and Calc will get into a loop inside the rewrite mechanism itself.)
  1222. The `phase', `schedule', and `iterations' markers do not work in
  1223. `EvalRules'. If the rule set is divided into phases, only the phase 1
  1224. rules are applied, and the schedule is ignored. The rules are always
  1225. repeated as many times as possible.
  1226. The `EvalRules' are applied to all function calls in a formula, but
  1227. not to numbers (and other number-like objects like error forms), nor to
  1228. vectors or individual variable names. (Though they will apply to
  1229. _components_ of vectors and error forms when appropriate.) You might
  1230. try to make a variable `phihat' which automatically expands to its
  1231. definition without the need to press `=' by writing the rule
  1232. `quote(phihat) := (1-sqrt(5))/2', but unfortunately this rule will not
  1233. work as part of `EvalRules'.
  1234. Finally, another limitation is that Calc sometimes calls its built-in
  1235. functions directly rather than going through the default
  1236. simplifications. When it does this, `EvalRules' will not be able to
  1237. override those functions. For example, when you take the absolute
  1238. value of the complex number `(2, 3)', Calc computes `sqrt(2*2 + 3*3)'
  1239. by calling the multiplication, addition, and square root functions
  1240. directly rather than applying the default simplifications to this
  1241. formula. So an `EvalRules' rule that (perversely) rewrites `sqrt(13)
  1242. := 6' would not apply. (However, if you put Calc into Symbolic mode so
  1243. that `sqrt(13)' will be left in symbolic form by the built-in square
  1244. root function, your rule will be able to apply. But if the complex
  1245. number were `(3,4)', so that `sqrt(25)' must be calculated, then
  1246. Symbolic mode will not help because `sqrt(25)' can be evaluated exactly
  1247. to 5.)
  1248. One subtle restriction that normally only manifests itself with
  1249. `EvalRules' is that while a given rewrite rule is in the process of
  1250. being checked, that same rule cannot be recursively applied. Calc
  1251. effectively removes the rule from its rule set while checking the rule,
  1252. then puts it back once the match succeeds or fails. (The technical
  1253. reason for this is that compiled pattern programs are not reentrant.)
  1254. For example, consider the rule `foo(x) := x :: foo(x/2) > 0' attempting
  1255. to match `foo(8)'. This rule will be inactive while the condition
  1256. `foo(4) > 0' is checked, even though it might be an integral part of
  1257. evaluating that condition. Note that this is not a problem for the
  1258. more usual recursive type of rule, such as `foo(x) := foo(x/2)',
  1259. because there the rule has succeeded and been reactivated by the time
  1260. the righthand side is evaluated.
  1261. If `EvalRules' has no stored value (its default state), or if
  1262. anything but a vector is stored in it, then it is ignored.
  1263. Even though Calc's rewrite mechanism is designed to compare rewrite
  1264. rules to formulas as quickly as possible, storing rules in `EvalRules'
  1265. may make Calc run substantially slower. This is particularly true of
  1266. rules where the top-level call is a commonly used function, or is not
  1267. fixed. The rule `f(n) := n f(n-1) :: n>0' will only activate the
  1268. rewrite mechanism for calls to the function `f', but `lg(n) + lg(m) :=
  1269. lg(n m)' will check every `+' operator.
  1270. apply(f, [a*b]) := apply(f, [a]) + apply(f, [b]) :: in(f, [ln, log10])
  1271. may seem more "efficient" than two separate rules for `ln' and `log10',
  1272. but actually it is vastly less efficient because rules with `apply' as
  1273. the top-level pattern must be tested against _every_ function call that
  1274. is simplified.
  1275. Suppose you want `sin(a + b)' to be expanded out not all the time,
  1276. but only when `a s' is used to simplify the formula. The variable
  1277. `AlgSimpRules' holds rules for this purpose. The `a s' command will
  1278. apply `EvalRules' and `AlgSimpRules' to the formula, as well as all of
  1279. its built-in simplifications.
  1280. Most of the special limitations for `EvalRules' don't apply to
  1281. `AlgSimpRules'. Calc simply does an `a r AlgSimpRules' command with an
  1282. infinite repeat count as the first step of `a s'. It then applies its
  1283. own built-in simplifications throughout the formula, and then repeats
  1284. these two steps (along with applying the default simplifications) until
  1285. no further changes are possible.
  1286. There are also `ExtSimpRules' and `UnitSimpRules' variables that are
  1287. used by `a e' and `u s', respectively; these commands also apply
  1288. `EvalRules' and `AlgSimpRules'. The variable `IntegSimpRules' contains
  1289. simplification rules that are used only during integration by `a i'.
  1290. 
  1291. File: calc, Node: Debugging Rewrites, Next: Examples of Rewrite Rules, Prev: Automatic Rewrites, Up: Rewrite Rules
  1292. 12.11.12 Debugging Rewrites
  1293. ---------------------------
  1294. If a buffer named `*Trace*' exists, the rewrite mechanism will record
  1295. some useful information there as it operates. The original formula is
  1296. written there, as is the result of each successful rewrite, and the
  1297. final result of the rewriting. All phase changes are also noted.
  1298. Calc always appends to `*Trace*'. You must empty this buffer
  1299. yourself periodically if it is in danger of growing unwieldy.
  1300. Note that the rewriting mechanism is substantially slower when the
  1301. `*Trace*' buffer exists, even if the buffer is not visible on the
  1302. screen. Once you are done, you will probably want to kill this buffer
  1303. (with `C-x k *Trace* <RET>'). If you leave it in existence and forget
  1304. about it, all your future rewrite commands will be needlessly slow.
  1305. 
  1306. File: calc, Node: Examples of Rewrite Rules, Prev: Debugging Rewrites, Up: Rewrite Rules
  1307. 12.11.13 Examples of Rewrite Rules
  1308. ----------------------------------
  1309. Returning to the example of substituting the pattern `sin(x)^2 +
  1310. cos(x)^2' with 1, we saw that the rule `opt(a) sin(x)^2 + opt(a)
  1311. cos(x)^2 := a' does a good job of finding suitable cases. Another
  1312. solution would be to use the rule `cos(x)^2 := 1 - sin(x)^2', followed
  1313. by algebraic simplification if necessary. This rule will be the most
  1314. effective way to do the job, but at the expense of making some changes
  1315. that you might not desire.
  1316. Another algebraic rewrite rule is `exp(x+y) := exp(x) exp(y)'. To
  1317. make this work with the `j r' command so that it can be easily targeted
  1318. to a particular exponential in a large formula, you might wish to write
  1319. the rule as `select(exp(x+y)) := select(exp(x) exp(y))'. The `select'
  1320. markers will be ignored by the regular `a r' command (*note Selections
  1321. with Rewrite Rules::).
  1322. A surprisingly useful rewrite rule is `a/(b-c) := a*(b+c)/(b^2-c^2)'.
  1323. This will simplify the formula whenever `b' and/or `c' can be made
  1324. simpler by squaring. For example, applying this rule to `2 / (sqrt(2)
  1325. + 3)' yields `6:7 - 2:7 sqrt(2)' (assuming Symbolic mode has been
  1326. enabled to keep the square root from being evaluated to a
  1327. floating-point approximation). This rule is also useful when working
  1328. with symbolic complex numbers, e.g., `(a + b i) / (c + d i)'.
  1329. As another example, we could define our own "triangular numbers"
  1330. function with the rules `[tri(0) := 0, tri(n) := n + tri(n-1) :: n>0]'.
  1331. Enter this vector and store it in a variable: `s t trirules'. Now,
  1332. given a suitable formula like `tri(5)' on the stack, type `a r trirules'
  1333. to apply these rules repeatedly. After six applications, `a r' will
  1334. stop with 15 on the stack. Once these rules are debugged, it would
  1335. probably be most useful to add them to `EvalRules' so that Calc will
  1336. evaluate the new `tri' function automatically. We could then use `Z K'
  1337. on the keyboard macro `' tri($) <RET>' to make a command that applies
  1338. `tri' to the value on the top of the stack. *Note Programming::.
  1339. The following rule set, contributed by Francois Pinard, implements
  1340. "quaternions", a generalization of the concept of complex numbers.
  1341. Quaternions have four components, and are here represented by function
  1342. calls `quat(W, [X, Y, Z])' with "real part" W and the three "imaginary"
  1343. parts collected into a vector. Various arithmetical operations on
  1344. quaternions are supported. To use these rules, either add them to
  1345. `EvalRules', or create a command based on `a r' for simplifying
  1346. quaternion formulas. A convenient way to enter quaternions would be a
  1347. command defined by a keyboard macro containing: `' quat($$$$, [$$$, $$,
  1348. $]) <RET>'.
  1349. [ quat(w, x, y, z) := quat(w, [x, y, z]),
  1350. quat(w, [0, 0, 0]) := w,
  1351. abs(quat(w, v)) := hypot(w, v),
  1352. -quat(w, v) := quat(-w, -v),
  1353. r + quat(w, v) := quat(r + w, v) :: real(r),
  1354. r - quat(w, v) := quat(r - w, -v) :: real(r),
  1355. quat(w1, v1) + quat(w2, v2) := quat(w1 + w2, v1 + v2),
  1356. r * quat(w, v) := quat(r * w, r * v) :: real(r),
  1357. plain(quat(w1, v1) * quat(w2, v2))
  1358. := quat(w1 * w2 - v1 * v2, w1 * v2 + w2 * v1 + cross(v1, v2)),
  1359. quat(w1, v1) / r := quat(w1 / r, v1 / r) :: real(r),
  1360. z / quat(w, v) := z * quatinv(quat(w, v)),
  1361. quatinv(quat(w, v)) := quat(w, -v) / (w^2 + v^2),
  1362. quatsqr(quat(w, v)) := quat(w^2 - v^2, 2 * w * v),
  1363. quat(w, v)^k := quatsqr(quat(w, v)^(k / 2))
  1364. :: integer(k) :: k > 0 :: k % 2 = 0,
  1365. quat(w, v)^k := quatsqr(quat(w, v)^((k - 1) / 2)) * quat(w, v)
  1366. :: integer(k) :: k > 2,
  1367. quat(w, v)^-k := quatinv(quat(w, v)^k) :: integer(k) :: k > 0 ]
  1368. Quaternions, like matrices, have non-commutative multiplication. In
  1369. other words, `q1 * q2 = q2 * q1' is not necessarily true if `q1' and
  1370. `q2' are `quat' forms. The `quat*quat' rule above uses `plain' to
  1371. prevent Calc from rearranging the product. It may also be wise to add
  1372. the line `[quat(), matrix]' to the `Decls' matrix, to ensure that
  1373. Calc's other algebraic operations will not rearrange a quaternion
  1374. product. *Note Declarations::.
  1375. These rules also accept a four-argument `quat' form, converting it
  1376. to the preferred form in the first rule. If you would rather see
  1377. results in the four-argument form, just append the two items `phase(2),
  1378. quat(w, [x, y, z]) := quat(w, x, y, z)' to the end of the rule set.
  1379. (But remember that multi-phase rule sets don't work in `EvalRules'.)
  1380. 
  1381. File: calc, Node: Units, Next: Store and Recall, Prev: Algebra, Up: Top
  1382. 13 Operating on Units
  1383. *********************
  1384. One special interpretation of algebraic formulas is as numbers with
  1385. units. For example, the formula `5 m / s^2' can be read "five meters
  1386. per second squared." The commands in this chapter help you manipulate
  1387. units expressions in this form. Units-related commands begin with the
  1388. `u' prefix key.
  1389. * Menu:
  1390. * Basic Operations on Units::
  1391. * The Units Table::
  1392. * Predefined Units::
  1393. * User-Defined Units::
  1394. * Logarithmic Units::
  1395. * Musical Notes::
  1396. 
  1397. File: calc, Node: Basic Operations on Units, Next: The Units Table, Prev: Units, Up: Units
  1398. 13.1 Basic Operations on Units
  1399. ==============================
  1400. A "units expression" is a formula which is basically a number
  1401. multiplied and/or divided by one or more "unit names", which may
  1402. optionally be raised to integer powers. Actually, the value part need
  1403. not be a number; any product or quotient involving unit names is a units
  1404. expression. Many of the units commands will also accept any formula,
  1405. where the command applies to all units expressions which appear in the
  1406. formula.
  1407. A unit name is a variable whose name appears in the "unit table", or
  1408. a variable whose name is a prefix character like `k' (for "kilo") or
  1409. `u' (for "micro") followed by a name in the unit table. A substantial
  1410. table of built-in units is provided with Calc; *note Predefined
  1411. Units::. You can also define your own unit names; *note User-Defined
  1412. Units::.
  1413. Note that if the value part of a units expression is exactly `1', it
  1414. will be removed by the Calculator's automatic algebra routines: The
  1415. formula `1 mm' is "simplified" to `mm'. This is only a display
  1416. anomaly, however; `mm' will work just fine as a representation of one
  1417. millimeter.
  1418. You may find that Algebraic mode (*note Algebraic Entry::) makes
  1419. working with units expressions easier. Otherwise, you will have to
  1420. remember to hit the apostrophe key every time you wish to enter units.
  1421. The `u s' (`calc-simplify-units') [`usimplify'] command simplifies a
  1422. units expression. It uses `a s' (`calc-simplify') to simplify the
  1423. expression first as a regular algebraic formula; it then looks for
  1424. features that can be further simplified by converting one object's units
  1425. to be compatible with another's. For example, `5 m + 23 mm' will
  1426. simplify to `5.023 m'. When different but compatible units are added,
  1427. the righthand term's units are converted to match those of the lefthand
  1428. term. *Note Simplification Modes::, for a way to have this done
  1429. automatically at all times.
  1430. Units simplification also handles quotients of two units with the
  1431. same dimensionality, as in `2 in s/L cm' to `5.08 s/L'; fractional
  1432. powers of unit expressions, as in `sqrt(9 mm^2)' to `3 mm' and `sqrt(9
  1433. acre)' to a quantity in meters; and `floor', `ceil', `round', `rounde',
  1434. `roundu', `trunc', `float', `frac', `abs', and `clean' applied to units
  1435. expressions, in which case the operation in question is applied only to
  1436. the numeric part of the expression. Finally, trigonometric functions
  1437. of quantities with units of angle are evaluated, regardless of the
  1438. current angular mode.
  1439. The `u c' (`calc-convert-units') command converts a units expression
  1440. to new, compatible units. For example, given the units expression `55
  1441. mph', typing `u c m/s <RET>' produces `24.5872 m/s'. If you have
  1442. previously converted a units expression with the same type of units (in
  1443. this case, distance over time), you will be offered the previous choice
  1444. of new units as a default. Continuing the above example, entering the
  1445. units expression `100 km/hr' and typing `u c <RET>' (without specifying
  1446. new units) produces `27.7777777778 m/s'.
  1447. The `u c' command treats temperature units (like `degC' and `K') as
  1448. relative temperatures. For example, `u c' converts `10 degC' to `18
  1449. degF': A change of 10 degrees Celsius corresponds to a change of 18
  1450. degrees Fahrenheit. To convert absolute temperatures, you can use the
  1451. `u t' (`calc-convert-temperature') command. The value on the stack
  1452. must be a simple units expression with units of temperature only. This
  1453. command would convert `10 degC' to `50 degF', the equivalent
  1454. temperature on the Fahrenheit scale.
  1455. While many of Calc's conversion factors are exact, some are
  1456. necessarily approximate. If Calc is in fraction mode (*note Fraction
  1457. Mode::), then unit conversions will try to give exact, rational
  1458. conversions, but it isn't always possible. Given `55 mph' in fraction
  1459. mode, typing `u c m/s <RET>' produces `15367:625 m/s', for example,
  1460. while typing `u c au/yr <RET>' produces `5.18665819999e-3 au/yr'.
  1461. If the units you request are inconsistent with the original units,
  1462. the number will be converted into your units times whatever "remainder"
  1463. units are left over. For example, converting `55 mph' into acres
  1464. produces `6.08e-3 acre / m s'. (Recall that multiplication binds more
  1465. strongly than division in Calc formulas, so the units here are acres
  1466. per meter-second.) Remainder units are expressed in terms of
  1467. "fundamental" units like `m' and `s', regardless of the input units.
  1468. One special exception is that if you specify a single unit name, and
  1469. a compatible unit appears somewhere in the units expression, then that
  1470. compatible unit will be converted to the new unit and the remaining
  1471. units in the expression will be left alone. For example, given the
  1472. input `980 cm/s^2', the command `u c ms' will change the `s' to `ms' to
  1473. get `9.8e-4 cm/ms^2'. The "remainder unit" `cm' is left alone rather
  1474. than being changed to the base unit `m'.
  1475. You can use explicit unit conversion instead of the `u s' command to
  1476. gain more control over the units of the result of an expression. For
  1477. example, given `5 m + 23 mm', you can type `u c m' or `u c mm' to
  1478. express the result in either meters or millimeters. (For that matter,
  1479. you could type `u c fath' to express the result in fathoms, if you
  1480. preferred!)
  1481. In place of a specific set of units, you can also enter one of the
  1482. units system names `si', `mks' (equivalent), or `cgs'. For example, `u
  1483. c si <RET>' converts the expression into International System of Units
  1484. (SI) base units. Also, `u c base' converts to Calc's base units, which
  1485. are the same as `si' units except that `base' uses `g' as the
  1486. fundamental unit of mass whereas `si' uses `kg'.
  1487. The `u c' command also accepts "composite units", which are
  1488. expressed as the sum of several compatible unit names. For example,
  1489. converting `30.5 in' to units `mi+ft+in' (miles, feet, and inches)
  1490. produces `2 ft + 6.5 in'. Calc first sorts the unit names into order
  1491. of decreasing relative size. It then accounts for as much of the input
  1492. quantity as it can using an integer number times the largest unit, then
  1493. moves on to the next smaller unit, and so on. Only the smallest unit
  1494. may have a non-integer amount attached in the result. A few standard
  1495. unit names exist for common combinations, such as `mfi' for `mi+ft+in',
  1496. and `tpo' for `ton+lb+oz'. Composite units are expanded as if by `a
  1497. x', so that `(ft+in)/hr' is first converted to `ft/hr+in/hr'.
  1498. If the value on the stack does not contain any units, `u c' will
  1499. prompt first for the old units which this value should be considered to
  1500. have, then for the new units. Assuming the old and new units you give
  1501. are consistent with each other, the result also will not contain any
  1502. units. For example, `u c cm <RET> in <RET>' converts the number 2 on
  1503. the stack to 5.08.
  1504. The `u b' (`calc-base-units') command is shorthand for `u c base';
  1505. it converts the units expression on the top of the stack into `base'
  1506. units. If `u s' does not simplify a units expression as far as you
  1507. would like, try `u b'.
  1508. Like the `u c' command, the `u b' command treats temperature units
  1509. as relative temperatures.
  1510. The `u r' (`calc-remove-units') command removes units from the
  1511. formula at the top of the stack. The `u x' (`calc-extract-units')
  1512. command extracts only the units portion of a formula. These commands
  1513. essentially replace every term of the formula that does or doesn't
  1514. (respectively) look like a unit name by the constant 1, then resimplify
  1515. the formula.
  1516. The `u a' (`calc-autorange-units') command turns on and off a mode
  1517. in which unit prefixes like `k' ("kilo") are automatically applied to
  1518. keep the numeric part of a units expression in a reasonable range.
  1519. This mode affects `u s' and all units conversion commands except `u b'.
  1520. For example, with autoranging on, `12345 Hz' will be simplified to
  1521. `12.345 kHz'. Autoranging is useful for some kinds of units (like `Hz'
  1522. and `m'), but is probably undesirable for non-metric units like `ft'
  1523. and `tbsp'. (Composite units are more appropriate for those; see
  1524. above.)
  1525. Autoranging always applies the prefix to the leftmost unit name.
  1526. Calc chooses the largest prefix that causes the number to be greater
  1527. than or equal to 1.0. Thus an increasing sequence of adjusted times
  1528. would be `1 ms, 10 ms, 100 ms, 1 s, 10 s, 100 s, 1 ks'. Generally the
  1529. rule of thumb is that the number will be adjusted to be in the interval
  1530. `[1 .. 1000)', although there are several exceptions to this rule.
  1531. First, if the unit has a power then this is not possible; `0.1 s^2'
  1532. simplifies to `100000 ms^2'. Second, the "centi-" prefix is allowed to
  1533. form `cm' (centimeters), but will not apply to other units. The
  1534. "deci-," "deka-," and "hecto-" prefixes are never used. Thus the
  1535. allowable interval is `[1 .. 10)' for millimeters and `[1 .. 100)' for
  1536. centimeters. Finally, a prefix will not be added to a unit if the
  1537. resulting name is also the actual name of another unit; `1e-15 t' would
  1538. normally be considered a "femto-ton," but it is written as `1000 at'
  1539. (1000 atto-tons) instead because `ft' would be confused with feet.
  1540. 
  1541. File: calc, Node: The Units Table, Next: Predefined Units, Prev: Basic Operations on Units, Up: Units
  1542. 13.2 The Units Table
  1543. ====================
  1544. The `u v' (`calc-enter-units-table') command displays the units table
  1545. in another buffer called `*Units Table*'. Each entry in this table
  1546. gives the unit name as it would appear in an expression, the definition
  1547. of the unit in terms of simpler units, and a full name or description of
  1548. the unit. Fundamental units are defined as themselves; these are the
  1549. units produced by the `u b' command. The fundamental units are meters,
  1550. seconds, grams, kelvins, amperes, candelas, moles, radians, and
  1551. steradians.
  1552. The Units Table buffer also displays the Unit Prefix Table. Note
  1553. that two prefixes, "kilo" and "hecto," accept either upper- or
  1554. lower-case prefix letters. `Meg' is also accepted as a synonym for the
  1555. `M' prefix. Whenever a unit name can be interpreted as either a
  1556. built-in name or a prefix followed by another built-in name, the former
  1557. interpretation wins. For example, `2 pt' means two pints, not two
  1558. pico-tons.
  1559. The Units Table buffer, once created, is not rebuilt unless you
  1560. define new units. To force the buffer to be rebuilt, give any numeric
  1561. prefix argument to `u v'.
  1562. The `u V' (`calc-view-units-table') command is like `u v' except
  1563. that the cursor is not moved into the Units Table buffer. You can type
  1564. `u V' again to remove the Units Table from the display. To return from
  1565. the Units Table buffer after a `u v', type `C-x * c' again or use the
  1566. regular Emacs `C-x o' (`other-window') command. You can also kill the
  1567. buffer with `C-x k' if you wish; the actual units table is safely
  1568. stored inside the Calculator.
  1569. The `u g' (`calc-get-unit-definition') command retrieves a unit's
  1570. defining expression and pushes it onto the Calculator stack. For
  1571. example, `u g in' will produce the expression `2.54 cm'. This is the
  1572. same definition for the unit that would appear in the Units Table
  1573. buffer. Note that this command works only for actual unit names; `u g
  1574. km' will report that no such unit exists, for example, because `km' is
  1575. really the unit `m' with a `k' ("kilo") prefix. To see a definition of
  1576. a unit in terms of base units, it is easier to push the unit name on
  1577. the stack and then reduce it to base units with `u b'.
  1578. The `u e' (`calc-explain-units') command displays an English
  1579. description of the units of the expression on the stack. For example,
  1580. for the expression `62 km^2 g / s^2 mol K', the description is
  1581. "Square-Kilometer Gram per (Second-squared Mole Degree-Kelvin)." This
  1582. command uses the English descriptions that appear in the righthand
  1583. column of the Units Table.
  1584. 
  1585. File: calc, Node: Predefined Units, Next: User-Defined Units, Prev: The Units Table, Up: Units
  1586. 13.3 Predefined Units
  1587. =====================
  1588. The definitions of many units have changed over the years. For example,
  1589. the meter was originally defined in 1791 as one ten-millionth of the
  1590. distance from the equator to the north pole. In order to be more
  1591. precise, the definition was adjusted several times, and now a meter is
  1592. defined as the distance that light will travel in a vacuum in
  1593. 1/299792458 of a second; consequently, the speed of light in a vacuum
  1594. is exactly 299792458 m/s. Many other units have been redefined in
  1595. terms of fundamental physical processes; a second, for example, is
  1596. currently defined as 9192631770 periods of a certain radiation related
  1597. to the cesium-133 atom. The only SI unit that is not based on a
  1598. fundamental physical process (although there are efforts to change
  1599. this) is the kilogram, which was originally defined as the mass of one
  1600. liter of water, but is now defined as the mass of the International
  1601. Prototype Kilogram (IPK), a cylinder of platinum-iridium kept at the
  1602. Bureau International des Poids et Mesures in Se`vres, France. (There
  1603. are several copies of the IPK throughout the world.) The British
  1604. imperial units, once defined in terms of physical objects, were
  1605. redefined in 1963 in terms of SI units. The US customary units, which
  1606. were the same as British units until the British imperial system was
  1607. created in 1824, were also defined in terms of the SI units in 1893.
  1608. Because of these redefinitions, conversions between metric, British
  1609. Imperial, and US customary units can often be done precisely.
  1610. Since the exact definitions of many kinds of units have evolved over
  1611. the years, and since certain countries sometimes have local differences
  1612. in their definitions, it is a good idea to examine Calc's definition of
  1613. a unit before depending on its exact value. For example, there are
  1614. three different units for gallons, corresponding to the US (`gal'),
  1615. Canadian (`galC'), and British (`galUK') definitions. Also, note that
  1616. `oz' is a standard ounce of mass, `ozt' is a Troy ounce, and `ozfl' is
  1617. a fluid ounce.
  1618. The temperature units corresponding to degrees Kelvin and Centigrade
  1619. (Celsius) are the same in this table, since most units commands treat
  1620. temperatures as being relative. The `calc-convert-temperature' command
  1621. has special rules for handling the different absolute magnitudes of the
  1622. various temperature scales.
  1623. The unit of volume "liters" can be referred to by either the
  1624. lower-case `l' or the upper-case `L'.
  1625. The unit `A' stands for Amperes; the name `Ang' is used for
  1626. Angstroms.
  1627. The unit `pt' stands for pints; the name `point' stands for a
  1628. typographical point, defined by `72 point = 1 in'. This is slightly
  1629. different than the point defined by the American Typefounder's
  1630. Association in 1886, but the point used by Calc has become standard
  1631. largely due to its use by the PostScript page description language.
  1632. There is also `texpt', which stands for a printer's point as defined by
  1633. the TeX typesetting system: `72.27 texpt = 1 in'. Other units used by
  1634. TeX are available; they are `texpc' (a pica), `texbp' (a "big point",
  1635. equal to a standard point which is larger than the point used by TeX),
  1636. `texdd' (a Didot point), `texcc' (a Cicero) and `texsp' (a scaled TeX
  1637. point, all dimensions representable in TeX are multiples of this value).
  1638. When Calc is using the TeX or LaTeX language mode (*note TeX and
  1639. LaTeX Language Modes::), the TeX specific unit names will not use the
  1640. `tex' prefix; the unit name for a TeX point will be `pt' instead of
  1641. `texpt', for example. To avoid conflicts, the unit names for pint and
  1642. parsec will simply be `pint' and `parsec' instead of `pt' and `pc'.
  1643. The unit `e' stands for the elementary (electron) unit of charge;
  1644. because algebra command could mistake this for the special constant
  1645. `e', Calc provides the alternate unit name `ech' which is preferable to
  1646. `e'.
  1647. The name `g' stands for one gram of mass; there is also `gf', one
  1648. gram of force. (Likewise for `lb', pounds, and `lbf'.) Meanwhile, one
  1649. "`g'" of acceleration is denoted `ga'.
  1650. The unit `ton' is a U.S. ton of `2000 lb', and `t' is a metric ton
  1651. of `1000 kg'.
  1652. The names `s' (or `sec') and `min' refer to units of time; `arcsec'
  1653. and `arcmin' are units of angle.
  1654. Some "units" are really physical constants; for example, `c'
  1655. represents the speed of light, and `h' represents Planck's constant.
  1656. You can use these just like other units: converting `.5 c' to `m/s'
  1657. expresses one-half the speed of light in meters per second. You can
  1658. also use this merely as a handy reference; the `u g' command gets the
  1659. definition of one of these constants in its normal terms, and `u b'
  1660. expresses the definition in base units.
  1661. Two units, `pi' and `alpha' (the fine structure constant,
  1662. approximately 1/137) are dimensionless. The units simplification
  1663. commands simply treat these names as equivalent to their corresponding
  1664. values. However you can, for example, use `u c' to convert a pure
  1665. number into multiples of the fine structure constant, or `u b' to
  1666. convert this back into a pure number. (When `u c' prompts for the "old
  1667. units," just enter a blank line to signify that the value really is
  1668. unitless.)
  1669. 
  1670. File: calc, Node: User-Defined Units, Next: Logarithmic Units, Prev: Predefined Units, Up: Units
  1671. 13.4 User-Defined Units
  1672. =======================
  1673. Calc provides ways to get quick access to your selected "favorite"
  1674. units, as well as ways to define your own new units.
  1675. To select your favorite units, store a vector of unit names or
  1676. expressions in the Calc variable `Units'. The `u 1' through `u 9'
  1677. commands (`calc-quick-units') provide access to these units. If the
  1678. value on the top of the stack is a plain number (with no units
  1679. attached), then `u 1' gives it the specified units. (Basically, it
  1680. multiplies the number by the first item in the `Units' vector.) If the
  1681. number on the stack _does_ have units, then `u 1' converts that number
  1682. to the new units. For example, suppose the vector `[in, ft]' is stored
  1683. in `Units'. Then `30 u 1' will create the expression `30 in', and `u
  1684. 2' will convert that expression to `2.5 ft'.
  1685. The `u 0' command accesses the tenth element of `Units'. Only ten
  1686. quick units may be defined at a time. If the `Units' variable has no
  1687. stored value (the default), or if its value is not a vector, then the
  1688. quick-units commands will not function. The `s U' command is a
  1689. convenient way to edit the `Units' variable; *note Operations on
  1690. Variables::.
  1691. The `u d' (`calc-define-unit') command records the units expression
  1692. on the top of the stack as the definition for a new, user-defined unit.
  1693. For example, putting `16.5 ft' on the stack and typing `u d rod'
  1694. defines the new unit `rod' to be equivalent to 16.5 feet. The unit
  1695. conversion and simplification commands will now treat `rod' just like
  1696. any other unit of length. You will also be prompted for an optional
  1697. English description of the unit, which will appear in the Units Table.
  1698. If you wish the definition of this unit to be displayed in a special
  1699. way in the Units Table buffer (such as with an asterisk to indicate an
  1700. approximate value), then you can call this command with an argument,
  1701. `C-u u d'; you will then also be prompted for a string that will be
  1702. used to display the definition.
  1703. The `u u' (`calc-undefine-unit') command removes a user-defined
  1704. unit. It is not possible to remove one of the predefined units,
  1705. however.
  1706. If you define a unit with an existing unit name, your new definition
  1707. will replace the original definition of that unit. If the unit was a
  1708. predefined unit, the old definition will not be replaced, only
  1709. "shadowed." The built-in definition will reappear if you later use `u
  1710. u' to remove the shadowing definition.
  1711. To create a new fundamental unit, use either 1 or the unit name
  1712. itself as the defining expression. Otherwise the expression can
  1713. involve any other units that you like (except for composite units like
  1714. `mfi'). You can create a new composite unit with a sum of other units
  1715. as the defining expression. The next unit operation like `u c' or `u v'
  1716. will rebuild the internal unit table incorporating your modifications.
  1717. Note that erroneous definitions (such as two units defined in terms of
  1718. each other) will not be detected until the unit table is next rebuilt;
  1719. `u v' is a convenient way to force this to happen.
  1720. Temperature units are treated specially inside the Calculator; it is
  1721. not possible to create user-defined temperature units.
  1722. The `u p' (`calc-permanent-units') command stores the user-defined
  1723. units in your Calc init file (the file given by the variable
  1724. `calc-settings-file', typically `~/.emacs.d/calc.el'), so that the
  1725. units will still be available in subsequent Emacs sessions. If there
  1726. was already a set of user-defined units in your Calc init file, it is
  1727. replaced by the new set. (*Note General Mode Commands::, for a way to
  1728. tell Calc to use a different file for the Calc init file.)
  1729. 
  1730. File: calc, Node: Logarithmic Units, Next: Musical Notes, Prev: User-Defined Units, Up: Units
  1731. 13.5 Logarithmic Units
  1732. ======================
  1733. The units `dB' (decibels) and `Np' (nepers) are logarithmic units which
  1734. are manipulated differently than standard units. Calc provides
  1735. commands to work with these logarithmic units.
  1736. Decibels and nepers are used to measure power quantities as well as
  1737. field quantities (quantities whose squares are proportional to power);
  1738. these two types of quantities are handled slightly different from each
  1739. other. By default the Calc commands work as if power quantities are
  1740. being used; with the `H' prefix the Calc commands work as if field
  1741. quantities are being used.
  1742. The decibel level of a power P1, relative to a reference power P0,
  1743. is defined to be 10 log10(P1/P0) dB. (The factor of 10 is because a
  1744. decibel, as its name implies, is one-tenth of a bel. The bel, named
  1745. after Alexander Graham Bell, was considered to be too large of a unit
  1746. and was effectively replaced by the decibel.) If F is a field quantity
  1747. with power P=k F^2, then a reference quantity of F0 would correspond to
  1748. a power of P0=k F0^2. If P1=k F1^2, then
  1749. 10 log10(P1/P0) = 10 log10(F1^2/F0^2) = 20 log10(F1/F0).
  1750. In order to get the same decibel level regardless of whether a field
  1751. quantity or the corresponding power quantity is used, the decibel
  1752. level of a field quantity F1, relative to a reference F0, is defined as
  1753. 20 log10(F1/F0) dB. For example, the decibel value of a sound pressure
  1754. level of 60 uPa relative to 20 uPa (the threshold of human hearing) is
  1755. 20 log10(60 uPa/ 20 uPa) dB = 20 log10(3) dB, which is about 9.54 dB.
  1756. Note that in taking the ratio, the original units cancel and so these
  1757. logarithmic units are dimensionless.
  1758. Nepers (named after John Napier, who is credited with inventing the
  1759. logarithm) are similar to bels except they use natural logarithms
  1760. instead of common logarithms. The neper level of a power P1, relative
  1761. to a reference power P0, is (1/2) ln(P1/P0) Np. The neper level of a
  1762. field F1, relative to a reference field F0, is ln(F1/F0) Np.
  1763. For power quantities, Calc uses 1 mW as the default reference
  1764. quantity; this default can be changed by changing the value of the
  1765. customizable variable `calc-lu-power-reference' (*note Customizing
  1766. Calc::). For field quantities, Calc uses 20 uPa as the default
  1767. reference quantity; this is the value used in acoustics which is where
  1768. decibels are commonly encountered. This default can be changed by
  1769. changing the value of the customizable variable
  1770. `calc-lu-field-reference' (*note Customizing Calc::). A non-default
  1771. reference quantity will be read from the stack if the capital `O'
  1772. prefix is used.
  1773. The `l q' (`calc-lu-quant') [`lupquant'] command computes the power
  1774. quantity corresponding to a given number of logarithmic units. With the
  1775. capital `O' prefix, `O l q', the reference level will be read from the
  1776. top of the stack. (In an algebraic formula, `lupquant' can be given an
  1777. optional second argument which will be used for the reference level.)
  1778. For example, `20 dB <RET> l q' will return `100 mW'; `20 dB <RET> 4 W
  1779. <RET> O l q' will return `400 W'. The `H l q' [`lufquant'] command
  1780. behaves like `l q' but computes field quantities instead of power
  1781. quantities.
  1782. The `l d' (`calc-db') [`dbpower'] command will compute the decibel
  1783. level of a power quantity using the default reference level; `H l d'
  1784. [`dbfield'] will compute the decibel level of a field quantity. The
  1785. commands `l n' (`calc-np') [`nppower'] and `H l n' [`npfield'] will
  1786. similarly compute neper levels. With the capital `O' prefix these
  1787. commands will read a reference level from the stack; in an algebraic
  1788. formula the reference level can be given as an optional second argument.
  1789. The sum of two power or field quantities doesn't correspond to the
  1790. sum of the corresponding decibel or neper levels. If the powers
  1791. corresponding to decibel levels D1 and D2 are added, the corresponding
  1792. decibel level "sum" will be
  1793. 10 log10(10^(D1/10) + 10^(D2/10)) dB.
  1794. When field quantities are combined, it often means the corresponding
  1795. powers are added and so the above formula might be used. In acoustics,
  1796. for example, the sound pressure level is a field quantity and so the
  1797. decibels are often defined using the field formula, but the sound
  1798. pressure levels are combined as the sound power levels, and so the
  1799. above formula should be used. If two field quantities themselves are
  1800. added, the new decibel level will be
  1801. 20 log10(10^(D1/20) + 10^(D2/20)) dB.
  1802. If the power corresponding to D dB is multiplied by a number N, then
  1803. the corresponding decibel level will be
  1804. D + 10 log10(N) dB,
  1805. if a field quantity is multiplied by N the corresponding decibel level
  1806. will be
  1807. D + 20 log10(N) dB.
  1808. There are similar formulas for combining nepers. The `l +'
  1809. (`calc-lu-plus') [`lupadd'] command will "add" two logarithmic unit
  1810. power levels this way; with the `H' prefix, `H l +' [`lufadd'] will add
  1811. logarithmic unit field levels. Similarly, logarithmic units can be
  1812. "subtracted" with `l -' (`calc-lu-minus') [`lupsub'] or `H l -'
  1813. [`lufsub']. The `l *' (`calc-lu-times') [`lupmul'] and `H l *'
  1814. [`lufmul'] commands will "multiply" a logarithmic unit by a number; the
  1815. `l /' (`calc-lu-divide') [`lupdiv'] and `H l /' [`lufdiv'] commands
  1816. will "divide" a logarithmic unit by a number. Note that the reference
  1817. quantities don't play a role in this arithmetic.
  1818. 
  1819. File: calc, Node: Musical Notes, Prev: Logarithmic Units, Up: Units
  1820. 13.6 Musical Notes
  1821. ==================
  1822. Calc can convert between musical notes and their associated
  1823. frequencies. Notes can be given using either scientific pitch notation
  1824. or midi numbers. Since these note systems are basically logarithmic
  1825. scales, Calc uses the `l' prefix for functions operating on notes.
  1826. Scientific pitch notation refers to a note by giving a letter A
  1827. through G, possibly followed by a flat or sharp) with a subscript
  1828. indicating an octave number. Each octave starts with C and ends with B
  1829. and the octave numbered 0 was chosen to correspond to the lowest
  1830. audible frequency. Using this system, middle C (about 261.625 Hz)
  1831. corresponds to the note `C' in octave 4 and is denoted `C_4'. Any
  1832. frequency can be described by giving a note plus an offset in cents
  1833. (where a cent is a ratio of frequencies so that a semitone consists of
  1834. 100 cents).
  1835. The midi note number system assigns numbers to notes so that
  1836. `C_(-1)' corresponds to the midi note number 0 and `G_9' corresponds to
  1837. the midi note number 127. A midi controller can have up to 128 keys
  1838. and each midi note number from 0 to 127 corresponds to a possible key.
  1839. The `l s' (`calc-spn') [`spn'] command converts either a frequency
  1840. or a midi number to scientific pitch notation. For example, `500 Hz'
  1841. gets converted to `B_4 + 21.3094853649 cents' and `84' to `C_6'.
  1842. The `l m' (`calc-midi') [`midi'] command converts either a frequency
  1843. or a note given in scientific pitch notation to the corresponding midi
  1844. number. For example, `C_6' gets converted to 84 and `440 Hz' to 69.
  1845. The `l f' (`calc-freq') [`freq'] command converts either either a
  1846. midi number or a note given in scientific pitch notation to the
  1847. corresponding frequency. For example, `Asharp_2 + 30 cents' gets
  1848. converted to `118.578040134 Hz' and `55' to `195.99771799 Hz'.
  1849. Since the frequencies of notes are not usually given exactly (and are
  1850. typically irrational), the customizable variable `calc-note-threshold'
  1851. determines how close (in cents) a frequency needs to be to a note to be
  1852. recognized as that note (*note Customizing Calc::). This variable has
  1853. a default value of `1'. For example, middle C is approximately
  1854. `261.625565302 Hz'; this frequency is often shortened to `261.625 Hz'.
  1855. Without `calc-note-threshold' (or a value of `0'), Calc would convert
  1856. `261.625 Hz' to scientific pitch notation `B_3 + 99.9962592773 cents';
  1857. with the default value of `1', Calc converts `261.625 Hz' to `C_4'.
  1858. 
  1859. File: calc, Node: Store and Recall, Next: Graphics, Prev: Units, Up: Top
  1860. 14 Storing and Recalling
  1861. ************************
  1862. Calculator variables are really just Lisp variables that contain numbers
  1863. or formulas in a form that Calc can understand. The commands in this
  1864. section allow you to manipulate variables conveniently. Commands
  1865. related to variables use the `s' prefix key.
  1866. * Menu:
  1867. * Storing Variables::
  1868. * Recalling Variables::
  1869. * Operations on Variables::
  1870. * Let Command::
  1871. * Evaluates-To Operator::
  1872. 
  1873. File: calc, Node: Storing Variables, Next: Recalling Variables, Prev: Store and Recall, Up: Store and Recall
  1874. 14.1 Storing Variables
  1875. ======================
  1876. The `s s' (`calc-store') command stores the value at the top of the
  1877. stack into a specified variable. It prompts you to enter the name of
  1878. the variable. If you press a single digit, the value is stored
  1879. immediately in one of the "quick" variables `q0' through `q9'. Or you
  1880. can enter any variable name.
  1881. The `s s' command leaves the stored value on the stack. There is
  1882. also an `s t' (`calc-store-into') command, which removes a value from
  1883. the stack and stores it in a variable.
  1884. If the top of stack value is an equation `a = 7' or assignment `a :=
  1885. 7' with a variable on the lefthand side, then Calc will assign that
  1886. variable with that value by default, i.e., if you type `s s <RET>' or
  1887. `s t <RET>'. In this example, the value 7 would be stored in the
  1888. variable `a'. (If you do type a variable name at the prompt, the
  1889. top-of-stack value is stored in its entirety, even if it is an
  1890. equation: `s s b <RET>' with `a := 7' on the stack stores `a := 7' in
  1891. `b'.)
  1892. In fact, the top of stack value can be a vector of equations or
  1893. assignments with different variables on their lefthand sides; the
  1894. default will be to store all the variables with their corresponding
  1895. righthand sides simultaneously.
  1896. It is also possible to type an equation or assignment directly at
  1897. the prompt for the `s s' or `s t' command: `s s foo = 7'. In this
  1898. case the expression to the right of the `=' or `:=' symbol is evaluated
  1899. as if by the `=' command, and that value is stored in the variable. No
  1900. value is taken from the stack; `s s' and `s t' are equivalent when used
  1901. in this way.
  1902. The prefix keys `s' and `t' may be followed immediately by a digit;
  1903. `s 9' is equivalent to `s s 9', and `t 9' is equivalent to `s t 9'.
  1904. (The `t' prefix is otherwise used for trail and time/date commands.)
  1905. There are also several "arithmetic store" commands. For example, `s
  1906. +' removes a value from the stack and adds it to the specified
  1907. variable. The other arithmetic stores are `s -', `s *', `s /', `s ^',
  1908. and `s |' (vector concatenation), plus `s n' and `s &' which negate or
  1909. invert the value in a variable, and `s [' and `s ]' which decrease or
  1910. increase a variable by one.
  1911. All the arithmetic stores accept the Inverse prefix to reverse the
  1912. order of the operands. If `v' represents the contents of the variable,
  1913. and `a' is the value drawn from the stack, then regular `s -' assigns
  1914. `v := v - a', but `I s -' assigns `v := a - v'. While `I s *' might
  1915. seem pointless, it is useful if matrix multiplication is involved.
  1916. Actually, all the arithmetic stores use formulas designed to behave
  1917. usefully both forwards and backwards:
  1918. s + v := v + a v := a + v
  1919. s - v := v - a v := a - v
  1920. s * v := v * a v := a * v
  1921. s / v := v / a v := a / v
  1922. s ^ v := v ^ a v := a ^ v
  1923. s | v := v | a v := a | v
  1924. s n v := v / (-1) v := (-1) / v
  1925. s & v := v ^ (-1) v := (-1) ^ v
  1926. s [ v := v - 1 v := 1 - v
  1927. s ] v := v - (-1) v := (-1) - v
  1928. In the last four cases, a numeric prefix argument will be used in
  1929. place of the number one. (For example, `M-2 s ]' increases a variable
  1930. by 2, and `M-2 I s ]' replaces a variable by minus-two minus the
  1931. variable.
  1932. The first six arithmetic stores can also be typed `s t +', `s t -',
  1933. etc. The commands `s s +', `s s -', and so on are analogous arithmetic
  1934. stores that don't remove the value `a' from the stack.
  1935. All arithmetic stores report the new value of the variable in the
  1936. Trail for your information. They signal an error if the variable
  1937. previously had no stored value. If default simplifications have been
  1938. turned off, the arithmetic stores temporarily turn them on for numeric
  1939. arguments only (i.e., they temporarily do an `m N' command). *Note
  1940. Simplification Modes::. Large vectors put in the trail by these
  1941. commands always use abbreviated (`t .') mode.
  1942. The `s m' command is a general way to adjust a variable's value
  1943. using any Calc function. It is a "mapping" command analogous to `V M',
  1944. `V R', etc. *Note Reducing and Mapping::, to see how to specify a
  1945. function for a mapping command. Basically, all you do is type the Calc
  1946. command key that would invoke that function normally. For example, `s
  1947. m n' applies the `n' key to negate the contents of the variable, so `s
  1948. m n' is equivalent to `s n'. Also, `s m Q' takes the square root of
  1949. the value stored in a variable, `s m v v' uses `v v' to reverse the
  1950. vector stored in the variable, and `s m H I S' takes the hyperbolic
  1951. arcsine of the variable contents.
  1952. If the mapping function takes two or more arguments, the additional
  1953. arguments are taken from the stack; the old value of the variable is
  1954. provided as the first argument. Thus `s m -' with `a' on the stack
  1955. computes `v - a', just like `s -'. With the Inverse prefix, the
  1956. variable's original value becomes the _last_ argument instead of the
  1957. first. Thus `I s m -' is also equivalent to `I s -'.
  1958. The `s x' (`calc-store-exchange') command exchanges the value of a
  1959. variable with the value on the top of the stack. Naturally, the
  1960. variable must already have a stored value for this to work.
  1961. You can type an equation or assignment at the `s x' prompt. The
  1962. command `s x a=6' takes no values from the stack; instead, it pushes
  1963. the old value of `a' on the stack and stores `a = 6'.
  1964. Until you store something in them, most variables are "void," that
  1965. is, they contain no value at all. If they appear in an algebraic
  1966. formula they will be left alone even if you press `=' (`calc-evaluate').
  1967. The `s u' (`calc-unstore') command returns a variable to the void state.
  1968. The `s c' (`calc-copy-variable') command copies the stored value of
  1969. one variable to another. One way it differs from a simple `s r'
  1970. followed by an `s t' (aside from saving keystrokes) is that the value
  1971. never goes on the stack and thus is never rounded, evaluated, or
  1972. simplified in any way; it is not even rounded down to the current
  1973. precision.
  1974. The only variables with predefined values are the "special constants"
  1975. `pi', `e', `i', `phi', and `gamma'. You are free to unstore these
  1976. variables or to store new values into them if you like, although some
  1977. of the algebraic-manipulation functions may assume these variables
  1978. represent their standard values. Calc displays a warning if you change
  1979. the value of one of these variables, or of one of the other special
  1980. variables `inf', `uinf', and `nan' (which are normally void).
  1981. Note that `pi' doesn't actually have 3.14159265359 stored in it, but
  1982. rather a special magic value that evaluates to `pi' at the current
  1983. precision. Likewise `e', `i', and `phi' evaluate according to the
  1984. current precision or polar mode. If you recall a value from `pi' and
  1985. store it back, this magic property will be lost. The magic property is
  1986. preserved, however, when a variable is copied with `s c'.
  1987. If one of the "special constants" is redefined (or undefined) so that
  1988. it no longer has its magic property, the property can be restored with
  1989. `s k' (`calc-copy-special-constant'). This command will prompt for a
  1990. special constant and a variable to store it in, and so a special
  1991. constant can be stored in any variable. Here, the special constant that
  1992. you enter doesn't depend on the value of the corresponding variable;
  1993. `pi' will represent 3.14159... regardless of what is currently stored
  1994. in the Calc variable `pi'. If one of the other special variables,
  1995. `inf', `uinf' or `nan', is given a value, its original behavior can be
  1996. restored by voiding it with `s u'.
  1997. 
  1998. File: calc, Node: Recalling Variables, Next: Operations on Variables, Prev: Storing Variables, Up: Store and Recall
  1999. 14.2 Recalling Variables
  2000. ========================
  2001. The most straightforward way to extract the stored value from a variable
  2002. is to use the `s r' (`calc-recall') command. This command prompts for
  2003. a variable name (similarly to `calc-store'), looks up the value of the
  2004. specified variable, and pushes that value onto the stack. It is an
  2005. error to try to recall a void variable.
  2006. It is also possible to recall the value from a variable by
  2007. evaluating a formula containing that variable. For example, `' a <RET>
  2008. =' is the same as `s r a <RET>' except that if the variable is void, the
  2009. former will simply leave the formula `a' on the stack whereas the
  2010. latter will produce an error message.
  2011. The `r' prefix may be followed by a digit, so that `r 9' is
  2012. equivalent to `s r 9'.
  2013. 
  2014. File: calc, Node: Operations on Variables, Next: Let Command, Prev: Recalling Variables, Up: Store and Recall
  2015. 14.3 Other Operations on Variables
  2016. ==================================
  2017. The `s e' (`calc-edit-variable') command edits the stored value of a
  2018. variable without ever putting that value on the stack or simplifying or
  2019. evaluating the value. It prompts for the name of the variable to edit.
  2020. If the variable has no stored value, the editing buffer will start out
  2021. empty. If the editing buffer is empty when you press `C-c C-c' to
  2022. finish, the variable will be made void. *Note Editing Stack Entries::,
  2023. for a general description of editing.
  2024. The `s e' command is especially useful for creating and editing
  2025. rewrite rules which are stored in variables. Sometimes these rules
  2026. contain formulas which must not be evaluated until the rules are
  2027. actually used. (For example, they may refer to `deriv(x,y)', where `x'
  2028. will someday become some expression involving `y'; if you let Calc
  2029. evaluate the rule while you are defining it, Calc will replace
  2030. `deriv(x,y)' with 0 because the formula `x' does not itself refer to
  2031. `y'.) By contrast, recalling the variable, editing with ``', and
  2032. storing will evaluate the variable's value as a side effect of putting
  2033. the value on the stack.
  2034. There are several special-purpose variable-editing commands that use
  2035. the `s' prefix followed by a shifted letter:
  2036. `s A'
  2037. Edit `AlgSimpRules'. *Note Algebraic Simplifications::.
  2038. `s D'
  2039. Edit `Decls'. *Note Declarations::.
  2040. `s E'
  2041. Edit `EvalRules'. *Note Default Simplifications::.
  2042. `s F'
  2043. Edit `FitRules'. *Note Curve Fitting::.
  2044. `s G'
  2045. Edit `GenCount'. *Note Solving Equations::.
  2046. `s H'
  2047. Edit `Holidays'. *Note Business Days::.
  2048. `s I'
  2049. Edit `IntegLimit'. *Note Calculus::.
  2050. `s L'
  2051. Edit `LineStyles'. *Note Graphics::.
  2052. `s P'
  2053. Edit `PointStyles'. *Note Graphics::.
  2054. `s R'
  2055. Edit `PlotRejects'. *Note Graphics::.
  2056. `s T'
  2057. Edit `TimeZone'. *Note Time Zones::.
  2058. `s U'
  2059. Edit `Units'. *Note User-Defined Units::.
  2060. `s X'
  2061. Edit `ExtSimpRules'. *Note Unsafe Simplifications::.
  2062. These commands are just versions of `s e' that use fixed variable
  2063. names rather than prompting for the variable name.
  2064. The `s p' (`calc-permanent-variable') command saves a variable's
  2065. value permanently in your Calc init file (the file given by the
  2066. variable `calc-settings-file', typically `~/.emacs.d/calc.el'), so that
  2067. its value will still be available in future Emacs sessions. You can
  2068. re-execute `s p' later on to update the saved value, but the only way
  2069. to remove a saved variable is to edit your calc init file by hand.
  2070. (*Note General Mode Commands::, for a way to tell Calc to use a
  2071. different file for the Calc init file.)
  2072. If you do not specify the name of a variable to save (i.e., `s p
  2073. <RET>'), all Calc variables with defined values are saved except for
  2074. the special constants `pi', `e', `i', `phi', and `gamma'; the variables
  2075. `TimeZone' and `PlotRejects'; `FitRules', `DistribRules', and other
  2076. built-in rewrite rules; and `PlotDataN' variables generated by the
  2077. graphics commands. (You can still save these variables by explicitly
  2078. naming them in an `s p' command.)
  2079. The `s i' (`calc-insert-variables') command writes the values of all
  2080. Calc variables into a specified buffer. The variables are written with
  2081. the prefix `var-' in the form of Lisp `setq' commands which store the
  2082. values in string form. You can place these commands in your Calc init
  2083. file (or `.emacs') if you wish, though in this case it would be easier
  2084. to use `s p <RET>'. (Note that `s i' omits the same set of variables
  2085. as `s p <RET>'; the difference is that `s i' will store the variables
  2086. in any buffer, and it also stores in a more human-readable format.)
  2087. 
  2088. File: calc, Node: Let Command, Next: Evaluates-To Operator, Prev: Operations on Variables, Up: Store and Recall
  2089. 14.4 The Let Command
  2090. ====================
  2091. If you have an expression like `a+b^2' on the stack and you wish to
  2092. compute its value where `b=3', you can simply store 3 in `b' and then
  2093. press `=' to reevaluate the formula. This has the side-effect of
  2094. leaving the stored value of 3 in `b' for future operations.
  2095. The `s l' (`calc-let') command evaluates a formula under a
  2096. _temporary_ assignment of a variable. It stores the value on the top
  2097. of the stack into the specified variable, then evaluates the
  2098. second-to-top stack entry, then restores the original value (or lack of
  2099. one) in the variable. Thus after `' a+b^2 <RET> 3 s l b <RET>', the
  2100. stack will contain the formula `a + 9'. The subsequent command
  2101. `5 s l a <RET>' will replace this formula with the number 14. The
  2102. variables `a' and `b' are not permanently affected in any way by these
  2103. commands.
  2104. The value on the top of the stack may be an equation or assignment,
  2105. or a vector of equations or assignments, in which case the default will
  2106. be analogous to the case of `s t <RET>'. *Note Storing Variables::.
  2107. Also, you can answer the variable-name prompt with an equation or
  2108. assignment: `s l b=3 <RET>' is the same as storing 3 on the stack and
  2109. typing `s l b <RET>'.
  2110. The `a b' (`calc-substitute') command is another way to substitute a
  2111. variable with a value in a formula. It does an actual substitution
  2112. rather than temporarily assigning the variable and evaluating. For
  2113. example, letting `n=2' in `f(n pi)' with `a b' will produce `f(2 pi)',
  2114. whereas `s l' would give `f(6.28)' since the evaluation step will also
  2115. evaluate `pi'.
  2116. 
  2117. File: calc, Node: Evaluates-To Operator, Prev: Let Command, Up: Store and Recall
  2118. 14.5 The Evaluates-To Operator
  2119. ==============================
  2120. The special algebraic symbol `=>' is known as the "evaluates-to
  2121. operator". (It will show up as an `evalto' function call in other
  2122. language modes like Pascal and LaTeX.) This is a binary operator, that
  2123. is, it has a lefthand and a righthand argument, although it can be
  2124. entered with the righthand argument omitted.
  2125. A formula like `A => B' is evaluated by Calc as follows: First, A
  2126. is not simplified or modified in any way. The previous value of
  2127. argument B is thrown away; the formula A is then copied and evaluated
  2128. as if by the `=' command according to all current modes and stored
  2129. variable values, and the result is installed as the new value of B.
  2130. For example, suppose you enter the algebraic formula `2 + 3 => 17'.
  2131. The number 17 is ignored, and the lefthand argument is left in its
  2132. unevaluated form; the result is the formula `2 + 3 => 5'.
  2133. You can enter an `=>' formula either directly using algebraic entry
  2134. (in which case the righthand side may be omitted since it is going to
  2135. be replaced right away anyhow), or by using the `s =' (`calc-evalto')
  2136. command, which takes A from the stack and replaces it with `A => B'.
  2137. Calc keeps track of all `=>' operators on the stack, and recomputes
  2138. them whenever anything changes that might affect their values, i.e., a
  2139. mode setting or variable value. This occurs only if the `=>' operator
  2140. is at the top level of the formula, or if it is part of a top-level
  2141. vector. In other words, pushing `2 + (a => 17)' will change the 17 to
  2142. the actual value of `a' when you enter the formula, but the result will
  2143. not be dynamically updated when `a' is changed later because the `=>'
  2144. operator is buried inside a sum. However, a vector of `=>' operators
  2145. will be recomputed, since it is convenient to push a vector like `[a
  2146. =>, b =>, c =>]' on the stack to make a concise display of all the
  2147. variables in your problem. (Another way to do this would be to use
  2148. `[a, b, c] =>', which provides a slightly different format of display.
  2149. You can use whichever you find easiest to read.)
  2150. The `m C' (`calc-auto-recompute') command allows you to turn this
  2151. automatic recomputation on or off. If you turn recomputation off, you
  2152. must explicitly recompute an `=>' operator on the stack in one of the
  2153. usual ways, such as by pressing `='. Turning recomputation off
  2154. temporarily can save a lot of time if you will be changing several
  2155. modes or variables before you look at the `=>' entries again.
  2156. Most commands are not especially useful with `=>' operators as
  2157. arguments. For example, given `x + 2 => 17', it won't work to type `1
  2158. +' to get `x + 3 => 18'. If you want to operate on the lefthand side
  2159. of the `=>' operator on the top of the stack, type `j 1' (that's the
  2160. digit "one") to select the lefthand side, execute your commands, then
  2161. type `j u' to unselect.
  2162. All current modes apply when an `=>' operator is computed, including
  2163. the current simplification mode. Recall that the formula `x + y + x'
  2164. is not handled by Calc's default simplifications, but the `a s' command
  2165. will reduce it to the simpler form `y + 2 x'. You can also type `m A'
  2166. to enable an Algebraic Simplification mode in which the equivalent of
  2167. `a s' is used on all of Calc's results. If you enter `x + y + x =>'
  2168. normally, the result will be `x + y + x => x + y + x'. If you change to
  2169. Algebraic Simplification mode, the result will be `x + y + x => y + 2
  2170. x'. However, just pressing `a s' once will have no effect on `x + y +
  2171. x => x + y + x', because the righthand side depends only on the
  2172. lefthand side and the current mode settings, and the lefthand side is
  2173. not affected by commands like `a s'.
  2174. The "let" command (`s l') has an interesting interaction with the
  2175. `=>' operator. The `s l' command evaluates the second-to-top stack
  2176. entry with the top stack entry supplying a temporary value for a given
  2177. variable. As you might expect, if that stack entry is an `=>' operator
  2178. its righthand side will temporarily show this value for the variable.
  2179. In fact, all `=>'s on the stack will be updated if they refer to that
  2180. variable. But this change is temporary in the sense that the next
  2181. command that causes Calc to look at those stack entries will make them
  2182. revert to the old variable value.
  2183. 2: a => a 2: a => 17 2: a => a
  2184. 1: a + 1 => a + 1 1: a + 1 => 18 1: a + 1 => a + 1
  2185. . . .
  2186. 17 s l a <RET> p 8 <RET>
  2187. Here the `p 8' command changes the current precision, thus causing
  2188. the `=>' forms to be recomputed after the influence of the "let" is
  2189. gone. The `d <SPC>' command (`calc-refresh') is a handy way to force
  2190. the `=>' operators on the stack to be recomputed without any other side
  2191. effects.
  2192. Embedded mode also uses `=>' operators. In Embedded mode, the
  2193. lefthand side of an `=>' operator can refer to variables assigned
  2194. elsewhere in the file by `:=' operators. The assignment operator `a :=
  2195. 17' does not actually do anything by itself. But Embedded mode
  2196. recognizes it and marks it as a sort of file-local definition of the
  2197. variable. You can enter `:=' operators in Algebraic mode, or by using
  2198. the `s :' (`calc-assign') [`assign'] command which takes a variable and
  2199. value from the stack and replaces them with an assignment.
  2200. *Note TeX and LaTeX Language Modes::, for the way `=>' appears in
  2201. TeX language output. The "eqn" mode gives similar treatment to `=>'.
  2202. 
  2203. File: calc, Node: Graphics, Next: Kill and Yank, Prev: Store and Recall, Up: Top
  2204. 15 Graphics
  2205. ***********
  2206. The commands for graphing data begin with the `g' prefix key. Calc
  2207. uses GNUPLOT 2.0 or later to do graphics. These commands will only work
  2208. if GNUPLOT is available on your system. (While GNUPLOT sounds like a
  2209. relative of GNU Emacs, it is actually completely unrelated. However,
  2210. it is free software. It can be obtained from
  2211. `http://www.gnuplot.info'.)
  2212. If you have GNUPLOT installed on your system but Calc is unable to
  2213. find it, you may need to set the `calc-gnuplot-name' variable in your
  2214. Calc init file or `.emacs'. You may also need to set some Lisp
  2215. variables to show Calc how to run GNUPLOT on your system; these are
  2216. described under `g D' and `g O' below. If you are using the X window
  2217. system or MS-Windows, Calc will configure GNUPLOT for you
  2218. automatically. If you have GNUPLOT 3.0 or later and you are using a
  2219. Unix or GNU system without X, Calc will configure GNUPLOT to display
  2220. graphs using simple character graphics that will work on any
  2221. Posix-compatible terminal.
  2222. * Menu:
  2223. * Basic Graphics::
  2224. * Three Dimensional Graphics::
  2225. * Managing Curves::
  2226. * Graphics Options::
  2227. * Devices::
  2228. 
  2229. File: calc, Node: Basic Graphics, Next: Three Dimensional Graphics, Prev: Graphics, Up: Graphics
  2230. 15.1 Basic Graphics
  2231. ===================
  2232. The easiest graphics command is `g f' (`calc-graph-fast'). This
  2233. command takes two vectors of equal length from the stack. The vector
  2234. at the top of the stack represents the "y" values of the various data
  2235. points. The vector in the second-to-top position represents the
  2236. corresponding "x" values. This command runs GNUPLOT (if it has not
  2237. already been started by previous graphing commands) and displays the
  2238. set of data points. The points will be connected by lines, and there
  2239. will also be some kind of symbol to indicate the points themselves.
  2240. The "x" entry may instead be an interval form, in which case suitable
  2241. "x" values are interpolated between the minimum and maximum values of
  2242. the interval (whether the interval is open or closed is ignored).
  2243. The "x" entry may also be a number, in which case Calc uses the
  2244. sequence of "x" values `x', `x+1', `x+2', etc. (Generally the number 0
  2245. or 1 would be used for `x' in this case.)
  2246. The "y" entry may be any formula instead of a vector. Calc
  2247. effectively uses `N' (`calc-eval-num') to evaluate variables in the
  2248. formula; the result of this must be a formula in a single (unassigned)
  2249. variable. The formula is plotted with this variable taking on the
  2250. various "x" values. Graphs of formulas by default use lines without
  2251. symbols at the computed data points. Note that if neither "x" nor "y"
  2252. is a vector, Calc guesses at a reasonable number of data points to use.
  2253. See the `g N' command below. (The "x" values must be either a vector
  2254. or an interval if "y" is a formula.)
  2255. If "y" is (or evaluates to) a formula of the form `xy(X, Y)' then
  2256. the result is a parametric plot. The two arguments of the fictitious
  2257. `xy' function are used as the "x" and "y" coordinates of the curve,
  2258. respectively. In this case the "x" vector or interval you specified is
  2259. not directly visible in the graph. For example, if "x" is the interval
  2260. `[0..360]' and "y" is the formula `xy(sin(t), cos(t))', the resulting
  2261. graph will be a circle.
  2262. Also, "x" and "y" may each be variable names, in which case Calc
  2263. looks for suitable vectors, intervals, or formulas stored in those
  2264. variables.
  2265. The "x" and "y" values for the data points (as pulled from the
  2266. vectors, calculated from the formulas, or interpolated from the
  2267. intervals) should be real numbers (integers, fractions, or floats).
  2268. One exception to this is that the "y" entry can consist of a vector of
  2269. numbers combined with error forms, in which case the points will be
  2270. plotted with the appropriate error bars. Other than this, if either
  2271. the "x" value or the "y" value of a given data point is not a real
  2272. number, that data point will be omitted from the graph. The points on
  2273. either side of the invalid point will _not_ be connected by a line.
  2274. See the documentation for `g a' below for a description of the way
  2275. numeric prefix arguments affect `g f'.
  2276. If you store an empty vector in the variable `PlotRejects' (i.e., `[
  2277. ] s t PlotRejects'), Calc will append information to this vector for
  2278. every data point which was rejected because its "x" or "y" values were
  2279. not real numbers. The result will be a matrix where each row holds the
  2280. curve number, data point number, "x" value, and "y" value for a
  2281. rejected data point. *Note Evaluates-To Operator::, for a handy way to
  2282. keep tabs on the current value of `PlotRejects'. *Note Operations on
  2283. Variables::, for the `s R' command which is another easy way to examine
  2284. `PlotRejects'.
  2285. To clear the graphics display, type `g c' (`calc-graph-clear'). If
  2286. the GNUPLOT output device is an X window, the window will go away.
  2287. Effects on other kinds of output devices will vary. You don't need to
  2288. use `g c' if you don't want to--if you give another `g f' or `g p'
  2289. command later on, it will reuse the existing graphics window if there
  2290. is one.
  2291. 
  2292. File: calc, Node: Three Dimensional Graphics, Next: Managing Curves, Prev: Basic Graphics, Up: Graphics
  2293. 15.2 Three-Dimensional Graphics
  2294. ===============================
  2295. The `g F' (`calc-graph-fast-3d') command makes a three-dimensional
  2296. graph. It works only if you have GNUPLOT 3.0 or later; with GNUPLOT
  2297. 2.0, you will see a GNUPLOT error message if you try this command.
  2298. The `g F' command takes three values from the stack, called "x",
  2299. "y", and "z", respectively. As was the case for 2D graphs, there are
  2300. several options for these values.
  2301. In the first case, "x" and "y" are each vectors (not necessarily of
  2302. the same length); either or both may instead be interval forms. The
  2303. "z" value must be a matrix with the same number of rows as elements in
  2304. "x", and the same number of columns as elements in "y". The result is
  2305. a surface plot where `z_ij' is the height of the point at coordinate
  2306. `(x_i, y_j)' on the surface. The 3D graph will be displayed from a
  2307. certain default viewpoint; you can change this viewpoint by adding a
  2308. `set view' to the `*Gnuplot Commands*' buffer as described later. See
  2309. the GNUPLOT documentation for a description of the `set view' command.
  2310. Each point in the matrix will be displayed as a dot in the graph,
  2311. and these points will be connected by a grid of lines ("isolines").
  2312. In the second case, "x", "y", and "z" are all vectors of equal
  2313. length. The resulting graph displays a 3D line instead of a surface,
  2314. where the coordinates of points along the line are successive triplets
  2315. of values from the input vectors.
  2316. In the third case, "x" and "y" are vectors or interval forms, and
  2317. "z" is any formula involving two variables (not counting variables with
  2318. assigned values). These variables are sorted into alphabetical order;
  2319. the first takes on values from "x" and the second takes on values from
  2320. "y" to form a matrix of results that are graphed as a 3D surface.
  2321. If the "z" formula evaluates to a call to the fictitious function
  2322. `xyz(X, Y, Z)', then the result is a "parametric surface." In this
  2323. case, the axes of the graph are taken from the X and Y values in these
  2324. calls, and the "x" and "y" values from the input vectors or intervals
  2325. are used only to specify the range of inputs to the formula. For
  2326. example, plotting `[0..360], [0..180], xyz(sin(x)*sin(y),
  2327. cos(x)*sin(y), cos(y))' will draw a sphere. (Since the default
  2328. resolution for 3D plots is 5 steps in each of "x" and "y", this will
  2329. draw a very crude sphere. You could use the `g N' command, described
  2330. below, to increase this resolution, or specify the "x" and "y" values as
  2331. vectors with more than 5 elements.
  2332. It is also possible to have a function in a regular `g f' plot
  2333. evaluate to an `xyz' call. Since `g f' plots a line, not a surface,
  2334. the result will be a 3D parametric line. For example, `[[0..720],
  2335. xyz(sin(x), cos(x), x)]' will plot two turns of a helix (a
  2336. three-dimensional spiral).
  2337. As for `g f', each of "x", "y", and "z" may instead be variables
  2338. containing the relevant data.
  2339. 
  2340. File: calc, Node: Managing Curves, Next: Graphics Options, Prev: Three Dimensional Graphics, Up: Graphics
  2341. 15.3 Managing Curves
  2342. ====================
  2343. The `g f' command is really shorthand for the following commands: `C-u
  2344. g d g a g p'. Likewise, `g F' is shorthand for `C-u g d g A g p'.
  2345. You can gain more control over your graph by using these commands
  2346. directly.
  2347. The `g a' (`calc-graph-add') command adds the "curve" represented by
  2348. the two values on the top of the stack to the current graph. You can
  2349. have any number of curves in the same graph. When you give the `g p'
  2350. command, all the curves will be drawn superimposed on the same axes.
  2351. The `g a' command (and many others that affect the current graph)
  2352. will cause a special buffer, `*Gnuplot Commands*', to be displayed in
  2353. another window. This buffer is a template of the commands that will be
  2354. sent to GNUPLOT when it is time to draw the graph. The first `g a'
  2355. command adds a `plot' command to this buffer. Succeeding `g a'
  2356. commands add extra curves onto that `plot' command. Other
  2357. graph-related commands put other GNUPLOT commands into this buffer. In
  2358. normal usage you never need to work with this buffer directly, but you
  2359. can if you wish. The only constraint is that there must be only one
  2360. `plot' command, and it must be the last command in the buffer. If you
  2361. want to save and later restore a complete graph configuration, you can
  2362. use regular Emacs commands to save and restore the contents of the
  2363. `*Gnuplot Commands*' buffer.
  2364. If the values on the stack are not variable names, `g a' will invent
  2365. variable names for them (of the form `PlotDataN') and store the values
  2366. in those variables. The "x" and "y" variables are what go into the
  2367. `plot' command in the template. If you add a curve that uses a certain
  2368. variable and then later change that variable, you can replot the graph
  2369. without having to delete and re-add the curve. That's because the
  2370. variable name, not the vector, interval or formula itself, is what was
  2371. added by `g a'.
  2372. A numeric prefix argument on `g a' or `g f' changes the way stack
  2373. entries are interpreted as curves. With a positive prefix argument
  2374. `n', the top `n' stack entries are "y" values for `n' different curves
  2375. which share a common "x" value in the `n+1'st stack entry. (Thus `g a'
  2376. with no prefix argument is equivalent to `C-u 1 g a'.)
  2377. A prefix of zero or plain `C-u' means to take two stack entries, "x"
  2378. and "y" as usual, but to interpret "y" as a vector of "y" values for
  2379. several curves that share a common "x".
  2380. A negative prefix argument tells Calc to read `n' vectors from the
  2381. stack; each vector `[x, y]' describes an independent curve. This is
  2382. the only form of `g a' that creates several curves at once that don't
  2383. have common "x" values. (Of course, the range of "x" values covered by
  2384. all the curves ought to be roughly the same if they are to look nice on
  2385. the same graph.)
  2386. For example, to plot `sin(n x)' for integers `n' from 1 to 5, you
  2387. could use `v x' to create a vector of integers (`n'), then `V M '' or
  2388. `V M $' to map `sin(n x)' across this vector. The resulting vector of
  2389. formulas is suitable for use as the "y" argument to a `C-u g a' or `C-u
  2390. g f' command.
  2391. The `g A' (`calc-graph-add-3d') command adds a 3D curve to the
  2392. graph. It is not valid to intermix 2D and 3D curves in a single graph.
  2393. This command takes three arguments, "x", "y", and "z", from the stack.
  2394. With a positive prefix `n', it takes `n+2' arguments (common "x" and
  2395. "y", plus `n' separate "z"s). With a zero prefix, it takes three stack
  2396. entries but the "z" entry is a vector of curve values. With a negative
  2397. prefix `-n', it takes `n' vectors of the form `[x, y, z]'. The `g A'
  2398. command works by adding a `splot' (surface-plot) command to the
  2399. `*Gnuplot Commands*' buffer.
  2400. (Although `g a' adds a 2D `plot' command to the `*Gnuplot Commands*'
  2401. buffer, Calc changes this to `splot' before sending it to GNUPLOT if it
  2402. notices that the data points are evaluating to `xyz' calls. It will
  2403. not work to mix 2D and 3D `g a' curves in a single graph, although Calc
  2404. does not currently check for this.)
  2405. The `g d' (`calc-graph-delete') command deletes the most recently
  2406. added curve from the graph. It has no effect if there are no curves in
  2407. the graph. With a numeric prefix argument of any kind, it deletes all
  2408. of the curves from the graph.
  2409. The `g H' (`calc-graph-hide') command "hides" or "unhides" the most
  2410. recently added curve. A hidden curve will not appear in the actual
  2411. plot, but information about it such as its name and line and point
  2412. styles will be retained.
  2413. The `g j' (`calc-graph-juggle') command moves the curve at the end
  2414. of the list (the "most recently added curve") to the front of the list.
  2415. The next-most-recent curve is thus exposed for `g d' or similar
  2416. commands to use. With `g j' you can work with any curve in the graph
  2417. even though curve-related commands only affect the last curve in the
  2418. list.
  2419. The `g p' (`calc-graph-plot') command uses GNUPLOT to draw the graph
  2420. described in the `*Gnuplot Commands*' buffer. Any GNUPLOT parameters
  2421. which are not defined by commands in this buffer are reset to their
  2422. default values. The variables named in the `plot' command are written
  2423. to a temporary data file and the variable names are then replaced by
  2424. the file name in the template. The resulting plotting commands are fed
  2425. to the GNUPLOT program. See the documentation for the GNUPLOT program
  2426. for more specific information. All temporary files are removed when
  2427. Emacs or GNUPLOT exits.
  2428. If you give a formula for "y", Calc will remember all the values that
  2429. it calculates for the formula so that later plots can reuse these
  2430. values. Calc throws out these saved values when you change any
  2431. circumstances that may affect the data, such as switching from Degrees
  2432. to Radians mode, or changing the value of a parameter in the formula.
  2433. You can force Calc to recompute the data from scratch by giving a
  2434. negative numeric prefix argument to `g p'.
  2435. Calc uses a fairly rough step size when graphing formulas over
  2436. intervals. This is to ensure quick response. You can "refine" a plot
  2437. by giving a positive numeric prefix argument to `g p'. Calc goes
  2438. through the data points it has computed and saved from previous plots
  2439. of the function, and computes and inserts a new data point midway
  2440. between each of the existing points. You can refine a plot any number
  2441. of times, but beware that the amount of calculation involved doubles
  2442. each time.
  2443. Calc does not remember computed values for 3D graphs. This means the
  2444. numerix prefix argument, if any, to `g p' is effectively ignored if the
  2445. current graph is three-dimensional.
  2446. The `g P' (`calc-graph-print') command is like `g p', except that it
  2447. sends the output to a printer instead of to the screen. More
  2448. precisely, `g p' looks for `set terminal' or `set output' commands in
  2449. the `*Gnuplot Commands*' buffer; lacking these it uses the default
  2450. settings. However, `g P' ignores `set terminal' and `set output'
  2451. commands and uses a different set of default values. All of these
  2452. values are controlled by the `g D' and `g O' commands discussed below.
  2453. Provided everything is set up properly, `g p' will plot to the screen
  2454. unless you have specified otherwise and `g P' will always plot to the
  2455. printer.
  2456. 
  2457. File: calc, Node: Graphics Options, Next: Devices, Prev: Managing Curves, Up: Graphics
  2458. 15.4 Graphics Options
  2459. =====================
  2460. The `g g' (`calc-graph-grid') command turns the "grid" on and off. It
  2461. is off by default; tick marks appear only at the edges of the graph.
  2462. With the grid turned on, dotted lines appear across the graph at each
  2463. tick mark. Note that this command only changes the setting in
  2464. `*Gnuplot Commands*'; to see the effects of the change you must give
  2465. another `g p' command.
  2466. The `g b' (`calc-graph-border') command turns the border (the box
  2467. that surrounds the graph) on and off. It is on by default. This
  2468. command will only work with GNUPLOT 3.0 and later versions.
  2469. The `g k' (`calc-graph-key') command turns the "key" on and off.
  2470. The key is a chart in the corner of the graph that shows the
  2471. correspondence between curves and line styles. It is off by default,
  2472. and is only really useful if you have several curves on the same graph.
  2473. The `g N' (`calc-graph-num-points') command allows you to select the
  2474. number of data points in the graph. This only affects curves where
  2475. neither "x" nor "y" is specified as a vector. Enter a blank line to
  2476. revert to the default value (initially 15). With no prefix argument,
  2477. this command affects only the current graph. With a positive prefix
  2478. argument this command changes or, if you enter a blank line, displays
  2479. the default number of points used for all graphs created by `g a' that
  2480. don't specify the resolution explicitly. With a negative prefix
  2481. argument, this command changes or displays the default value (initially
  2482. 5) used for 3D graphs created by `g A'. Note that a 3D setting of 5
  2483. means that a total of `5^2 = 25' points will be computed for the
  2484. surface.
  2485. Data values in the graph of a function are normally computed to a
  2486. precision of five digits, regardless of the current precision at the
  2487. time. This is usually more than adequate, but there are cases where it
  2488. will not be. For example, plotting `1 + x' with `x' in the interval
  2489. `[0 .. 1e-6]' will round all the data points down to 1.0! Putting the
  2490. command `set precision N' in the `*Gnuplot Commands*' buffer will cause
  2491. the data to be computed at precision N instead of 5. Since this is
  2492. such a rare case, there is no keystroke-based command to set the
  2493. precision.
  2494. The `g h' (`calc-graph-header') command sets the title for the
  2495. graph. This will show up centered above the graph. The default title
  2496. is blank (no title).
  2497. The `g n' (`calc-graph-name') command sets the title of an
  2498. individual curve. Like the other curve-manipulating commands, it
  2499. affects the most recently added curve, i.e., the last curve on the list
  2500. in the `*Gnuplot Commands*' buffer. To set the title of the other
  2501. curves you must first juggle them to the end of the list with `g j', or
  2502. edit the `*Gnuplot Commands*' buffer by hand. Curve titles appear in
  2503. the key; if the key is turned off they are not used.
  2504. The `g t' (`calc-graph-title-x') and `g T' (`calc-graph-title-y')
  2505. commands set the titles on the "x" and "y" axes, respectively. These
  2506. titles appear next to the tick marks on the left and bottom edges of
  2507. the graph, respectively. Calc does not have commands to control the
  2508. tick marks themselves, but you can edit them into the `*Gnuplot
  2509. Commands*' buffer if you wish. See the GNUPLOT documentation for
  2510. details.
  2511. The `g r' (`calc-graph-range-x') and `g R' (`calc-graph-range-y')
  2512. commands set the range of values on the "x" and "y" axes, respectively.
  2513. You are prompted to enter a suitable range. This should be either a
  2514. pair of numbers of the form, `MIN:MAX', or a blank line to revert to the
  2515. default behavior of setting the range based on the range of values in
  2516. the data, or `$' to take the range from the top of the stack. Ranges
  2517. on the stack can be represented as either interval forms or vectors:
  2518. `[MIN .. MAX]' or `[MIN, MAX]'.
  2519. The `g l' (`calc-graph-log-x') and `g L' (`calc-graph-log-y')
  2520. commands allow you to set either or both of the axes of the graph to be
  2521. logarithmic instead of linear.
  2522. For 3D plots, `g C-t', `g C-r', and `g C-l' (those are letters with
  2523. the Control key held down) are the corresponding commands for the "z"
  2524. axis.
  2525. The `g z' (`calc-graph-zero-x') and `g Z' (`calc-graph-zero-y')
  2526. commands control whether a dotted line is drawn to indicate the "x"
  2527. and/or "y" zero axes. (These are the same dotted lines that would be
  2528. drawn there anyway if you used `g g' to turn the "grid" feature on.)
  2529. Zero-axis lines are on by default, and may be turned off only in
  2530. GNUPLOT 3.0 and later versions. They are not available for 3D plots.
  2531. The `g s' (`calc-graph-line-style') command turns the connecting
  2532. lines on or off for the most recently added curve, and optionally
  2533. selects the style of lines to be used for that curve. Plain `g s'
  2534. simply toggles the lines on and off. With a numeric prefix argument,
  2535. `g s' turns lines on and sets a particular line style. Line style
  2536. numbers start at one and their meanings vary depending on the output
  2537. device. GNUPLOT guarantees that there will be at least six different
  2538. line styles available for any device.
  2539. The `g S' (`calc-graph-point-style') command similarly turns the
  2540. symbols at the data points on or off, or sets the point style. If you
  2541. turn both lines and points off, the data points will show as tiny dots.
  2542. If the "y" values being plotted contain error forms and the connecting
  2543. lines are turned off, then this command will also turn the error bars
  2544. on or off.
  2545. Another way to specify curve styles is with the `LineStyles' and
  2546. `PointStyles' variables. These variables initially have no stored
  2547. values, but if you store a vector of integers in one of these variables,
  2548. the `g a' and `g f' commands will use those style numbers instead of
  2549. the defaults for new curves that are added to the graph. An entry
  2550. should be a positive integer for a specific style, or 0 to let the
  2551. style be chosen automatically, or -1 to turn off lines or points
  2552. altogether. If there are more curves than elements in the vector, the
  2553. last few curves will continue to have the default styles. Of course,
  2554. you can later use `g s' and `g S' to change any of these styles.
  2555. For example, `'[2 -1 3] <RET> s t LineStyles' causes the first curve
  2556. to have lines in style number 2, the second curve to have no connecting
  2557. lines, and the third curve to have lines in style 3. Point styles will
  2558. still be assigned automatically, but you could store another vector in
  2559. `PointStyles' to define them, too.
  2560. 
  2561. File: calc, Node: Devices, Prev: Graphics Options, Up: Graphics
  2562. 15.5 Graphical Devices
  2563. ======================
  2564. The `g D' (`calc-graph-device') command sets the device name (or
  2565. "terminal name" in GNUPLOT lingo) to be used by `g p' commands on this
  2566. graph. It does not affect the permanent default device name. If you
  2567. enter a blank name, the device name reverts to the default. Enter `?'
  2568. to see a list of supported devices.
  2569. With a positive numeric prefix argument, `g D' instead sets the
  2570. default device name, used by all plots in the future which do not
  2571. override it with a plain `g D' command. If you enter a blank line this
  2572. command shows you the current default. The special name `default'
  2573. signifies that Calc should choose `x11' if the X window system is in
  2574. use (as indicated by the presence of a `DISPLAY' environment variable),
  2575. `windows' on MS-Windows, or otherwise `dumb' under GNUPLOT 3.0 and
  2576. later, or `postscript' under GNUPLOT 2.0. This is the initial default
  2577. value.
  2578. The `dumb' device is an interface to "dumb terminals," i.e.,
  2579. terminals with no special graphics facilities. It writes a crude
  2580. picture of the graph composed of characters like `-' and `|' to a
  2581. buffer called `*Gnuplot Trail*', which Calc then displays. The graph
  2582. is made the same size as the Emacs screen, which on most dumb terminals
  2583. will be 80x24 characters. The graph is displayed in an Emacs
  2584. "recursive edit"; type `q' or `C-c C-c' to exit the recursive edit and
  2585. return to Calc. Note that the `dumb' device is present only in GNUPLOT
  2586. 3.0 and later versions.
  2587. The word `dumb' may be followed by two numbers separated by spaces.
  2588. These are the desired width and height of the graph in characters.
  2589. Also, the device name `big' is like `dumb' but creates a graph four
  2590. times the width and height of the Emacs screen. You will then have to
  2591. scroll around to view the entire graph. In the `*Gnuplot Trail*'
  2592. buffer, <SPC>, <DEL>, `<', and `>' are defined to scroll by one
  2593. screenful in each of the four directions.
  2594. With a negative numeric prefix argument, `g D' sets or displays the
  2595. device name used by `g P' (`calc-graph-print'). This is initially
  2596. `postscript'. If you don't have a PostScript printer, you may decide
  2597. once again to use `dumb' to create a plot on any text-only printer.
  2598. The `g O' (`calc-graph-output') command sets the name of the output
  2599. file used by GNUPLOT. For some devices, notably `x11' and `windows',
  2600. there is no output file and this information is not used. Many other
  2601. "devices" are really file formats like `postscript'; in these cases the
  2602. output in the desired format goes into the file you name with `g O'.
  2603. Type `g O stdout <RET>' to set GNUPLOT to write to its standard output
  2604. stream, i.e., to `*Gnuplot Trail*'. This is the default setting.
  2605. Another special output name is `tty', which means that GNUPLOT is
  2606. going to write graphics commands directly to its standard output, which
  2607. you wish Emacs to pass through to your terminal. Tektronix graphics
  2608. terminals, among other devices, operate this way. Calc does this by
  2609. telling GNUPLOT to write to a temporary file, then running a sub-shell
  2610. executing the command `cat tempfile >/dev/tty'. On typical Unix
  2611. systems, this will copy the temporary file directly to the terminal,
  2612. bypassing Emacs entirely. You will have to type `C-l' to Emacs
  2613. afterwards to refresh the screen.
  2614. Once again, `g O' with a positive or negative prefix argument sets
  2615. the default or printer output file names, respectively. In each case
  2616. you can specify `auto', which causes Calc to invent a temporary file
  2617. name for each `g p' (or `g P') command. This temporary file will be
  2618. deleted once it has been displayed or printed. If the output file name
  2619. is not `auto', the file is not automatically deleted.
  2620. The default and printer devices and output files can be saved
  2621. permanently by the `m m' (`calc-save-modes') command. The default
  2622. number of data points (see `g N') and the X geometry (see `g X') are
  2623. also saved. Other graph information is _not_ saved; you can save a
  2624. graph's configuration simply by saving the contents of the `*Gnuplot
  2625. Commands*' buffer.
  2626. You may wish to configure the default and printer devices and output
  2627. files for the whole system. The relevant Lisp variables are
  2628. `calc-gnuplot-default-device' and `-output', and
  2629. `calc-gnuplot-print-device' and `-output'. The output file names must
  2630. be either strings as described above, or Lisp expressions which are
  2631. evaluated on the fly to get the output file names.
  2632. Other important Lisp variables are `calc-gnuplot-plot-command' and
  2633. `calc-gnuplot-print-command', which give the system commands to display
  2634. or print the output of GNUPLOT, respectively. These may be `nil' if no
  2635. command is necessary, or strings which can include `%s' to signify the
  2636. name of the file to be displayed or printed. Or, these variables may
  2637. contain Lisp expressions which are evaluated to display or print the
  2638. output. These variables are customizable (*note Customizing Calc::).
  2639. The `g x' (`calc-graph-display') command lets you specify on which X
  2640. window system display your graphs should be drawn. Enter a blank line
  2641. to see the current display name. This command has no effect unless the
  2642. current device is `x11'.
  2643. The `g X' (`calc-graph-geometry') command is a similar command for
  2644. specifying the position and size of the X window. The normal value is
  2645. `default', which generally means your window manager will let you place
  2646. the window interactively. Entering `800x500+0+0' would create an
  2647. 800-by-500 pixel window in the upper-left corner of the screen. This
  2648. command has no effect if the current device is `windows'.
  2649. The buffer called `*Gnuplot Trail*' holds a transcript of the
  2650. session with GNUPLOT. This shows the commands Calc has "typed" to
  2651. GNUPLOT and the responses it has received. Calc tries to notice when an
  2652. error message has appeared here and display the buffer for you when
  2653. this happens. You can check this buffer yourself if you suspect
  2654. something has gone wrong(1).
  2655. The `g C' (`calc-graph-command') command prompts you to enter any
  2656. line of text, then simply sends that line to the current GNUPLOT
  2657. process. The `*Gnuplot Trail*' buffer looks deceptively like a Shell
  2658. buffer but you can't type commands in it yourself. Instead, you must
  2659. use `g C' for this purpose.
  2660. The `g v' (`calc-graph-view-commands') and `g V'
  2661. (`calc-graph-view-trail') commands display the `*Gnuplot Commands*' and
  2662. `*Gnuplot Trail*' buffers, respectively, in another window. This
  2663. happens automatically when Calc thinks there is something you will want
  2664. to see in either of these buffers. If you type `g v' or `g V' when the
  2665. relevant buffer is already displayed, the buffer is hidden again.
  2666. (Note that on MS-Windows, the `*Gnuplot Trail*' buffer will usually
  2667. show nothing of interest, because GNUPLOT's responses are not
  2668. communicated back to Calc.)
  2669. One reason to use `g v' is to add your own commands to the `*Gnuplot
  2670. Commands*' buffer. Press `g v', then use `C-x o' to switch into that
  2671. window. For example, GNUPLOT has `set label' and `set arrow' commands
  2672. that allow you to annotate your plots. Since Calc doesn't understand
  2673. these commands, you have to add them to the `*Gnuplot Commands*' buffer
  2674. yourself, then use `g p' to replot using these new commands. Note that
  2675. your commands must appear _before_ the `plot' command. To get help on
  2676. any GNUPLOT feature, type, e.g., `g C help set label'. You may have to
  2677. type `g C <RET>' a few times to clear the "press return for more" or
  2678. "subtopic of ..." requests. Note that Calc always sends commands (like
  2679. `set nolabel') to reset all plotting parameters to the defaults before
  2680. each plot, so to delete a label all you need to do is delete the `set
  2681. label' line you added (or comment it out with `#') and then replot with
  2682. `g p'.
  2683. You can use `g q' (`calc-graph-quit') to kill the GNUPLOT process
  2684. that is running. The next graphing command you give will start a fresh
  2685. GNUPLOT process. The word `Graph' appears in the Calc window's mode
  2686. line whenever a GNUPLOT process is currently running. The GNUPLOT
  2687. process is automatically killed when you exit Emacs if you haven't
  2688. killed it manually by then.
  2689. The `g K' (`calc-graph-kill') command is like `g q' except that it
  2690. also views the `*Gnuplot Trail*' buffer so that you can see the process
  2691. being killed. This is better if you are killing GNUPLOT because you
  2692. think it has gotten stuck.
  2693. ---------- Footnotes ----------
  2694. (1) On MS-Windows, due to the peculiarities of how the Windows
  2695. version of GNUPLOT (called `wgnuplot') works, the GNUPLOT responses are
  2696. not communicated back to Calc. Instead, you need to look them up in
  2697. the GNUPLOT command window that is displayed as in normal interactive
  2698. usage of GNUPLOT.
  2699. 
  2700. File: calc, Node: Kill and Yank, Next: Keypad Mode, Prev: Graphics, Up: Top
  2701. 16 Kill and Yank Functions
  2702. **************************
  2703. The commands in this chapter move information between the Calculator and
  2704. other Emacs editing buffers.
  2705. In many cases Embedded mode is an easier and more natural way to
  2706. work with Calc from a regular editing buffer. *Note Embedded Mode::.
  2707. * Menu:
  2708. * Killing From Stack::
  2709. * Yanking Into Stack::
  2710. * Saving Into Registers::
  2711. * Inserting From Registers::
  2712. * Grabbing From Buffers::
  2713. * Yanking Into Buffers::
  2714. * X Cut and Paste::
  2715. 
  2716. File: calc, Node: Killing From Stack, Next: Yanking Into Stack, Prev: Kill and Yank, Up: Kill and Yank
  2717. 16.1 Killing from the Stack
  2718. ===========================
  2719. "Kill" commands are Emacs commands that insert text into the "kill
  2720. ring," from which it can later be "yanked" by a `C-y' command. Three
  2721. common kill commands in normal Emacs are `C-k', which kills one line,
  2722. `C-w', which kills the region between mark and point, and `M-w', which
  2723. puts the region into the kill ring without actually deleting it. All
  2724. of these commands work in the Calculator, too, although in the
  2725. Calculator they operate on whole stack entries, so they "round up" the
  2726. specified region to encompass full lines. (To copy only parts of
  2727. lines, the `M-C-w' command in the Calculator will copy the region to
  2728. the kill ring without any "rounding up", just like the `M-w' command in
  2729. normal Emacs.) Also, `M-k' has been provided to complete the set; it
  2730. puts the current line into the kill ring without deleting anything.
  2731. The kill commands are unusual in that they pay attention to the
  2732. location of the cursor in the Calculator buffer. If the cursor is on
  2733. or below the bottom line, the kill commands operate on the top of the
  2734. stack. Otherwise, they operate on whatever stack element the cursor is
  2735. on. The text is copied into the kill ring exactly as it appears on the
  2736. screen, including line numbers if they are enabled.
  2737. A numeric prefix argument to `C-k' or `M-k' affects the number of
  2738. lines killed. A positive argument kills the current line and `n-1'
  2739. lines below it. A negative argument kills the `-n' lines above the
  2740. current line. Again this mirrors the behavior of the standard Emacs
  2741. `C-k' command. Although a whole line is always deleted, `C-k' with no
  2742. argument copies only the number itself into the kill ring, whereas
  2743. `C-k' with a prefix argument of 1 copies the number with its trailing
  2744. newline.
  2745. 
  2746. File: calc, Node: Yanking Into Stack, Next: Saving Into Registers, Prev: Killing From Stack, Up: Kill and Yank
  2747. 16.2 Yanking into the Stack
  2748. ===========================
  2749. The `C-y' command yanks the most recently killed text back into the
  2750. Calculator. It pushes this value onto the top of the stack regardless
  2751. of the cursor position. In general it re-parses the killed text as a
  2752. number or formula (or a list of these separated by commas or newlines).
  2753. However if the thing being yanked is something that was just killed
  2754. from the Calculator itself, its full internal structure is yanked. For
  2755. example, if you have set the floating-point display mode to show only
  2756. four significant digits, then killing and re-yanking 3.14159 (which
  2757. displays as 3.142) will yank the full 3.14159, even though yanking it
  2758. into any other buffer would yank the number in its displayed form,
  2759. 3.142. (Since the default display modes show all objects to their full
  2760. precision, this feature normally makes no difference.)
  2761. 
  2762. File: calc, Node: Saving Into Registers, Next: Inserting From Registers, Prev: Yanking Into Stack, Up: Kill and Yank
  2763. 16.3 Saving into Registers
  2764. ==========================
  2765. An alternative to killing and yanking stack entries is using registers
  2766. in Calc. Saving stack entries in registers is like saving text in
  2767. normal Emacs registers; although, like Calc's kill commands, register
  2768. commands always operate on whole stack entries.
  2769. Registers in Calc are places to store stack entries for later use;
  2770. each register is indexed by a single character. To store the current
  2771. region (rounded up, of course, to include full stack entries) into a
  2772. register, use the command `r s' (`calc-copy-to-register'). You will
  2773. then be prompted for a register to use, the next character you type
  2774. will be the index for the register. To store the region in register R,
  2775. the full command will be `r s R'. With an argument, `C-u r s R', the
  2776. region being copied to the register will be deleted from the Calc
  2777. buffer.
  2778. It is possible to add additional stack entries to a register. The
  2779. command `M-x calc-append-to-register' will prompt for a register, then
  2780. add the stack entries in the region to the end of the register
  2781. contents. The command `M-x calc-prepend-to-register' will similarly
  2782. prompt for a register and add the stack entries in the region to the
  2783. beginning of the register contents. Both commands take `C-u'
  2784. arguments, which will cause the region to be deleted after being added
  2785. to the register.
  2786. 
  2787. File: calc, Node: Inserting From Registers, Next: Grabbing From Buffers, Prev: Saving Into Registers, Up: Kill and Yank
  2788. 16.4 Inserting from Registers
  2789. =============================
  2790. The command `r i' (`calc-insert-register') will prompt for a register,
  2791. then insert the contents of that register into the Calculator. If the
  2792. contents of the register were placed there from within Calc, then the
  2793. full internal structure of the contents will be inserted into the
  2794. Calculator, otherwise whatever text is in the register is reparsed and
  2795. then inserted into the Calculator.
  2796. 
  2797. File: calc, Node: Grabbing From Buffers, Next: Yanking Into Buffers, Prev: Inserting From Registers, Up: Kill and Yank
  2798. 16.5 Grabbing from Other Buffers
  2799. ================================
  2800. The `C-x * g' (`calc-grab-region') command takes the text between point
  2801. and mark in the current buffer and attempts to parse it as a vector of
  2802. values. Basically, it wraps the text in vector brackets `[ ]' unless
  2803. the text already is enclosed in vector brackets, then reads the text as
  2804. if it were an algebraic entry. The contents of the vector may be
  2805. numbers, formulas, or any other Calc objects. If the `C-x * g' command
  2806. works successfully, it does an automatic `C-x * c' to enter the
  2807. Calculator buffer.
  2808. A numeric prefix argument grabs the specified number of lines around
  2809. point, ignoring the mark. A positive prefix grabs from point to the
  2810. `n'th following newline (so that `M-1 C-x * g' grabs from point to the
  2811. end of the current line); a negative prefix grabs from point back to
  2812. the `n+1'st preceding newline. In these cases the text that is grabbed
  2813. is exactly the same as the text that `C-k' would delete given that
  2814. prefix argument.
  2815. A prefix of zero grabs the current line; point may be anywhere on the
  2816. line.
  2817. A plain `C-u' prefix interprets the region between point and mark as
  2818. a single number or formula rather than a vector. For example, `C-x *
  2819. g' on the text `2 a b' produces the vector of three values `[2, a, b]',
  2820. but `C-u C-x * g' on the same region reads a formula which is a product
  2821. of three things: `2 a b'. (The text `a + b', on the other hand, will
  2822. be grabbed as a vector of one element by plain `C-x * g' because the
  2823. interpretation `[a, +, b]' would be a syntax error.)
  2824. If a different language has been specified (*note Language Modes::),
  2825. the grabbed text will be interpreted according to that language.
  2826. The `C-x * r' (`calc-grab-rectangle') command takes the text between
  2827. point and mark and attempts to parse it as a matrix. If point and mark
  2828. are both in the leftmost column, the lines in between are parsed in
  2829. their entirety. Otherwise, point and mark define the corners of a
  2830. rectangle whose contents are parsed.
  2831. Each line of the grabbed area becomes a row of the matrix. The
  2832. result will actually be a vector of vectors, which Calc will treat as a
  2833. matrix only if every row contains the same number of values.
  2834. If a line contains a portion surrounded by square brackets (or curly
  2835. braces), that portion is interpreted as a vector which becomes a row of
  2836. the matrix. Any text surrounding the bracketed portion on the line is
  2837. ignored.
  2838. Otherwise, the entire line is interpreted as a row vector as if it
  2839. were surrounded by square brackets. Leading line numbers (in the
  2840. format used in the Calc stack buffer) are ignored. If you wish to
  2841. force this interpretation (even if the line contains bracketed
  2842. portions), give a negative numeric prefix argument to the `C-x * r'
  2843. command.
  2844. If you give a numeric prefix argument of zero or plain `C-u', each
  2845. line is instead interpreted as a single formula which is converted into
  2846. a one-element vector. Thus the result of `C-u C-x * r' will be a
  2847. one-column matrix. For example, suppose one line of the data is the
  2848. expression `2 a'. A plain `C-x * r' will interpret this as `[2 a]',
  2849. which in turn is read as a two-element vector that forms one row of the
  2850. matrix. But a `C-u C-x * r' will interpret this row as `[2*a]'.
  2851. If you give a positive numeric prefix argument N, then each line
  2852. will be split up into columns of width N; each column is parsed
  2853. separately as a matrix element. If a line contained `2 +/- 3 4 +/- 5',
  2854. then grabbing with a prefix argument of 8 would correctly split the
  2855. line into two error forms.
  2856. *Note Matrix Functions::, to see how to pull the matrix apart into
  2857. its constituent rows and columns. (If it is a 1x1 matrix, just hit `v
  2858. u' (`calc-unpack') twice.)
  2859. The `C-x * :' (`calc-grab-sum-down') command is a handy way to grab
  2860. a rectangle of data and sum its columns. It is equivalent to typing
  2861. `C-x * r', followed by `V R : +' (the vector reduction command that
  2862. sums the columns of a matrix; *note Reducing::). The result of the
  2863. command will be a vector of numbers, one for each column in the input
  2864. data. The `C-x * _' (`calc-grab-sum-across') command similarly grabs a
  2865. rectangle and sums its rows by executing `V R _ +'.
  2866. As well as being more convenient, `C-x * :' and `C-x * _' are also
  2867. much faster because they don't actually place the grabbed vector on the
  2868. stack. In a `C-x * r V R : +' sequence, formatting the vector for
  2869. display on the stack takes a large fraction of the total time (unless
  2870. you have planned ahead and used `v .' and `t .' modes).
  2871. For example, suppose we have a column of numbers in a file which we
  2872. wish to sum. Go to one corner of the column and press `C-@' to set the
  2873. mark; go to the other corner and type `C-x * :'. Since there is only
  2874. one column, the result will be a vector of one number, the sum. (You
  2875. can type `v u' to unpack this vector into a plain number if you want to
  2876. do further arithmetic with it.)
  2877. To compute the product of the column of numbers, we would have to do
  2878. it "by hand" since there's no special grab-and-multiply command. Use
  2879. `C-x * r' to grab the column of numbers into the calculator in the form
  2880. of a column matrix. The statistics command `u *' is a handy way to
  2881. find the product of a vector or matrix of numbers. *Note Statistical
  2882. Operations::. Another approach would be to use an explicit column
  2883. reduction command, `V R : *'.
  2884. 
  2885. File: calc, Node: Yanking Into Buffers, Next: X Cut and Paste, Prev: Grabbing From Buffers, Up: Kill and Yank
  2886. 16.6 Yanking into Other Buffers
  2887. ===============================
  2888. The plain `y' (`calc-copy-to-buffer') command inserts the number at the
  2889. top of the stack into the most recently used normal editing buffer.
  2890. (More specifically, this is the most recently used buffer which is
  2891. displayed in a window and whose name does not begin with `*'. If there
  2892. is no such buffer, this is the most recently used buffer except for
  2893. Calculator and Calc Trail buffers.) The number is inserted exactly as
  2894. it appears and without a newline. (If line-numbering is enabled, the
  2895. line number is normally not included.) The number is _not_ removed
  2896. from the stack.
  2897. With a prefix argument, `y' inserts several numbers, one per line.
  2898. A positive argument inserts the specified number of values from the top
  2899. of the stack. A negative argument inserts the `n'th value from the top
  2900. of the stack. An argument of zero inserts the entire stack. Note that
  2901. `y' with an argument of 1 is slightly different from `y' with no
  2902. argument; the former always copies full lines, whereas the latter
  2903. strips off the trailing newline.
  2904. With a lone `C-u' as a prefix argument, `y' _replaces_ the region in
  2905. the other buffer with the yanked text, then quits the Calculator,
  2906. leaving you in that buffer. A typical use would be to use `C-x * g' to
  2907. read a region of data into the Calculator, operate on the data to
  2908. produce a new matrix, then type `C-u y' to replace the original data
  2909. with the new data. One might wish to alter the matrix display style
  2910. (*note Vector and Matrix Formats::) or change the current display
  2911. language (*note Language Modes::) before doing this. Also, note that
  2912. this command replaces a linear region of text (as grabbed by `C-x *
  2913. g'), not a rectangle (as grabbed by `C-x * r').
  2914. If the editing buffer is in overwrite (as opposed to insert) mode,
  2915. and the `C-u' prefix was not used, then the yanked number will
  2916. overwrite the characters following point rather than being inserted
  2917. before those characters. The usual conventions of overwrite mode are
  2918. observed; for example, characters will be inserted at the end of a line
  2919. rather than overflowing onto the next line. Yanking a multi-line
  2920. object such as a matrix in overwrite mode overwrites the next N lines
  2921. in the buffer, lengthening or shortening each line as necessary.
  2922. Finally, if the thing being yanked is a simple integer or floating-point
  2923. number (like `-1.2345e-3') and the characters following point also make
  2924. up such a number, then Calc will replace that number with the new
  2925. number, lengthening or shortening as necessary. The concept of
  2926. "overwrite mode" has thus been generalized from overwriting characters
  2927. to overwriting one complete number with another.
  2928. The `C-x * y' key sequence is equivalent to `y' except that it can
  2929. be typed anywhere, not just in Calc. This provides an easy way to
  2930. guarantee that Calc knows which editing buffer you want to use!
  2931. 
  2932. File: calc, Node: X Cut and Paste, Prev: Yanking Into Buffers, Up: Kill and Yank
  2933. 16.7 X Cut and Paste
  2934. ====================
  2935. If you are using Emacs with the X window system, there is an easier way
  2936. to move small amounts of data into and out of the calculator: Use the
  2937. mouse-oriented cut and paste facilities of X.
  2938. The default bindings for a three-button mouse cause the left button
  2939. to move the Emacs cursor to the given place, the right button to select
  2940. the text between the cursor and the clicked location, and the middle
  2941. button to yank the selection into the buffer at the clicked location.
  2942. So, if you have a Calc window and an editing window on your Emacs
  2943. screen, you can use left-click/right-click to select a number, vector,
  2944. or formula from one window, then middle-click to paste that value into
  2945. the other window. When you paste text into the Calc window, Calc
  2946. interprets it as an algebraic entry. It doesn't matter where you click
  2947. in the Calc window; the new value is always pushed onto the top of the
  2948. stack.
  2949. The `xterm' program that is typically used for general-purpose shell
  2950. windows in X interprets the mouse buttons in the same way. So you can
  2951. use the mouse to move data between Calc and any other Unix program.
  2952. One nice feature of `xterm' is that a double left-click selects one
  2953. word, and a triple left-click selects a whole line. So you can usually
  2954. transfer a single number into Calc just by double-clicking on it in the
  2955. shell, then middle-clicking in the Calc window.
  2956. 
  2957. File: calc, Node: Keypad Mode, Next: Embedded Mode, Prev: Kill and Yank, Up: Top
  2958. 17 Keypad Mode
  2959. **************
  2960. The `C-x * k' (`calc-keypad') command starts the Calculator and
  2961. displays a picture of a calculator-style keypad. If you are using the
  2962. X window system, you can click on any of the "keys" in the keypad using
  2963. the left mouse button to operate the calculator. The original window
  2964. remains the selected window; in Keypad mode you can type in your file
  2965. while simultaneously performing calculations with the mouse.
  2966. If you have used `C-x * b' first, `C-x * k' instead invokes the
  2967. `full-calc-keypad' command, which takes over the whole Emacs screen and
  2968. displays the keypad, the Calc stack, and the Calc trail all at once.
  2969. This mode would normally be used when running Calc standalone (*note
  2970. Standalone Operation::).
  2971. If you aren't using the X window system, you must switch into the
  2972. `*Calc Keypad*' window, place the cursor on the desired "key," and type
  2973. <SPC> or <RET>. If you think this is easier than using Calc normally,
  2974. go right ahead.
  2975. Calc commands are more or less the same in Keypad mode. Certain
  2976. keypad keys differ slightly from the corresponding normal Calc
  2977. keystrokes; all such deviations are described below.
  2978. Keypad mode includes many more commands than will fit on the keypad
  2979. at once. Click the right mouse button [`calc-keypad-menu'] to switch
  2980. to the next menu. The bottom five rows of the keypad stay the same;
  2981. the top three rows change to a new set of commands. To return to
  2982. earlier menus, click the middle mouse button [`calc-keypad-menu-back']
  2983. or simply advance through the menus until you wrap around. Typing
  2984. <TAB> inside the keypad window is equivalent to clicking the right
  2985. mouse button there.
  2986. You can always click the <EXEC> button and type any normal Calc key
  2987. sequence. This is equivalent to switching into the Calc buffer, typing
  2988. the keys, then switching back to your original buffer.
  2989. * Menu:
  2990. * Keypad Main Menu::
  2991. * Keypad Functions Menu::
  2992. * Keypad Binary Menu::
  2993. * Keypad Vectors Menu::
  2994. * Keypad Modes Menu::
  2995. 
  2996. File: calc, Node: Keypad Main Menu, Next: Keypad Functions Menu, Prev: Keypad Mode, Up: Keypad Mode
  2997. 17.1 Main Menu
  2998. ==============
  2999. |----+----+--Calc---+----+----1
  3000. |FLR |CEIL|RND |TRNC|CLN2|FLT |
  3001. |----+----+----+----+----+----|
  3002. | LN |EXP | |ABS |IDIV|MOD |
  3003. |----+----+----+----+----+----|
  3004. |SIN |COS |TAN |SQRT|y^x |1/x |
  3005. |----+----+----+----+----+----|
  3006. | ENTER |+/- |EEX |UNDO| <- |
  3007. |-----+---+-+--+--+-+---++----|
  3008. | INV | 7 | 8 | 9 | / |
  3009. |-----+-----+-----+-----+-----|
  3010. | HYP | 4 | 5 | 6 | * |
  3011. |-----+-----+-----+-----+-----|
  3012. |EXEC | 1 | 2 | 3 | - |
  3013. |-----+-----+-----+-----+-----|
  3014. | OFF | 0 | . | PI | + |
  3015. |-----+-----+-----+-----+-----+
  3016. This is the menu that appears the first time you start Keypad mode. It
  3017. will show up in a vertical window on the right side of your screen.
  3018. Above this menu is the traditional Calc stack display. On a 24-line
  3019. screen you will be able to see the top three stack entries.
  3020. The ten digit keys, decimal point, and <EEX> key are used for
  3021. entering numbers in the obvious way. <EEX> begins entry of an exponent
  3022. in scientific notation. Just as with regular Calc, the number is
  3023. pushed onto the stack as soon as you press <ENTER> or any other
  3024. function key.
  3025. The <+/-> key corresponds to normal Calc's `n' key. During numeric
  3026. entry it changes the sign of the number or of the exponent. At other
  3027. times it changes the sign of the number on the top of the stack.
  3028. The <INV> and <HYP> keys modify other keys. As well as having the
  3029. effects described elsewhere in this manual, Keypad mode defines several
  3030. other "inverse" operations. These are described below and in the
  3031. following sections.
  3032. The <ENTER> key finishes the current numeric entry, or otherwise
  3033. duplicates the top entry on the stack.
  3034. The <UNDO> key undoes the most recent Calc operation. `INV UNDO' is
  3035. the "redo" command, and `HYP UNDO' is "last arguments" (`M-<RET>').
  3036. The <<-> key acts as a "backspace" during numeric entry. At other
  3037. times it removes the top stack entry. `INV <-' clears the entire
  3038. stack. `HYP <-' takes an integer from the stack, then removes that
  3039. many additional stack elements.
  3040. The <EXEC> key prompts you to enter any keystroke sequence that
  3041. would normally work in Calc mode. This can include a numeric prefix if
  3042. you wish. It is also possible simply to switch into the Calc window
  3043. and type commands in it; there is nothing "magic" about this window
  3044. when Keypad mode is active.
  3045. The other keys in this display perform their obvious calculator
  3046. functions. <CLN2> rounds the top-of-stack by temporarily reducing the
  3047. precision by 2 digits. <FLT> converts an integer or fraction on the
  3048. top of the stack to floating-point.
  3049. The <INV> and <HYP> keys combined with several of these keys give
  3050. you access to some common functions even if the appropriate menu is not
  3051. displayed. Obviously you don't need to learn these keys unless you
  3052. find yourself wasting time switching among the menus.
  3053. `INV +/-'
  3054. is the same as <1/x>.
  3055. `INV +'
  3056. is the same as <SQRT>.
  3057. `INV -'
  3058. is the same as <CONJ>.
  3059. `INV *'
  3060. is the same as <y^x>.
  3061. `INV /'
  3062. is the same as <INV y^x> (the `x'th root of `y').
  3063. `HYP/INV 1'
  3064. are the same as <SIN> / `INV SIN'.
  3065. `HYP/INV 2'
  3066. are the same as <COS> / `INV COS'.
  3067. `HYP/INV 3'
  3068. are the same as <TAN> / `INV TAN'.
  3069. `INV/HYP 4'
  3070. are the same as <LN> / `HYP LN'.
  3071. `INV/HYP 5'
  3072. are the same as <EXP> / `HYP EXP'.
  3073. `INV 6'
  3074. is the same as <ABS>.
  3075. `INV 7'
  3076. is the same as <RND> (`calc-round').
  3077. `INV 8'
  3078. is the same as <CLN2>.
  3079. `INV 9'
  3080. is the same as <FLT> (`calc-float').
  3081. `INV 0'
  3082. is the same as <IMAG>.
  3083. `INV .'
  3084. is the same as <PREC>.
  3085. `INV ENTER'
  3086. is the same as <SWAP>.
  3087. `HYP ENTER'
  3088. is the same as <RLL3>.
  3089. `INV HYP ENTER'
  3090. is the same as <OVER>.
  3091. `HYP +/-'
  3092. packs the top two stack entries as an error form.
  3093. `HYP EEX'
  3094. packs the top two stack entries as a modulo form.
  3095. `INV EEX'
  3096. creates an interval form; this removes an integer which is one of
  3097. 0 `[]', 1 `[)', 2 `(]' or 3 `()', followed by the two limits of
  3098. the interval.
  3099. The `OFF' key turns Calc off; typing `C-x * k' or `C-x * *' again
  3100. has the same effect. This is analogous to typing `q' or hitting `C-x *
  3101. c' again in the normal calculator. If Calc is running standalone (the
  3102. `full-calc-keypad' command appeared in the command line that started
  3103. Emacs), then `OFF' is replaced with `EXIT'; clicking on this actually
  3104. exits Emacs itself.
  3105. 
  3106. File: calc, Node: Keypad Functions Menu, Next: Keypad Binary Menu, Prev: Keypad Main Menu, Up: Keypad Mode
  3107. 17.2 Functions Menu
  3108. ===================
  3109. |----+----+----+----+----+----2
  3110. |IGAM|BETA|IBET|ERF |BESJ|BESY|
  3111. |----+----+----+----+----+----|
  3112. |IMAG|CONJ| RE |ATN2|RAND|RAGN|
  3113. |----+----+----+----+----+----|
  3114. |GCD |FACT|DFCT|BNOM|PERM|NXTP|
  3115. |----+----+----+----+----+----|
  3116. This menu provides various operations from the `f' and `k' prefix keys.
  3117. <IMAG> multiplies the number on the stack by the imaginary number `i
  3118. = (0, 1)'.
  3119. <RE> extracts the real part a complex number. `INV RE' extracts the
  3120. imaginary part.
  3121. <RAND> takes a number from the top of the stack and computes a
  3122. random number greater than or equal to zero but less than that number.
  3123. (*Note Random Numbers::.) <RAGN> is the "random again" command; it
  3124. computes another random number using the same limit as last time.
  3125. <INV GCD> computes the LCM (least common multiple) function.
  3126. <INV FACT> is the gamma function. `gamma(x) = (x-1)!'.
  3127. <PERM> is the number-of-permutations function, which is on the `H k
  3128. c' key in normal Calc.
  3129. <NXTP> finds the next prime after a number. `INV NXTP' finds the
  3130. previous prime.
  3131. 
  3132. File: calc, Node: Keypad Binary Menu, Next: Keypad Vectors Menu, Prev: Keypad Functions Menu, Up: Keypad Mode
  3133. 17.3 Binary Menu
  3134. ================
  3135. |----+----+----+----+----+----3
  3136. |AND | OR |XOR |NOT |LSH |RSH |
  3137. |----+----+----+----+----+----|
  3138. |DEC |HEX |OCT |BIN |WSIZ|ARSH|
  3139. |----+----+----+----+----+----|
  3140. | A | B | C | D | E | F |
  3141. |----+----+----+----+----+----|
  3142. The keys in this menu perform operations on binary integers. Note that
  3143. both logical and arithmetic right-shifts are provided. <INV LSH>
  3144. rotates one bit to the left.
  3145. The "difference" function (normally on `b d') is on <INV AND>. The
  3146. "clip" function (normally on `b c') is on <INV NOT>.
  3147. The <DEC>, <HEX>, <OCT>, and <BIN> keys select the current radix for
  3148. display and entry of numbers: Decimal, hexadecimal, octal, or binary.
  3149. The six letter keys <A> through <F> are used for entering hexadecimal
  3150. numbers.
  3151. The <WSIZ> key displays the current word size for binary operations
  3152. and allows you to enter a new word size. You can respond to the prompt
  3153. using either the keyboard or the digits and <ENTER> from the keypad.
  3154. The initial word size is 32 bits.
  3155. 
  3156. File: calc, Node: Keypad Vectors Menu, Next: Keypad Modes Menu, Prev: Keypad Binary Menu, Up: Keypad Mode
  3157. 17.4 Vectors Menu
  3158. =================
  3159. |----+----+----+----+----+----4
  3160. |SUM |PROD|MAX |MAP*|MAP^|MAP$|
  3161. |----+----+----+----+----+----|
  3162. |MINV|MDET|MTRN|IDNT|CRSS|"x" |
  3163. |----+----+----+----+----+----|
  3164. |PACK|UNPK|INDX|BLD |LEN |... |
  3165. |----+----+----+----+----+----|
  3166. The keys in this menu operate on vectors and matrices.
  3167. <PACK> removes an integer N from the top of the stack; the next N
  3168. stack elements are removed and packed into a vector, which is replaced
  3169. onto the stack. Thus the sequence `1 ENTER 3 ENTER 5 ENTER 3 PACK'
  3170. enters the vector `[1, 3, 5]' onto the stack. To enter a matrix, build
  3171. each row on the stack as a vector, then use a final <PACK> to collect
  3172. the rows into a matrix.
  3173. <UNPK> unpacks the vector on the stack, pushing each of its
  3174. components separately.
  3175. <INDX> removes an integer N, then builds a vector of integers from 1
  3176. to N. `INV INDX' takes three numbers from the stack: The vector size
  3177. N, the starting number, and the increment. `BLD' takes an integer N
  3178. and any value X and builds a vector of N copies of X.
  3179. <IDNT> removes an integer N, then builds an N-by-N identity matrix.
  3180. <LEN> replaces a vector by its length, an integer.
  3181. <...> turns on or off "abbreviated" display mode for large vectors.
  3182. <MINV>, <MDET>, <MTRN>, and <CROSS> are the matrix inverse,
  3183. determinant, and transpose, and vector cross product.
  3184. <SUM> replaces a vector by the sum of its elements. It is
  3185. equivalent to `u +' in normal Calc (*note Statistical Operations::).
  3186. <PROD> computes the product of the elements of a vector, and <MAX>
  3187. computes the maximum of all the elements of a vector.
  3188. <INV SUM> computes the alternating sum of the first element minus
  3189. the second, plus the third, minus the fourth, and so on. <INV MAX>
  3190. computes the minimum of the vector elements.
  3191. <HYP SUM> computes the mean of the vector elements. <HYP PROD>
  3192. computes the sample standard deviation. <HYP MAX> computes the median.
  3193. <MAP*> multiplies two vectors elementwise. It is equivalent to the
  3194. `V M *' command. <MAP^> computes powers elementwise. The arguments
  3195. must be vectors of equal length, or one must be a vector and the other
  3196. must be a plain number. For example, `2 MAP^' squares all the elements
  3197. of a vector.
  3198. <MAP$> maps the formula on the top of the stack across the vector in
  3199. the second-to-top position. If the formula contains several variables,
  3200. Calc takes that many vectors starting at the second-to-top position and
  3201. matches them to the variables in alphabetical order. The result is a
  3202. vector of the same size as the input vectors, whose elements are the
  3203. formula evaluated with the variables set to the various sets of numbers
  3204. in those vectors. For example, you could simulate <MAP^> using <MAP$>
  3205. with the formula `x^y'.
  3206. The `"x"' key pushes the variable name `x' onto the stack. To build
  3207. the formula `x^2 + 6', you would use the key sequence `"x" 2 y^x 6 +'.
  3208. This formula would then be suitable for use with the <MAP$> key
  3209. described above. With <INV>, <HYP>, or <INV> and <HYP>, the `"x"' key
  3210. pushes the variable names `y', `z', and `t', respectively.
  3211. 
  3212. File: calc, Node: Keypad Modes Menu, Prev: Keypad Vectors Menu, Up: Keypad Mode
  3213. 17.5 Modes Menu
  3214. ===============
  3215. |----+----+----+----+----+----5
  3216. |FLT |FIX |SCI |ENG |GRP | |
  3217. |----+----+----+----+----+----|
  3218. |RAD |DEG |FRAC|POLR|SYMB|PREC|
  3219. |----+----+----+----+----+----|
  3220. |SWAP|RLL3|RLL4|OVER|STO |RCL |
  3221. |----+----+----+----+----+----|
  3222. The keys in this menu manipulate modes, variables, and the stack.
  3223. The <FLT>, <FIX>, <SCI>, and <ENG> keys select floating-point,
  3224. fixed-point, scientific, or engineering notation. <FIX> displays two
  3225. digits after the decimal by default; the others display full precision.
  3226. With the <INV> prefix, these keys pop a number-of-digits argument from
  3227. the stack.
  3228. The <GRP> key turns grouping of digits with commas on or off. `INV
  3229. GRP' enables grouping to the right of the decimal point as well as to
  3230. the left.
  3231. The <RAD> and <DEG> keys switch between radians and degrees for
  3232. trigonometric functions.
  3233. The <FRAC> key turns Fraction mode on or off. This affects whether
  3234. commands like `/' with integer arguments produce fractional or
  3235. floating-point results.
  3236. The <POLR> key turns Polar mode on or off, determining whether polar
  3237. or rectangular complex numbers are used by default.
  3238. The <SYMB> key turns Symbolic mode on or off, in which operations
  3239. that would produce inexact floating-point results are left unevaluated
  3240. as algebraic formulas.
  3241. The <PREC> key selects the current precision. Answer with the
  3242. keyboard or with the keypad digit and <ENTER> keys.
  3243. The <SWAP> key exchanges the top two stack elements. The <RLL3> key
  3244. rotates the top three stack elements upwards. The <RLL4> key rotates
  3245. the top four stack elements upwards. The <OVER> key duplicates the
  3246. second-to-top stack element.
  3247. The <STO> and <RCL> keys are analogous to `s t' and `s r' in regular
  3248. Calc. *Note Store and Recall::. Click the <STO> or <RCL> key, then
  3249. one of the ten digits. (Named variables are not available in Keypad
  3250. mode.) You can also use, for example, `STO + 3' to add to register 3.
  3251. 
  3252. File: calc, Node: Embedded Mode, Next: Programming, Prev: Keypad Mode, Up: Top
  3253. 18 Embedded Mode
  3254. ****************
  3255. Embedded mode in Calc provides an alternative to copying numbers and
  3256. formulas back and forth between editing buffers and the Calc stack. In
  3257. Embedded mode, your editing buffer becomes temporarily linked to the
  3258. stack and this copying is taken care of automatically.
  3259. * Menu:
  3260. * Basic Embedded Mode::
  3261. * More About Embedded Mode::
  3262. * Assignments in Embedded Mode::
  3263. * Mode Settings in Embedded Mode::
  3264. * Customizing Embedded Mode::
  3265. 
  3266. File: calc, Node: Basic Embedded Mode, Next: More About Embedded Mode, Prev: Embedded Mode, Up: Embedded Mode
  3267. 18.1 Basic Embedded Mode
  3268. ========================
  3269. To enter Embedded mode, position the Emacs point (cursor) on a formula
  3270. in any buffer and press `C-x * e' (`calc-embedded'). Note that `C-x *
  3271. e' is not to be used in the Calc stack buffer like most Calc commands,
  3272. but rather in regular editing buffers that are visiting your own files.
  3273. Calc will try to guess an appropriate language based on the major
  3274. mode of the editing buffer. (*Note Language Modes::.) If the current
  3275. buffer is in `latex-mode', for example, Calc will set its language to
  3276. LaTeX. Similarly, Calc will use TeX language for `tex-mode',
  3277. `plain-tex-mode' and `context-mode', C language for `c-mode' and
  3278. `c++-mode', FORTRAN language for `fortran-mode' and `f90-mode', Pascal
  3279. for `pascal-mode', and eqn for `nroff-mode' (*note Customizing Calc::).
  3280. These can be overridden with Calc's mode changing commands (*note Mode
  3281. Settings in Embedded Mode::). If no suitable language is available,
  3282. Calc will continue with its current language.
  3283. Calc normally scans backward and forward in the buffer for the
  3284. nearest opening and closing "formula delimiters". The simplest
  3285. delimiters are blank lines. Other delimiters that Embedded mode
  3286. understands are:
  3287. 1. The TeX and LaTeX math delimiters `$ $', `$$ $$', `\[ \]', and `\(
  3288. \)';
  3289. 2. Lines beginning with `\begin' and `\end' (except matrix
  3290. delimiters);
  3291. 3. Lines beginning with `@' (Texinfo delimiters).
  3292. 4. Lines beginning with `.EQ' and `.EN' ("eqn" delimiters);
  3293. 5. Lines containing a single `%' or `.\"' symbol and nothing else.
  3294. *Note Customizing Embedded Mode::, to see how to make Calc recognize
  3295. your own favorite delimiters. Delimiters like `$ $' can appear on
  3296. their own separate lines or in-line with the formula.
  3297. If you give a positive or negative numeric prefix argument, Calc
  3298. instead uses the current point as one end of the formula, and includes
  3299. that many lines forward or backward (respectively, including the current
  3300. line). Explicit delimiters are not necessary in this case.
  3301. With a prefix argument of zero, Calc uses the current region
  3302. (delimited by point and mark) instead of formula delimiters. With a
  3303. prefix argument of `C-u' only, Calc uses the current line as the
  3304. formula.
  3305. The `C-x * w' (`calc-embedded-word') command will start Embedded
  3306. mode on the current "word"; in this case Calc will scan for the first
  3307. non-numeric character (i.e., the first character that is not a digit,
  3308. sign, decimal point, or upper- or lower-case `e') forward and backward
  3309. to delimit the formula.
  3310. When you enable Embedded mode for a formula, Calc reads the text
  3311. between the delimiters and tries to interpret it as a Calc formula.
  3312. Calc can generally identify TeX formulas and Big-style formulas even if
  3313. the language mode is wrong. If Calc can't make sense of the formula,
  3314. it beeps and refuses to enter Embedded mode. But if the current
  3315. language is wrong, Calc can sometimes parse the formula successfully
  3316. (but incorrectly); for example, the C expression `atan(a[1])' can be
  3317. parsed in Normal language mode, but the `atan' won't correspond to the
  3318. built-in `arctan' function, and the `a[1]' will be interpreted as `a'
  3319. times the vector `[1]'!
  3320. If you press `C-x * e' or `C-x * w' to activate an embedded formula
  3321. which is blank, say with the cursor on the space between the two
  3322. delimiters `$ $', Calc will immediately prompt for an algebraic entry.
  3323. Only one formula in one buffer can be enabled at a time. If you
  3324. move to another area of the current buffer and give Calc commands, Calc
  3325. turns Embedded mode off for the old formula and then tries to restart
  3326. Embedded mode at the new position. Other buffers are not affected by
  3327. Embedded mode.
  3328. When Embedded mode begins, Calc pushes the current formula onto the
  3329. stack. No Calc stack window is created; however, Calc copies the
  3330. top-of-stack position into the original buffer at all times. You can
  3331. create a Calc window by hand with `C-x * o' if you find you need to see
  3332. the entire stack.
  3333. For example, typing `C-x * e' while somewhere in the formula `n>2'
  3334. in the following line enables Embedded mode on that inequality:
  3335. We define $F_n = F_(n-1)+F_(n-2)$ for all $n>2$.
  3336. The formula `n>2' will be pushed onto the Calc stack, and the top of
  3337. stack will be copied back into the editing buffer. This means that
  3338. spaces will appear around the `>' symbol to match Calc's usual display
  3339. style:
  3340. We define $F_n = F_(n-1)+F_(n-2)$ for all $n > 2$.
  3341. No spaces have appeared around the `+' sign because it's in a different
  3342. formula, one which we have not yet touched with Embedded mode.
  3343. Now that Embedded mode is enabled, keys you type in this buffer are
  3344. interpreted as Calc commands. At this point we might use the "commute"
  3345. command `j C' to reverse the inequality. This is a selection-based
  3346. command for which we first need to move the cursor onto the operator
  3347. (`>' in this case) that needs to be commuted.
  3348. We define $F_n = F_(n-1)+F_(n-2)$ for all $2 < n$.
  3349. The `C-x * o' command is a useful way to open a Calc window without
  3350. actually selecting that window. Giving this command verifies that `2 <
  3351. n' is also on the Calc stack. Typing `17 <RET>' would produce:
  3352. We define $F_n = F_(n-1)+F_(n-2)$ for all $17$.
  3353. with `2 < n' and `17' on the stack; typing <TAB> at this point will
  3354. exchange the two stack values and restore `2 < n' to the embedded
  3355. formula. Even though you can't normally see the stack in Embedded
  3356. mode, it is still there and it still operates in the same way. But, as
  3357. with old-fashioned RPN calculators, you can only see the value at the
  3358. top of the stack at any given time (unless you use `C-x * o').
  3359. Typing `C-x * e' again turns Embedded mode off. The Calc window
  3360. reveals that the formula `2 < n' is automatically removed from the
  3361. stack, but the `17' is not. Entering Embedded mode always pushes one
  3362. thing onto the stack, and leaving Embedded mode always removes one
  3363. thing. Anything else that happens on the stack is entirely your
  3364. business as far as Embedded mode is concerned.
  3365. If you press `C-x * e' in the wrong place by accident, it is
  3366. possible that Calc will be able to parse the nearby text as a formula
  3367. and will mangle that text in an attempt to redisplay it "properly" in
  3368. the current language mode. If this happens, press `C-x * e' again to
  3369. exit Embedded mode, then give the regular Emacs "undo" command (`C-_'
  3370. or `C-x u') to put the text back the way it was before Calc edited it.
  3371. Note that Calc's own Undo command (typed before you turn Embedded mode
  3372. back off) will not do you any good, because as far as Calc is concerned
  3373. you haven't done anything with this formula yet.
  3374. 
  3375. File: calc, Node: More About Embedded Mode, Next: Assignments in Embedded Mode, Prev: Basic Embedded Mode, Up: Embedded Mode
  3376. 18.2 More About Embedded Mode
  3377. =============================
  3378. When Embedded mode "activates" a formula, i.e., when it examines the
  3379. formula for the first time since the buffer was created or loaded, Calc
  3380. tries to sense the language in which the formula was written. If the
  3381. formula contains any LaTeX-like `\' sequences, it is parsed (i.e.,
  3382. read) in LaTeX mode. If the formula appears to be written in
  3383. multi-line Big mode, it is parsed in Big mode. Otherwise, it is parsed
  3384. according to the current language mode.
  3385. Note that Calc does not change the current language mode according
  3386. the formula it reads in. Even though it can read a LaTeX formula when
  3387. not in LaTeX mode, it will immediately rewrite this formula using
  3388. whatever language mode is in effect.
  3389. Calc's parser is unable to read certain kinds of formulas. For
  3390. example, with `v ]' (`calc-matrix-brackets') you can specify matrix
  3391. display styles which the parser is unable to recognize as matrices.
  3392. The `d p' (`calc-show-plain') command turns on a mode in which a
  3393. "plain" version of a formula is placed in front of the fully-formatted
  3394. version. When Calc reads a formula that has such a plain version in
  3395. front, it reads the plain version and ignores the formatted version.
  3396. Plain formulas are preceded and followed by `%%%' signs by default.
  3397. This notation has the advantage that the `%' character begins a comment
  3398. in TeX and LaTeX, so if your formula is embedded in a TeX or LaTeX
  3399. document its plain version will be invisible in the final printed copy.
  3400. Certain major modes have different delimiters to ensure that the
  3401. "plain" version will be in a comment for those modes, also. See *note
  3402. Customizing Embedded Mode:: to see how to change the "plain" formula
  3403. delimiters.
  3404. There are several notations which Calc's parser for "big" formatted
  3405. formulas can't yet recognize. In particular, it can't read the large
  3406. symbols for `sum', `prod', and `integ', and it can't handle `=>' with
  3407. the righthand argument omitted. Also, Calc won't recognize special
  3408. formats you have defined with the `Z C' command (*note User-Defined
  3409. Compositions::). In these cases it is important to use "plain" mode to
  3410. make sure Calc will be able to read your formula later.
  3411. Another example where "plain" mode is important is if you have
  3412. specified a float mode with few digits of precision. Normally any
  3413. digits that are computed but not displayed will simply be lost when you
  3414. save and re-load your embedded buffer, but "plain" mode allows you to
  3415. make sure that the complete number is present in the file as well as
  3416. the rounded-down number.
  3417. Embedded buffers remember active formulas for as long as they exist
  3418. in Emacs memory. Suppose you have an embedded formula which is `pi' to
  3419. the normal 12 decimal places, and then type `C-u 5 d n' to display only
  3420. five decimal places. If you then type `d n', all 12 places reappear
  3421. because the full number is still there on the Calc stack. More
  3422. surprisingly, even if you exit Embedded mode and later re-enter it for
  3423. that formula, typing `d n' will restore all 12 places because each
  3424. buffer remembers all its active formulas. However, if you save the
  3425. buffer in a file and reload it in a new Emacs session, all
  3426. non-displayed digits will have been lost unless you used "plain" mode.
  3427. In some applications of Embedded mode, you will want to have a
  3428. sequence of copies of a formula that show its evolution as you work on
  3429. it. For example, you might want to have a sequence like this in your
  3430. file (elaborating here on the example from the "Getting Started"
  3431. chapter):
  3432. The derivative of
  3433. ln(ln(x))
  3434. is
  3435. (the derivative of ln(ln(x)))
  3436. whose value at x = 2 is
  3437. (the value)
  3438. and at x = 3 is
  3439. (the value)
  3440. The `C-x * d' (`calc-embedded-duplicate') command is a handy way to
  3441. make sequences like this. If you type `C-x * d', the formula under the
  3442. cursor (which may or may not have Embedded mode enabled for it at the
  3443. time) is copied immediately below and Embedded mode is then enabled for
  3444. that copy.
  3445. For this example, you would start with just
  3446. The derivative of
  3447. ln(ln(x))
  3448. and press `C-x * d' with the cursor on this formula. The result is
  3449. The derivative of
  3450. ln(ln(x))
  3451. ln(ln(x))
  3452. with the second copy of the formula enabled in Embedded mode. You can
  3453. now press `a d x <RET>' to take the derivative, and `C-x * d C-x * d'
  3454. to make two more copies of the derivative. To complete the
  3455. computations, type `3 s l x <RET>' to evaluate the last formula, then
  3456. move up to the second-to-last formula and type `2 s l x <RET>'.
  3457. Finally, you would want to press `C-x * e' to exit Embedded mode,
  3458. then go up and insert the necessary text in between the various
  3459. formulas and numbers.
  3460. The `C-x * f' (`calc-embedded-new-formula') command creates a new
  3461. embedded formula at the current point. It inserts some default
  3462. delimiters, which are usually just blank lines, and then does an
  3463. algebraic entry to get the formula (which is then enabled for Embedded
  3464. mode). This is just shorthand for typing the delimiters yourself,
  3465. positioning the cursor between the new delimiters, and pressing `C-x *
  3466. e'. The key sequence `C-x * '' is equivalent to `C-x * f'.
  3467. The `C-x * n' (`calc-embedded-next') and `C-x * p'
  3468. (`calc-embedded-previous') commands move the cursor to the next or
  3469. previous active embedded formula in the buffer. They can take positive
  3470. or negative prefix arguments to move by several formulas. Note that
  3471. these commands do not actually examine the text of the buffer looking
  3472. for formulas; they only see formulas which have previously been
  3473. activated in Embedded mode. In fact, `C-x * n' and `C-x * p' are a
  3474. useful way to tell which embedded formulas are currently active. Also,
  3475. note that these commands do not enable Embedded mode on the next or
  3476. previous formula, they just move the cursor.
  3477. The `C-x * `' (`calc-embedded-edit') command edits the embedded
  3478. formula at the current point as if by ``' (`calc-edit'). Embedded mode
  3479. does not have to be enabled for this to work. Press `C-c C-c' to
  3480. finish the edit, or `C-x k' to cancel.
  3481. 
  3482. File: calc, Node: Assignments in Embedded Mode, Next: Mode Settings in Embedded Mode, Prev: More About Embedded Mode, Up: Embedded Mode
  3483. 18.3 Assignments in Embedded Mode
  3484. =================================
  3485. The `:=' (assignment) and `=>' ("evaluates-to") operators are
  3486. especially useful in Embedded mode. They allow you to make a
  3487. definition in one formula, then refer to that definition in other
  3488. formulas embedded in the same buffer.
  3489. An embedded formula which is an assignment to a variable, as in
  3490. foo := 5
  3491. records `5' as the stored value of `foo' for the purposes of Embedded
  3492. mode operations in the current buffer. It does _not_ actually store
  3493. `5' as the "global" value of `foo', however. Regular Calc operations,
  3494. and Embedded formulas in other buffers, will not see this assignment.
  3495. One way to use this assigned value is simply to create an Embedded
  3496. formula elsewhere that refers to `foo', and to press `=' in that
  3497. formula. However, this permanently replaces the `foo' in the formula
  3498. with its current value. More interesting is to use `=>' elsewhere:
  3499. foo + 7 => 12
  3500. *Note Evaluates-To Operator::, for a general discussion of `=>'.
  3501. If you move back and change the assignment to `foo', any `=>'
  3502. formulas which refer to it are automatically updated.
  3503. foo := 17
  3504. foo + 7 => 24
  3505. The obvious question then is, _how_ can one easily change the
  3506. assignment to `foo'? If you simply select the formula in Embedded mode
  3507. and type 17, the assignment itself will be replaced by the 17. The
  3508. effect on the other formula will be that the variable `foo' becomes
  3509. unassigned:
  3510. 17
  3511. foo + 7 => foo + 7
  3512. The right thing to do is first to use a selection command (`j 2'
  3513. will do the trick) to select the righthand side of the assignment.
  3514. Then, `17 <TAB> <DEL>' will swap the 17 into place (*note Selecting
  3515. Subformulas::, to see how this works).
  3516. The `C-x * j' (`calc-embedded-select') command provides an easy way
  3517. to operate on assignments. It is just like `C-x * e', except that if
  3518. the enabled formula is an assignment, it uses `j 2' to select the
  3519. righthand side. If the enabled formula is an evaluates-to, it uses `j
  3520. 1' to select the lefthand side. A formula can also be a combination of
  3521. both:
  3522. bar := foo + 3 => 20
  3523. in which case `C-x * j' will select the middle part (`foo + 3').
  3524. The formula is automatically deselected when you leave Embedded mode.
  3525. Another way to change the assignment to `foo' would simply be to
  3526. edit the number using regular Emacs editing rather than Embedded mode.
  3527. Then, we have to find a way to get Embedded mode to notice the change.
  3528. The `C-x * u' (`calc-embedded-update-formula') command is a convenient
  3529. way to do this.
  3530. foo := 6
  3531. foo + 7 => 13
  3532. Pressing `C-x * u' is much like pressing `C-x * e = C-x * e', that
  3533. is, temporarily enabling Embedded mode for the formula under the cursor
  3534. and then evaluating it with `='. But `C-x * u' does not actually use
  3535. `C-x * e', and in fact another formula somewhere else can be enabled in
  3536. Embedded mode while you use `C-x * u' and that formula will not be
  3537. disturbed.
  3538. With a numeric prefix argument, `C-x * u' updates all active `=>'
  3539. formulas in the buffer. Formulas which have not yet been activated in
  3540. Embedded mode, and formulas which do not have `=>' as their top-level
  3541. operator, are not affected by this. (This is useful only if you have
  3542. used `m C'; see below.)
  3543. With a plain `C-u' prefix, `C-u C-x * u' updates only in the region
  3544. between mark and point rather than in the whole buffer.
  3545. `C-x * u' is also a handy way to activate a formula, such as an `=>'
  3546. formula that has freshly been typed in or loaded from a file.
  3547. The `C-x * a' (`calc-embedded-activate') command scans through the
  3548. current buffer and activates all embedded formulas that contain `:=' or
  3549. `=>' symbols. This does not mean that Embedded mode is actually turned
  3550. on, but only that the formulas' positions are registered with Embedded
  3551. mode so that the `=>' values can be properly updated as assignments are
  3552. changed.
  3553. It is a good idea to type `C-x * a' right after loading a file that
  3554. uses embedded `=>' operators. Emacs includes a nifty "buffer-local
  3555. variables" feature that you can use to do this automatically. The idea
  3556. is to place near the end of your file a few lines that look like this:
  3557. --- Local Variables: ---
  3558. --- eval:(calc-embedded-activate) ---
  3559. --- End: ---
  3560. where the leading and trailing `---' can be replaced by any suitable
  3561. strings (which must be the same on all three lines) or omitted
  3562. altogether; in a TeX or LaTeX file, `%' would be a good leading string
  3563. and no trailing string would be necessary. In a C program, `/*' and
  3564. `*/' would be good leading and trailing strings.
  3565. When Emacs loads a file into memory, it checks for a Local Variables
  3566. section like this one at the end of the file. If it finds this
  3567. section, it does the specified things (in this case, running `C-x * a'
  3568. automatically) before editing of the file begins. The Local Variables
  3569. section must be within 3000 characters of the end of the file for Emacs
  3570. to find it, and it must be in the last page of the file if the file has
  3571. any page separators. *Note Local Variables in Files: (emacs)File
  3572. Variables.
  3573. Note that `C-x * a' does not update the formulas it finds. To do
  3574. this, type, say, `M-1 C-x * u' after `C-x * a'. Generally this should
  3575. not be a problem, though, because the formulas will have been
  3576. up-to-date already when the file was saved.
  3577. Normally, `C-x * a' activates all the formulas it finds, but any
  3578. previous active formulas remain active as well. With a positive
  3579. numeric prefix argument, `C-x * a' first deactivates all current active
  3580. formulas, then actives the ones it finds in its scan of the buffer.
  3581. With a negative prefix argument, `C-x * a' simply deactivates all
  3582. formulas.
  3583. Embedded mode has two symbols, `Active' and `~Active', which it puts
  3584. next to the major mode name in a buffer's mode line. It puts `Active'
  3585. if it has reason to believe that all formulas in the buffer are active,
  3586. because you have typed `C-x * a' and Calc has not since had to
  3587. deactivate any formulas (which can happen if Calc goes to update an
  3588. `=>' formula somewhere because a variable changed, and finds that the
  3589. formula is no longer there due to some kind of editing outside of
  3590. Embedded mode). Calc puts `~Active' in the mode line if some, but
  3591. probably not all, formulas in the buffer are active. This happens if
  3592. you activate a few formulas one at a time but never use `C-x * a', or
  3593. if you used `C-x * a' but then Calc had to deactivate a formula because
  3594. it lost track of it. If neither of these symbols appears in the mode
  3595. line, no embedded formulas are active in the buffer (e.g., before
  3596. Embedded mode has been used, or after a `M-- C-x * a').
  3597. Embedded formulas can refer to assignments both before and after them
  3598. in the buffer. If there are several assignments to a variable, the
  3599. nearest preceding assignment is used if there is one, otherwise the
  3600. following assignment is used.
  3601. x => 1
  3602. x := 1
  3603. x => 1
  3604. x := 2
  3605. x => 2
  3606. As well as simple variables, you can also assign to subscript
  3607. expressions of the form `VAR_NUMBER' (as in `x_0'), or `VAR_VAR' (as in
  3608. `x_max'). Assignments to other kinds of objects can be represented by
  3609. Calc, but the automatic linkage between assignments and references works
  3610. only for plain variables and these two kinds of subscript expressions.
  3611. If there are no assignments to a given variable, the global stored
  3612. value for the variable is used (*note Storing Variables::), or, if no
  3613. value is stored, the variable is left in symbolic form. Note that
  3614. global stored values will be lost when the file is saved and loaded in
  3615. a later Emacs session, unless you have used the `s p'
  3616. (`calc-permanent-variable') command to save them; *note Operations on
  3617. Variables::.
  3618. The `m C' (`calc-auto-recompute') command turns automatic
  3619. recomputation of `=>' forms on and off. If you turn automatic
  3620. recomputation off, you will have to use `C-x * u' to update these
  3621. formulas manually after an assignment has been changed. If you plan to
  3622. change several assignments at once, it may be more efficient to type `m
  3623. C', change all the assignments, then use `M-1 C-x * u' to update the
  3624. entire buffer afterwards. The `m C' command also controls `=>'
  3625. formulas on the stack; *note Evaluates-To Operator::. When you turn
  3626. automatic recomputation back on, the stack will be updated but the
  3627. Embedded buffer will not; you must use `C-x * u' to update the buffer
  3628. by hand.
  3629. 
  3630. File: calc, Node: Mode Settings in Embedded Mode, Next: Customizing Embedded Mode, Prev: Assignments in Embedded Mode, Up: Embedded Mode
  3631. 18.4 Mode Settings in Embedded Mode
  3632. ===================================
  3633. The mode settings can be changed while Calc is in embedded mode, but by
  3634. default they will revert to their original values when embedded mode is
  3635. ended. However, the modes saved when the mode-recording mode is `Save'
  3636. (see below) and the modes in effect when the `m e'
  3637. (`calc-embedded-preserve-modes') command is given will be preserved
  3638. when embedded mode is ended.
  3639. Embedded mode has a rather complicated mechanism for handling mode
  3640. settings in Embedded formulas. It is possible to put annotations in
  3641. the file that specify mode settings either global to the entire file or
  3642. local to a particular formula or formulas. In the latter case,
  3643. different modes can be specified for use when a formula is the enabled
  3644. Embedded mode formula.
  3645. When you give any mode-setting command, like `m f' (for Fraction
  3646. mode) or `d s' (for scientific notation), Embedded mode adds a line
  3647. like the following one to the file just before the opening delimiter of
  3648. the formula.
  3649. % [calc-mode: fractions: t]
  3650. % [calc-mode: float-format: (sci 0)]
  3651. When Calc interprets an embedded formula, it scans the text before
  3652. the formula for mode-setting annotations like these and sets the Calc
  3653. buffer to match these modes. Modes not explicitly described in the
  3654. file are not changed. Calc scans all the way to the top of the file,
  3655. or up to a line of the form
  3656. % [calc-defaults]
  3657. which you can insert at strategic places in the file if this backward
  3658. scan is getting too slow, or just to provide a barrier between one
  3659. "zone" of mode settings and another.
  3660. If the file contains several annotations for the same mode, the
  3661. closest one before the formula is used. Annotations after the formula
  3662. are never used (except for global annotations, described below).
  3663. The scan does not look for the leading `% ', only for the square
  3664. brackets and the text they enclose. In fact, the leading characters
  3665. are different for different major modes. You can edit the mode
  3666. annotations to a style that works better in context if you wish. *Note
  3667. Customizing Embedded Mode::, to see how to change the style that Calc
  3668. uses when it generates the annotations. You can write mode annotations
  3669. into the file yourself if you know the syntax; the easiest way to find
  3670. the syntax for a given mode is to let Calc write the annotation for it
  3671. once and see what it does.
  3672. If you give a mode-changing command for a mode that already has a
  3673. suitable annotation just above the current formula, Calc will modify
  3674. that annotation rather than generating a new, conflicting one.
  3675. Mode annotations have three parts, separated by colons. (Spaces
  3676. after the colons are optional.) The first identifies the kind of mode
  3677. setting, the second is a name for the mode itself, and the third is the
  3678. value in the form of a Lisp symbol, number, or list. Annotations with
  3679. unrecognizable text in the first or second parts are ignored. The
  3680. third part is not checked to make sure the value is of a valid type or
  3681. range; if you write an annotation by hand, be sure to give a proper
  3682. value or results will be unpredictable. Mode-setting annotations are
  3683. case-sensitive.
  3684. While Embedded mode is enabled, the word `Local' appears in the mode
  3685. line. This is to show that mode setting commands generate annotations
  3686. that are "local" to the current formula or set of formulas. The `m R'
  3687. (`calc-mode-record-mode') command causes Calc to generate different
  3688. kinds of annotations. Pressing `m R' repeatedly cycles through the
  3689. possible modes.
  3690. `LocEdit' and `LocPerm' modes generate annotations that look like
  3691. this, respectively:
  3692. % [calc-edit-mode: float-format: (sci 0)]
  3693. % [calc-perm-mode: float-format: (sci 5)]
  3694. The first kind of annotation will be used only while a formula is
  3695. enabled in Embedded mode. The second kind will be used only when the
  3696. formula is _not_ enabled. (Whether the formula is "active" or not,
  3697. i.e., whether Calc has seen this formula yet, is not relevant here.)
  3698. `Global' mode generates an annotation like this at the end of the
  3699. file:
  3700. % [calc-global-mode: fractions t]
  3701. Global mode annotations affect all formulas throughout the file, and
  3702. may appear anywhere in the file. This allows you to tuck your mode
  3703. annotations somewhere out of the way, say, on a new page of the file,
  3704. as long as those mode settings are suitable for all formulas in the
  3705. file.
  3706. Enabling a formula with `C-x * e' causes a fresh scan for local mode
  3707. annotations; you will have to use this after adding annotations above a
  3708. formula by hand to get the formula to notice them. Updating a formula
  3709. with `C-x * u' will also re-scan the local modes, but global modes are
  3710. only re-scanned by `C-x * a'.
  3711. Another way that modes can get out of date is if you add a local
  3712. mode annotation to a formula that has another formula after it. In
  3713. this example, we have used the `d s' command while the first of the two
  3714. embedded formulas is active. But the second formula has not changed
  3715. its style to match, even though by the rules of reading annotations the
  3716. `(sci 0)' applies to it, too.
  3717. % [calc-mode: float-format: (sci 0)]
  3718. 1.23e2
  3719. 456.
  3720. We would have to go down to the other formula and press `C-x * u' on
  3721. it in order to get it to notice the new annotation.
  3722. Two more mode-recording modes selectable by `m R' are available
  3723. which are also available outside of Embedded mode. (*note General Mode
  3724. Commands::.) They are `Save', in which mode settings are recorded
  3725. permanently in your Calc init file (the file given by the variable
  3726. `calc-settings-file', typically `~/.emacs.d/calc.el') rather than by
  3727. annotating the current document, and no-recording mode (where there is
  3728. no symbol like `Save' or `Local' in the mode line), in which
  3729. mode-changing commands do not leave any annotations at all.
  3730. When Embedded mode is not enabled, mode-recording modes except for
  3731. `Save' have no effect.
  3732. 
  3733. File: calc, Node: Customizing Embedded Mode, Prev: Mode Settings in Embedded Mode, Up: Embedded Mode
  3734. 18.5 Customizing Embedded Mode
  3735. ==============================
  3736. You can modify Embedded mode's behavior by setting various Lisp
  3737. variables described here. These variables are customizable (*note
  3738. Customizing Calc::), or you can use `M-x set-variable' or `M-x
  3739. edit-options' to adjust a variable on the fly. (Another possibility
  3740. would be to use a file-local variable annotation at the end of the file;
  3741. *note Local Variables in Files: (emacs)File Variables.) Many of the
  3742. variables given mentioned here can be set to depend on the major mode
  3743. of the editing buffer (*note Customizing Calc::).
  3744. The `calc-embedded-open-formula' variable holds a regular expression
  3745. for the opening delimiter of a formula. *Note Regular Expression
  3746. Search: (emacs)Regexp Search, to see how regular expressions work.
  3747. Basically, a regular expression is a pattern that Calc can search for.
  3748. A regular expression that considers blank lines, `$', and `$$' to be
  3749. opening delimiters is `"\\`\\|^\n\\|\\$\\$?"'. Just in case the
  3750. meaning of this regular expression is not completely plain, let's go
  3751. through it in detail.
  3752. The surrounding `" "' marks quote the text between them as a Lisp
  3753. string. If you left them off, `set-variable' or `edit-options' would
  3754. try to read the regular expression as a Lisp program.
  3755. The most obvious property of this regular expression is that it
  3756. contains indecently many backslashes. There are actually two levels of
  3757. backslash usage going on here. First, when Lisp reads a quoted string,
  3758. all pairs of characters beginning with a backslash are interpreted as
  3759. special characters. Here, `\n' changes to a new-line character, and
  3760. `\\' changes to a single backslash. So the actual regular expression
  3761. seen by Calc is `\`\|^ (newline) \|\$\$?'.
  3762. Regular expressions also consider pairs beginning with backslash to
  3763. have special meanings. Sometimes the backslash is used to quote a
  3764. character that otherwise would have a special meaning in a regular
  3765. expression, like `$', which normally means "end-of-line," or `?', which
  3766. means that the preceding item is optional. So `\$\$?' matches either
  3767. one or two dollar signs.
  3768. The other codes in this regular expression are `^', which matches
  3769. "beginning-of-line," `\|', which means "or," and `\`', which matches
  3770. "beginning-of-buffer." So the whole pattern means that a formula
  3771. begins at the beginning of the buffer, or on a newline that occurs at
  3772. the beginning of a line (i.e., a blank line), or at one or two dollar
  3773. signs.
  3774. The default value of `calc-embedded-open-formula' looks just like
  3775. this example, with several more alternatives added on to recognize
  3776. various other common kinds of delimiters.
  3777. By the way, the reason to use `^\n' rather than `^$' or `\n\n',
  3778. which also would appear to match blank lines, is that the former
  3779. expression actually "consumes" only one newline character as _part of_
  3780. the delimiter, whereas the latter expressions consume zero or two
  3781. newlines, respectively. The former choice gives the most natural
  3782. behavior when Calc must operate on a whole formula including its
  3783. delimiters.
  3784. See the Emacs manual for complete details on regular expressions.
  3785. But just for your convenience, here is a list of all characters which
  3786. must be quoted with backslash (like `\$') to avoid some special
  3787. interpretation: `. * + ? [ ] ^ $ \'. (Note the backslash in this
  3788. list; for example, to match `\[' you must use `"\\\\\\["'. An exercise
  3789. for the reader is to account for each of these six backslashes!)
  3790. The `calc-embedded-close-formula' variable holds a regular
  3791. expression for the closing delimiter of a formula. A closing regular
  3792. expression to match the above example would be `"\\'\\|\n$\\|\\$\\$?"'.
  3793. This is almost the same as the other one, except it now uses `\''
  3794. ("end-of-buffer") and `\n$' (newline occurring at end of line, yet
  3795. another way of describing a blank line that is more appropriate for this
  3796. case).
  3797. The `calc-embedded-word-regexp' variable holds a regular expression
  3798. used to define an expression to look for (a "word") when you type `C-x
  3799. * w' to enable Embedded mode.
  3800. The `calc-embedded-open-plain' variable is a string which begins a
  3801. "plain" formula written in front of the formatted formula when `d p'
  3802. mode is turned on. Note that this is an actual string, not a regular
  3803. expression, because Calc must be able to write this string into a
  3804. buffer as well as to recognize it. The default string is `"%%% "'
  3805. (note the trailing space), but may be different for certain major modes.
  3806. The `calc-embedded-close-plain' variable is a string which ends a
  3807. "plain" formula. The default is `" %%%\n"', but may be different for
  3808. different major modes. Without the trailing newline here, the first
  3809. line of a Big mode formula that followed might be shifted over with
  3810. respect to the other lines.
  3811. The `calc-embedded-open-new-formula' variable is a string which is
  3812. inserted at the front of a new formula when you type `C-x * f'. Its
  3813. default value is `"\n\n"'. If this string begins with a newline
  3814. character and the `C-x * f' is typed at the beginning of a line, `C-x *
  3815. f' will skip this first newline to avoid introducing unnecessary blank
  3816. lines in the file.
  3817. The `calc-embedded-close-new-formula' variable is the corresponding
  3818. string which is inserted at the end of a new formula. Its default
  3819. value is also `"\n\n"'. The final newline is omitted by `C-x * f' if
  3820. typed at the end of a line. (It follows that if `C-x * f' is typed on
  3821. a blank line, both a leading opening newline and a trailing closing
  3822. newline are omitted.)
  3823. The `calc-embedded-announce-formula' variable is a regular
  3824. expression which is sure to be followed by an embedded formula. The
  3825. `C-x * a' command searches for this pattern as well as for `=>' and
  3826. `:=' operators. Note that `C-x * a' will not activate just anything
  3827. surrounded by formula delimiters; after all, blank lines are considered
  3828. formula delimiters by default! But if your language includes a
  3829. delimiter which can only occur actually in front of a formula, you can
  3830. take advantage of it here. The default pattern is `"%Embed\n\\(%
  3831. .*\n\\)*"', but may be different for different major modes. This
  3832. pattern will check for `%Embed' followed by any number of lines
  3833. beginning with `%' and a space. This last is important to make Calc
  3834. consider mode annotations part of the pattern, so that the formula's
  3835. opening delimiter really is sure to follow the pattern.
  3836. The `calc-embedded-open-mode' variable is a string (not a regular
  3837. expression) which should precede a mode annotation. Calc never scans
  3838. for this string; Calc always looks for the annotation itself. But this
  3839. is the string that is inserted before the opening bracket when Calc
  3840. adds an annotation on its own. The default is `"% "', but may be
  3841. different for different major modes.
  3842. The `calc-embedded-close-mode' variable is a string which follows a
  3843. mode annotation written by Calc. Its default value is simply a
  3844. newline, `"\n"', but may be different for different major modes. If
  3845. you change this, it is a good idea still to end with a newline so that
  3846. mode annotations will appear on lines by themselves.
  3847. 
  3848. File: calc, Node: Programming, Next: Copying, Prev: Embedded Mode, Up: Top
  3849. 19 Programming
  3850. **************
  3851. There are several ways to "program" the Emacs Calculator, depending on
  3852. the nature of the problem you need to solve.
  3853. 1. "Keyboard macros" allow you to record a sequence of keystrokes and
  3854. play them back at a later time. This is just the standard Emacs
  3855. keyboard macro mechanism, dressed up with a few more features such
  3856. as loops and conditionals.
  3857. 2. "Algebraic definitions" allow you to use any formula to define a
  3858. new function. This function can then be used in algebraic
  3859. formulas or as an interactive command.
  3860. 3. "Rewrite rules" are discussed in the section on algebra commands.
  3861. *Note Rewrite Rules::. If you put your rewrite rules in the
  3862. variable `EvalRules', they will be applied automatically to all
  3863. Calc results in just the same way as an internal "rule" is applied
  3864. to evaluate `sqrt(9)' to 3 and so on. *Note Automatic Rewrites::.
  3865. 4. "Lisp" is the programming language that Calc (and most of Emacs)
  3866. is written in. If the above techniques aren't powerful enough, you
  3867. can write Lisp functions to do anything that built-in Calc commands
  3868. can do. Lisp code is also somewhat faster than keyboard macros or
  3869. rewrite rules.
  3870. Programming features are available through the `z' and `Z' prefix
  3871. keys. New commands that you define are two-key sequences beginning
  3872. with `z'. Commands for managing these definitions use the shift-`Z'
  3873. prefix. (The `Z T' (`calc-timing') command is described elsewhere;
  3874. *note Troubleshooting Commands::. The `Z C'
  3875. (`calc-user-define-composition') command is also described elsewhere;
  3876. *note User-Defined Compositions::.)
  3877. * Menu:
  3878. * Creating User Keys::
  3879. * Keyboard Macros::
  3880. * Invocation Macros::
  3881. * Algebraic Definitions::
  3882. * Lisp Definitions::
  3883. 
  3884. File: calc, Node: Creating User Keys, Next: Keyboard Macros, Prev: Programming, Up: Programming
  3885. 19.1 Creating User Keys
  3886. =======================
  3887. Any Calculator command may be bound to a key using the `Z D'
  3888. (`calc-user-define') command. Actually, it is bound to a two-key
  3889. sequence beginning with the lower-case `z' prefix.
  3890. The `Z D' command first prompts for the key to define. For example,
  3891. press `Z D a' to define the new key sequence `z a'. You are then
  3892. prompted for the name of the Calculator command that this key should
  3893. run. For example, the `calc-sincos' command is not normally available
  3894. on a key. Typing `Z D s sincos <RET>' programs the `z s' key sequence
  3895. to run `calc-sincos'. This definition will remain in effect for the
  3896. rest of this Emacs session, or until you redefine `z s' to be something
  3897. else.
  3898. You can actually bind any Emacs command to a `z' key sequence by
  3899. backspacing over the `calc-' when you are prompted for the command name.
  3900. As with any other prefix key, you can type `z ?' to see a list of
  3901. all the two-key sequences you have defined that start with `z'.
  3902. Initially, no `z' sequences (except `z ?' itself) are defined.
  3903. User keys are typically letters, but may in fact be any key.
  3904. (<META>-keys are not permitted, nor are a terminal's special function
  3905. keys which generate multi-character sequences when pressed.) You can
  3906. define different commands on the shifted and unshifted versions of a
  3907. letter if you wish.
  3908. The `Z U' (`calc-user-undefine') command unbinds a user key. For
  3909. example, the key sequence `Z U s' will undefine the `sincos' key we
  3910. defined above.
  3911. The `Z P' (`calc-user-define-permanent') command makes a key binding
  3912. permanent so that it will remain in effect even in future Emacs
  3913. sessions. (It does this by adding a suitable bit of Lisp code into
  3914. your Calc init file; that is, the file given by the variable
  3915. `calc-settings-file', typically `~/.emacs.d/calc.el'.) For example, `Z
  3916. P s' would register our `sincos' command permanently. If you later
  3917. wish to unregister this command you must edit your Calc init file by
  3918. hand. (*Note General Mode Commands::, for a way to tell Calc to use a
  3919. different file for the Calc init file.)
  3920. The `Z P' command also saves the user definition, if any, for the
  3921. command bound to the key. After `Z F' and `Z C', a given user key
  3922. could invoke a command, which in turn calls an algebraic function,
  3923. which might have one or more special display formats. A single `Z P'
  3924. command will save all of these definitions. To save an algebraic
  3925. function, type `'' (the apostrophe) when prompted for a key, and type
  3926. the function name. To save a command without its key binding, type
  3927. `M-x' and enter a function name. (The `calc-' prefix will
  3928. automatically be inserted for you.) (If the command you give implies a
  3929. function, the function will be saved, and if the function has any
  3930. display formats, those will be saved, but not the other way around:
  3931. Saving a function will not save any commands or key bindings associated
  3932. with the function.)
  3933. The `Z E' (`calc-user-define-edit') command edits the definition of
  3934. a user key. This works for keys that have been defined by either
  3935. keyboard macros or formulas; further details are contained in the
  3936. relevant following sections.
  3937. 
  3938. File: calc, Node: Keyboard Macros, Next: Invocation Macros, Prev: Creating User Keys, Up: Programming
  3939. 19.2 Programming with Keyboard Macros
  3940. =====================================
  3941. The easiest way to "program" the Emacs Calculator is to use standard
  3942. keyboard macros. Press `C-x (' to begin recording a macro. From this
  3943. point on, keystrokes you type will be saved away as well as performing
  3944. their usual functions. Press `C-x )' to end recording. Press
  3945. shift-`X' (or the standard Emacs key sequence `C-x e') to execute your
  3946. keyboard macro by replaying the recorded keystrokes. *Note Keyboard
  3947. Macros: (emacs)Keyboard Macros, for further information.
  3948. When you use `X' to invoke a keyboard macro, the entire macro is
  3949. treated as a single command by the undo and trail features. The stack
  3950. display buffer is not updated during macro execution, but is instead
  3951. fixed up once the macro completes. Thus, commands defined with keyboard
  3952. macros are convenient and efficient. The `C-x e' command, on the other
  3953. hand, invokes the keyboard macro with no special treatment: Each
  3954. command in the macro will record its own undo information and trail
  3955. entry, and update the stack buffer accordingly. If your macro uses
  3956. features outside of Calc's control to operate on the contents of the
  3957. Calc stack buffer, or if it includes Undo, Redo, or last-arguments
  3958. commands, you must use `C-x e' to make sure the buffer and undo list
  3959. are up-to-date at all times. You could also consider using `K'
  3960. (`calc-keep-args') instead of `M-<RET>' (`calc-last-args').
  3961. Calc extends the standard Emacs keyboard macros in several ways.
  3962. Keyboard macros can be used to create user-defined commands. Keyboard
  3963. macros can include conditional and iteration structures, somewhat
  3964. analogous to those provided by a traditional programmable calculator.
  3965. * Menu:
  3966. * Naming Keyboard Macros::
  3967. * Conditionals in Macros::
  3968. * Loops in Macros::
  3969. * Local Values in Macros::
  3970. * Queries in Macros::
  3971. 
  3972. File: calc, Node: Naming Keyboard Macros, Next: Conditionals in Macros, Prev: Keyboard Macros, Up: Keyboard Macros
  3973. 19.2.1 Naming Keyboard Macros
  3974. -----------------------------
  3975. Once you have defined a keyboard macro, you can bind it to a `z' key
  3976. sequence with the `Z K' (`calc-user-define-kbd-macro') command. This
  3977. command prompts first for a key, then for a command name. For example,
  3978. if you type `C-x ( n <TAB> n <TAB> C-x )' you will define a keyboard
  3979. macro which negates the top two numbers on the stack (<TAB> swaps the
  3980. top two stack elements). Now you can type `Z K n <RET>' to define this
  3981. keyboard macro onto the `z n' key sequence. The default command name
  3982. (if you answer the second prompt with just the <RET> key as in this
  3983. example) will be something like `calc-User-n'. The keyboard macro will
  3984. now be available as both `z n' and `M-x calc-User-n'. You can
  3985. backspace and enter a more descriptive command name if you wish.
  3986. Macros defined by `Z K' act like single commands; they are executed
  3987. in the same way as by the `X' key. If you wish to define the macro as
  3988. a standard no-frills Emacs macro (to be executed as if by `C-x e'),
  3989. give a negative prefix argument to `Z K'.
  3990. Once you have bound your keyboard macro to a key, you can use `Z P'
  3991. to register it permanently with Emacs. *Note Creating User Keys::.
  3992. The `Z E' (`calc-user-define-edit') command on a key that has been
  3993. defined by a keyboard macro tries to use the `edmacro' package edit the
  3994. macro. Type `C-c C-c' to finish editing and update the definition
  3995. stored on the key, or, to cancel the edit, kill the buffer with `C-x k'.
  3996. The special characters `RET', `LFD', `TAB', `SPC', `DEL', and `NUL'
  3997. must be entered as these three character sequences, written in all
  3998. uppercase, as must the prefixes `C-' and `M-'. Spaces and line breaks
  3999. are ignored. Other characters are copied verbatim into the keyboard
  4000. macro. Basically, the notation is the same as is used in all of this
  4001. manual's examples, except that the manual takes some liberties with
  4002. spaces: When we say `' [1 2 3] <RET>', we take it for granted that it
  4003. is clear we really mean `' [1 <SPC> 2 <SPC> 3] <RET>'.
  4004. The `C-x * m' (`read-kbd-macro') command reads an Emacs "region" of
  4005. spelled-out keystrokes and defines it as the current keyboard macro.
  4006. It is a convenient way to define a keyboard macro that has been stored
  4007. in a file, or to define a macro without executing it at the same time.
  4008. 
  4009. File: calc, Node: Conditionals in Macros, Next: Loops in Macros, Prev: Naming Keyboard Macros, Up: Keyboard Macros
  4010. 19.2.2 Conditionals in Keyboard Macros
  4011. --------------------------------------
  4012. The `Z [' (`calc-kbd-if') and `Z ]' (`calc-kbd-end-if') commands allow
  4013. you to put simple tests in a keyboard macro. When Calc sees the `Z [',
  4014. it pops an object from the stack and, if the object is a non-zero
  4015. value, continues executing keystrokes. But if the object is zero, or
  4016. if it is not provably nonzero, Calc skips ahead to the matching `Z ]'
  4017. keystroke. *Note Logical Operations::, for a set of commands for
  4018. performing tests which conveniently produce 1 for true and 0 for false.
  4019. For example, `<RET> 0 a < Z [ n Z ]' implements an absolute-value
  4020. function in the form of a keyboard macro. This macro duplicates the
  4021. number on the top of the stack, pushes zero and compares using `a <'
  4022. (`calc-less-than'), then, if the number was less than zero, executes
  4023. `n' (`calc-change-sign'). Otherwise, the change-sign command is
  4024. skipped.
  4025. To program this macro, type `C-x (', type the above sequence of
  4026. keystrokes, then type `C-x )'. Note that the keystrokes will be
  4027. executed while you are making the definition as well as when you later
  4028. re-execute the macro by typing `X'. Thus you should make sure a
  4029. suitable number is on the stack before defining the macro so that you
  4030. don't get a stack-underflow error during the definition process.
  4031. Conditionals can be nested arbitrarily. However, there should be
  4032. exactly one `Z ]' for each `Z [' in a keyboard macro.
  4033. The `Z :' (`calc-kbd-else') command allows you to choose between two
  4034. keystroke sequences. The general format is `COND Z [ THEN-PART Z :
  4035. ELSE-PART Z ]'. If COND is true (i.e., if the top of stack contains a
  4036. non-zero number after COND has been executed), the THEN-PART will be
  4037. executed and the ELSE-PART will be skipped. Otherwise, the THEN-PART
  4038. will be skipped and the ELSE-PART will be executed.
  4039. The `Z |' (`calc-kbd-else-if') command allows you to choose between
  4040. any number of alternatives. For example, `COND1 Z [ PART1 Z : COND2 Z
  4041. | PART2 Z : PART3 Z ]' will execute PART1 if COND1 is true, otherwise
  4042. it will execute PART2 if COND2 is true, otherwise it will execute PART3.
  4043. More precisely, `Z [' pops a number and conditionally skips to the
  4044. next matching `Z :' or `Z ]' key. `Z ]' has no effect when actually
  4045. executed. `Z :' skips to the next matching `Z ]'. `Z |' pops a number
  4046. and conditionally skips to the next matching `Z :' or `Z ]'; thus, `Z
  4047. [' and `Z |' are functionally equivalent except that `Z [' participates
  4048. in nesting but `Z |' does not.
  4049. Calc's conditional and looping constructs work by scanning the
  4050. keyboard macro for occurrences of character sequences like `Z:' and
  4051. `Z]'. One side-effect of this is that if you use these constructs you
  4052. must be careful that these character pairs do not occur by accident in
  4053. other parts of the macros. Since Calc rarely uses shift-`Z' for any
  4054. purpose except as a prefix character, this is not likely to be a
  4055. problem. Another side-effect is that it will not work to define your
  4056. own custom key bindings for these commands. Only the standard
  4057. shift-`Z' bindings will work correctly.
  4058. If Calc gets stuck while skipping characters during the definition
  4059. of a macro, type `Z C-g' to cancel the definition. (Typing plain `C-g'
  4060. actually adds a `C-g' keystroke to the macro.)
  4061. 
  4062. File: calc, Node: Loops in Macros, Next: Local Values in Macros, Prev: Conditionals in Macros, Up: Keyboard Macros
  4063. 19.2.3 Loops in Keyboard Macros
  4064. -------------------------------
  4065. The `Z <' (`calc-kbd-repeat') and `Z >' (`calc-kbd-end-repeat')
  4066. commands pop a number from the stack, which must be an integer, then
  4067. repeat the keystrokes between the brackets the specified number of
  4068. times. If the integer is zero or negative, the body is skipped
  4069. altogether. For example, `1 <TAB> Z < 2 * Z >' computes two to a
  4070. nonnegative integer power. First, we push 1 on the stack and then swap
  4071. the integer argument back to the top. The `Z <' pops that argument
  4072. leaving the 1 back on top of the stack. Then, we repeat a
  4073. multiply-by-two step however many times.
  4074. Once again, the keyboard macro is executed as it is being entered.
  4075. In this case it is especially important to set up reasonable initial
  4076. conditions before making the definition: Suppose the integer 1000 just
  4077. happened to be sitting on the stack before we typed the above
  4078. definition! Another approach is to enter a harmless dummy definition
  4079. for the macro, then go back and edit in the real one with a `Z E'
  4080. command. Yet another approach is to type the macro as written-out
  4081. keystroke names in a buffer, then use `C-x * m' (`read-kbd-macro') to
  4082. read the macro.
  4083. The `Z /' (`calc-kbd-break') command allows you to break out of a
  4084. keyboard macro loop prematurely. It pops an object from the stack; if
  4085. that object is true (a non-zero number), control jumps out of the
  4086. innermost enclosing `Z <' ... `Z >' loop and continues after the `Z >'.
  4087. If the object is false, the `Z /' has no effect. Thus `COND Z /' is
  4088. similar to `if (COND) break;' in the C language.
  4089. The `Z (' (`calc-kbd-for') and `Z )' (`calc-kbd-end-for') commands
  4090. are similar to `Z <' and `Z >', except that they make the value of the
  4091. counter available inside the loop. The general layout is `INIT FINAL Z
  4092. ( BODY STEP Z )'. The `Z (' command pops initial and final values from
  4093. the stack. It then creates a temporary internal counter and
  4094. initializes it with the value INIT. The `Z (' command then repeatedly
  4095. pushes the counter value onto the stack and executes BODY and STEP,
  4096. adding STEP to the counter each time until the loop finishes.
  4097. By default, the loop finishes when the counter becomes greater than
  4098. (or less than) FINAL, assuming INITIAL is less than (greater than)
  4099. FINAL. If INITIAL is equal to FINAL, the body executes exactly once.
  4100. The body of the loop always executes at least once. For example, `0 1
  4101. 10 Z ( 2 ^ + 1 Z )' computes the sum of the squares of the integers
  4102. from 1 to 10, in steps of 1.
  4103. If you give a numeric prefix argument of 1 to `Z (', the loop is
  4104. forced to use upward-counting conventions. In this case, if INITIAL is
  4105. greater than FINAL the body will not be executed at all. Note that
  4106. STEP may still be negative in this loop; the prefix argument merely
  4107. constrains the loop-finished test. Likewise, a prefix argument of -1
  4108. forces downward-counting conventions.
  4109. The `Z {' (`calc-kbd-loop') and `Z }' (`calc-kbd-end-loop') commands
  4110. are similar to `Z <' and `Z >', except that they do not pop a count
  4111. from the stack--they effectively create an infinite loop. Every `Z {'
  4112. ... `Z }' loop ought to include at least one `Z /' to make sure the loop
  4113. doesn't run forever. (If any error message occurs which causes Emacs
  4114. to beep, the keyboard macro will also be halted; this is a standard
  4115. feature of Emacs. You can also generally press `C-g' to halt a running
  4116. keyboard macro, although not all versions of Unix support this feature.)
  4117. The conditional and looping constructs are not actually tied to
  4118. keyboard macros, but they are most often used in that context. For
  4119. example, the keystrokes `10 Z < 23 <RET> Z >' push ten copies of 23
  4120. onto the stack. This can be typed "live" just as easily as in a macro
  4121. definition.
  4122. *Note Conditionals in Macros::, for some additional notes about
  4123. conditional and looping commands.
  4124. 
  4125. File: calc, Node: Local Values in Macros, Next: Queries in Macros, Prev: Loops in Macros, Up: Keyboard Macros
  4126. 19.2.4 Local Values in Macros
  4127. -----------------------------
  4128. Keyboard macros sometimes want to operate under known conditions
  4129. without affecting surrounding conditions. For example, a keyboard
  4130. macro may wish to turn on Fraction mode, or set a particular precision,
  4131. independent of the user's normal setting for those modes.
  4132. Macros also sometimes need to use local variables. Assignments to
  4133. local variables inside the macro should not affect any variables
  4134. outside the macro. The `Z `' (`calc-kbd-push') and `Z ''
  4135. (`calc-kbd-pop') commands give you both of these capabilities.
  4136. When you type `Z `' (with a backquote or accent grave character),
  4137. the values of various mode settings are saved away. The ten "quick"
  4138. variables `q0' through `q9' are also saved. When you type `Z '' (with
  4139. an apostrophe), these values are restored. Pairs of `Z `' and `Z ''
  4140. commands may be nested.
  4141. If a keyboard macro halts due to an error in between a `Z `' and a
  4142. `Z '', the saved values will be restored correctly even though the
  4143. macro never reaches the `Z '' command. Thus you can use `Z `' and `Z
  4144. '' without having to worry about what happens in exceptional conditions.
  4145. If you type `Z `' "live" (not in a keyboard macro), Calc puts you
  4146. into a "recursive edit." You can tell you are in a recursive edit
  4147. because there will be extra square brackets in the mode line, as in
  4148. `[(Calculator)]'. These brackets will go away when you type the
  4149. matching `Z '' command. The modes and quick variables will be saved
  4150. and restored in just the same way as if actual keyboard macros were
  4151. involved.
  4152. The modes saved by `Z `' and `Z '' are the current precision and
  4153. binary word size, the angular mode (Deg, Rad, or HMS), the
  4154. simplification mode, Algebraic mode, Symbolic mode, Infinite mode,
  4155. Matrix or Scalar mode, Fraction mode, and the current complex mode
  4156. (Polar or Rectangular). The ten "quick" variables' values (or lack
  4157. thereof) are also saved.
  4158. Most mode-setting commands act as toggles, but with a numeric prefix
  4159. they force the mode either on (positive prefix) or off (negative or
  4160. zero prefix). Since you don't know what the environment might be when
  4161. you invoke your macro, it's best to use prefix arguments for all
  4162. mode-setting commands inside the macro.
  4163. In fact, `C-u Z `' is like `Z `' except that it sets the modes
  4164. listed above to their default values. As usual, the matching `Z ''
  4165. will restore the modes to their settings from before the `C-u Z `'.
  4166. Also, `Z `' with a negative prefix argument resets the algebraic mode
  4167. to its default (off) but leaves the other modes the same as they were
  4168. outside the construct.
  4169. The contents of the stack and trail, values of non-quick variables,
  4170. and other settings such as the language mode and the various display
  4171. modes, are _not_ affected by `Z `' and `Z ''.
  4172. 
  4173. File: calc, Node: Queries in Macros, Prev: Local Values in Macros, Up: Keyboard Macros
  4174. 19.2.5 Queries in Keyboard Macros
  4175. ---------------------------------
  4176. The `Z #' (`calc-kbd-query') command prompts for an algebraic entry
  4177. which takes its input from the keyboard, even during macro execution.
  4178. All the normal conventions of algebraic input, including the use of `$'
  4179. characters, are supported. The prompt message itself is taken from the
  4180. top of the stack, and so must be entered (as a string) before the `Z #'
  4181. command. (Recall, as a string it can be entered by pressing the `"'
  4182. key and will appear as a vector when it is put on the stack. The
  4183. prompt message is only put on the stack to provide a prompt for the `Z
  4184. #' command; it will not play any role in any subsequent calculations.)
  4185. This command allows your keyboard macros to accept numbers or formulas
  4186. as interactive input.
  4187. As an example, `2 <RET> "Power: " <RET> Z # 3 <RET> ^' will prompt
  4188. for input with "Power: " in the minibuffer, then return 2 to the
  4189. provided power. (The response to the prompt that's given, 3 in this
  4190. example, will not be part of the macro.)
  4191. *Note Keyboard Macro Query: (emacs)Keyboard Macro Query, for a
  4192. description of `C-x q' (`kbd-macro-query'), the standard Emacs way to
  4193. accept keyboard input during a keyboard macro. In particular, you can
  4194. use `C-x q' to enter a recursive edit, which allows the user to perform
  4195. any Calculator operations interactively before pressing `C-M-c' to
  4196. return control to the keyboard macro.
  4197. 
  4198. File: calc, Node: Invocation Macros, Next: Algebraic Definitions, Prev: Keyboard Macros, Up: Programming
  4199. 19.3 Invocation Macros
  4200. ======================
  4201. Calc provides one special keyboard macro, called up by `C-x * z'
  4202. (`calc-user-invocation'), that is intended to allow you to define your
  4203. own special way of starting Calc. To define this "invocation macro,"
  4204. create the macro in the usual way with `C-x (' and `C-x )', then type
  4205. `Z I' (`calc-user-define-invocation'). There is only one invocation
  4206. macro, so you don't need to type any additional letters after `Z I'.
  4207. From now on, you can type `C-x * z' at any time to execute your
  4208. invocation macro.
  4209. For example, suppose you find yourself often grabbing rectangles of
  4210. numbers into Calc and multiplying their columns. You can do this by
  4211. typing `C-x * r' to grab, and `V R : *' to multiply columns. To make
  4212. this into an invocation macro, just type `C-x ( C-x * r V R : * C-x )',
  4213. then `Z I'. Then, to multiply a rectangle of data, just mark the data
  4214. in its buffer in the usual way and type `C-x * z'.
  4215. Invocation macros are treated like regular Emacs keyboard macros;
  4216. all the special features described above for `Z K'-style macros do not
  4217. apply. `C-x * z' is just like `C-x e', except that it uses the macro
  4218. that was last stored by `Z I'. (In fact, the macro does not even have
  4219. to have anything to do with Calc!)
  4220. The `m m' command saves the last invocation macro defined by `Z I'
  4221. along with all the other Calc mode settings. *Note General Mode
  4222. Commands::.
  4223. 
  4224. File: calc, Node: Algebraic Definitions, Next: Lisp Definitions, Prev: Invocation Macros, Up: Programming
  4225. 19.4 Programming with Formulas
  4226. ==============================
  4227. Another way to create a new Calculator command uses algebraic formulas.
  4228. The `Z F' (`calc-user-define-formula') command stores the formula at
  4229. the top of the stack as the definition for a key. This command prompts
  4230. for five things: The key, the command name, the function name, the
  4231. argument list, and the behavior of the command when given non-numeric
  4232. arguments.
  4233. For example, suppose we type `' a+2b <RET>' to push the formula `a +
  4234. 2*b' onto the stack. We now type `Z F m' to define this formula on the
  4235. `z m' key sequence. The next prompt is for a command name, beginning
  4236. with `calc-', which should be the long (`M-x') form for the new
  4237. command. If you simply press <RET>, a default name like `calc-User-m'
  4238. will be constructed. In our example, suppose we enter `spam <RET>' to
  4239. define the new command as `calc-spam'.
  4240. If you want to give the formula a long-style name only, you can press
  4241. <SPC> or <RET> when asked which single key to use. For example `Z F
  4242. <RET> spam <RET>' defines the new command as `M-x calc-spam', with no
  4243. keyboard equivalent.
  4244. The third prompt is for an algebraic function name. The default is
  4245. to use the same name as the command name but without the `calc-'
  4246. prefix. (If this is of the form `User-m', the hyphen is removed so it
  4247. won't be taken for a minus sign in algebraic formulas.) This is the
  4248. name you will use if you want to enter your new function in an
  4249. algebraic formula. Suppose we enter `yow <RET>'. Then the new
  4250. function can be invoked by pushing two numbers on the stack and typing
  4251. `z m' or `x spam', or by entering the algebraic formula `yow(x,y)'.
  4252. The fourth prompt is for the function's argument list. This is used
  4253. to associate values on the stack with the variables that appear in the
  4254. formula. The default is a list of all variables which appear in the
  4255. formula, sorted into alphabetical order. In our case, the default
  4256. would be `(a b)'. This means that, when the user types `z m', the
  4257. Calculator will remove two numbers from the stack, substitute these
  4258. numbers for `a' and `b' (respectively) in the formula, then simplify
  4259. the formula and push the result on the stack. In other words, `10
  4260. <RET> 100 z m' would replace the 10 and 100 on the stack with the
  4261. number 210, which is `a + 2 b' with `a=10' and `b=100'. Likewise, the
  4262. formula `yow(10, 100)' will be evaluated by substituting `a=10' and
  4263. `b=100' in the definition.
  4264. You can rearrange the order of the names before pressing <RET> to
  4265. control which stack positions go to which variables in the formula. If
  4266. you remove a variable from the argument list, that variable will be left
  4267. in symbolic form by the command. Thus using an argument list of `(b)'
  4268. for our function would cause `10 z m' to replace the 10 on the stack
  4269. with the formula `a + 20'. If we had used an argument list of `(b a)',
  4270. the result with inputs 10 and 100 would have been 120.
  4271. You can also put a nameless function on the stack instead of just a
  4272. formula, as in `<a, b : a + 2 b>'. *Note Specifying Operators::. In
  4273. this example, the command will be defined by the formula `a + 2 b'
  4274. using the argument list `(a b)'.
  4275. The final prompt is a y-or-n question concerning what to do if
  4276. symbolic arguments are given to your function. If you answer `y', then
  4277. executing `z m' (using the original argument list `(a b)') with
  4278. arguments `10' and `x' will leave the function in symbolic form, i.e.,
  4279. `yow(10,x)'. On the other hand, if you answer `n', then the formula
  4280. will always be expanded, even for non-constant arguments: `10 + 2 x'.
  4281. If you never plan to feed algebraic formulas to your new function, it
  4282. doesn't matter how you answer this question.
  4283. If you answered `y' to this question you can still cause a function
  4284. call to be expanded by typing `a "' (`calc-expand-formula'). Also,
  4285. Calc will expand the function if necessary when you take a derivative
  4286. or integral or solve an equation involving the function.
  4287. Once you have defined a formula on a key, you can retrieve this
  4288. formula with the `Z G' (`calc-user-define-get-defn') command. Press a
  4289. key, and this command pushes the formula that was used to define that
  4290. key onto the stack. Actually, it pushes a nameless function that
  4291. specifies both the argument list and the defining formula. You will get
  4292. an error message if the key is undefined, or if the key was not defined
  4293. by a `Z F' command.
  4294. The `Z E' (`calc-user-define-edit') command on a key that has been
  4295. defined by a formula uses a variant of the `calc-edit' command to edit
  4296. the defining formula. Press `C-c C-c' to finish editing and store the
  4297. new formula back in the definition, or kill the buffer with `C-x k' to
  4298. cancel the edit. (The argument list and other properties of the
  4299. definition are unchanged; to adjust the argument list, you can use `Z
  4300. G' to grab the function onto the stack, edit with ``', and then
  4301. re-execute the `Z F' command.)
  4302. As usual, the `Z P' command records your definition permanently. In
  4303. this case it will permanently record all three of the relevant
  4304. definitions: the key, the command, and the function.
  4305. You may find it useful to turn off the default simplifications with
  4306. `m O' (`calc-no-simplify-mode') when entering a formula to be used as a
  4307. function definition. For example, the formula `deriv(a^2,v)' which
  4308. might be used to define a new function `dsqr(a,v)' will be "simplified"
  4309. to 0 immediately upon entry since `deriv' considers `a' to be constant
  4310. with respect to `v'. Turning off default simplifications cures this
  4311. problem: The definition will be stored in symbolic form without ever
  4312. activating the `deriv' function. Press `m D' to turn the default
  4313. simplifications back on afterwards.
  4314. 
  4315. File: calc, Node: Lisp Definitions, Prev: Algebraic Definitions, Up: Programming
  4316. 19.5 Programming with Lisp
  4317. ==========================
  4318. The Calculator can be programmed quite extensively in Lisp. All you do
  4319. is write a normal Lisp function definition, but with `defmath' in place
  4320. of `defun'. This has the same form as `defun', but it automagically
  4321. replaces calls to standard Lisp functions like `+' and `zerop' with
  4322. calls to the corresponding functions in Calc's own library. Thus you
  4323. can write natural-looking Lisp code which operates on all of the
  4324. standard Calculator data types. You can then use `Z D' if you wish to
  4325. bind your new command to a `z'-prefix key sequence. The `Z E' command
  4326. will not edit a Lisp-based definition.
  4327. Emacs Lisp is described in the GNU Emacs Lisp Reference Manual.
  4328. This section assumes a familiarity with Lisp programming concepts; if
  4329. you do not know Lisp, you may find keyboard macros or rewrite rules to
  4330. be an easier way to program the Calculator.
  4331. This section first discusses ways to write commands, functions, or
  4332. small programs to be executed inside of Calc. Then it discusses how
  4333. your own separate programs are able to call Calc from the outside.
  4334. Finally, there is a list of internal Calc functions and data structures
  4335. for the true Lisp enthusiast.
  4336. * Menu:
  4337. * Defining Functions::
  4338. * Defining Simple Commands::
  4339. * Defining Stack Commands::
  4340. * Argument Qualifiers::
  4341. * Example Definitions::
  4342. * Calling Calc from Your Programs::
  4343. * Internals::
  4344. 
  4345. File: calc, Node: Defining Functions, Next: Defining Simple Commands, Prev: Lisp Definitions, Up: Lisp Definitions
  4346. 19.5.1 Defining New Functions
  4347. -----------------------------
  4348. The `defmath' function (actually a Lisp macro) is like `defun' except
  4349. that code in the body of the definition can make use of the full range
  4350. of Calculator data types. The prefix `calcFunc-' is added to the
  4351. specified name to get the actual Lisp function name. As a simple
  4352. example,
  4353. (defmath myfact (n)
  4354. (if (> n 0)
  4355. (* n (myfact (1- n)))
  4356. 1))
  4357. This actually expands to the code,
  4358. (defun calcFunc-myfact (n)
  4359. (if (math-posp n)
  4360. (math-mul n (calcFunc-myfact (math-add n -1)))
  4361. 1))
  4362. This function can be used in algebraic expressions, e.g., `myfact(5)'.
  4363. The `myfact' function as it is defined above has the bug that an
  4364. expression `myfact(a+b)' will be simplified to 1 because the formula
  4365. `a+b' is not considered to be `posp'. A robust factorial function
  4366. would be written along the following lines:
  4367. (defmath myfact (n)
  4368. (if (> n 0)
  4369. (* n (myfact (1- n)))
  4370. (if (= n 0)
  4371. 1
  4372. nil))) ; this could be simplified as: (and (= n 0) 1)
  4373. If a function returns `nil', it is left unsimplified by the
  4374. Calculator (except that its arguments will be simplified). Thus,
  4375. `myfact(a+1+2)' will be simplified to `myfact(a+3)' but no further.
  4376. Beware that every time the Calculator reexamines this formula it will
  4377. attempt to resimplify it, so your function ought to detect the
  4378. returning-`nil' case as efficiently as possible.
  4379. The following standard Lisp functions are treated by `defmath': `+',
  4380. `-', `*', `/', `%', `^' or `expt', `=', `<', `>', `<=', `>=', `/=',
  4381. `1+', `1-', `logand', `logior', `logxor', `logandc2', `lognot'. Also,
  4382. `~=' is an abbreviation for `math-nearly-equal', which is useful in
  4383. implementing Taylor series.
  4384. For other functions FUNC, if a function by the name `calcFunc-FUNC'
  4385. exists it is used, otherwise if a function by the name `math-FUNC'
  4386. exists it is used, otherwise if FUNC itself is defined as a function it
  4387. is used, otherwise `calcFunc-FUNC' is used on the assumption that this
  4388. is a to-be-defined math function. Also, if the function name is quoted
  4389. as in `('integerp a)' the function name is always used exactly as
  4390. written (but not quoted).
  4391. Variable names have `var-' prepended to them unless they appear in
  4392. the function's argument list or in an enclosing `let', `let*', `for',
  4393. or `foreach' form, or their names already contain a `-' character.
  4394. Thus a reference to `foo' is the same as a reference to `var-foo'.
  4395. A few other Lisp extensions are available in `defmath' definitions:
  4396. * The `elt' function accepts any number of index variables. Note
  4397. that Calc vectors are stored as Lisp lists whose first element is
  4398. the symbol `vec'; thus, `(elt v 2)' yields the second element of
  4399. vector `v', and `(elt m i j)' yields one element of a Calc matrix.
  4400. * The `setq' function has been extended to act like the Common Lisp
  4401. `setf' function. (The name `setf' is recognized as a synonym of
  4402. `setq'.) Specifically, the first argument of `setq' can be an
  4403. `nth', `elt', `car', or `cdr' form, in which case the effect is to
  4404. store into the specified element of a list. Thus, `(setq (elt m i
  4405. j) x)' stores `x' into one element of a matrix.
  4406. * A `for' looping construct is available. For example, `(for ((i 0
  4407. 10)) body)' executes `body' once for each binding of `i' from zero
  4408. to 10. This is like a `let' form in that `i' is temporarily bound
  4409. to the loop count without disturbing its value outside the `for'
  4410. construct. Nested loops, as in `(for ((i 0 10) (j 0 (1- i) 2))
  4411. body)', are also available. For each value of `i' from zero to 10,
  4412. `j' counts from 0 to `i-1' in steps of two. Note that `for' has
  4413. the same general outline as `let*', except that each element of
  4414. the header is a list of three or four things, not just two.
  4415. * The `foreach' construct loops over elements of a list. For
  4416. example, `(foreach ((x (cdr v))) body)' executes `body' with `x'
  4417. bound to each element of Calc vector `v' in turn. The purpose of
  4418. `cdr' here is to skip over the initial `vec' symbol in the vector.
  4419. * The `break' function breaks out of the innermost enclosing
  4420. `while', `for', or `foreach' loop. If given a value, as in
  4421. `(break x)', this value is returned by the loop. (Lisp loops
  4422. otherwise always return `nil'.)
  4423. * The `return' function prematurely returns from the enclosing
  4424. function. For example, `(return (+ x y))' returns `x+y' as the
  4425. value of a function. You can use `return' anywhere inside the
  4426. body of the function.
  4427. Non-integer numbers (and extremely large integers) cannot be included
  4428. directly into a `defmath' definition. This is because the Lisp reader
  4429. will fail to parse them long before `defmath' ever gets control.
  4430. Instead, use the notation, `:"3.1415"'. In fact, any algebraic formula
  4431. can go between the quotes. For example,
  4432. (defmath sqexp (x) ; sqexp(x) == sqrt(exp(x)) == exp(x*0.5)
  4433. (and (numberp x)
  4434. (exp :"x * 0.5")))
  4435. expands to
  4436. (defun calcFunc-sqexp (x)
  4437. (and (math-numberp x)
  4438. (calcFunc-exp (math-mul x '(float 5 -1)))))
  4439. Note the use of `numberp' as a guard to ensure that the argument is
  4440. a number first, returning `nil' if not. The exponential function could
  4441. itself have been included in the expression, if we had preferred:
  4442. `:"exp(x * 0.5)"'. As another example, the multiplication-and-recursion
  4443. step of `myfact' could have been written
  4444. :"n * myfact(n-1)"
  4445. A good place to put your `defmath' commands is your Calc init file
  4446. (the file given by `calc-settings-file', typically
  4447. `~/.emacs.d/calc.el'), which will not be loaded until Calc starts. If
  4448. a file named `.emacs' exists in your home directory, Emacs reads and
  4449. executes the Lisp forms in this file as it starts up. While it may
  4450. seem reasonable to put your favorite `defmath' commands there, this has
  4451. the unfortunate side-effect that parts of the Calculator must be loaded
  4452. in to process the `defmath' commands whether or not you will actually
  4453. use the Calculator! If you want to put the `defmath' commands there
  4454. (for example, if you redefine `calc-settings-file' to be `.emacs'), a
  4455. better effect can be had by writing
  4456. (put 'calc-define 'thing '(progn
  4457. (defmath ... )
  4458. (defmath ... )
  4459. ))
  4460. The `put' function adds a "property" to a symbol. Each Lisp symbol has
  4461. a list of properties associated with it. Here we add a property with a
  4462. name of `thing' and a `(progn ...)' form as its value. When Calc
  4463. starts up, and at the start of every Calc command, the property list
  4464. for the symbol `calc-define' is checked and the values of any
  4465. properties found are evaluated as Lisp forms. The properties are
  4466. removed as they are evaluated. The property names (like `thing') are
  4467. not used; you should choose something like the name of your project so
  4468. as not to conflict with other properties.
  4469. The net effect is that you can put the above code in your `.emacs'
  4470. file and it will not be executed until Calc is loaded. Or, you can put
  4471. that same code in another file which you load by hand either before or
  4472. after Calc itself is loaded.
  4473. The properties of `calc-define' are evaluated in the same order that
  4474. they were added. They can assume that the Calc modules `calc.el',
  4475. `calc-ext.el', and `calc-macs.el' have been fully loaded, and that the
  4476. `*Calculator*' buffer will be the current buffer.
  4477. If your `calc-define' property only defines algebraic functions, you
  4478. can be sure that it will have been evaluated before Calc tries to call
  4479. your function, even if the file defining the property is loaded after
  4480. Calc is loaded. But if the property defines commands or key sequences,
  4481. it may not be evaluated soon enough. (Suppose it defines the new
  4482. command `tweak-calc'; the user can load your file, then type `M-x
  4483. tweak-calc' before Calc has had chance to do anything.) To protect
  4484. against this situation, you can put
  4485. (run-hooks 'calc-check-defines)
  4486. at the end of your file. The `calc-check-defines' function is what
  4487. looks for and evaluates properties on `calc-define'; `run-hooks' has
  4488. the advantage that it is quietly ignored if `calc-check-defines' is not
  4489. yet defined because Calc has not yet been loaded.
  4490. Examples of things that ought to be enclosed in a `calc-define'
  4491. property are `defmath' calls, `define-key' calls that modify the Calc
  4492. key map, and any calls that redefine things defined inside Calc.
  4493. Ordinary `defun's need not be enclosed with `calc-define'.
  4494. 
  4495. File: calc, Node: Defining Simple Commands, Next: Defining Stack Commands, Prev: Defining Functions, Up: Lisp Definitions
  4496. 19.5.2 Defining New Simple Commands
  4497. -----------------------------------
  4498. If a `defmath' form contains an `interactive' clause, it defines a
  4499. Calculator command. Actually such a `defmath' results in _two_
  4500. function definitions: One, a `calcFunc-' function as was just
  4501. described, with the `interactive' clause removed. Two, a `calc-'
  4502. function with a suitable `interactive' clause and some sort of wrapper
  4503. to make the command work in the Calc environment.
  4504. In the simple case, the `interactive' clause has the same form as
  4505. for normal Emacs Lisp commands:
  4506. (defmath increase-precision (delta)
  4507. "Increase precision by DELTA." ; This is the "documentation string"
  4508. (interactive "p") ; Register this as a M-x-able command
  4509. (setq calc-internal-prec (+ calc-internal-prec delta)))
  4510. This expands to the pair of definitions,
  4511. (defun calc-increase-precision (delta)
  4512. "Increase precision by DELTA."
  4513. (interactive "p")
  4514. (calc-wrapper
  4515. (setq calc-internal-prec (math-add calc-internal-prec delta))))
  4516. (defun calcFunc-increase-precision (delta)
  4517. "Increase precision by DELTA."
  4518. (setq calc-internal-prec (math-add calc-internal-prec delta)))
  4519. where in this case the latter function would never really be used! Note
  4520. that since the Calculator stores small integers as plain Lisp integers,
  4521. the `math-add' function will work just as well as the native `+' even
  4522. when the intent is to operate on native Lisp integers.
  4523. The `calc-wrapper' call invokes a macro which surrounds the body of
  4524. the function with code that looks roughly like this:
  4525. (let ((calc-command-flags nil))
  4526. (unwind-protect
  4527. (save-current-buffer
  4528. (calc-select-buffer)
  4529. _body of function_
  4530. _renumber stack_
  4531. _clear_ Working _message_)
  4532. _realign cursor and window_
  4533. _clear Inverse, Hyperbolic, and Keep Args flags_
  4534. _update Emacs mode line_))
  4535. The `calc-select-buffer' function selects the `*Calculator*' buffer
  4536. if necessary, say, because the command was invoked from inside the
  4537. `*Calc Trail*' window.
  4538. You can call, for example, `(calc-set-command-flag 'no-align)' to
  4539. set the above-mentioned command flags. Calc routines recognize the
  4540. following command flags:
  4541. `renum-stack'
  4542. Stack line numbers `1:', `2:', and so on must be renumbered after
  4543. this command completes. This is set by routines like `calc-push'.
  4544. `clear-message'
  4545. Calc should call `(message "")' if this command completes normally
  4546. (to clear a "Working..." message out of the echo area).
  4547. `no-align'
  4548. Do not move the cursor back to the `.' top-of-stack marker.
  4549. `position-point'
  4550. Use the variables `calc-position-point-line' and
  4551. `calc-position-point-column' to position the cursor after this
  4552. command finishes.
  4553. `keep-flags'
  4554. Do not clear `calc-inverse-flag', `calc-hyperbolic-flag', and
  4555. `calc-keep-args-flag' at the end of this command.
  4556. `do-edit'
  4557. Switch to buffer `*Calc Edit*' after this command.
  4558. `hold-trail'
  4559. Do not move trail pointer to end of trail when something is
  4560. recorded there.
  4561. Calc reserves a special prefix key, shift-`Y', for user-written
  4562. extensions to Calc. There are no built-in commands that work with this
  4563. prefix key; you must call `define-key' from Lisp (probably from inside
  4564. a `calc-define' property) to add to it. Initially only `Y ?' is
  4565. defined; it takes help messages from a list of strings (initially
  4566. `nil') in the variable `calc-Y-help-msgs'. All other undefined keys
  4567. except for `Y' are reserved for use by future versions of Calc.
  4568. If you are writing a Calc enhancement which you expect to give to
  4569. others, it is best to minimize the number of `Y'-key sequences you use.
  4570. In fact, if you have more than one key sequence you should consider
  4571. defining three-key sequences with a `Y', then a key that stands for
  4572. your package, then a third key for the particular command within your
  4573. package.
  4574. Users may wish to install several Calc enhancements, and it is
  4575. possible that several enhancements will choose to use the same key. In
  4576. the example below, a variable `inc-prec-base-key' has been defined to
  4577. contain the key that identifies the `inc-prec' package. Its value is
  4578. initially `"P"', but a user can change this variable if necessary
  4579. without having to modify the file.
  4580. Here is a complete file, `inc-prec.el', which makes a `Y P I'
  4581. command that increases the precision, and a `Y P D' command that
  4582. decreases the precision.
  4583. ;;; Increase and decrease Calc precision. Dave Gillespie, 5/31/91.
  4584. ;; (Include copyright or copyleft stuff here.)
  4585. (defvar inc-prec-base-key "P"
  4586. "Base key for inc-prec.el commands.")
  4587. (put 'calc-define 'inc-prec '(progn
  4588. (define-key calc-mode-map (format "Y%sI" inc-prec-base-key)
  4589. 'increase-precision)
  4590. (define-key calc-mode-map (format "Y%sD" inc-prec-base-key)
  4591. 'decrease-precision)
  4592. (setq calc-Y-help-msgs
  4593. (cons (format "%s + Inc-prec, Dec-prec" inc-prec-base-key)
  4594. calc-Y-help-msgs))
  4595. (defmath increase-precision (delta)
  4596. "Increase precision by DELTA."
  4597. (interactive "p")
  4598. (setq calc-internal-prec (+ calc-internal-prec delta)))
  4599. (defmath decrease-precision (delta)
  4600. "Decrease precision by DELTA."
  4601. (interactive "p")
  4602. (setq calc-internal-prec (- calc-internal-prec delta)))
  4603. )) ; end of calc-define property
  4604. (run-hooks 'calc-check-defines)
  4605. 
  4606. File: calc, Node: Defining Stack Commands, Next: Argument Qualifiers, Prev: Defining Simple Commands, Up: Lisp Definitions
  4607. 19.5.3 Defining New Stack-Based Commands
  4608. ----------------------------------------
  4609. To define a new computational command which takes and/or leaves
  4610. arguments on the stack, a special form of `interactive' clause is used.
  4611. (interactive NUM TAG)
  4612. where NUM is an integer, and TAG is a string. The effect is to pop NUM
  4613. values off the stack, resimplify them by calling `calc-normalize', and
  4614. hand them to your function according to the function's argument list.
  4615. Your function may include `&optional' and `&rest' parameters, so long
  4616. as calling the function with NUM parameters is valid.
  4617. Your function must return either a number or a formula in a form
  4618. acceptable to Calc, or a list of such numbers or formulas. These
  4619. value(s) are pushed onto the stack when the function completes. They
  4620. are also recorded in the Calc Trail buffer on a line beginning with TAG,
  4621. a string of (normally) four characters or less. If you omit TAG or use
  4622. `nil' as a tag, the result is not recorded in the trail.
  4623. As an example, the definition
  4624. (defmath myfact (n)
  4625. "Compute the factorial of the integer at the top of the stack."
  4626. (interactive 1 "fact")
  4627. (if (> n 0)
  4628. (* n (myfact (1- n)))
  4629. (and (= n 0) 1)))
  4630. is a version of the factorial function shown previously which can be
  4631. used as a command as well as an algebraic function. It expands to
  4632. (defun calc-myfact ()
  4633. "Compute the factorial of the integer at the top of the stack."
  4634. (interactive)
  4635. (calc-slow-wrapper
  4636. (calc-enter-result 1 "fact"
  4637. (cons 'calcFunc-myfact (calc-top-list-n 1)))))
  4638. (defun calcFunc-myfact (n)
  4639. "Compute the factorial of the integer at the top of the stack."
  4640. (if (math-posp n)
  4641. (math-mul n (calcFunc-myfact (math-add n -1)))
  4642. (and (math-zerop n) 1)))
  4643. The `calc-slow-wrapper' function is a version of `calc-wrapper' that
  4644. automatically puts up a `Working...' message before the computation
  4645. begins. (This message can be turned off by the user with an `m w'
  4646. (`calc-working') command.)
  4647. The `calc-top-list-n' function returns a list of the specified number
  4648. of values from the top of the stack. It resimplifies each value by
  4649. calling `calc-normalize'. If its argument is zero it returns an empty
  4650. list. It does not actually remove these values from the stack.
  4651. The `calc-enter-result' function takes an integer NUM and string TAG
  4652. as described above, plus a third argument which is either a Calculator
  4653. data object or a list of such objects. These objects are resimplified
  4654. and pushed onto the stack after popping the specified number of values
  4655. from the stack. If TAG is non-`nil', the values being pushed are also
  4656. recorded in the trail.
  4657. Note that if `calcFunc-myfact' returns `nil' this represents "leave
  4658. the function in symbolic form." To return an actual empty list, in the
  4659. sense that `calc-enter-result' will push zero elements back onto the
  4660. stack, you should return the special value `'(nil)', a list containing
  4661. the single symbol `nil'.
  4662. The `interactive' declaration can actually contain a limited
  4663. Emacs-style code string as well which comes just before NUM and TAG.
  4664. Currently the only Emacs code supported is `"p"', as in
  4665. (defmath foo (a b &optional c)
  4666. (interactive "p" 2 "foo")
  4667. BODY)
  4668. In this example, the command `calc-foo' will evaluate the expression
  4669. `foo(a,b)' if executed with no argument, or `foo(a,b,n)' if executed
  4670. with a numeric prefix argument of `n'.
  4671. The other code string allowed is `"m"' (unrelated to the usual `"m"'
  4672. code as used with `defun'). It uses the numeric prefix argument as the
  4673. number of objects to remove from the stack and pass to the function.
  4674. In this case, the integer NUM serves as a default number of arguments
  4675. to be used when no prefix is supplied.
  4676. 
  4677. File: calc, Node: Argument Qualifiers, Next: Example Definitions, Prev: Defining Stack Commands, Up: Lisp Definitions
  4678. 19.5.4 Argument Qualifiers
  4679. --------------------------
  4680. Anywhere a parameter name can appear in the parameter list you can also
  4681. use an "argument qualifier". Thus the general form of a definition is:
  4682. (defmath NAME (PARAM PARAM...
  4683. &optional PARAM PARAM...
  4684. &rest PARAM)
  4685. BODY)
  4686. where each PARAM is either a symbol or a list of the form
  4687. (QUAL PARAM)
  4688. The following qualifiers are recognized:
  4689. `complete'
  4690. The argument must not be an incomplete vector, interval, or
  4691. complex number. (This is rarely needed since the Calculator
  4692. itself will never call your function with an incomplete argument.
  4693. But there is nothing stopping your own Lisp code from calling your
  4694. function with an incomplete argument.)
  4695. `integer'
  4696. The argument must be an integer. If it is an integer-valued float
  4697. it will be accepted but converted to integer form. Non-integers
  4698. and formulas are rejected.
  4699. `natnum'
  4700. Like `integer', but the argument must be non-negative.
  4701. `fixnum'
  4702. Like `integer', but the argument must fit into a native Lisp
  4703. integer, which on most systems means less than 2^23 in absolute
  4704. value. The argument is converted into Lisp-integer form if
  4705. necessary.
  4706. `float'
  4707. The argument is converted to floating-point format if it is a
  4708. number or vector. If it is a formula it is left alone. (The
  4709. argument is never actually rejected by this qualifier.)
  4710. `PRED'
  4711. The argument must satisfy predicate PRED, which is one of the
  4712. standard Calculator predicates. *Note Predicates::.
  4713. `not-PRED'
  4714. The argument must _not_ satisfy predicate PRED.
  4715. For example,
  4716. (defmath foo (a (constp (not-matrixp b)) &optional (float c)
  4717. &rest (integer d))
  4718. BODY)
  4719. expands to
  4720. (defun calcFunc-foo (a b &optional c &rest d)
  4721. (and (math-matrixp b)
  4722. (math-reject-arg b 'not-matrixp))
  4723. (or (math-constp b)
  4724. (math-reject-arg b 'constp))
  4725. (and c (setq c (math-check-float c)))
  4726. (setq d (mapcar 'math-check-integer d))
  4727. BODY)
  4728. which performs the necessary checks and conversions before executing the
  4729. body of the function.
  4730. 
  4731. File: calc, Node: Example Definitions, Next: Calling Calc from Your Programs, Prev: Argument Qualifiers, Up: Lisp Definitions
  4732. 19.5.5 Example Definitions
  4733. --------------------------
  4734. This section includes some Lisp programming examples on a larger scale.
  4735. These programs make use of some of the Calculator's internal functions;
  4736. *note Internals::.
  4737. * Menu:
  4738. * Bit Counting Example::
  4739. * Sine Example::
  4740. 
  4741. File: calc, Node: Bit Counting Example, Next: Sine Example, Prev: Example Definitions, Up: Example Definitions
  4742. 19.5.5.1 Bit-Counting
  4743. .....................
  4744. Calc does not include a built-in function for counting the number of
  4745. "one" bits in a binary integer. It's easy to invent one using `b u' to
  4746. convert the integer to a set, and `V #' to count the elements of that
  4747. set; let's write a function that counts the bits without having to
  4748. create an intermediate set.
  4749. (defmath bcount ((natnum n))
  4750. (interactive 1 "bcnt")
  4751. (let ((count 0))
  4752. (while (> n 0)
  4753. (if (oddp n)
  4754. (setq count (1+ count)))
  4755. (setq n (lsh n -1)))
  4756. count))
  4757. When this is expanded by `defmath', it will become the following Emacs
  4758. Lisp function:
  4759. (defun calcFunc-bcount (n)
  4760. (setq n (math-check-natnum n))
  4761. (let ((count 0))
  4762. (while (math-posp n)
  4763. (if (math-oddp n)
  4764. (setq count (math-add count 1)))
  4765. (setq n (calcFunc-lsh n -1)))
  4766. count))
  4767. If the input numbers are large, this function involves a fair amount
  4768. of arithmetic. A binary right shift is essentially a division by two;
  4769. recall that Calc stores integers in decimal form so bit shifts must
  4770. involve actual division.
  4771. To gain a bit more efficiency, we could divide the integer into
  4772. N-bit chunks, each of which can be handled quickly because they fit
  4773. into Lisp integers. It turns out that Calc's arithmetic routines are
  4774. especially fast when dividing by an integer less than 1000, so we can
  4775. set N = 9 bits and use repeated division by 512:
  4776. (defmath bcount ((natnum n))
  4777. (interactive 1 "bcnt")
  4778. (let ((count 0))
  4779. (while (not (fixnump n))
  4780. (let ((qr (idivmod n 512)))
  4781. (setq count (+ count (bcount-fixnum (cdr qr)))
  4782. n (car qr))))
  4783. (+ count (bcount-fixnum n))))
  4784. (defun bcount-fixnum (n)
  4785. (let ((count 0))
  4786. (while (> n 0)
  4787. (setq count (+ count (logand n 1))
  4788. n (lsh n -1)))
  4789. count))
  4790. Note that the second function uses `defun', not `defmath'. Because
  4791. this function deals only with native Lisp integers ("fixnums"), it can
  4792. use the actual Emacs `+' and related functions rather than the slower
  4793. but more general Calc equivalents which `defmath' uses.
  4794. The `idivmod' function does an integer division, returning both the
  4795. quotient and the remainder at once. Again, note that while it might
  4796. seem that `(logand n 511)' and `(lsh n -9)' are more efficient ways to
  4797. split off the bottom nine bits of `n', actually they are less efficient
  4798. because each operation is really a division by 512 in disguise;
  4799. `idivmod' allows us to do the same thing with a single division by 512.
  4800. 
  4801. File: calc, Node: Sine Example, Prev: Bit Counting Example, Up: Example Definitions
  4802. 19.5.5.2 The Sine Function
  4803. ..........................
  4804. A somewhat limited sine function could be defined as follows, using the
  4805. well-known Taylor series expansion for `sin(x)':
  4806. (defmath mysin ((float (anglep x)))
  4807. (interactive 1 "mysn")
  4808. (setq x (to-radians x)) ; Convert from current angular mode.
  4809. (let ((sum x) ; Initial term of Taylor expansion of sin.
  4810. newsum
  4811. (nfact 1) ; "nfact" equals "n" factorial at all times.
  4812. (xnegsqr :"-(x^2)")) ; "xnegsqr" equals -x^2.
  4813. (for ((n 3 100 2)) ; Upper limit of 100 is a good precaution.
  4814. (working "mysin" sum) ; Display "Working" message, if enabled.
  4815. (setq nfact (* nfact (1- n) n)
  4816. x (* x xnegsqr)
  4817. newsum (+ sum (/ x nfact)))
  4818. (if (~= newsum sum) ; If newsum is "nearly equal to" sum,
  4819. (break)) ; then we are done.
  4820. (setq sum newsum))
  4821. sum))
  4822. The actual `sin' function in Calc works by first reducing the problem
  4823. to a sine or cosine of a nonnegative number less than `pi/4'. This
  4824. ensures that the Taylor series will converge quickly. Also, the
  4825. calculation is carried out with two extra digits of precision to guard
  4826. against cumulative round-off in `sum'. Finally, complex arguments are
  4827. allowed and handled by a separate algorithm.
  4828. (defmath mysin ((float (scalarp x)))
  4829. (interactive 1 "mysn")
  4830. (setq x (to-radians x)) ; Convert from current angular mode.
  4831. (with-extra-prec 2 ; Evaluate with extra precision.
  4832. (cond ((complexp x)
  4833. (mysin-complex x))
  4834. ((< x 0)
  4835. (- (mysin-raw (- x))) ; Always call mysin-raw with x >= 0.
  4836. (t (mysin-raw x))))))
  4837. (defmath mysin-raw (x)
  4838. (cond ((>= x 7)
  4839. (mysin-raw (% x (two-pi)))) ; Now x < 7.
  4840. ((> x (pi-over-2))
  4841. (- (mysin-raw (- x (pi))))) ; Now -pi/2 <= x <= pi/2.
  4842. ((> x (pi-over-4))
  4843. (mycos-raw (- x (pi-over-2)))) ; Now -pi/2 <= x <= pi/4.
  4844. ((< x (- (pi-over-4)))
  4845. (- (mycos-raw (+ x (pi-over-2))))) ; Now -pi/4 <= x <= pi/4,
  4846. (t (mysin-series x)))) ; so the series will be efficient.
  4847. where `mysin-complex' is an appropriate function to handle complex
  4848. numbers, `mysin-series' is the routine to compute the sine Taylor
  4849. series as before, and `mycos-raw' is a function analogous to
  4850. `mysin-raw' for cosines.
  4851. The strategy is to ensure that `x' is nonnegative before calling
  4852. `mysin-raw'. This function then recursively reduces its argument to a
  4853. suitable range, namely, plus-or-minus `pi/4'. Note that each test, and
  4854. particularly the first comparison against 7, is designed so that small
  4855. roundoff errors cannot produce an infinite loop. (Suppose we compared
  4856. with `(two-pi)' instead; if due to roundoff problems the modulo
  4857. operator ever returned `(two-pi)' exactly, an infinite recursion could
  4858. result!) We use modulo only for arguments that will clearly get
  4859. reduced, knowing that the next rule will catch any reductions that this
  4860. rule misses.
  4861. If a program is being written for general use, it is important to
  4862. code it carefully as shown in this second example. For quick-and-dirty
  4863. programs, when you know that your own use of the sine function will
  4864. never encounter a large argument, a simpler program like the first one
  4865. shown is fine.
  4866. 
  4867. File: calc, Node: Calling Calc from Your Programs, Next: Internals, Prev: Example Definitions, Up: Lisp Definitions
  4868. 19.5.6 Calling Calc from Your Lisp Programs
  4869. -------------------------------------------
  4870. A later section (*note Internals::) gives a full description of Calc's
  4871. internal Lisp functions. It's not hard to call Calc from inside your
  4872. programs, but the number of these functions can be daunting. So Calc
  4873. provides one special "programmer-friendly" function called `calc-eval'
  4874. that can be made to do just about everything you need. It's not as
  4875. fast as the low-level Calc functions, but it's much simpler to use!
  4876. It may seem that `calc-eval' itself has a daunting number of
  4877. options, but they all stem from one simple operation.
  4878. In its simplest manifestation, `(calc-eval "1+2")' parses the string
  4879. `"1+2"' as if it were a Calc algebraic entry and returns the result
  4880. formatted as a string: `"3"'.
  4881. Since `calc-eval' is on the list of recommended `autoload'
  4882. functions, you don't need to make any special preparations to load Calc
  4883. before calling `calc-eval' the first time. Calc will be loaded and
  4884. initialized for you.
  4885. All the Calc modes that are currently in effect will be used when
  4886. evaluating the expression and formatting the result.
  4887. 19.5.6.1 Additional Arguments to `calc-eval'
  4888. ............................................
  4889. If the input string parses to a list of expressions, Calc returns the
  4890. results separated by `", "'. You can specify a different separator by
  4891. giving a second string argument to `calc-eval': `(calc-eval "1+2,3+4"
  4892. ";")' returns `"3;7"'.
  4893. The "separator" can also be any of several Lisp symbols which
  4894. request other behaviors from `calc-eval'. These are discussed one by
  4895. one below.
  4896. You can give additional arguments to be substituted for `$', `$$',
  4897. and so on in the main expression. For example, `(calc-eval "$/$$" nil
  4898. "7" "1+1")' evaluates the expression `"7/(1+1)"' to yield the result
  4899. `"3.5"' (assuming Fraction mode is not in effect). Note the `nil' used
  4900. as a placeholder for the item-separator argument.
  4901. 19.5.6.2 Error Handling
  4902. .......................
  4903. If `calc-eval' encounters an error, it returns a list containing the
  4904. character position of the error, plus a suitable message as a string.
  4905. Note that `1 / 0' is _not_ an error by Calc's standards; it simply
  4906. returns the string `"1 / 0"' which is the division left in symbolic
  4907. form. But `(calc-eval "1/")' will return the list `(2 "Expected a
  4908. number")'.
  4909. If you bind the variable `calc-eval-error' to `t' using a `let' form
  4910. surrounding the call to `calc-eval', errors instead call the Emacs
  4911. `error' function which aborts to the Emacs command loop with a beep and
  4912. an error message.
  4913. If you bind this variable to the symbol `string', error messages are
  4914. returned as strings instead of lists. The character position is
  4915. ignored.
  4916. As a courtesy to other Lisp code which may be using Calc, be sure to
  4917. bind `calc-eval-error' using `let' rather than changing it permanently
  4918. with `setq'.
  4919. 19.5.6.3 Numbers Only
  4920. .....................
  4921. Sometimes it is preferable to treat `1 / 0' as an error rather than
  4922. returning a symbolic result. If you pass the symbol `num' as the
  4923. second argument to `calc-eval', results that are not constants are
  4924. treated as errors. The error message reported is the first `calc-why'
  4925. message if there is one, or otherwise "Number expected."
  4926. A result is "constant" if it is a number, vector, or other object
  4927. that does not include variables or function calls. If it is a vector,
  4928. the components must themselves be constants.
  4929. 19.5.6.4 Default Modes
  4930. ......................
  4931. If the first argument to `calc-eval' is a list whose first element is a
  4932. formula string, then `calc-eval' sets all the various Calc modes to
  4933. their default values while the formula is evaluated and formatted. For
  4934. example, the precision is set to 12 digits, digit grouping is turned
  4935. off, and the Normal language mode is used.
  4936. This same principle applies to the other options discussed below.
  4937. If the first argument would normally be X, then it can also be the list
  4938. `(X)' to use the default mode settings.
  4939. If there are other elements in the list, they are taken as
  4940. variable-name/value pairs which override the default mode settings.
  4941. Look at the documentation at the front of the `calc.el' file to find
  4942. the names of the Lisp variables for the various modes. The mode
  4943. settings are restored to their original values when `calc-eval' is done.
  4944. For example, `(calc-eval '("$+$$" calc-internal-prec 8) 'num a b)'
  4945. computes the sum of two numbers, requiring a numeric result, and using
  4946. default mode settings except that the precision is 8 instead of the
  4947. default of 12.
  4948. It's usually best to use this form of `calc-eval' unless your
  4949. program actually considers the interaction with Calc's mode settings to
  4950. be a feature. This will avoid all sorts of potential "gotchas";
  4951. consider what happens with `(calc-eval "sqrt(2)" 'num)' when the user
  4952. has left Calc in Symbolic mode or No-Simplify mode.
  4953. As another example, `(equal (calc-eval '("$<$$") nil a b) "1")'
  4954. checks if the number in string `a' is less than the one in string `b'.
  4955. Without using a list, the integer 1 might come out in a variety of
  4956. formats which would be hard to test for conveniently: `"1"', `"8#1"',
  4957. `"00001"'. (But see "Predicates" mode, below.)
  4958. 19.5.6.5 Raw Numbers
  4959. ....................
  4960. Normally all input and output for `calc-eval' is done with strings.
  4961. You can do arithmetic with, say, `(calc-eval "$+$$" nil a b)' in place
  4962. of `(+ a b)', but this is very inefficient since the numbers must be
  4963. converted to and from string format as they are passed from one
  4964. `calc-eval' to the next.
  4965. If the separator is the symbol `raw', the result will be returned as
  4966. a raw Calc data structure rather than a string. You can read about how
  4967. these objects look in the following sections, but usually you can treat
  4968. them as "black box" objects with no important internal structure.
  4969. There is also a `rawnum' symbol, which is a combination of `raw'
  4970. (returning a raw Calc object) and `num' (signaling an error if that
  4971. object is not a constant).
  4972. You can pass a raw Calc object to `calc-eval' in place of a string,
  4973. either as the formula itself or as one of the `$' arguments. Thus
  4974. `(calc-eval "$+$$" 'raw a b)' is an addition function that operates on
  4975. raw Calc objects. Of course in this case it would be easier to call
  4976. the low-level `math-add' function in Calc, if you can remember its name.
  4977. In particular, note that a plain Lisp integer is acceptable to Calc
  4978. as a raw object. (All Lisp integers are accepted on input, but
  4979. integers of more than six decimal digits are converted to "big-integer"
  4980. form for output. *Note Data Type Formats::.)
  4981. When it comes time to display the object, just use `(calc-eval a)'
  4982. to format it as a string.
  4983. It is an error if the input expression evaluates to a list of
  4984. values. The separator symbol `list' is like `raw' except that it
  4985. returns a list of one or more raw Calc objects.
  4986. Note that a Lisp string is not a valid Calc object, nor is a list
  4987. containing a string. Thus you can still safely distinguish all the
  4988. various kinds of error returns discussed above.
  4989. 19.5.6.6 Predicates
  4990. ...................
  4991. If the separator symbol is `pred', the result of the formula is treated
  4992. as a true/false value; `calc-eval' returns `t' or `nil', respectively.
  4993. A value is considered "true" if it is a non-zero number, or false if it
  4994. is zero or if it is not a number.
  4995. For example, `(calc-eval "$<$$" 'pred a b)' tests whether one value
  4996. is less than another.
  4997. As usual, it is also possible for `calc-eval' to return one of the
  4998. error indicators described above. Lisp will interpret such an
  4999. indicator as "true" if you don't check for it explicitly. If you wish
  5000. to have an error register as "false", use something like `(eq
  5001. (calc-eval ...) t)'.
  5002. 19.5.6.7 Variable Values
  5003. ........................
  5004. Variables in the formula passed to `calc-eval' are not normally
  5005. replaced by their values. If you wish this, you can use the `evalv'
  5006. function (*note Algebraic Manipulation::). For example, if 4 is stored
  5007. in Calc variable `a' (i.e., in Lisp variable `var-a'), then `(calc-eval
  5008. "a+pi")' will return the formula `"a + pi"', but `(calc-eval
  5009. "evalv(a+pi)")' will return `"7.14159265359"'.
  5010. To store in a Calc variable, just use `setq' to store in the
  5011. corresponding Lisp variable. (This is obtained by prepending `var-' to
  5012. the Calc variable name.) Calc routines will understand either string
  5013. or raw form values stored in variables, although raw data objects are
  5014. much more efficient. For example, to increment the Calc variable `a':
  5015. (setq var-a (calc-eval "evalv(a+1)" 'raw))
  5016. 19.5.6.8 Stack Access
  5017. .....................
  5018. If the separator symbol is `push', the formula argument is evaluated
  5019. (with possible `$' expansions, as usual). The result is pushed onto
  5020. the Calc stack. The return value is `nil' (unless there is an error
  5021. from evaluating the formula, in which case the return value depends on
  5022. `calc-eval-error' in the usual way).
  5023. If the separator symbol is `pop', the first argument to `calc-eval'
  5024. must be an integer instead of a string. That many values are popped
  5025. from the stack and thrown away. A negative argument deletes the entry
  5026. at that stack level. The return value is the number of elements
  5027. remaining in the stack after popping; `(calc-eval 0 'pop)' is a good
  5028. way to measure the size of the stack.
  5029. If the separator symbol is `top', the first argument to `calc-eval'
  5030. must again be an integer. The value at that stack level is formatted
  5031. as a string and returned. Thus `(calc-eval 1 'top)' returns the
  5032. top-of-stack value. If the integer is out of range, `nil' is returned.
  5033. The separator symbol `rawtop' is just like `top' except that the
  5034. stack entry is returned as a raw Calc object instead of as a string.
  5035. In all of these cases the first argument can be made a list in order
  5036. to force the default mode settings, as described above. Thus
  5037. `(calc-eval '(2 calc-number-radix 16) 'top)' returns the second-to-top
  5038. stack entry, formatted as a string using the default instead of current
  5039. display modes, except that the radix is hexadecimal instead of decimal.
  5040. It is, of course, polite to put the Calc stack back the way you
  5041. found it when you are done, unless the user of your program is actually
  5042. expecting it to affect the stack.
  5043. Note that you do not actually have to switch into the `*Calculator*'
  5044. buffer in order to use `calc-eval'; it temporarily switches into the
  5045. stack buffer if necessary.
  5046. 19.5.6.9 Keyboard Macros
  5047. ........................
  5048. If the separator symbol is `macro', the first argument must be a string
  5049. of characters which Calc can execute as a sequence of keystrokes. This
  5050. switches into the Calc buffer for the duration of the macro. For
  5051. example, `(calc-eval "vx5\rVR+" 'macro)' pushes the vector
  5052. `[1,2,3,4,5]' on the stack and then replaces it with the sum of those
  5053. numbers. Note that `\r' is the Lisp notation for the carriage-return,
  5054. <RET>, character.
  5055. If your keyboard macro wishes to pop the stack, `\C-d' is safer than
  5056. `\177' (the <DEL> character) because some installations may have
  5057. switched the meanings of <DEL> and `C-h'. Calc always interprets `C-d'
  5058. as a synonym for "pop-stack" regardless of key mapping.
  5059. If you provide a third argument to `calc-eval', evaluation of the
  5060. keyboard macro will leave a record in the Trail using that argument as
  5061. a tag string. Normally the Trail is unaffected.
  5062. The return value in this case is always `nil'.
  5063. 19.5.6.10 Lisp Evaluation
  5064. .........................
  5065. Finally, if the separator symbol is `eval', then the Lisp `eval'
  5066. function is called on the first argument, which must be a Lisp
  5067. expression rather than a Calc formula. Remember to quote the
  5068. expression so that it is not evaluated until inside `calc-eval'.
  5069. The difference from plain `eval' is that `calc-eval' switches to the
  5070. Calc buffer before evaluating the expression. For example, `(calc-eval
  5071. '(setq calc-internal-prec 17) 'eval)' will correctly affect the
  5072. buffer-local Calc precision variable.
  5073. An alternative would be `(calc-eval '(calc-precision 17) 'eval)'.
  5074. This is evaluating a call to the function that is normally invoked by
  5075. the `p' key, giving it 17 as its "numeric prefix argument." Note that
  5076. this function will leave a message in the echo area as a side effect.
  5077. Also, all Calc functions switch to the Calc buffer automatically if not
  5078. invoked from there, so the above call is also equivalent to
  5079. `(calc-precision 17)' by itself. In all cases, Calc uses
  5080. `save-excursion' to switch back to your original buffer when it is done.
  5081. As usual the first argument can be a list that begins with a Lisp
  5082. expression to use default instead of current mode settings.
  5083. The result of `calc-eval' in this usage is just the result returned
  5084. by the evaluated Lisp expression.
  5085. 19.5.6.11 Example
  5086. .................
  5087. Here is a sample Emacs command that uses `calc-eval'. Suppose you have
  5088. a document with lots of references to temperatures on the Fahrenheit
  5089. scale, say "98.6 F", and you wish to convert these references to
  5090. Centigrade. The following command does this conversion. Place the
  5091. Emacs cursor right after the letter "F" and invoke the command to
  5092. change "98.6 F" to "37 C". Or, if the temperature is already in
  5093. Centigrade form, the command changes it back to Fahrenheit.
  5094. (defun convert-temp ()
  5095. (interactive)
  5096. (save-excursion
  5097. (re-search-backward "[^-.0-9]\\([-.0-9]+\\) *\\([FC]\\)")
  5098. (let* ((top1 (match-beginning 1))
  5099. (bot1 (match-end 1))
  5100. (number (buffer-substring top1 bot1))
  5101. (top2 (match-beginning 2))
  5102. (bot2 (match-end 2))
  5103. (type (buffer-substring top2 bot2)))
  5104. (if (equal type "F")
  5105. (setq type "C"
  5106. number (calc-eval "($ - 32)*5/9" nil number))
  5107. (setq type "F"
  5108. number (calc-eval "$*9/5 + 32" nil number)))
  5109. (goto-char top2)
  5110. (delete-region top2 bot2)
  5111. (insert-before-markers type)
  5112. (goto-char top1)
  5113. (delete-region top1 bot1)
  5114. (if (string-match "\\.$" number) ; change "37." to "37"
  5115. (setq number (substring number 0 -1)))
  5116. (insert number))))
  5117. Note the use of `insert-before-markers' when changing between "F"
  5118. and "C", so that the character winds up before the cursor instead of
  5119. after it.