calc.go 236 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067
  1. // Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX / XLSM / XLTM files. Supports reading and writing
  7. // spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports
  8. // complex components by high compatibility, and provided streaming API for
  9. // generating or reading data from a worksheet with huge amounts of data. This
  10. // library needs Go version 1.15 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "container/list"
  15. "errors"
  16. "fmt"
  17. "math"
  18. "math/cmplx"
  19. "math/rand"
  20. "net/url"
  21. "reflect"
  22. "regexp"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "unicode"
  28. "unsafe"
  29. "github.com/xuri/efp"
  30. "golang.org/x/text/language"
  31. "golang.org/x/text/message"
  32. )
  33. // Excel formula errors
  34. const (
  35. formulaErrorDIV = "#DIV/0!"
  36. formulaErrorNAME = "#NAME?"
  37. formulaErrorNA = "#N/A"
  38. formulaErrorNUM = "#NUM!"
  39. formulaErrorVALUE = "#VALUE!"
  40. formulaErrorREF = "#REF!"
  41. formulaErrorNULL = "#NULL"
  42. formulaErrorSPILL = "#SPILL!"
  43. formulaErrorCALC = "#CALC!"
  44. formulaErrorGETTINGDATA = "#GETTING_DATA"
  45. )
  46. // Numeric precision correct numeric values as legacy Excel application
  47. // https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft_Excel In the
  48. // top figure the fraction 1/9000 in Excel is displayed. Although this number
  49. // has a decimal representation that is an infinite string of ones, Excel
  50. // displays only the leading 15 figures. In the second line, the number one
  51. // is added to the fraction, and again Excel displays only 15 figures.
  52. const numericPrecision = 1000000000000000
  53. const maxFinancialIterations = 128
  54. const financialPercision = 1.0e-08
  55. // cellRef defines the structure of a cell reference.
  56. type cellRef struct {
  57. Col int
  58. Row int
  59. Sheet string
  60. }
  61. // cellRef defines the structure of a cell range.
  62. type cellRange struct {
  63. From cellRef
  64. To cellRef
  65. }
  66. // formula criteria condition enumeration.
  67. const (
  68. _ byte = iota
  69. criteriaEq
  70. criteriaLe
  71. criteriaGe
  72. criteriaL
  73. criteriaG
  74. criteriaBeg
  75. criteriaEnd
  76. criteriaErr
  77. )
  78. // formulaCriteria defined formula criteria parser result.
  79. type formulaCriteria struct {
  80. Type byte
  81. Condition string
  82. }
  83. // ArgType is the type if formula argument type.
  84. type ArgType byte
  85. // Formula argument types enumeration.
  86. const (
  87. ArgUnknown ArgType = iota
  88. ArgNumber
  89. ArgString
  90. ArgList
  91. ArgMatrix
  92. ArgError
  93. ArgEmpty
  94. )
  95. // formulaArg is the argument of a formula or function.
  96. type formulaArg struct {
  97. SheetName string
  98. Number float64
  99. String string
  100. List []formulaArg
  101. Matrix [][]formulaArg
  102. Boolean bool
  103. Error string
  104. Type ArgType
  105. cellRefs, cellRanges *list.List
  106. }
  107. // Value returns a string data type of the formula argument.
  108. func (fa formulaArg) Value() (value string) {
  109. switch fa.Type {
  110. case ArgNumber:
  111. if fa.Boolean {
  112. if fa.Number == 0 {
  113. return "FALSE"
  114. }
  115. return "TRUE"
  116. }
  117. return fmt.Sprintf("%g", fa.Number)
  118. case ArgString:
  119. return fa.String
  120. case ArgError:
  121. return fa.Error
  122. }
  123. return
  124. }
  125. // ToNumber returns a formula argument with number data type.
  126. func (fa formulaArg) ToNumber() formulaArg {
  127. var n float64
  128. var err error
  129. switch fa.Type {
  130. case ArgString:
  131. n, err = strconv.ParseFloat(fa.String, 64)
  132. if err != nil {
  133. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  134. }
  135. case ArgNumber:
  136. n = fa.Number
  137. }
  138. return newNumberFormulaArg(n)
  139. }
  140. // ToBool returns a formula argument with boolean data type.
  141. func (fa formulaArg) ToBool() formulaArg {
  142. var b bool
  143. var err error
  144. switch fa.Type {
  145. case ArgString:
  146. b, err = strconv.ParseBool(fa.String)
  147. if err != nil {
  148. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  149. }
  150. case ArgNumber:
  151. if fa.Boolean && fa.Number == 1 {
  152. b = true
  153. }
  154. }
  155. return newBoolFormulaArg(b)
  156. }
  157. // ToList returns a formula argument with array data type.
  158. func (fa formulaArg) ToList() []formulaArg {
  159. switch fa.Type {
  160. case ArgMatrix:
  161. list := []formulaArg{}
  162. for _, row := range fa.Matrix {
  163. list = append(list, row...)
  164. }
  165. return list
  166. case ArgList:
  167. return fa.List
  168. case ArgNumber, ArgString, ArgError, ArgUnknown:
  169. return []formulaArg{fa}
  170. }
  171. return nil
  172. }
  173. // formulaFuncs is the type of the formula functions.
  174. type formulaFuncs struct {
  175. f *File
  176. sheet, cell string
  177. }
  178. // tokenPriority defined basic arithmetic operator priority.
  179. var tokenPriority = map[string]int{
  180. "^": 5,
  181. "*": 4,
  182. "/": 4,
  183. "+": 3,
  184. "-": 3,
  185. "=": 2,
  186. "<>": 2,
  187. "<": 2,
  188. "<=": 2,
  189. ">": 2,
  190. ">=": 2,
  191. "&": 1,
  192. }
  193. // CalcCellValue provides a function to get calculated cell value. This
  194. // feature is currently in working processing. Array formula, table formula
  195. // and some other formulas are not supported currently.
  196. //
  197. // Supported formula functions:
  198. //
  199. // ABS
  200. // ACOS
  201. // ACOSH
  202. // ACOT
  203. // ACOTH
  204. // AND
  205. // ARABIC
  206. // ASIN
  207. // ASINH
  208. // ATAN
  209. // ATAN2
  210. // ATANH
  211. // AVERAGE
  212. // AVERAGEA
  213. // BASE
  214. // BESSELI
  215. // BESSELJ
  216. // BESSELK
  217. // BESSELY
  218. // BIN2DEC
  219. // BIN2HEX
  220. // BIN2OCT
  221. // BITAND
  222. // BITLSHIFT
  223. // BITOR
  224. // BITRSHIFT
  225. // BITXOR
  226. // CEILING
  227. // CEILING.MATH
  228. // CEILING.PRECISE
  229. // CHAR
  230. // CHOOSE
  231. // CLEAN
  232. // CODE
  233. // COLUMN
  234. // COLUMNS
  235. // COMBIN
  236. // COMBINA
  237. // COMPLEX
  238. // CONCAT
  239. // CONCATENATE
  240. // COS
  241. // COSH
  242. // COT
  243. // COTH
  244. // COUNT
  245. // COUNTA
  246. // COUNTBLANK
  247. // CSC
  248. // CSCH
  249. // CUMIPMT
  250. // CUMPRINC
  251. // DATE
  252. // DATEDIF
  253. // DB
  254. // DDB
  255. // DEC2BIN
  256. // DEC2HEX
  257. // DEC2OCT
  258. // DECIMAL
  259. // DEGREES
  260. // DOLLARDE
  261. // DOLLARFR
  262. // EFFECT
  263. // ENCODEURL
  264. // EVEN
  265. // EXACT
  266. // EXP
  267. // FACT
  268. // FACTDOUBLE
  269. // FALSE
  270. // FIND
  271. // FINDB
  272. // FISHER
  273. // FISHERINV
  274. // FIXED
  275. // FLOOR
  276. // FLOOR.MATH
  277. // FLOOR.PRECISE
  278. // FV
  279. // FVSCHEDULE
  280. // GAMMA
  281. // GAMMALN
  282. // GCD
  283. // HARMEAN
  284. // HEX2BIN
  285. // HEX2DEC
  286. // HEX2OCT
  287. // HLOOKUP
  288. // IF
  289. // IFERROR
  290. // IMABS
  291. // IMAGINARY
  292. // IMARGUMENT
  293. // IMCONJUGATE
  294. // IMCOS
  295. // IMCOSH
  296. // IMCOT
  297. // IMCSC
  298. // IMCSCH
  299. // IMDIV
  300. // IMEXP
  301. // IMLN
  302. // IMLOG10
  303. // IMLOG2
  304. // IMPOWER
  305. // IMPRODUCT
  306. // IMREAL
  307. // IMSEC
  308. // IMSECH
  309. // IMSIN
  310. // IMSINH
  311. // IMSQRT
  312. // IMSUB
  313. // IMSUM
  314. // IMTAN
  315. // INT
  316. // IPMT
  317. // IRR
  318. // ISBLANK
  319. // ISERR
  320. // ISERROR
  321. // ISEVEN
  322. // ISNA
  323. // ISNONTEXT
  324. // ISNUMBER
  325. // ISODD
  326. // ISTEXT
  327. // ISO.CEILING
  328. // ISPMT
  329. // KURT
  330. // LARGE
  331. // LCM
  332. // LEFT
  333. // LEFTB
  334. // LEN
  335. // LENB
  336. // LN
  337. // LOG
  338. // LOG10
  339. // LOOKUP
  340. // LOWER
  341. // MAX
  342. // MDETERM
  343. // MEDIAN
  344. // MID
  345. // MIDB
  346. // MIN
  347. // MINA
  348. // MIRR
  349. // MOD
  350. // MROUND
  351. // MULTINOMIAL
  352. // MUNIT
  353. // N
  354. // NA
  355. // NOMINAL
  356. // NORM.DIST
  357. // NORMDIST
  358. // NORM.INV
  359. // NORMINV
  360. // NORM.S.DIST
  361. // NORMSDIST
  362. // NORM.S.INV
  363. // NORMSINV
  364. // NOT
  365. // NOW
  366. // NPER
  367. // NPV
  368. // OCT2BIN
  369. // OCT2DEC
  370. // OCT2HEX
  371. // ODD
  372. // OR
  373. // PDURATION
  374. // PERCENTILE.INC
  375. // PERCENTILE
  376. // PERMUT
  377. // PERMUTATIONA
  378. // PI
  379. // PMT
  380. // POISSON.DIST
  381. // POISSON
  382. // POWER
  383. // PPMT
  384. // PRODUCT
  385. // PROPER
  386. // QUARTILE
  387. // QUARTILE.INC
  388. // QUOTIENT
  389. // RADIANS
  390. // RAND
  391. // RANDBETWEEN
  392. // REPLACE
  393. // REPLACEB
  394. // REPT
  395. // RIGHT
  396. // RIGHTB
  397. // ROMAN
  398. // ROUND
  399. // ROUNDDOWN
  400. // ROUNDUP
  401. // ROW
  402. // ROWS
  403. // SEC
  404. // SECH
  405. // SHEET
  406. // SIGN
  407. // SIN
  408. // SINH
  409. // SKEW
  410. // SMALL
  411. // SQRT
  412. // SQRTPI
  413. // STDEV
  414. // STDEV.S
  415. // STDEVA
  416. // SUBSTITUTE
  417. // SUM
  418. // SUMIF
  419. // SUMSQ
  420. // T
  421. // TAN
  422. // TANH
  423. // TODAY
  424. // TRIM
  425. // TRUE
  426. // TRUNC
  427. // UNICHAR
  428. // UNICODE
  429. // UPPER
  430. // VAR.P
  431. // VARP
  432. // VLOOKUP
  433. //
  434. func (f *File) CalcCellValue(sheet, cell string) (result string, err error) {
  435. var (
  436. formula string
  437. token efp.Token
  438. )
  439. if formula, err = f.GetCellFormula(sheet, cell); err != nil {
  440. return
  441. }
  442. ps := efp.ExcelParser()
  443. tokens := ps.Parse(formula)
  444. if tokens == nil {
  445. return
  446. }
  447. if token, err = f.evalInfixExp(sheet, cell, tokens); err != nil {
  448. return
  449. }
  450. result = token.TValue
  451. isNum, precision := isNumeric(result)
  452. if isNum && precision > 15 {
  453. num, _ := roundPrecision(result)
  454. result = strings.ToUpper(num)
  455. }
  456. return
  457. }
  458. // getPriority calculate arithmetic operator priority.
  459. func getPriority(token efp.Token) (pri int) {
  460. pri = tokenPriority[token.TValue]
  461. if token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix {
  462. pri = 6
  463. }
  464. if isBeginParenthesesToken(token) { // (
  465. pri = 0
  466. }
  467. return
  468. }
  469. // newNumberFormulaArg constructs a number formula argument.
  470. func newNumberFormulaArg(n float64) formulaArg {
  471. if math.IsNaN(n) {
  472. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  473. }
  474. return formulaArg{Type: ArgNumber, Number: n}
  475. }
  476. // newStringFormulaArg constructs a string formula argument.
  477. func newStringFormulaArg(s string) formulaArg {
  478. return formulaArg{Type: ArgString, String: s}
  479. }
  480. // newMatrixFormulaArg constructs a matrix formula argument.
  481. func newMatrixFormulaArg(m [][]formulaArg) formulaArg {
  482. return formulaArg{Type: ArgMatrix, Matrix: m}
  483. }
  484. // newListFormulaArg create a list formula argument.
  485. func newListFormulaArg(l []formulaArg) formulaArg {
  486. return formulaArg{Type: ArgList, List: l}
  487. }
  488. // newBoolFormulaArg constructs a boolean formula argument.
  489. func newBoolFormulaArg(b bool) formulaArg {
  490. var n float64
  491. if b {
  492. n = 1
  493. }
  494. return formulaArg{Type: ArgNumber, Number: n, Boolean: true}
  495. }
  496. // newErrorFormulaArg create an error formula argument of a given type with a
  497. // specified error message.
  498. func newErrorFormulaArg(formulaError, msg string) formulaArg {
  499. return formulaArg{Type: ArgError, String: formulaError, Error: msg}
  500. }
  501. // newEmptyFormulaArg create an empty formula argument.
  502. func newEmptyFormulaArg() formulaArg {
  503. return formulaArg{Type: ArgEmpty}
  504. }
  505. // evalInfixExp evaluate syntax analysis by given infix expression after
  506. // lexical analysis. Evaluate an infix expression containing formulas by
  507. // stacks:
  508. //
  509. // opd - Operand
  510. // opt - Operator
  511. // opf - Operation formula
  512. // opfd - Operand of the operation formula
  513. // opft - Operator of the operation formula
  514. // args - Arguments list of the operation formula
  515. //
  516. // TODO: handle subtypes: Nothing, Text, Logical, Error, Concatenation, Intersection, Union
  517. //
  518. func (f *File) evalInfixExp(sheet, cell string, tokens []efp.Token) (efp.Token, error) {
  519. var err error
  520. opdStack, optStack, opfStack, opfdStack, opftStack, argsStack := NewStack(), NewStack(), NewStack(), NewStack(), NewStack(), NewStack()
  521. for i := 0; i < len(tokens); i++ {
  522. token := tokens[i]
  523. // out of function stack
  524. if opfStack.Len() == 0 {
  525. if err = f.parseToken(sheet, token, opdStack, optStack); err != nil {
  526. return efp.Token{}, err
  527. }
  528. }
  529. // function start
  530. if isFunctionStartToken(token) {
  531. opfStack.Push(token)
  532. argsStack.Push(list.New().Init())
  533. continue
  534. }
  535. // in function stack, walk 2 token at once
  536. if opfStack.Len() > 0 {
  537. var nextToken efp.Token
  538. if i+1 < len(tokens) {
  539. nextToken = tokens[i+1]
  540. }
  541. // current token is args or range, skip next token, order required: parse reference first
  542. if token.TSubType == efp.TokenSubTypeRange {
  543. if !opftStack.Empty() {
  544. // parse reference: must reference at here
  545. result, err := f.parseReference(sheet, token.TValue)
  546. if err != nil {
  547. return efp.Token{TValue: formulaErrorNAME}, err
  548. }
  549. if result.Type != ArgString {
  550. return efp.Token{}, errors.New(formulaErrorVALUE)
  551. }
  552. opfdStack.Push(efp.Token{
  553. TType: efp.TokenTypeOperand,
  554. TSubType: efp.TokenSubTypeNumber,
  555. TValue: result.String,
  556. })
  557. continue
  558. }
  559. if nextToken.TType == efp.TokenTypeArgument || nextToken.TType == efp.TokenTypeFunction {
  560. // parse reference: reference or range at here
  561. result, err := f.parseReference(sheet, token.TValue)
  562. if err != nil {
  563. return efp.Token{TValue: formulaErrorNAME}, err
  564. }
  565. if result.Type == ArgUnknown {
  566. return efp.Token{}, errors.New(formulaErrorVALUE)
  567. }
  568. argsStack.Peek().(*list.List).PushBack(result)
  569. continue
  570. }
  571. }
  572. // check current token is opft
  573. if err = f.parseToken(sheet, token, opfdStack, opftStack); err != nil {
  574. return efp.Token{}, err
  575. }
  576. // current token is arg
  577. if token.TType == efp.TokenTypeArgument {
  578. for !opftStack.Empty() {
  579. // calculate trigger
  580. topOpt := opftStack.Peek().(efp.Token)
  581. if err := calculate(opfdStack, topOpt); err != nil {
  582. argsStack.Peek().(*list.List).PushFront(newErrorFormulaArg(formulaErrorVALUE, err.Error()))
  583. }
  584. opftStack.Pop()
  585. }
  586. if !opfdStack.Empty() {
  587. argsStack.Peek().(*list.List).PushBack(newStringFormulaArg(opfdStack.Pop().(efp.Token).TValue))
  588. }
  589. continue
  590. }
  591. // current token is logical
  592. if token.TType == efp.OperatorsInfix && token.TSubType == efp.TokenSubTypeLogical {
  593. }
  594. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeLogical {
  595. argsStack.Peek().(*list.List).PushBack(newStringFormulaArg(token.TValue))
  596. }
  597. // current token is text
  598. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeText {
  599. argsStack.Peek().(*list.List).PushBack(newStringFormulaArg(token.TValue))
  600. }
  601. if err = f.evalInfixExpFunc(sheet, cell, token, nextToken, opfStack, opdStack, opftStack, opfdStack, argsStack); err != nil {
  602. return efp.Token{}, err
  603. }
  604. }
  605. }
  606. for optStack.Len() != 0 {
  607. topOpt := optStack.Peek().(efp.Token)
  608. if err = calculate(opdStack, topOpt); err != nil {
  609. return efp.Token{}, err
  610. }
  611. optStack.Pop()
  612. }
  613. if opdStack.Len() == 0 {
  614. return efp.Token{}, ErrInvalidFormula
  615. }
  616. return opdStack.Peek().(efp.Token), err
  617. }
  618. // evalInfixExpFunc evaluate formula function in the infix expression.
  619. func (f *File) evalInfixExpFunc(sheet, cell string, token, nextToken efp.Token, opfStack, opdStack, opftStack, opfdStack, argsStack *Stack) error {
  620. if !isFunctionStopToken(token) {
  621. return nil
  622. }
  623. // current token is function stop
  624. for !opftStack.Empty() {
  625. // calculate trigger
  626. topOpt := opftStack.Peek().(efp.Token)
  627. if err := calculate(opfdStack, topOpt); err != nil {
  628. return err
  629. }
  630. opftStack.Pop()
  631. }
  632. // push opfd to args
  633. if opfdStack.Len() > 0 {
  634. argsStack.Peek().(*list.List).PushBack(newStringFormulaArg(opfdStack.Pop().(efp.Token).TValue))
  635. }
  636. // call formula function to evaluate
  637. arg := callFuncByName(&formulaFuncs{f: f, sheet: sheet, cell: cell}, strings.NewReplacer(
  638. "_xlfn.", "", ".", "dot").Replace(opfStack.Peek().(efp.Token).TValue),
  639. []reflect.Value{reflect.ValueOf(argsStack.Peek().(*list.List))})
  640. if arg.Type == ArgError && opfStack.Len() == 1 {
  641. return errors.New(arg.Value())
  642. }
  643. argsStack.Pop()
  644. opfStack.Pop()
  645. if opfStack.Len() > 0 { // still in function stack
  646. if nextToken.TType == efp.TokenTypeOperatorInfix {
  647. // mathematics calculate in formula function
  648. opfdStack.Push(efp.Token{TValue: arg.Value(), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  649. } else {
  650. argsStack.Peek().(*list.List).PushBack(arg)
  651. }
  652. } else {
  653. opdStack.Push(efp.Token{TValue: arg.Value(), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  654. }
  655. return nil
  656. }
  657. // calcPow evaluate exponentiation arithmetic operations.
  658. func calcPow(rOpd, lOpd string, opdStack *Stack) error {
  659. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  660. if err != nil {
  661. return err
  662. }
  663. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  664. if err != nil {
  665. return err
  666. }
  667. result := math.Pow(lOpdVal, rOpdVal)
  668. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  669. return nil
  670. }
  671. // calcEq evaluate equal arithmetic operations.
  672. func calcEq(rOpd, lOpd string, opdStack *Stack) error {
  673. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpd == lOpd)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  674. return nil
  675. }
  676. // calcNEq evaluate not equal arithmetic operations.
  677. func calcNEq(rOpd, lOpd string, opdStack *Stack) error {
  678. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpd != lOpd)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  679. return nil
  680. }
  681. // calcL evaluate less than arithmetic operations.
  682. func calcL(rOpd, lOpd string, opdStack *Stack) error {
  683. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  684. if err != nil {
  685. return err
  686. }
  687. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  688. if err != nil {
  689. return err
  690. }
  691. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal > lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  692. return nil
  693. }
  694. // calcLe evaluate less than or equal arithmetic operations.
  695. func calcLe(rOpd, lOpd string, opdStack *Stack) error {
  696. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  697. if err != nil {
  698. return err
  699. }
  700. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  701. if err != nil {
  702. return err
  703. }
  704. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal >= lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  705. return nil
  706. }
  707. // calcG evaluate greater than or equal arithmetic operations.
  708. func calcG(rOpd, lOpd string, opdStack *Stack) error {
  709. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  710. if err != nil {
  711. return err
  712. }
  713. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  714. if err != nil {
  715. return err
  716. }
  717. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal < lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  718. return nil
  719. }
  720. // calcGe evaluate greater than or equal arithmetic operations.
  721. func calcGe(rOpd, lOpd string, opdStack *Stack) error {
  722. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  723. if err != nil {
  724. return err
  725. }
  726. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  727. if err != nil {
  728. return err
  729. }
  730. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal <= lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  731. return nil
  732. }
  733. // calcSplice evaluate splice '&' operations.
  734. func calcSplice(rOpd, lOpd string, opdStack *Stack) error {
  735. opdStack.Push(efp.Token{TValue: lOpd + rOpd, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  736. return nil
  737. }
  738. // calcAdd evaluate addition arithmetic operations.
  739. func calcAdd(rOpd, lOpd string, opdStack *Stack) error {
  740. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  741. if err != nil {
  742. return err
  743. }
  744. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  745. if err != nil {
  746. return err
  747. }
  748. result := lOpdVal + rOpdVal
  749. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  750. return nil
  751. }
  752. // calcSubtract evaluate subtraction arithmetic operations.
  753. func calcSubtract(rOpd, lOpd string, opdStack *Stack) error {
  754. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  755. if err != nil {
  756. return err
  757. }
  758. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  759. if err != nil {
  760. return err
  761. }
  762. result := lOpdVal - rOpdVal
  763. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  764. return nil
  765. }
  766. // calcMultiply evaluate multiplication arithmetic operations.
  767. func calcMultiply(rOpd, lOpd string, opdStack *Stack) error {
  768. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  769. if err != nil {
  770. return err
  771. }
  772. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  773. if err != nil {
  774. return err
  775. }
  776. result := lOpdVal * rOpdVal
  777. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  778. return nil
  779. }
  780. // calcDiv evaluate division arithmetic operations.
  781. func calcDiv(rOpd, lOpd string, opdStack *Stack) error {
  782. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  783. if err != nil {
  784. return err
  785. }
  786. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  787. if err != nil {
  788. return err
  789. }
  790. result := lOpdVal / rOpdVal
  791. if rOpdVal == 0 {
  792. return errors.New(formulaErrorDIV)
  793. }
  794. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  795. return nil
  796. }
  797. // calculate evaluate basic arithmetic operations.
  798. func calculate(opdStack *Stack, opt efp.Token) error {
  799. if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorPrefix {
  800. if opdStack.Len() < 1 {
  801. return ErrInvalidFormula
  802. }
  803. opd := opdStack.Pop().(efp.Token)
  804. opdVal, err := strconv.ParseFloat(opd.TValue, 64)
  805. if err != nil {
  806. return err
  807. }
  808. result := 0 - opdVal
  809. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  810. }
  811. tokenCalcFunc := map[string]func(rOpd, lOpd string, opdStack *Stack) error{
  812. "^": calcPow,
  813. "*": calcMultiply,
  814. "/": calcDiv,
  815. "+": calcAdd,
  816. "=": calcEq,
  817. "<>": calcNEq,
  818. "<": calcL,
  819. "<=": calcLe,
  820. ">": calcG,
  821. ">=": calcGe,
  822. "&": calcSplice,
  823. }
  824. if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorInfix {
  825. if opdStack.Len() < 2 {
  826. return ErrInvalidFormula
  827. }
  828. rOpd := opdStack.Pop().(efp.Token)
  829. lOpd := opdStack.Pop().(efp.Token)
  830. if err := calcSubtract(rOpd.TValue, lOpd.TValue, opdStack); err != nil {
  831. return err
  832. }
  833. }
  834. fn, ok := tokenCalcFunc[opt.TValue]
  835. if ok {
  836. if opdStack.Len() < 2 {
  837. return ErrInvalidFormula
  838. }
  839. rOpd := opdStack.Pop().(efp.Token)
  840. lOpd := opdStack.Pop().(efp.Token)
  841. if err := fn(rOpd.TValue, lOpd.TValue, opdStack); err != nil {
  842. return err
  843. }
  844. }
  845. return nil
  846. }
  847. // parseOperatorPrefixToken parse operator prefix token.
  848. func (f *File) parseOperatorPrefixToken(optStack, opdStack *Stack, token efp.Token) (err error) {
  849. if optStack.Len() == 0 {
  850. optStack.Push(token)
  851. } else {
  852. tokenPriority := getPriority(token)
  853. topOpt := optStack.Peek().(efp.Token)
  854. topOptPriority := getPriority(topOpt)
  855. if tokenPriority > topOptPriority {
  856. optStack.Push(token)
  857. } else {
  858. for tokenPriority <= topOptPriority {
  859. optStack.Pop()
  860. if err = calculate(opdStack, topOpt); err != nil {
  861. return
  862. }
  863. if optStack.Len() > 0 {
  864. topOpt = optStack.Peek().(efp.Token)
  865. topOptPriority = getPriority(topOpt)
  866. continue
  867. }
  868. break
  869. }
  870. optStack.Push(token)
  871. }
  872. }
  873. return
  874. }
  875. // isFunctionStartToken determine if the token is function stop.
  876. func isFunctionStartToken(token efp.Token) bool {
  877. return token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStart
  878. }
  879. // isFunctionStopToken determine if the token is function stop.
  880. func isFunctionStopToken(token efp.Token) bool {
  881. return token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStop
  882. }
  883. // isBeginParenthesesToken determine if the token is begin parentheses: (.
  884. func isBeginParenthesesToken(token efp.Token) bool {
  885. return token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStart
  886. }
  887. // isEndParenthesesToken determine if the token is end parentheses: ).
  888. func isEndParenthesesToken(token efp.Token) bool {
  889. return token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStop
  890. }
  891. // isOperatorPrefixToken determine if the token is parse operator prefix
  892. // token.
  893. func isOperatorPrefixToken(token efp.Token) bool {
  894. _, ok := tokenPriority[token.TValue]
  895. if (token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix) || (ok && token.TType == efp.TokenTypeOperatorInfix) {
  896. return true
  897. }
  898. return false
  899. }
  900. // getDefinedNameRefTo convert defined name to reference range.
  901. func (f *File) getDefinedNameRefTo(definedNameName string, currentSheet string) (refTo string) {
  902. for _, definedName := range f.GetDefinedName() {
  903. if definedName.Name == definedNameName {
  904. refTo = definedName.RefersTo
  905. // worksheet scope takes precedence over scope workbook when both definedNames exist
  906. if definedName.Scope == currentSheet {
  907. break
  908. }
  909. }
  910. }
  911. return refTo
  912. }
  913. // parseToken parse basic arithmetic operator priority and evaluate based on
  914. // operators and operands.
  915. func (f *File) parseToken(sheet string, token efp.Token, opdStack, optStack *Stack) error {
  916. // parse reference: must reference at here
  917. if token.TSubType == efp.TokenSubTypeRange {
  918. refTo := f.getDefinedNameRefTo(token.TValue, sheet)
  919. if refTo != "" {
  920. token.TValue = refTo
  921. }
  922. result, err := f.parseReference(sheet, token.TValue)
  923. if err != nil {
  924. return errors.New(formulaErrorNAME)
  925. }
  926. if result.Type != ArgString {
  927. return errors.New(formulaErrorVALUE)
  928. }
  929. token.TValue = result.String
  930. token.TType = efp.TokenTypeOperand
  931. token.TSubType = efp.TokenSubTypeNumber
  932. }
  933. if isOperatorPrefixToken(token) {
  934. if err := f.parseOperatorPrefixToken(optStack, opdStack, token); err != nil {
  935. return err
  936. }
  937. }
  938. if isBeginParenthesesToken(token) { // (
  939. optStack.Push(token)
  940. }
  941. if isEndParenthesesToken(token) { // )
  942. for !isBeginParenthesesToken(optStack.Peek().(efp.Token)) { // != (
  943. topOpt := optStack.Peek().(efp.Token)
  944. if err := calculate(opdStack, topOpt); err != nil {
  945. return err
  946. }
  947. optStack.Pop()
  948. }
  949. optStack.Pop()
  950. }
  951. // opd
  952. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeNumber {
  953. opdStack.Push(token)
  954. }
  955. return nil
  956. }
  957. // parseReference parse reference and extract values by given reference
  958. // characters and default sheet name.
  959. func (f *File) parseReference(sheet, reference string) (arg formulaArg, err error) {
  960. reference = strings.Replace(reference, "$", "", -1)
  961. refs, cellRanges, cellRefs := list.New(), list.New(), list.New()
  962. for _, ref := range strings.Split(reference, ":") {
  963. tokens := strings.Split(ref, "!")
  964. cr := cellRef{}
  965. if len(tokens) == 2 { // have a worksheet name
  966. cr.Sheet = tokens[0]
  967. // cast to cell coordinates
  968. if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[1]); err != nil {
  969. // cast to column
  970. if cr.Col, err = ColumnNameToNumber(tokens[1]); err != nil {
  971. // cast to row
  972. if cr.Row, err = strconv.Atoi(tokens[1]); err != nil {
  973. err = newInvalidColumnNameError(tokens[1])
  974. return
  975. }
  976. cr.Col = TotalColumns
  977. }
  978. }
  979. if refs.Len() > 0 {
  980. e := refs.Back()
  981. cellRefs.PushBack(e.Value.(cellRef))
  982. refs.Remove(e)
  983. }
  984. refs.PushBack(cr)
  985. continue
  986. }
  987. // cast to cell coordinates
  988. if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[0]); err != nil {
  989. // cast to column
  990. if cr.Col, err = ColumnNameToNumber(tokens[0]); err != nil {
  991. // cast to row
  992. if cr.Row, err = strconv.Atoi(tokens[0]); err != nil {
  993. err = newInvalidColumnNameError(tokens[0])
  994. return
  995. }
  996. cr.Col = TotalColumns
  997. }
  998. cellRanges.PushBack(cellRange{
  999. From: cellRef{Sheet: sheet, Col: cr.Col, Row: 1},
  1000. To: cellRef{Sheet: sheet, Col: cr.Col, Row: TotalRows},
  1001. })
  1002. cellRefs.Init()
  1003. arg, err = f.rangeResolver(cellRefs, cellRanges)
  1004. return
  1005. }
  1006. e := refs.Back()
  1007. if e == nil {
  1008. cr.Sheet = sheet
  1009. refs.PushBack(cr)
  1010. continue
  1011. }
  1012. cellRanges.PushBack(cellRange{
  1013. From: e.Value.(cellRef),
  1014. To: cr,
  1015. })
  1016. refs.Remove(e)
  1017. }
  1018. if refs.Len() > 0 {
  1019. e := refs.Back()
  1020. cellRefs.PushBack(e.Value.(cellRef))
  1021. refs.Remove(e)
  1022. }
  1023. arg, err = f.rangeResolver(cellRefs, cellRanges)
  1024. return
  1025. }
  1026. // prepareValueRange prepare value range.
  1027. func prepareValueRange(cr cellRange, valueRange []int) {
  1028. if cr.From.Row < valueRange[0] || valueRange[0] == 0 {
  1029. valueRange[0] = cr.From.Row
  1030. }
  1031. if cr.From.Col < valueRange[2] || valueRange[2] == 0 {
  1032. valueRange[2] = cr.From.Col
  1033. }
  1034. if cr.To.Row > valueRange[1] || valueRange[1] == 0 {
  1035. valueRange[1] = cr.To.Row
  1036. }
  1037. if cr.To.Col > valueRange[3] || valueRange[3] == 0 {
  1038. valueRange[3] = cr.To.Col
  1039. }
  1040. }
  1041. // prepareValueRef prepare value reference.
  1042. func prepareValueRef(cr cellRef, valueRange []int) {
  1043. if cr.Row < valueRange[0] || valueRange[0] == 0 {
  1044. valueRange[0] = cr.Row
  1045. }
  1046. if cr.Col < valueRange[2] || valueRange[2] == 0 {
  1047. valueRange[2] = cr.Col
  1048. }
  1049. if cr.Row > valueRange[1] || valueRange[1] == 0 {
  1050. valueRange[1] = cr.Row
  1051. }
  1052. if cr.Col > valueRange[3] || valueRange[3] == 0 {
  1053. valueRange[3] = cr.Col
  1054. }
  1055. }
  1056. // rangeResolver extract value as string from given reference and range list.
  1057. // This function will not ignore the empty cell. For example, A1:A2:A2:B3 will
  1058. // be reference A1:B3.
  1059. func (f *File) rangeResolver(cellRefs, cellRanges *list.List) (arg formulaArg, err error) {
  1060. arg.cellRefs, arg.cellRanges = cellRefs, cellRanges
  1061. // value range order: from row, to row, from column, to column
  1062. valueRange := []int{0, 0, 0, 0}
  1063. var sheet string
  1064. // prepare value range
  1065. for temp := cellRanges.Front(); temp != nil; temp = temp.Next() {
  1066. cr := temp.Value.(cellRange)
  1067. if cr.From.Sheet != cr.To.Sheet {
  1068. err = errors.New(formulaErrorVALUE)
  1069. }
  1070. rng := []int{cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row}
  1071. _ = sortCoordinates(rng)
  1072. cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row = rng[0], rng[1], rng[2], rng[3]
  1073. prepareValueRange(cr, valueRange)
  1074. if cr.From.Sheet != "" {
  1075. sheet = cr.From.Sheet
  1076. }
  1077. }
  1078. for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
  1079. cr := temp.Value.(cellRef)
  1080. if cr.Sheet != "" {
  1081. sheet = cr.Sheet
  1082. }
  1083. prepareValueRef(cr, valueRange)
  1084. }
  1085. // extract value from ranges
  1086. if cellRanges.Len() > 0 {
  1087. arg.Type = ArgMatrix
  1088. for row := valueRange[0]; row <= valueRange[1]; row++ {
  1089. var matrixRow = []formulaArg{}
  1090. for col := valueRange[2]; col <= valueRange[3]; col++ {
  1091. var cell, value string
  1092. if cell, err = CoordinatesToCellName(col, row); err != nil {
  1093. return
  1094. }
  1095. if value, err = f.GetCellValue(sheet, cell); err != nil {
  1096. return
  1097. }
  1098. matrixRow = append(matrixRow, formulaArg{
  1099. String: value,
  1100. Type: ArgString,
  1101. })
  1102. }
  1103. arg.Matrix = append(arg.Matrix, matrixRow)
  1104. }
  1105. return
  1106. }
  1107. // extract value from references
  1108. for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
  1109. cr := temp.Value.(cellRef)
  1110. var cell string
  1111. if cell, err = CoordinatesToCellName(cr.Col, cr.Row); err != nil {
  1112. return
  1113. }
  1114. if arg.String, err = f.GetCellValue(cr.Sheet, cell); err != nil {
  1115. return
  1116. }
  1117. arg.Type = ArgString
  1118. }
  1119. return
  1120. }
  1121. // callFuncByName calls the no error or only error return function with
  1122. // reflect by given receiver, name and parameters.
  1123. func callFuncByName(receiver interface{}, name string, params []reflect.Value) (arg formulaArg) {
  1124. function := reflect.ValueOf(receiver).MethodByName(name)
  1125. if function.IsValid() {
  1126. rt := function.Call(params)
  1127. if len(rt) == 0 {
  1128. return
  1129. }
  1130. arg = rt[0].Interface().(formulaArg)
  1131. return
  1132. }
  1133. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("not support %s function", name))
  1134. }
  1135. // formulaCriteriaParser parse formula criteria.
  1136. func formulaCriteriaParser(exp string) (fc *formulaCriteria) {
  1137. fc = &formulaCriteria{}
  1138. if exp == "" {
  1139. return
  1140. }
  1141. if match := regexp.MustCompile(`^([0-9]+)$`).FindStringSubmatch(exp); len(match) > 1 {
  1142. fc.Type, fc.Condition = criteriaEq, match[1]
  1143. return
  1144. }
  1145. if match := regexp.MustCompile(`^=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1146. fc.Type, fc.Condition = criteriaEq, match[1]
  1147. return
  1148. }
  1149. if match := regexp.MustCompile(`^<=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1150. fc.Type, fc.Condition = criteriaLe, match[1]
  1151. return
  1152. }
  1153. if match := regexp.MustCompile(`^>=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1154. fc.Type, fc.Condition = criteriaGe, match[1]
  1155. return
  1156. }
  1157. if match := regexp.MustCompile(`^<(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1158. fc.Type, fc.Condition = criteriaL, match[1]
  1159. return
  1160. }
  1161. if match := regexp.MustCompile(`^>(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  1162. fc.Type, fc.Condition = criteriaG, match[1]
  1163. return
  1164. }
  1165. if strings.Contains(exp, "*") {
  1166. if strings.HasPrefix(exp, "*") {
  1167. fc.Type, fc.Condition = criteriaEnd, strings.TrimPrefix(exp, "*")
  1168. }
  1169. if strings.HasSuffix(exp, "*") {
  1170. fc.Type, fc.Condition = criteriaBeg, strings.TrimSuffix(exp, "*")
  1171. }
  1172. return
  1173. }
  1174. fc.Type, fc.Condition = criteriaEq, exp
  1175. return
  1176. }
  1177. // formulaCriteriaEval evaluate formula criteria expression.
  1178. func formulaCriteriaEval(val string, criteria *formulaCriteria) (result bool, err error) {
  1179. var value, expected float64
  1180. var e error
  1181. var prepareValue = func(val, cond string) (value float64, expected float64, err error) {
  1182. if value, err = strconv.ParseFloat(val, 64); err != nil {
  1183. return
  1184. }
  1185. if expected, err = strconv.ParseFloat(criteria.Condition, 64); err != nil {
  1186. return
  1187. }
  1188. return
  1189. }
  1190. switch criteria.Type {
  1191. case criteriaEq:
  1192. return val == criteria.Condition, err
  1193. case criteriaLe:
  1194. value, expected, e = prepareValue(val, criteria.Condition)
  1195. return value <= expected && e == nil, err
  1196. case criteriaGe:
  1197. value, expected, e = prepareValue(val, criteria.Condition)
  1198. return value >= expected && e == nil, err
  1199. case criteriaL:
  1200. value, expected, e = prepareValue(val, criteria.Condition)
  1201. return value < expected && e == nil, err
  1202. case criteriaG:
  1203. value, expected, e = prepareValue(val, criteria.Condition)
  1204. return value > expected && e == nil, err
  1205. case criteriaBeg:
  1206. return strings.HasPrefix(val, criteria.Condition), err
  1207. case criteriaEnd:
  1208. return strings.HasSuffix(val, criteria.Condition), err
  1209. }
  1210. return
  1211. }
  1212. // Engineering Functions
  1213. // BESSELI function the modified Bessel function, which is equivalent to the
  1214. // Bessel function evaluated for purely imaginary arguments. The syntax of
  1215. // the Besseli function is:
  1216. //
  1217. // BESSELI(x,n)
  1218. //
  1219. func (fn *formulaFuncs) BESSELI(argsList *list.List) formulaArg {
  1220. if argsList.Len() != 2 {
  1221. return newErrorFormulaArg(formulaErrorVALUE, "BESSELI requires 2 numeric arguments")
  1222. }
  1223. return fn.bassel(argsList, true)
  1224. }
  1225. // BESSELJ function returns the Bessel function, Jn(x), for a specified order
  1226. // and value of x. The syntax of the function is:
  1227. //
  1228. // BESSELJ(x,n)
  1229. //
  1230. func (fn *formulaFuncs) BESSELJ(argsList *list.List) formulaArg {
  1231. if argsList.Len() != 2 {
  1232. return newErrorFormulaArg(formulaErrorVALUE, "BESSELJ requires 2 numeric arguments")
  1233. }
  1234. return fn.bassel(argsList, false)
  1235. }
  1236. // bassel is an implementation of the formula function BESSELI and BESSELJ.
  1237. func (fn *formulaFuncs) bassel(argsList *list.List, modfied bool) formulaArg {
  1238. x, n := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Back().Value.(formulaArg).ToNumber()
  1239. if x.Type != ArgNumber {
  1240. return x
  1241. }
  1242. if n.Type != ArgNumber {
  1243. return n
  1244. }
  1245. max, x1 := 100, x.Number*0.5
  1246. x2 := x1 * x1
  1247. x1 = math.Pow(x1, n.Number)
  1248. n1, n2, n3, n4, add := fact(n.Number), 1.0, 0.0, n.Number, false
  1249. result := x1 / n1
  1250. t := result * 0.9
  1251. for result != t && max != 0 {
  1252. x1 *= x2
  1253. n3++
  1254. n1 *= n3
  1255. n4++
  1256. n2 *= n4
  1257. t = result
  1258. if modfied || add {
  1259. result += (x1 / n1 / n2)
  1260. } else {
  1261. result -= (x1 / n1 / n2)
  1262. }
  1263. max--
  1264. add = !add
  1265. }
  1266. return newNumberFormulaArg(result)
  1267. }
  1268. // BESSELK function calculates the modified Bessel functions, Kn(x), which are
  1269. // also known as the hyperbolic Bessel Functions. These are the equivalent of
  1270. // the Bessel functions, evaluated for purely imaginary arguments. The syntax
  1271. // of the function is:
  1272. //
  1273. // BESSELK(x,n)
  1274. //
  1275. func (fn *formulaFuncs) BESSELK(argsList *list.List) formulaArg {
  1276. if argsList.Len() != 2 {
  1277. return newErrorFormulaArg(formulaErrorVALUE, "BESSELK requires 2 numeric arguments")
  1278. }
  1279. x, n := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Back().Value.(formulaArg).ToNumber()
  1280. if x.Type != ArgNumber {
  1281. return x
  1282. }
  1283. if n.Type != ArgNumber {
  1284. return n
  1285. }
  1286. if x.Number <= 0 || n.Number < 0 {
  1287. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1288. }
  1289. var result float64
  1290. switch math.Floor(n.Number) {
  1291. case 0:
  1292. result = fn.besselK0(x)
  1293. case 1:
  1294. result = fn.besselK1(x)
  1295. default:
  1296. result = fn.besselK2(x, n)
  1297. }
  1298. return newNumberFormulaArg(result)
  1299. }
  1300. // besselK0 is an implementation of the formula function BESSELK.
  1301. func (fn *formulaFuncs) besselK0(x formulaArg) float64 {
  1302. var y float64
  1303. if x.Number <= 2 {
  1304. n2 := x.Number * 0.5
  1305. y = n2 * n2
  1306. args := list.New()
  1307. args.PushBack(x)
  1308. args.PushBack(newNumberFormulaArg(0))
  1309. return -math.Log(n2)*fn.BESSELI(args).Number +
  1310. (-0.57721566 + y*(0.42278420+y*(0.23069756+y*(0.3488590e-1+y*(0.262698e-2+y*
  1311. (0.10750e-3+y*0.74e-5))))))
  1312. }
  1313. y = 2 / x.Number
  1314. return math.Exp(-x.Number) / math.Sqrt(x.Number) *
  1315. (1.25331414 + y*(-0.7832358e-1+y*(0.2189568e-1+y*(-0.1062446e-1+y*
  1316. (0.587872e-2+y*(-0.251540e-2+y*0.53208e-3))))))
  1317. }
  1318. // besselK1 is an implementation of the formula function BESSELK.
  1319. func (fn *formulaFuncs) besselK1(x formulaArg) float64 {
  1320. var n2, y float64
  1321. if x.Number <= 2 {
  1322. n2 = x.Number * 0.5
  1323. y = n2 * n2
  1324. args := list.New()
  1325. args.PushBack(x)
  1326. args.PushBack(newNumberFormulaArg(1))
  1327. return math.Log(n2)*fn.BESSELI(args).Number +
  1328. (1+y*(0.15443144+y*(-0.67278579+y*(-0.18156897+y*(-0.1919402e-1+y*(-0.110404e-2+y*(-0.4686e-4)))))))/x.Number
  1329. }
  1330. y = 2 / x.Number
  1331. return math.Exp(-x.Number) / math.Sqrt(x.Number) *
  1332. (1.25331414 + y*(0.23498619+y*(-0.3655620e-1+y*(0.1504268e-1+y*(-0.780353e-2+y*
  1333. (0.325614e-2+y*(-0.68245e-3)))))))
  1334. }
  1335. // besselK2 is an implementation of the formula function BESSELK.
  1336. func (fn *formulaFuncs) besselK2(x, n formulaArg) float64 {
  1337. tox, bkm, bk, bkp := 2/x.Number, fn.besselK0(x), fn.besselK1(x), 0.0
  1338. for i := 1.0; i < n.Number; i++ {
  1339. bkp = bkm + i*tox*bk
  1340. bkm = bk
  1341. bk = bkp
  1342. }
  1343. return bk
  1344. }
  1345. // BESSELY function returns the Bessel function, Yn(x), (also known as the
  1346. // Weber function or the Neumann function), for a specified order and value
  1347. // of x. The syntax of the function is:
  1348. //
  1349. // BESSELY(x,n)
  1350. //
  1351. func (fn *formulaFuncs) BESSELY(argsList *list.List) formulaArg {
  1352. if argsList.Len() != 2 {
  1353. return newErrorFormulaArg(formulaErrorVALUE, "BESSELY requires 2 numeric arguments")
  1354. }
  1355. x, n := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Back().Value.(formulaArg).ToNumber()
  1356. if x.Type != ArgNumber {
  1357. return x
  1358. }
  1359. if n.Type != ArgNumber {
  1360. return n
  1361. }
  1362. if x.Number <= 0 || n.Number < 0 {
  1363. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1364. }
  1365. var result float64
  1366. switch math.Floor(n.Number) {
  1367. case 0:
  1368. result = fn.besselY0(x)
  1369. case 1:
  1370. result = fn.besselY1(x)
  1371. default:
  1372. result = fn.besselY2(x, n)
  1373. }
  1374. return newNumberFormulaArg(result)
  1375. }
  1376. // besselY0 is an implementation of the formula function BESSELY.
  1377. func (fn *formulaFuncs) besselY0(x formulaArg) float64 {
  1378. var y float64
  1379. if x.Number < 8 {
  1380. y = x.Number * x.Number
  1381. f1 := -2957821389.0 + y*(7062834065.0+y*(-512359803.6+y*(10879881.29+y*
  1382. (-86327.92757+y*228.4622733))))
  1383. f2 := 40076544269.0 + y*(745249964.8+y*(7189466.438+y*
  1384. (47447.26470+y*(226.1030244+y))))
  1385. args := list.New()
  1386. args.PushBack(x)
  1387. args.PushBack(newNumberFormulaArg(0))
  1388. return f1/f2 + 0.636619772*fn.BESSELJ(args).Number*math.Log(x.Number)
  1389. }
  1390. z := 8.0 / x.Number
  1391. y = z * z
  1392. xx := x.Number - 0.785398164
  1393. f1 := 1 + y*(-0.1098628627e-2+y*(0.2734510407e-4+y*(-0.2073370639e-5+y*0.2093887211e-6)))
  1394. f2 := -0.1562499995e-1 + y*(0.1430488765e-3+y*(-0.6911147651e-5+y*(0.7621095161e-6+y*
  1395. (-0.934945152e-7))))
  1396. return math.Sqrt(0.636619772/x.Number) * (math.Sin(xx)*f1 + z*math.Cos(xx)*f2)
  1397. }
  1398. // besselY1 is an implementation of the formula function BESSELY.
  1399. func (fn *formulaFuncs) besselY1(x formulaArg) float64 {
  1400. if x.Number < 8 {
  1401. y := x.Number * x.Number
  1402. f1 := x.Number * (-0.4900604943e13 + y*(0.1275274390e13+y*(-0.5153438139e11+y*
  1403. (0.7349264551e9+y*(-0.4237922726e7+y*0.8511937935e4)))))
  1404. f2 := 0.2499580570e14 + y*(0.4244419664e12+y*(0.3733650367e10+y*(0.2245904002e8+y*
  1405. (0.1020426050e6+y*(0.3549632885e3+y)))))
  1406. args := list.New()
  1407. args.PushBack(x)
  1408. args.PushBack(newNumberFormulaArg(1))
  1409. return f1/f2 + 0.636619772*(fn.BESSELJ(args).Number*math.Log(x.Number)-1/x.Number)
  1410. }
  1411. return math.Sqrt(0.636619772/x.Number) * math.Sin(x.Number-2.356194491)
  1412. }
  1413. // besselY2 is an implementation of the formula function BESSELY.
  1414. func (fn *formulaFuncs) besselY2(x, n formulaArg) float64 {
  1415. tox, bym, by, byp := 2/x.Number, fn.besselY0(x), fn.besselY1(x), 0.0
  1416. for i := 1.0; i < n.Number; i++ {
  1417. byp = i*tox*by - bym
  1418. bym = by
  1419. by = byp
  1420. }
  1421. return by
  1422. }
  1423. // BIN2DEC function converts a Binary (a base-2 number) into a decimal number.
  1424. // The syntax of the function is:
  1425. //
  1426. // BIN2DEC(number)
  1427. //
  1428. func (fn *formulaFuncs) BIN2DEC(argsList *list.List) formulaArg {
  1429. if argsList.Len() != 1 {
  1430. return newErrorFormulaArg(formulaErrorVALUE, "BIN2DEC requires 1 numeric argument")
  1431. }
  1432. token := argsList.Front().Value.(formulaArg)
  1433. number := token.ToNumber()
  1434. if number.Type != ArgNumber {
  1435. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  1436. }
  1437. return fn.bin2dec(token.Value())
  1438. }
  1439. // BIN2HEX function converts a Binary (Base 2) number into a Hexadecimal
  1440. // (Base 16) number. The syntax of the function is:
  1441. //
  1442. // BIN2HEX(number,[places])
  1443. //
  1444. func (fn *formulaFuncs) BIN2HEX(argsList *list.List) formulaArg {
  1445. if argsList.Len() < 1 {
  1446. return newErrorFormulaArg(formulaErrorVALUE, "BIN2HEX requires at least 1 argument")
  1447. }
  1448. if argsList.Len() > 2 {
  1449. return newErrorFormulaArg(formulaErrorVALUE, "BIN2HEX allows at most 2 arguments")
  1450. }
  1451. token := argsList.Front().Value.(formulaArg)
  1452. number := token.ToNumber()
  1453. if number.Type != ArgNumber {
  1454. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  1455. }
  1456. decimal, newList := fn.bin2dec(token.Value()), list.New()
  1457. if decimal.Type != ArgNumber {
  1458. return decimal
  1459. }
  1460. newList.PushBack(decimal)
  1461. if argsList.Len() == 2 {
  1462. newList.PushBack(argsList.Back().Value.(formulaArg))
  1463. }
  1464. return fn.dec2x("BIN2HEX", newList)
  1465. }
  1466. // BIN2OCT function converts a Binary (Base 2) number into an Octal (Base 8)
  1467. // number. The syntax of the function is:
  1468. //
  1469. // BIN2OCT(number,[places])
  1470. //
  1471. func (fn *formulaFuncs) BIN2OCT(argsList *list.List) formulaArg {
  1472. if argsList.Len() < 1 {
  1473. return newErrorFormulaArg(formulaErrorVALUE, "BIN2OCT requires at least 1 argument")
  1474. }
  1475. if argsList.Len() > 2 {
  1476. return newErrorFormulaArg(formulaErrorVALUE, "BIN2OCT allows at most 2 arguments")
  1477. }
  1478. token := argsList.Front().Value.(formulaArg)
  1479. number := token.ToNumber()
  1480. if number.Type != ArgNumber {
  1481. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  1482. }
  1483. decimal, newList := fn.bin2dec(token.Value()), list.New()
  1484. if decimal.Type != ArgNumber {
  1485. return decimal
  1486. }
  1487. newList.PushBack(decimal)
  1488. if argsList.Len() == 2 {
  1489. newList.PushBack(argsList.Back().Value.(formulaArg))
  1490. }
  1491. return fn.dec2x("BIN2OCT", newList)
  1492. }
  1493. // bin2dec is an implementation of the formula function BIN2DEC.
  1494. func (fn *formulaFuncs) bin2dec(number string) formulaArg {
  1495. decimal, length := 0.0, len(number)
  1496. for i := length; i > 0; i-- {
  1497. s := string(number[length-i])
  1498. if i == 10 && s == "1" {
  1499. decimal += math.Pow(-2.0, float64(i-1))
  1500. continue
  1501. }
  1502. if s == "1" {
  1503. decimal += math.Pow(2.0, float64(i-1))
  1504. continue
  1505. }
  1506. if s != "0" {
  1507. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1508. }
  1509. }
  1510. return newNumberFormulaArg(decimal)
  1511. }
  1512. // BITAND function returns the bitwise 'AND' for two supplied integers. The
  1513. // syntax of the function is:
  1514. //
  1515. // BITAND(number1,number2)
  1516. //
  1517. func (fn *formulaFuncs) BITAND(argsList *list.List) formulaArg {
  1518. return fn.bitwise("BITAND", argsList)
  1519. }
  1520. // BITLSHIFT function returns a supplied integer, shifted left by a specified
  1521. // number of bits. The syntax of the function is:
  1522. //
  1523. // BITLSHIFT(number1,shift_amount)
  1524. //
  1525. func (fn *formulaFuncs) BITLSHIFT(argsList *list.List) formulaArg {
  1526. return fn.bitwise("BITLSHIFT", argsList)
  1527. }
  1528. // BITOR function returns the bitwise 'OR' for two supplied integers. The
  1529. // syntax of the function is:
  1530. //
  1531. // BITOR(number1,number2)
  1532. //
  1533. func (fn *formulaFuncs) BITOR(argsList *list.List) formulaArg {
  1534. return fn.bitwise("BITOR", argsList)
  1535. }
  1536. // BITRSHIFT function returns a supplied integer, shifted right by a specified
  1537. // number of bits. The syntax of the function is:
  1538. //
  1539. // BITRSHIFT(number1,shift_amount)
  1540. //
  1541. func (fn *formulaFuncs) BITRSHIFT(argsList *list.List) formulaArg {
  1542. return fn.bitwise("BITRSHIFT", argsList)
  1543. }
  1544. // BITXOR function returns the bitwise 'XOR' (exclusive 'OR') for two supplied
  1545. // integers. The syntax of the function is:
  1546. //
  1547. // BITXOR(number1,number2)
  1548. //
  1549. func (fn *formulaFuncs) BITXOR(argsList *list.List) formulaArg {
  1550. return fn.bitwise("BITXOR", argsList)
  1551. }
  1552. // bitwise is an implementation of the formula function BITAND, BITLSHIFT,
  1553. // BITOR, BITRSHIFT and BITXOR.
  1554. func (fn *formulaFuncs) bitwise(name string, argsList *list.List) formulaArg {
  1555. if argsList.Len() != 2 {
  1556. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 2 numeric arguments", name))
  1557. }
  1558. num1, num2 := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Back().Value.(formulaArg).ToNumber()
  1559. if num1.Type != ArgNumber || num2.Type != ArgNumber {
  1560. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1561. }
  1562. max := math.Pow(2, 48) - 1
  1563. if num1.Number < 0 || num1.Number > max || num2.Number < 0 || num2.Number > max {
  1564. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1565. }
  1566. bitwiseFuncMap := map[string]func(a, b int) int{
  1567. "BITAND": func(a, b int) int { return a & b },
  1568. "BITLSHIFT": func(a, b int) int { return a << uint(b) },
  1569. "BITOR": func(a, b int) int { return a | b },
  1570. "BITRSHIFT": func(a, b int) int { return a >> uint(b) },
  1571. "BITXOR": func(a, b int) int { return a ^ b },
  1572. }
  1573. bitwiseFunc := bitwiseFuncMap[name]
  1574. return newNumberFormulaArg(float64(bitwiseFunc(int(num1.Number), int(num2.Number))))
  1575. }
  1576. // COMPLEX function takes two arguments, representing the real and the
  1577. // imaginary coefficients of a complex number, and from these, creates a
  1578. // complex number. The syntax of the function is:
  1579. //
  1580. // COMPLEX(real_num,i_num,[suffix])
  1581. //
  1582. func (fn *formulaFuncs) COMPLEX(argsList *list.List) formulaArg {
  1583. if argsList.Len() < 2 {
  1584. return newErrorFormulaArg(formulaErrorVALUE, "COMPLEX requires at least 2 arguments")
  1585. }
  1586. if argsList.Len() > 3 {
  1587. return newErrorFormulaArg(formulaErrorVALUE, "COMPLEX allows at most 3 arguments")
  1588. }
  1589. real, i, suffix := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Front().Next().Value.(formulaArg).ToNumber(), "i"
  1590. if real.Type != ArgNumber {
  1591. return real
  1592. }
  1593. if i.Type != ArgNumber {
  1594. return i
  1595. }
  1596. if argsList.Len() == 3 {
  1597. if suffix = strings.ToLower(argsList.Back().Value.(formulaArg).Value()); suffix != "i" && suffix != "j" {
  1598. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  1599. }
  1600. }
  1601. return newStringFormulaArg(cmplx2str(fmt.Sprint(complex(real.Number, i.Number)), suffix))
  1602. }
  1603. // cmplx2str replace complex number string characters.
  1604. func cmplx2str(c, suffix string) string {
  1605. if c == "(0+0i)" || c == "(-0+0i)" || c == "(0-0i)" || c == "(-0-0i)" {
  1606. return "0"
  1607. }
  1608. c = strings.TrimPrefix(c, "(")
  1609. c = strings.TrimPrefix(c, "+0+")
  1610. c = strings.TrimPrefix(c, "-0+")
  1611. c = strings.TrimSuffix(c, ")")
  1612. c = strings.TrimPrefix(c, "0+")
  1613. if strings.HasPrefix(c, "0-") {
  1614. c = "-" + strings.TrimPrefix(c, "0-")
  1615. }
  1616. c = strings.TrimPrefix(c, "0+")
  1617. c = strings.TrimSuffix(c, "+0i")
  1618. c = strings.TrimSuffix(c, "-0i")
  1619. c = strings.NewReplacer("+1i", "+i", "-1i", "-i").Replace(c)
  1620. c = strings.Replace(c, "i", suffix, -1)
  1621. return c
  1622. }
  1623. // str2cmplx convert complex number string characters.
  1624. func str2cmplx(c string) string {
  1625. c = strings.Replace(c, "j", "i", -1)
  1626. if c == "i" {
  1627. c = "1i"
  1628. }
  1629. c = strings.NewReplacer("+i", "+1i", "-i", "-1i").Replace(c)
  1630. return c
  1631. }
  1632. // DEC2BIN function converts a decimal number into a Binary (Base 2) number.
  1633. // The syntax of the function is:
  1634. //
  1635. // DEC2BIN(number,[places])
  1636. //
  1637. func (fn *formulaFuncs) DEC2BIN(argsList *list.List) formulaArg {
  1638. return fn.dec2x("DEC2BIN", argsList)
  1639. }
  1640. // DEC2HEX function converts a decimal number into a Hexadecimal (Base 16)
  1641. // number. The syntax of the function is:
  1642. //
  1643. // DEC2HEX(number,[places])
  1644. //
  1645. func (fn *formulaFuncs) DEC2HEX(argsList *list.List) formulaArg {
  1646. return fn.dec2x("DEC2HEX", argsList)
  1647. }
  1648. // DEC2OCT function converts a decimal number into an Octal (Base 8) number.
  1649. // The syntax of the function is:
  1650. //
  1651. // DEC2OCT(number,[places])
  1652. //
  1653. func (fn *formulaFuncs) DEC2OCT(argsList *list.List) formulaArg {
  1654. return fn.dec2x("DEC2OCT", argsList)
  1655. }
  1656. // dec2x is an implementation of the formula function DEC2BIN, DEC2HEX and
  1657. // DEC2OCT.
  1658. func (fn *formulaFuncs) dec2x(name string, argsList *list.List) formulaArg {
  1659. if argsList.Len() < 1 {
  1660. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires at least 1 argument", name))
  1661. }
  1662. if argsList.Len() > 2 {
  1663. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s allows at most 2 arguments", name))
  1664. }
  1665. decimal := argsList.Front().Value.(formulaArg).ToNumber()
  1666. if decimal.Type != ArgNumber {
  1667. return newErrorFormulaArg(formulaErrorVALUE, decimal.Error)
  1668. }
  1669. maxLimitMap := map[string]float64{
  1670. "DEC2BIN": 511,
  1671. "HEX2BIN": 511,
  1672. "OCT2BIN": 511,
  1673. "BIN2HEX": 549755813887,
  1674. "DEC2HEX": 549755813887,
  1675. "OCT2HEX": 549755813887,
  1676. "BIN2OCT": 536870911,
  1677. "DEC2OCT": 536870911,
  1678. "HEX2OCT": 536870911,
  1679. }
  1680. minLimitMap := map[string]float64{
  1681. "DEC2BIN": -512,
  1682. "HEX2BIN": -512,
  1683. "OCT2BIN": -512,
  1684. "BIN2HEX": -549755813888,
  1685. "DEC2HEX": -549755813888,
  1686. "OCT2HEX": -549755813888,
  1687. "BIN2OCT": -536870912,
  1688. "DEC2OCT": -536870912,
  1689. "HEX2OCT": -536870912,
  1690. }
  1691. baseMap := map[string]int{
  1692. "DEC2BIN": 2,
  1693. "HEX2BIN": 2,
  1694. "OCT2BIN": 2,
  1695. "BIN2HEX": 16,
  1696. "DEC2HEX": 16,
  1697. "OCT2HEX": 16,
  1698. "BIN2OCT": 8,
  1699. "DEC2OCT": 8,
  1700. "HEX2OCT": 8,
  1701. }
  1702. maxLimit, minLimit := maxLimitMap[name], minLimitMap[name]
  1703. base := baseMap[name]
  1704. if decimal.Number < minLimit || decimal.Number > maxLimit {
  1705. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1706. }
  1707. n := int64(decimal.Number)
  1708. binary := strconv.FormatUint(*(*uint64)(unsafe.Pointer(&n)), base)
  1709. if argsList.Len() == 2 {
  1710. places := argsList.Back().Value.(formulaArg).ToNumber()
  1711. if places.Type != ArgNumber {
  1712. return newErrorFormulaArg(formulaErrorVALUE, places.Error)
  1713. }
  1714. binaryPlaces := len(binary)
  1715. if places.Number < 0 || places.Number > 10 || binaryPlaces > int(places.Number) {
  1716. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1717. }
  1718. return newStringFormulaArg(strings.ToUpper(fmt.Sprintf("%s%s", strings.Repeat("0", int(places.Number)-binaryPlaces), binary)))
  1719. }
  1720. if decimal.Number < 0 && len(binary) > 10 {
  1721. return newStringFormulaArg(strings.ToUpper(binary[len(binary)-10:]))
  1722. }
  1723. return newStringFormulaArg(strings.ToUpper(binary))
  1724. }
  1725. // HEX2BIN function converts a Hexadecimal (Base 16) number into a Binary
  1726. // (Base 2) number. The syntax of the function is:
  1727. //
  1728. // HEX2BIN(number,[places])
  1729. //
  1730. func (fn *formulaFuncs) HEX2BIN(argsList *list.List) formulaArg {
  1731. if argsList.Len() < 1 {
  1732. return newErrorFormulaArg(formulaErrorVALUE, "HEX2BIN requires at least 1 argument")
  1733. }
  1734. if argsList.Len() > 2 {
  1735. return newErrorFormulaArg(formulaErrorVALUE, "HEX2BIN allows at most 2 arguments")
  1736. }
  1737. decimal, newList := fn.hex2dec(argsList.Front().Value.(formulaArg).Value()), list.New()
  1738. if decimal.Type != ArgNumber {
  1739. return decimal
  1740. }
  1741. newList.PushBack(decimal)
  1742. if argsList.Len() == 2 {
  1743. newList.PushBack(argsList.Back().Value.(formulaArg))
  1744. }
  1745. return fn.dec2x("HEX2BIN", newList)
  1746. }
  1747. // HEX2DEC function converts a hexadecimal (a base-16 number) into a decimal
  1748. // number. The syntax of the function is:
  1749. //
  1750. // HEX2DEC(number)
  1751. //
  1752. func (fn *formulaFuncs) HEX2DEC(argsList *list.List) formulaArg {
  1753. if argsList.Len() != 1 {
  1754. return newErrorFormulaArg(formulaErrorVALUE, "HEX2DEC requires 1 numeric argument")
  1755. }
  1756. return fn.hex2dec(argsList.Front().Value.(formulaArg).Value())
  1757. }
  1758. // HEX2OCT function converts a Hexadecimal (Base 16) number into an Octal
  1759. // (Base 8) number. The syntax of the function is:
  1760. //
  1761. // HEX2OCT(number,[places])
  1762. //
  1763. func (fn *formulaFuncs) HEX2OCT(argsList *list.List) formulaArg {
  1764. if argsList.Len() < 1 {
  1765. return newErrorFormulaArg(formulaErrorVALUE, "HEX2OCT requires at least 1 argument")
  1766. }
  1767. if argsList.Len() > 2 {
  1768. return newErrorFormulaArg(formulaErrorVALUE, "HEX2OCT allows at most 2 arguments")
  1769. }
  1770. decimal, newList := fn.hex2dec(argsList.Front().Value.(formulaArg).Value()), list.New()
  1771. if decimal.Type != ArgNumber {
  1772. return decimal
  1773. }
  1774. newList.PushBack(decimal)
  1775. if argsList.Len() == 2 {
  1776. newList.PushBack(argsList.Back().Value.(formulaArg))
  1777. }
  1778. return fn.dec2x("HEX2OCT", newList)
  1779. }
  1780. // hex2dec is an implementation of the formula function HEX2DEC.
  1781. func (fn *formulaFuncs) hex2dec(number string) formulaArg {
  1782. decimal, length := 0.0, len(number)
  1783. for i := length; i > 0; i-- {
  1784. num, err := strconv.ParseInt(string(number[length-i]), 16, 64)
  1785. if err != nil {
  1786. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1787. }
  1788. if i == 10 && string(number[length-i]) == "F" {
  1789. decimal += math.Pow(-16.0, float64(i-1))
  1790. continue
  1791. }
  1792. decimal += float64(num) * math.Pow(16.0, float64(i-1))
  1793. }
  1794. return newNumberFormulaArg(decimal)
  1795. }
  1796. // IMABS function returns the absolute value (the modulus) of a complex
  1797. // number. The syntax of the function is:
  1798. //
  1799. // IMABS(inumber)
  1800. //
  1801. func (fn *formulaFuncs) IMABS(argsList *list.List) formulaArg {
  1802. if argsList.Len() != 1 {
  1803. return newErrorFormulaArg(formulaErrorVALUE, "IMABS requires 1 argument")
  1804. }
  1805. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1806. if err != nil {
  1807. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1808. }
  1809. return newNumberFormulaArg(cmplx.Abs(inumber))
  1810. }
  1811. // IMAGINARY function returns the imaginary coefficient of a supplied complex
  1812. // number. The syntax of the function is:
  1813. //
  1814. // IMAGINARY(inumber)
  1815. //
  1816. func (fn *formulaFuncs) IMAGINARY(argsList *list.List) formulaArg {
  1817. if argsList.Len() != 1 {
  1818. return newErrorFormulaArg(formulaErrorVALUE, "IMAGINARY requires 1 argument")
  1819. }
  1820. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1821. if err != nil {
  1822. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1823. }
  1824. return newNumberFormulaArg(imag(inumber))
  1825. }
  1826. // IMARGUMENT function returns the phase (also called the argument) of a
  1827. // supplied complex number. The syntax of the function is:
  1828. //
  1829. // IMARGUMENT(inumber)
  1830. //
  1831. func (fn *formulaFuncs) IMARGUMENT(argsList *list.List) formulaArg {
  1832. if argsList.Len() != 1 {
  1833. return newErrorFormulaArg(formulaErrorVALUE, "IMARGUMENT requires 1 argument")
  1834. }
  1835. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1836. if err != nil {
  1837. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1838. }
  1839. return newNumberFormulaArg(cmplx.Phase(inumber))
  1840. }
  1841. // IMCONJUGATE function returns the complex conjugate of a supplied complex
  1842. // number. The syntax of the function is:
  1843. //
  1844. // IMCONJUGATE(inumber)
  1845. //
  1846. func (fn *formulaFuncs) IMCONJUGATE(argsList *list.List) formulaArg {
  1847. if argsList.Len() != 1 {
  1848. return newErrorFormulaArg(formulaErrorVALUE, "IMCONJUGATE requires 1 argument")
  1849. }
  1850. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1851. if err != nil {
  1852. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1853. }
  1854. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Conj(inumber)), "i"))
  1855. }
  1856. // IMCOS function returns the cosine of a supplied complex number. The syntax
  1857. // of the function is:
  1858. //
  1859. // IMCOS(inumber)
  1860. //
  1861. func (fn *formulaFuncs) IMCOS(argsList *list.List) formulaArg {
  1862. if argsList.Len() != 1 {
  1863. return newErrorFormulaArg(formulaErrorVALUE, "IMCOS requires 1 argument")
  1864. }
  1865. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1866. if err != nil {
  1867. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1868. }
  1869. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Cos(inumber)), "i"))
  1870. }
  1871. // IMCOSH function returns the hyperbolic cosine of a supplied complex number. The syntax
  1872. // of the function is:
  1873. //
  1874. // IMCOSH(inumber)
  1875. //
  1876. func (fn *formulaFuncs) IMCOSH(argsList *list.List) formulaArg {
  1877. if argsList.Len() != 1 {
  1878. return newErrorFormulaArg(formulaErrorVALUE, "IMCOSH requires 1 argument")
  1879. }
  1880. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1881. if err != nil {
  1882. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1883. }
  1884. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Cosh(inumber)), "i"))
  1885. }
  1886. // IMCOT function returns the cotangent of a supplied complex number. The syntax
  1887. // of the function is:
  1888. //
  1889. // IMCOT(inumber)
  1890. //
  1891. func (fn *formulaFuncs) IMCOT(argsList *list.List) formulaArg {
  1892. if argsList.Len() != 1 {
  1893. return newErrorFormulaArg(formulaErrorVALUE, "IMCOT requires 1 argument")
  1894. }
  1895. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1896. if err != nil {
  1897. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1898. }
  1899. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Cot(inumber)), "i"))
  1900. }
  1901. // IMCSC function returns the cosecant of a supplied complex number. The syntax
  1902. // of the function is:
  1903. //
  1904. // IMCSC(inumber)
  1905. //
  1906. func (fn *formulaFuncs) IMCSC(argsList *list.List) formulaArg {
  1907. if argsList.Len() != 1 {
  1908. return newErrorFormulaArg(formulaErrorVALUE, "IMCSC requires 1 argument")
  1909. }
  1910. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1911. if err != nil {
  1912. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1913. }
  1914. num := 1 / cmplx.Sin(inumber)
  1915. if cmplx.IsInf(num) {
  1916. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1917. }
  1918. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1919. }
  1920. // IMCSCH function returns the hyperbolic cosecant of a supplied complex
  1921. // number. The syntax of the function is:
  1922. //
  1923. // IMCSCH(inumber)
  1924. //
  1925. func (fn *formulaFuncs) IMCSCH(argsList *list.List) formulaArg {
  1926. if argsList.Len() != 1 {
  1927. return newErrorFormulaArg(formulaErrorVALUE, "IMCSCH requires 1 argument")
  1928. }
  1929. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1930. if err != nil {
  1931. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1932. }
  1933. num := 1 / cmplx.Sinh(inumber)
  1934. if cmplx.IsInf(num) {
  1935. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1936. }
  1937. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1938. }
  1939. // IMDIV function calculates the quotient of two complex numbers (i.e. divides
  1940. // one complex number by another). The syntax of the function is:
  1941. //
  1942. // IMDIV(inumber1,inumber2)
  1943. //
  1944. func (fn *formulaFuncs) IMDIV(argsList *list.List) formulaArg {
  1945. if argsList.Len() != 2 {
  1946. return newErrorFormulaArg(formulaErrorVALUE, "IMDIV requires 2 arguments")
  1947. }
  1948. inumber1, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1949. if err != nil {
  1950. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1951. }
  1952. inumber2, err := strconv.ParseComplex(str2cmplx(argsList.Back().Value.(formulaArg).Value()), 128)
  1953. if err != nil {
  1954. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1955. }
  1956. num := inumber1 / inumber2
  1957. if cmplx.IsInf(num) {
  1958. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1959. }
  1960. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1961. }
  1962. // IMEXP function returns the exponential of a supplied complex number. The
  1963. // syntax of the function is:
  1964. //
  1965. // IMEXP(inumber)
  1966. //
  1967. func (fn *formulaFuncs) IMEXP(argsList *list.List) formulaArg {
  1968. if argsList.Len() != 1 {
  1969. return newErrorFormulaArg(formulaErrorVALUE, "IMEXP requires 1 argument")
  1970. }
  1971. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1972. if err != nil {
  1973. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1974. }
  1975. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Exp(inumber)), "i"))
  1976. }
  1977. // IMLN function returns the natural logarithm of a supplied complex number.
  1978. // The syntax of the function is:
  1979. //
  1980. // IMLN(inumber)
  1981. //
  1982. func (fn *formulaFuncs) IMLN(argsList *list.List) formulaArg {
  1983. if argsList.Len() != 1 {
  1984. return newErrorFormulaArg(formulaErrorVALUE, "IMLN requires 1 argument")
  1985. }
  1986. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  1987. if err != nil {
  1988. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  1989. }
  1990. num := cmplx.Log(inumber)
  1991. if cmplx.IsInf(num) {
  1992. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  1993. }
  1994. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  1995. }
  1996. // IMLOG10 function returns the common (base 10) logarithm of a supplied
  1997. // complex number. The syntax of the function is:
  1998. //
  1999. // IMLOG10(inumber)
  2000. //
  2001. func (fn *formulaFuncs) IMLOG10(argsList *list.List) formulaArg {
  2002. if argsList.Len() != 1 {
  2003. return newErrorFormulaArg(formulaErrorVALUE, "IMLOG10 requires 1 argument")
  2004. }
  2005. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2006. if err != nil {
  2007. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2008. }
  2009. num := cmplx.Log10(inumber)
  2010. if cmplx.IsInf(num) {
  2011. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  2012. }
  2013. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  2014. }
  2015. // IMLOG2 function calculates the base 2 logarithm of a supplied complex
  2016. // number. The syntax of the function is:
  2017. //
  2018. // IMLOG2(inumber)
  2019. //
  2020. func (fn *formulaFuncs) IMLOG2(argsList *list.List) formulaArg {
  2021. if argsList.Len() != 1 {
  2022. return newErrorFormulaArg(formulaErrorVALUE, "IMLOG2 requires 1 argument")
  2023. }
  2024. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2025. if err != nil {
  2026. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2027. }
  2028. num := cmplx.Log(inumber)
  2029. if cmplx.IsInf(num) {
  2030. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  2031. }
  2032. return newStringFormulaArg(cmplx2str(fmt.Sprint(num/cmplx.Log(2)), "i"))
  2033. }
  2034. // IMPOWER function returns a supplied complex number, raised to a given
  2035. // power. The syntax of the function is:
  2036. //
  2037. // IMPOWER(inumber,number)
  2038. //
  2039. func (fn *formulaFuncs) IMPOWER(argsList *list.List) formulaArg {
  2040. if argsList.Len() != 2 {
  2041. return newErrorFormulaArg(formulaErrorVALUE, "IMPOWER requires 2 arguments")
  2042. }
  2043. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2044. if err != nil {
  2045. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2046. }
  2047. number, err := strconv.ParseComplex(str2cmplx(argsList.Back().Value.(formulaArg).Value()), 128)
  2048. if err != nil {
  2049. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2050. }
  2051. if inumber == 0 && number == 0 {
  2052. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  2053. }
  2054. num := cmplx.Pow(inumber, number)
  2055. if cmplx.IsInf(num) {
  2056. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  2057. }
  2058. return newStringFormulaArg(cmplx2str(fmt.Sprint(num), "i"))
  2059. }
  2060. // IMPRODUCT function calculates the product of two or more complex numbers.
  2061. // The syntax of the function is:
  2062. //
  2063. // IMPRODUCT(number1,[number2],...)
  2064. //
  2065. func (fn *formulaFuncs) IMPRODUCT(argsList *list.List) formulaArg {
  2066. product := complex128(1)
  2067. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  2068. token := arg.Value.(formulaArg)
  2069. switch token.Type {
  2070. case ArgString:
  2071. if token.Value() == "" {
  2072. continue
  2073. }
  2074. val, err := strconv.ParseComplex(str2cmplx(token.Value()), 128)
  2075. if err != nil {
  2076. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2077. }
  2078. product = product * val
  2079. case ArgNumber:
  2080. product = product * complex(token.Number, 0)
  2081. case ArgMatrix:
  2082. for _, row := range token.Matrix {
  2083. for _, value := range row {
  2084. if value.Value() == "" {
  2085. continue
  2086. }
  2087. val, err := strconv.ParseComplex(str2cmplx(value.Value()), 128)
  2088. if err != nil {
  2089. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2090. }
  2091. product = product * val
  2092. }
  2093. }
  2094. }
  2095. }
  2096. return newStringFormulaArg(cmplx2str(fmt.Sprint(product), "i"))
  2097. }
  2098. // IMREAL function returns the real coefficient of a supplied complex number.
  2099. // The syntax of the function is:
  2100. //
  2101. // IMREAL(inumber)
  2102. //
  2103. func (fn *formulaFuncs) IMREAL(argsList *list.List) formulaArg {
  2104. if argsList.Len() != 1 {
  2105. return newErrorFormulaArg(formulaErrorVALUE, "IMREAL requires 1 argument")
  2106. }
  2107. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2108. if err != nil {
  2109. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2110. }
  2111. return newStringFormulaArg(cmplx2str(fmt.Sprint(real(inumber)), "i"))
  2112. }
  2113. // IMSEC function returns the secant of a supplied complex number. The syntax
  2114. // of the function is:
  2115. //
  2116. // IMSEC(inumber)
  2117. //
  2118. func (fn *formulaFuncs) IMSEC(argsList *list.List) formulaArg {
  2119. if argsList.Len() != 1 {
  2120. return newErrorFormulaArg(formulaErrorVALUE, "IMSEC requires 1 argument")
  2121. }
  2122. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2123. if err != nil {
  2124. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2125. }
  2126. return newStringFormulaArg(cmplx2str(fmt.Sprint(1/cmplx.Cos(inumber)), "i"))
  2127. }
  2128. // IMSECH function returns the hyperbolic secant of a supplied complex number.
  2129. // The syntax of the function is:
  2130. //
  2131. // IMSECH(inumber)
  2132. //
  2133. func (fn *formulaFuncs) IMSECH(argsList *list.List) formulaArg {
  2134. if argsList.Len() != 1 {
  2135. return newErrorFormulaArg(formulaErrorVALUE, "IMSECH requires 1 argument")
  2136. }
  2137. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2138. if err != nil {
  2139. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2140. }
  2141. return newStringFormulaArg(cmplx2str(fmt.Sprint(1/cmplx.Cosh(inumber)), "i"))
  2142. }
  2143. // IMSIN function returns the Sine of a supplied complex number. The syntax of
  2144. // the function is:
  2145. //
  2146. // IMSIN(inumber)
  2147. //
  2148. func (fn *formulaFuncs) IMSIN(argsList *list.List) formulaArg {
  2149. if argsList.Len() != 1 {
  2150. return newErrorFormulaArg(formulaErrorVALUE, "IMSIN requires 1 argument")
  2151. }
  2152. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2153. if err != nil {
  2154. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2155. }
  2156. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Sin(inumber)), "i"))
  2157. }
  2158. // IMSINH function returns the hyperbolic sine of a supplied complex number.
  2159. // The syntax of the function is:
  2160. //
  2161. // IMSINH(inumber)
  2162. //
  2163. func (fn *formulaFuncs) IMSINH(argsList *list.List) formulaArg {
  2164. if argsList.Len() != 1 {
  2165. return newErrorFormulaArg(formulaErrorVALUE, "IMSINH requires 1 argument")
  2166. }
  2167. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2168. if err != nil {
  2169. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2170. }
  2171. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Sinh(inumber)), "i"))
  2172. }
  2173. // IMSQRT function returns the square root of a supplied complex number. The
  2174. // syntax of the function is:
  2175. //
  2176. // IMSQRT(inumber)
  2177. //
  2178. func (fn *formulaFuncs) IMSQRT(argsList *list.List) formulaArg {
  2179. if argsList.Len() != 1 {
  2180. return newErrorFormulaArg(formulaErrorVALUE, "IMSQRT requires 1 argument")
  2181. }
  2182. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2183. if err != nil {
  2184. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2185. }
  2186. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Sqrt(inumber)), "i"))
  2187. }
  2188. // IMSUB function calculates the difference between two complex numbers
  2189. // (i.e. subtracts one complex number from another). The syntax of the
  2190. // function is:
  2191. //
  2192. // IMSUB(inumber1,inumber2)
  2193. //
  2194. func (fn *formulaFuncs) IMSUB(argsList *list.List) formulaArg {
  2195. if argsList.Len() != 2 {
  2196. return newErrorFormulaArg(formulaErrorVALUE, "IMSUB requires 2 arguments")
  2197. }
  2198. i1, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2199. if err != nil {
  2200. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2201. }
  2202. i2, err := strconv.ParseComplex(str2cmplx(argsList.Back().Value.(formulaArg).Value()), 128)
  2203. if err != nil {
  2204. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2205. }
  2206. return newStringFormulaArg(cmplx2str(fmt.Sprint(i1-i2), "i"))
  2207. }
  2208. // IMSUM function calculates the sum of two or more complex numbers. The
  2209. // syntax of the function is:
  2210. //
  2211. // IMSUM(inumber1,inumber2,...)
  2212. //
  2213. func (fn *formulaFuncs) IMSUM(argsList *list.List) formulaArg {
  2214. if argsList.Len() < 1 {
  2215. return newErrorFormulaArg(formulaErrorVALUE, "IMSUM requires at least 1 argument")
  2216. }
  2217. var result complex128
  2218. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  2219. token := arg.Value.(formulaArg)
  2220. num, err := strconv.ParseComplex(str2cmplx(token.Value()), 128)
  2221. if err != nil {
  2222. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2223. }
  2224. result += num
  2225. }
  2226. return newStringFormulaArg(cmplx2str(fmt.Sprint(result), "i"))
  2227. }
  2228. // IMTAN function returns the tangent of a supplied complex number. The syntax
  2229. // of the function is:
  2230. //
  2231. // IMTAN(inumber)
  2232. //
  2233. func (fn *formulaFuncs) IMTAN(argsList *list.List) formulaArg {
  2234. if argsList.Len() != 1 {
  2235. return newErrorFormulaArg(formulaErrorVALUE, "IMTAN requires 1 argument")
  2236. }
  2237. inumber, err := strconv.ParseComplex(str2cmplx(argsList.Front().Value.(formulaArg).Value()), 128)
  2238. if err != nil {
  2239. return newErrorFormulaArg(formulaErrorNUM, err.Error())
  2240. }
  2241. return newStringFormulaArg(cmplx2str(fmt.Sprint(cmplx.Tan(inumber)), "i"))
  2242. }
  2243. // OCT2BIN function converts an Octal (Base 8) number into a Binary (Base 2)
  2244. // number. The syntax of the function is:
  2245. //
  2246. // OCT2BIN(number,[places])
  2247. //
  2248. func (fn *formulaFuncs) OCT2BIN(argsList *list.List) formulaArg {
  2249. if argsList.Len() < 1 {
  2250. return newErrorFormulaArg(formulaErrorVALUE, "OCT2BIN requires at least 1 argument")
  2251. }
  2252. if argsList.Len() > 2 {
  2253. return newErrorFormulaArg(formulaErrorVALUE, "OCT2BIN allows at most 2 arguments")
  2254. }
  2255. token := argsList.Front().Value.(formulaArg)
  2256. number := token.ToNumber()
  2257. if number.Type != ArgNumber {
  2258. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  2259. }
  2260. decimal, newList := fn.oct2dec(token.Value()), list.New()
  2261. newList.PushBack(decimal)
  2262. if argsList.Len() == 2 {
  2263. newList.PushBack(argsList.Back().Value.(formulaArg))
  2264. }
  2265. return fn.dec2x("OCT2BIN", newList)
  2266. }
  2267. // OCT2DEC function converts an Octal (a base-8 number) into a decimal number.
  2268. // The syntax of the function is:
  2269. //
  2270. // OCT2DEC(number)
  2271. //
  2272. func (fn *formulaFuncs) OCT2DEC(argsList *list.List) formulaArg {
  2273. if argsList.Len() != 1 {
  2274. return newErrorFormulaArg(formulaErrorVALUE, "OCT2DEC requires 1 numeric argument")
  2275. }
  2276. token := argsList.Front().Value.(formulaArg)
  2277. number := token.ToNumber()
  2278. if number.Type != ArgNumber {
  2279. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  2280. }
  2281. return fn.oct2dec(token.Value())
  2282. }
  2283. // OCT2HEX function converts an Octal (Base 8) number into a Hexadecimal
  2284. // (Base 16) number. The syntax of the function is:
  2285. //
  2286. // OCT2HEX(number,[places])
  2287. //
  2288. func (fn *formulaFuncs) OCT2HEX(argsList *list.List) formulaArg {
  2289. if argsList.Len() < 1 {
  2290. return newErrorFormulaArg(formulaErrorVALUE, "OCT2HEX requires at least 1 argument")
  2291. }
  2292. if argsList.Len() > 2 {
  2293. return newErrorFormulaArg(formulaErrorVALUE, "OCT2HEX allows at most 2 arguments")
  2294. }
  2295. token := argsList.Front().Value.(formulaArg)
  2296. number := token.ToNumber()
  2297. if number.Type != ArgNumber {
  2298. return newErrorFormulaArg(formulaErrorVALUE, number.Error)
  2299. }
  2300. decimal, newList := fn.oct2dec(token.Value()), list.New()
  2301. newList.PushBack(decimal)
  2302. if argsList.Len() == 2 {
  2303. newList.PushBack(argsList.Back().Value.(formulaArg))
  2304. }
  2305. return fn.dec2x("OCT2HEX", newList)
  2306. }
  2307. // oct2dec is an implementation of the formula function OCT2DEC.
  2308. func (fn *formulaFuncs) oct2dec(number string) formulaArg {
  2309. decimal, length := 0.0, len(number)
  2310. for i := length; i > 0; i-- {
  2311. num, _ := strconv.Atoi(string(number[length-i]))
  2312. if i == 10 && string(number[length-i]) == "7" {
  2313. decimal += math.Pow(-8.0, float64(i-1))
  2314. continue
  2315. }
  2316. decimal += float64(num) * math.Pow(8.0, float64(i-1))
  2317. }
  2318. return newNumberFormulaArg(decimal)
  2319. }
  2320. // Math and Trigonometric Functions
  2321. // ABS function returns the absolute value of any supplied number. The syntax
  2322. // of the function is:
  2323. //
  2324. // ABS(number)
  2325. //
  2326. func (fn *formulaFuncs) ABS(argsList *list.List) formulaArg {
  2327. if argsList.Len() != 1 {
  2328. return newErrorFormulaArg(formulaErrorVALUE, "ABS requires 1 numeric argument")
  2329. }
  2330. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2331. if arg.Type == ArgError {
  2332. return arg
  2333. }
  2334. return newNumberFormulaArg(math.Abs(arg.Number))
  2335. }
  2336. // ACOS function calculates the arccosine (i.e. the inverse cosine) of a given
  2337. // number, and returns an angle, in radians, between 0 and π. The syntax of
  2338. // the function is:
  2339. //
  2340. // ACOS(number)
  2341. //
  2342. func (fn *formulaFuncs) ACOS(argsList *list.List) formulaArg {
  2343. if argsList.Len() != 1 {
  2344. return newErrorFormulaArg(formulaErrorVALUE, "ACOS requires 1 numeric argument")
  2345. }
  2346. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2347. if arg.Type == ArgError {
  2348. return arg
  2349. }
  2350. return newNumberFormulaArg(math.Acos(arg.Number))
  2351. }
  2352. // ACOSH function calculates the inverse hyperbolic cosine of a supplied number.
  2353. // of the function is:
  2354. //
  2355. // ACOSH(number)
  2356. //
  2357. func (fn *formulaFuncs) ACOSH(argsList *list.List) formulaArg {
  2358. if argsList.Len() != 1 {
  2359. return newErrorFormulaArg(formulaErrorVALUE, "ACOSH requires 1 numeric argument")
  2360. }
  2361. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2362. if arg.Type == ArgError {
  2363. return arg
  2364. }
  2365. return newNumberFormulaArg(math.Acosh(arg.Number))
  2366. }
  2367. // ACOT function calculates the arccotangent (i.e. the inverse cotangent) of a
  2368. // given number, and returns an angle, in radians, between 0 and π. The syntax
  2369. // of the function is:
  2370. //
  2371. // ACOT(number)
  2372. //
  2373. func (fn *formulaFuncs) ACOT(argsList *list.List) formulaArg {
  2374. if argsList.Len() != 1 {
  2375. return newErrorFormulaArg(formulaErrorVALUE, "ACOT requires 1 numeric argument")
  2376. }
  2377. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2378. if arg.Type == ArgError {
  2379. return arg
  2380. }
  2381. return newNumberFormulaArg(math.Pi/2 - math.Atan(arg.Number))
  2382. }
  2383. // ACOTH function calculates the hyperbolic arccotangent (coth) of a supplied
  2384. // value. The syntax of the function is:
  2385. //
  2386. // ACOTH(number)
  2387. //
  2388. func (fn *formulaFuncs) ACOTH(argsList *list.List) formulaArg {
  2389. if argsList.Len() != 1 {
  2390. return newErrorFormulaArg(formulaErrorVALUE, "ACOTH requires 1 numeric argument")
  2391. }
  2392. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2393. if arg.Type == ArgError {
  2394. return arg
  2395. }
  2396. return newNumberFormulaArg(math.Atanh(1 / arg.Number))
  2397. }
  2398. // ARABIC function converts a Roman numeral into an Arabic numeral. The syntax
  2399. // of the function is:
  2400. //
  2401. // ARABIC(text)
  2402. //
  2403. func (fn *formulaFuncs) ARABIC(argsList *list.List) formulaArg {
  2404. if argsList.Len() != 1 {
  2405. return newErrorFormulaArg(formulaErrorVALUE, "ARABIC requires 1 numeric argument")
  2406. }
  2407. text := argsList.Front().Value.(formulaArg).Value()
  2408. if len(text) > 255 {
  2409. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  2410. }
  2411. text = strings.ToUpper(text)
  2412. number, actualStart, index, isNegative := 0, 0, len(text)-1, false
  2413. startIndex, subtractNumber, currentPartValue, currentCharValue, prevCharValue := 0, 0, 0, 0, -1
  2414. for index >= 0 && text[index] == ' ' {
  2415. index--
  2416. }
  2417. for actualStart <= index && text[actualStart] == ' ' {
  2418. actualStart++
  2419. }
  2420. if actualStart <= index && text[actualStart] == '-' {
  2421. isNegative = true
  2422. actualStart++
  2423. }
  2424. charMap := map[rune]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
  2425. for index >= actualStart {
  2426. startIndex = index
  2427. startChar := text[startIndex]
  2428. index--
  2429. for index >= actualStart && (text[index]|' ') == startChar {
  2430. index--
  2431. }
  2432. currentCharValue = charMap[rune(startChar)]
  2433. currentPartValue = (startIndex - index) * currentCharValue
  2434. if currentCharValue >= prevCharValue {
  2435. number += currentPartValue - subtractNumber
  2436. prevCharValue = currentCharValue
  2437. subtractNumber = 0
  2438. continue
  2439. }
  2440. subtractNumber += currentPartValue
  2441. }
  2442. if subtractNumber != 0 {
  2443. number -= subtractNumber
  2444. }
  2445. if isNegative {
  2446. number = -number
  2447. }
  2448. return newNumberFormulaArg(float64(number))
  2449. }
  2450. // ASIN function calculates the arcsine (i.e. the inverse sine) of a given
  2451. // number, and returns an angle, in radians, between -π/2 and π/2. The syntax
  2452. // of the function is:
  2453. //
  2454. // ASIN(number)
  2455. //
  2456. func (fn *formulaFuncs) ASIN(argsList *list.List) formulaArg {
  2457. if argsList.Len() != 1 {
  2458. return newErrorFormulaArg(formulaErrorVALUE, "ASIN requires 1 numeric argument")
  2459. }
  2460. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2461. if arg.Type == ArgError {
  2462. return arg
  2463. }
  2464. return newNumberFormulaArg(math.Asin(arg.Number))
  2465. }
  2466. // ASINH function calculates the inverse hyperbolic sine of a supplied number.
  2467. // The syntax of the function is:
  2468. //
  2469. // ASINH(number)
  2470. //
  2471. func (fn *formulaFuncs) ASINH(argsList *list.List) formulaArg {
  2472. if argsList.Len() != 1 {
  2473. return newErrorFormulaArg(formulaErrorVALUE, "ASINH requires 1 numeric argument")
  2474. }
  2475. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2476. if arg.Type == ArgError {
  2477. return arg
  2478. }
  2479. return newNumberFormulaArg(math.Asinh(arg.Number))
  2480. }
  2481. // ATAN function calculates the arctangent (i.e. the inverse tangent) of a
  2482. // given number, and returns an angle, in radians, between -π/2 and +π/2. The
  2483. // syntax of the function is:
  2484. //
  2485. // ATAN(number)
  2486. //
  2487. func (fn *formulaFuncs) ATAN(argsList *list.List) formulaArg {
  2488. if argsList.Len() != 1 {
  2489. return newErrorFormulaArg(formulaErrorVALUE, "ATAN requires 1 numeric argument")
  2490. }
  2491. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2492. if arg.Type == ArgError {
  2493. return arg
  2494. }
  2495. return newNumberFormulaArg(math.Atan(arg.Number))
  2496. }
  2497. // ATANH function calculates the inverse hyperbolic tangent of a supplied
  2498. // number. The syntax of the function is:
  2499. //
  2500. // ATANH(number)
  2501. //
  2502. func (fn *formulaFuncs) ATANH(argsList *list.List) formulaArg {
  2503. if argsList.Len() != 1 {
  2504. return newErrorFormulaArg(formulaErrorVALUE, "ATANH requires 1 numeric argument")
  2505. }
  2506. arg := argsList.Front().Value.(formulaArg).ToNumber()
  2507. if arg.Type == ArgError {
  2508. return arg
  2509. }
  2510. return newNumberFormulaArg(math.Atanh(arg.Number))
  2511. }
  2512. // ATAN2 function calculates the arctangent (i.e. the inverse tangent) of a
  2513. // given set of x and y coordinates, and returns an angle, in radians, between
  2514. // -π/2 and +π/2. The syntax of the function is:
  2515. //
  2516. // ATAN2(x_num,y_num)
  2517. //
  2518. func (fn *formulaFuncs) ATAN2(argsList *list.List) formulaArg {
  2519. if argsList.Len() != 2 {
  2520. return newErrorFormulaArg(formulaErrorVALUE, "ATAN2 requires 2 numeric arguments")
  2521. }
  2522. x := argsList.Back().Value.(formulaArg).ToNumber()
  2523. if x.Type == ArgError {
  2524. return x
  2525. }
  2526. y := argsList.Front().Value.(formulaArg).ToNumber()
  2527. if y.Type == ArgError {
  2528. return y
  2529. }
  2530. return newNumberFormulaArg(math.Atan2(x.Number, y.Number))
  2531. }
  2532. // BASE function converts a number into a supplied base (radix), and returns a
  2533. // text representation of the calculated value. The syntax of the function is:
  2534. //
  2535. // BASE(number,radix,[min_length])
  2536. //
  2537. func (fn *formulaFuncs) BASE(argsList *list.List) formulaArg {
  2538. if argsList.Len() < 2 {
  2539. return newErrorFormulaArg(formulaErrorVALUE, "BASE requires at least 2 arguments")
  2540. }
  2541. if argsList.Len() > 3 {
  2542. return newErrorFormulaArg(formulaErrorVALUE, "BASE allows at most 3 arguments")
  2543. }
  2544. var minLength int
  2545. var err error
  2546. number := argsList.Front().Value.(formulaArg).ToNumber()
  2547. if number.Type == ArgError {
  2548. return number
  2549. }
  2550. radix := argsList.Front().Next().Value.(formulaArg).ToNumber()
  2551. if radix.Type == ArgError {
  2552. return radix
  2553. }
  2554. if int(radix.Number) < 2 || int(radix.Number) > 36 {
  2555. return newErrorFormulaArg(formulaErrorVALUE, "radix must be an integer >= 2 and <= 36")
  2556. }
  2557. if argsList.Len() > 2 {
  2558. if minLength, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
  2559. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  2560. }
  2561. }
  2562. result := strconv.FormatInt(int64(number.Number), int(radix.Number))
  2563. if len(result) < minLength {
  2564. result = strings.Repeat("0", minLength-len(result)) + result
  2565. }
  2566. return newStringFormulaArg(strings.ToUpper(result))
  2567. }
  2568. // CEILING function rounds a supplied number away from zero, to the nearest
  2569. // multiple of a given number. The syntax of the function is:
  2570. //
  2571. // CEILING(number,significance)
  2572. //
  2573. func (fn *formulaFuncs) CEILING(argsList *list.List) formulaArg {
  2574. if argsList.Len() == 0 {
  2575. return newErrorFormulaArg(formulaErrorVALUE, "CEILING requires at least 1 argument")
  2576. }
  2577. if argsList.Len() > 2 {
  2578. return newErrorFormulaArg(formulaErrorVALUE, "CEILING allows at most 2 arguments")
  2579. }
  2580. number, significance, res := 0.0, 1.0, 0.0
  2581. n := argsList.Front().Value.(formulaArg).ToNumber()
  2582. if n.Type == ArgError {
  2583. return n
  2584. }
  2585. number = n.Number
  2586. if number < 0 {
  2587. significance = -1
  2588. }
  2589. if argsList.Len() > 1 {
  2590. s := argsList.Back().Value.(formulaArg).ToNumber()
  2591. if s.Type == ArgError {
  2592. return s
  2593. }
  2594. significance = s.Number
  2595. }
  2596. if significance < 0 && number > 0 {
  2597. return newErrorFormulaArg(formulaErrorVALUE, "negative sig to CEILING invalid")
  2598. }
  2599. if argsList.Len() == 1 {
  2600. return newNumberFormulaArg(math.Ceil(number))
  2601. }
  2602. number, res = math.Modf(number / significance)
  2603. if res > 0 {
  2604. number++
  2605. }
  2606. return newNumberFormulaArg(number * significance)
  2607. }
  2608. // CEILINGdotMATH function rounds a supplied number up to a supplied multiple
  2609. // of significance. The syntax of the function is:
  2610. //
  2611. // CEILING.MATH(number,[significance],[mode])
  2612. //
  2613. func (fn *formulaFuncs) CEILINGdotMATH(argsList *list.List) formulaArg {
  2614. if argsList.Len() == 0 {
  2615. return newErrorFormulaArg(formulaErrorVALUE, "CEILING.MATH requires at least 1 argument")
  2616. }
  2617. if argsList.Len() > 3 {
  2618. return newErrorFormulaArg(formulaErrorVALUE, "CEILING.MATH allows at most 3 arguments")
  2619. }
  2620. number, significance, mode := 0.0, 1.0, 1.0
  2621. n := argsList.Front().Value.(formulaArg).ToNumber()
  2622. if n.Type == ArgError {
  2623. return n
  2624. }
  2625. number = n.Number
  2626. if number < 0 {
  2627. significance = -1
  2628. }
  2629. if argsList.Len() > 1 {
  2630. s := argsList.Front().Next().Value.(formulaArg).ToNumber()
  2631. if s.Type == ArgError {
  2632. return s
  2633. }
  2634. significance = s.Number
  2635. }
  2636. if argsList.Len() == 1 {
  2637. return newNumberFormulaArg(math.Ceil(number))
  2638. }
  2639. if argsList.Len() > 2 {
  2640. m := argsList.Back().Value.(formulaArg).ToNumber()
  2641. if m.Type == ArgError {
  2642. return m
  2643. }
  2644. mode = m.Number
  2645. }
  2646. val, res := math.Modf(number / significance)
  2647. if res != 0 {
  2648. if number > 0 {
  2649. val++
  2650. } else if mode < 0 {
  2651. val--
  2652. }
  2653. }
  2654. return newNumberFormulaArg(val * significance)
  2655. }
  2656. // CEILINGdotPRECISE function rounds a supplied number up (regardless of the
  2657. // number's sign), to the nearest multiple of a given number. The syntax of
  2658. // the function is:
  2659. //
  2660. // CEILING.PRECISE(number,[significance])
  2661. //
  2662. func (fn *formulaFuncs) CEILINGdotPRECISE(argsList *list.List) formulaArg {
  2663. if argsList.Len() == 0 {
  2664. return newErrorFormulaArg(formulaErrorVALUE, "CEILING.PRECISE requires at least 1 argument")
  2665. }
  2666. if argsList.Len() > 2 {
  2667. return newErrorFormulaArg(formulaErrorVALUE, "CEILING.PRECISE allows at most 2 arguments")
  2668. }
  2669. number, significance := 0.0, 1.0
  2670. n := argsList.Front().Value.(formulaArg).ToNumber()
  2671. if n.Type == ArgError {
  2672. return n
  2673. }
  2674. number = n.Number
  2675. if number < 0 {
  2676. significance = -1
  2677. }
  2678. if argsList.Len() == 1 {
  2679. return newNumberFormulaArg(math.Ceil(number))
  2680. }
  2681. if argsList.Len() > 1 {
  2682. s := argsList.Back().Value.(formulaArg).ToNumber()
  2683. if s.Type == ArgError {
  2684. return s
  2685. }
  2686. significance = s.Number
  2687. significance = math.Abs(significance)
  2688. if significance == 0 {
  2689. return newNumberFormulaArg(significance)
  2690. }
  2691. }
  2692. val, res := math.Modf(number / significance)
  2693. if res != 0 {
  2694. if number > 0 {
  2695. val++
  2696. }
  2697. }
  2698. return newNumberFormulaArg(val * significance)
  2699. }
  2700. // COMBIN function calculates the number of combinations (in any order) of a
  2701. // given number objects from a set. The syntax of the function is:
  2702. //
  2703. // COMBIN(number,number_chosen)
  2704. //
  2705. func (fn *formulaFuncs) COMBIN(argsList *list.List) formulaArg {
  2706. if argsList.Len() != 2 {
  2707. return newErrorFormulaArg(formulaErrorVALUE, "COMBIN requires 2 argument")
  2708. }
  2709. number, chosen, val := 0.0, 0.0, 1.0
  2710. n := argsList.Front().Value.(formulaArg).ToNumber()
  2711. if n.Type == ArgError {
  2712. return n
  2713. }
  2714. number = n.Number
  2715. c := argsList.Back().Value.(formulaArg).ToNumber()
  2716. if c.Type == ArgError {
  2717. return c
  2718. }
  2719. chosen = c.Number
  2720. number, chosen = math.Trunc(number), math.Trunc(chosen)
  2721. if chosen > number {
  2722. return newErrorFormulaArg(formulaErrorVALUE, "COMBIN requires number >= number_chosen")
  2723. }
  2724. if chosen == number || chosen == 0 {
  2725. return newNumberFormulaArg(1)
  2726. }
  2727. for c := float64(1); c <= chosen; c++ {
  2728. val *= (number + 1 - c) / c
  2729. }
  2730. return newNumberFormulaArg(math.Ceil(val))
  2731. }
  2732. // COMBINA function calculates the number of combinations, with repetitions,
  2733. // of a given number objects from a set. The syntax of the function is:
  2734. //
  2735. // COMBINA(number,number_chosen)
  2736. //
  2737. func (fn *formulaFuncs) COMBINA(argsList *list.List) formulaArg {
  2738. if argsList.Len() != 2 {
  2739. return newErrorFormulaArg(formulaErrorVALUE, "COMBINA requires 2 argument")
  2740. }
  2741. var number, chosen float64
  2742. n := argsList.Front().Value.(formulaArg).ToNumber()
  2743. if n.Type == ArgError {
  2744. return n
  2745. }
  2746. number = n.Number
  2747. c := argsList.Back().Value.(formulaArg).ToNumber()
  2748. if c.Type == ArgError {
  2749. return c
  2750. }
  2751. chosen = c.Number
  2752. number, chosen = math.Trunc(number), math.Trunc(chosen)
  2753. if number < chosen {
  2754. return newErrorFormulaArg(formulaErrorVALUE, "COMBINA requires number > number_chosen")
  2755. }
  2756. if number == 0 {
  2757. return newNumberFormulaArg(number)
  2758. }
  2759. args := list.New()
  2760. args.PushBack(formulaArg{
  2761. String: fmt.Sprintf("%g", number+chosen-1),
  2762. Type: ArgString,
  2763. })
  2764. args.PushBack(formulaArg{
  2765. String: fmt.Sprintf("%g", number-1),
  2766. Type: ArgString,
  2767. })
  2768. return fn.COMBIN(args)
  2769. }
  2770. // COS function calculates the cosine of a given angle. The syntax of the
  2771. // function is:
  2772. //
  2773. // COS(number)
  2774. //
  2775. func (fn *formulaFuncs) COS(argsList *list.List) formulaArg {
  2776. if argsList.Len() != 1 {
  2777. return newErrorFormulaArg(formulaErrorVALUE, "COS requires 1 numeric argument")
  2778. }
  2779. val := argsList.Front().Value.(formulaArg).ToNumber()
  2780. if val.Type == ArgError {
  2781. return val
  2782. }
  2783. return newNumberFormulaArg(math.Cos(val.Number))
  2784. }
  2785. // COSH function calculates the hyperbolic cosine (cosh) of a supplied number.
  2786. // The syntax of the function is:
  2787. //
  2788. // COSH(number)
  2789. //
  2790. func (fn *formulaFuncs) COSH(argsList *list.List) formulaArg {
  2791. if argsList.Len() != 1 {
  2792. return newErrorFormulaArg(formulaErrorVALUE, "COSH requires 1 numeric argument")
  2793. }
  2794. val := argsList.Front().Value.(formulaArg).ToNumber()
  2795. if val.Type == ArgError {
  2796. return val
  2797. }
  2798. return newNumberFormulaArg(math.Cosh(val.Number))
  2799. }
  2800. // COT function calculates the cotangent of a given angle. The syntax of the
  2801. // function is:
  2802. //
  2803. // COT(number)
  2804. //
  2805. func (fn *formulaFuncs) COT(argsList *list.List) formulaArg {
  2806. if argsList.Len() != 1 {
  2807. return newErrorFormulaArg(formulaErrorVALUE, "COT requires 1 numeric argument")
  2808. }
  2809. val := argsList.Front().Value.(formulaArg).ToNumber()
  2810. if val.Type == ArgError {
  2811. return val
  2812. }
  2813. if val.Number == 0 {
  2814. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2815. }
  2816. return newNumberFormulaArg(1 / math.Tan(val.Number))
  2817. }
  2818. // COTH function calculates the hyperbolic cotangent (coth) of a supplied
  2819. // angle. The syntax of the function is:
  2820. //
  2821. // COTH(number)
  2822. //
  2823. func (fn *formulaFuncs) COTH(argsList *list.List) formulaArg {
  2824. if argsList.Len() != 1 {
  2825. return newErrorFormulaArg(formulaErrorVALUE, "COTH requires 1 numeric argument")
  2826. }
  2827. val := argsList.Front().Value.(formulaArg).ToNumber()
  2828. if val.Type == ArgError {
  2829. return val
  2830. }
  2831. if val.Number == 0 {
  2832. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2833. }
  2834. return newNumberFormulaArg((math.Exp(val.Number) + math.Exp(-val.Number)) / (math.Exp(val.Number) - math.Exp(-val.Number)))
  2835. }
  2836. // CSC function calculates the cosecant of a given angle. The syntax of the
  2837. // function is:
  2838. //
  2839. // CSC(number)
  2840. //
  2841. func (fn *formulaFuncs) CSC(argsList *list.List) formulaArg {
  2842. if argsList.Len() != 1 {
  2843. return newErrorFormulaArg(formulaErrorVALUE, "CSC requires 1 numeric argument")
  2844. }
  2845. val := argsList.Front().Value.(formulaArg).ToNumber()
  2846. if val.Type == ArgError {
  2847. return val
  2848. }
  2849. if val.Number == 0 {
  2850. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2851. }
  2852. return newNumberFormulaArg(1 / math.Sin(val.Number))
  2853. }
  2854. // CSCH function calculates the hyperbolic cosecant (csch) of a supplied
  2855. // angle. The syntax of the function is:
  2856. //
  2857. // CSCH(number)
  2858. //
  2859. func (fn *formulaFuncs) CSCH(argsList *list.List) formulaArg {
  2860. if argsList.Len() != 1 {
  2861. return newErrorFormulaArg(formulaErrorVALUE, "CSCH requires 1 numeric argument")
  2862. }
  2863. val := argsList.Front().Value.(formulaArg).ToNumber()
  2864. if val.Type == ArgError {
  2865. return val
  2866. }
  2867. if val.Number == 0 {
  2868. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2869. }
  2870. return newNumberFormulaArg(1 / math.Sinh(val.Number))
  2871. }
  2872. // DECIMAL function converts a text representation of a number in a specified
  2873. // base, into a decimal value. The syntax of the function is:
  2874. //
  2875. // DECIMAL(text,radix)
  2876. //
  2877. func (fn *formulaFuncs) DECIMAL(argsList *list.List) formulaArg {
  2878. if argsList.Len() != 2 {
  2879. return newErrorFormulaArg(formulaErrorVALUE, "DECIMAL requires 2 numeric arguments")
  2880. }
  2881. var text = argsList.Front().Value.(formulaArg).String
  2882. var radix int
  2883. var err error
  2884. radix, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String)
  2885. if err != nil {
  2886. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  2887. }
  2888. if len(text) > 2 && (strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X")) {
  2889. text = text[2:]
  2890. }
  2891. val, err := strconv.ParseInt(text, radix, 64)
  2892. if err != nil {
  2893. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  2894. }
  2895. return newNumberFormulaArg(float64(val))
  2896. }
  2897. // DEGREES function converts radians into degrees. The syntax of the function
  2898. // is:
  2899. //
  2900. // DEGREES(angle)
  2901. //
  2902. func (fn *formulaFuncs) DEGREES(argsList *list.List) formulaArg {
  2903. if argsList.Len() != 1 {
  2904. return newErrorFormulaArg(formulaErrorVALUE, "DEGREES requires 1 numeric argument")
  2905. }
  2906. val := argsList.Front().Value.(formulaArg).ToNumber()
  2907. if val.Type == ArgError {
  2908. return val
  2909. }
  2910. if val.Number == 0 {
  2911. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  2912. }
  2913. return newNumberFormulaArg(180.0 / math.Pi * val.Number)
  2914. }
  2915. // EVEN function rounds a supplied number away from zero (i.e. rounds a
  2916. // positive number up and a negative number down), to the next even number.
  2917. // The syntax of the function is:
  2918. //
  2919. // EVEN(number)
  2920. //
  2921. func (fn *formulaFuncs) EVEN(argsList *list.List) formulaArg {
  2922. if argsList.Len() != 1 {
  2923. return newErrorFormulaArg(formulaErrorVALUE, "EVEN requires 1 numeric argument")
  2924. }
  2925. number := argsList.Front().Value.(formulaArg).ToNumber()
  2926. if number.Type == ArgError {
  2927. return number
  2928. }
  2929. sign := math.Signbit(number.Number)
  2930. m, frac := math.Modf(number.Number / 2)
  2931. val := m * 2
  2932. if frac != 0 {
  2933. if !sign {
  2934. val += 2
  2935. } else {
  2936. val -= 2
  2937. }
  2938. }
  2939. return newNumberFormulaArg(val)
  2940. }
  2941. // EXP function calculates the value of the mathematical constant e, raised to
  2942. // the power of a given number. The syntax of the function is:
  2943. //
  2944. // EXP(number)
  2945. //
  2946. func (fn *formulaFuncs) EXP(argsList *list.List) formulaArg {
  2947. if argsList.Len() != 1 {
  2948. return newErrorFormulaArg(formulaErrorVALUE, "EXP requires 1 numeric argument")
  2949. }
  2950. number := argsList.Front().Value.(formulaArg).ToNumber()
  2951. if number.Type == ArgError {
  2952. return number
  2953. }
  2954. return newStringFormulaArg(strings.ToUpper(fmt.Sprintf("%g", math.Exp(number.Number))))
  2955. }
  2956. // fact returns the factorial of a supplied number.
  2957. func fact(number float64) float64 {
  2958. val := float64(1)
  2959. for i := float64(2); i <= number; i++ {
  2960. val *= i
  2961. }
  2962. return val
  2963. }
  2964. // FACT function returns the factorial of a supplied number. The syntax of the
  2965. // function is:
  2966. //
  2967. // FACT(number)
  2968. //
  2969. func (fn *formulaFuncs) FACT(argsList *list.List) formulaArg {
  2970. if argsList.Len() != 1 {
  2971. return newErrorFormulaArg(formulaErrorVALUE, "FACT requires 1 numeric argument")
  2972. }
  2973. number := argsList.Front().Value.(formulaArg).ToNumber()
  2974. if number.Type == ArgError {
  2975. return number
  2976. }
  2977. if number.Number < 0 {
  2978. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  2979. }
  2980. return newNumberFormulaArg(fact(number.Number))
  2981. }
  2982. // FACTDOUBLE function returns the double factorial of a supplied number. The
  2983. // syntax of the function is:
  2984. //
  2985. // FACTDOUBLE(number)
  2986. //
  2987. func (fn *formulaFuncs) FACTDOUBLE(argsList *list.List) formulaArg {
  2988. if argsList.Len() != 1 {
  2989. return newErrorFormulaArg(formulaErrorVALUE, "FACTDOUBLE requires 1 numeric argument")
  2990. }
  2991. val := 1.0
  2992. number := argsList.Front().Value.(formulaArg).ToNumber()
  2993. if number.Type == ArgError {
  2994. return number
  2995. }
  2996. if number.Number < 0 {
  2997. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  2998. }
  2999. for i := math.Trunc(number.Number); i > 1; i -= 2 {
  3000. val *= i
  3001. }
  3002. return newStringFormulaArg(strings.ToUpper(fmt.Sprintf("%g", val)))
  3003. }
  3004. // FLOOR function rounds a supplied number towards zero to the nearest
  3005. // multiple of a specified significance. The syntax of the function is:
  3006. //
  3007. // FLOOR(number,significance)
  3008. //
  3009. func (fn *formulaFuncs) FLOOR(argsList *list.List) formulaArg {
  3010. if argsList.Len() != 2 {
  3011. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR requires 2 numeric arguments")
  3012. }
  3013. number := argsList.Front().Value.(formulaArg).ToNumber()
  3014. if number.Type == ArgError {
  3015. return number
  3016. }
  3017. significance := argsList.Back().Value.(formulaArg).ToNumber()
  3018. if significance.Type == ArgError {
  3019. return significance
  3020. }
  3021. if significance.Number < 0 && number.Number >= 0 {
  3022. return newErrorFormulaArg(formulaErrorNUM, "invalid arguments to FLOOR")
  3023. }
  3024. val := number.Number
  3025. val, res := math.Modf(val / significance.Number)
  3026. if res != 0 {
  3027. if number.Number < 0 && res < 0 {
  3028. val--
  3029. }
  3030. }
  3031. return newStringFormulaArg(strings.ToUpper(fmt.Sprintf("%g", val*significance.Number)))
  3032. }
  3033. // FLOORdotMATH function rounds a supplied number down to a supplied multiple
  3034. // of significance. The syntax of the function is:
  3035. //
  3036. // FLOOR.MATH(number,[significance],[mode])
  3037. //
  3038. func (fn *formulaFuncs) FLOORdotMATH(argsList *list.List) formulaArg {
  3039. if argsList.Len() == 0 {
  3040. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR.MATH requires at least 1 argument")
  3041. }
  3042. if argsList.Len() > 3 {
  3043. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR.MATH allows at most 3 arguments")
  3044. }
  3045. significance, mode := 1.0, 1.0
  3046. number := argsList.Front().Value.(formulaArg).ToNumber()
  3047. if number.Type == ArgError {
  3048. return number
  3049. }
  3050. if number.Number < 0 {
  3051. significance = -1
  3052. }
  3053. if argsList.Len() > 1 {
  3054. s := argsList.Front().Next().Value.(formulaArg).ToNumber()
  3055. if s.Type == ArgError {
  3056. return s
  3057. }
  3058. significance = s.Number
  3059. }
  3060. if argsList.Len() == 1 {
  3061. return newNumberFormulaArg(math.Floor(number.Number))
  3062. }
  3063. if argsList.Len() > 2 {
  3064. m := argsList.Back().Value.(formulaArg).ToNumber()
  3065. if m.Type == ArgError {
  3066. return m
  3067. }
  3068. mode = m.Number
  3069. }
  3070. val, res := math.Modf(number.Number / significance)
  3071. if res != 0 && number.Number < 0 && mode > 0 {
  3072. val--
  3073. }
  3074. return newNumberFormulaArg(val * significance)
  3075. }
  3076. // FLOORdotPRECISE function rounds a supplied number down to a supplied
  3077. // multiple of significance. The syntax of the function is:
  3078. //
  3079. // FLOOR.PRECISE(number,[significance])
  3080. //
  3081. func (fn *formulaFuncs) FLOORdotPRECISE(argsList *list.List) formulaArg {
  3082. if argsList.Len() == 0 {
  3083. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR.PRECISE requires at least 1 argument")
  3084. }
  3085. if argsList.Len() > 2 {
  3086. return newErrorFormulaArg(formulaErrorVALUE, "FLOOR.PRECISE allows at most 2 arguments")
  3087. }
  3088. var significance float64
  3089. number := argsList.Front().Value.(formulaArg).ToNumber()
  3090. if number.Type == ArgError {
  3091. return number
  3092. }
  3093. if number.Number < 0 {
  3094. significance = -1
  3095. }
  3096. if argsList.Len() == 1 {
  3097. return newNumberFormulaArg(math.Floor(number.Number))
  3098. }
  3099. if argsList.Len() > 1 {
  3100. s := argsList.Back().Value.(formulaArg).ToNumber()
  3101. if s.Type == ArgError {
  3102. return s
  3103. }
  3104. significance = s.Number
  3105. significance = math.Abs(significance)
  3106. if significance == 0 {
  3107. return newNumberFormulaArg(significance)
  3108. }
  3109. }
  3110. val, res := math.Modf(number.Number / significance)
  3111. if res != 0 {
  3112. if number.Number < 0 {
  3113. val--
  3114. }
  3115. }
  3116. return newNumberFormulaArg(val * significance)
  3117. }
  3118. // gcd returns the greatest common divisor of two supplied integers.
  3119. func gcd(x, y float64) float64 {
  3120. x, y = math.Trunc(x), math.Trunc(y)
  3121. if x == 0 {
  3122. return y
  3123. }
  3124. if y == 0 {
  3125. return x
  3126. }
  3127. for x != y {
  3128. if x > y {
  3129. x = x - y
  3130. } else {
  3131. y = y - x
  3132. }
  3133. }
  3134. return x
  3135. }
  3136. // GCD function returns the greatest common divisor of two or more supplied
  3137. // integers. The syntax of the function is:
  3138. //
  3139. // GCD(number1,[number2],...)
  3140. //
  3141. func (fn *formulaFuncs) GCD(argsList *list.List) formulaArg {
  3142. if argsList.Len() == 0 {
  3143. return newErrorFormulaArg(formulaErrorVALUE, "GCD requires at least 1 argument")
  3144. }
  3145. var (
  3146. val float64
  3147. nums = []float64{}
  3148. )
  3149. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3150. token := arg.Value.(formulaArg)
  3151. switch token.Type {
  3152. case ArgString:
  3153. num := token.ToNumber()
  3154. if num.Type == ArgError {
  3155. return num
  3156. }
  3157. val = num.Number
  3158. case ArgNumber:
  3159. val = token.Number
  3160. }
  3161. nums = append(nums, val)
  3162. }
  3163. if nums[0] < 0 {
  3164. return newErrorFormulaArg(formulaErrorVALUE, "GCD only accepts positive arguments")
  3165. }
  3166. if len(nums) == 1 {
  3167. return newNumberFormulaArg(nums[0])
  3168. }
  3169. cd := nums[0]
  3170. for i := 1; i < len(nums); i++ {
  3171. if nums[i] < 0 {
  3172. return newErrorFormulaArg(formulaErrorVALUE, "GCD only accepts positive arguments")
  3173. }
  3174. cd = gcd(cd, nums[i])
  3175. }
  3176. return newNumberFormulaArg(cd)
  3177. }
  3178. // INT function truncates a supplied number down to the closest integer. The
  3179. // syntax of the function is:
  3180. //
  3181. // INT(number)
  3182. //
  3183. func (fn *formulaFuncs) INT(argsList *list.List) formulaArg {
  3184. if argsList.Len() != 1 {
  3185. return newErrorFormulaArg(formulaErrorVALUE, "INT requires 1 numeric argument")
  3186. }
  3187. number := argsList.Front().Value.(formulaArg).ToNumber()
  3188. if number.Type == ArgError {
  3189. return number
  3190. }
  3191. val, frac := math.Modf(number.Number)
  3192. if frac < 0 {
  3193. val--
  3194. }
  3195. return newNumberFormulaArg(val)
  3196. }
  3197. // ISOdotCEILING function rounds a supplied number up (regardless of the
  3198. // number's sign), to the nearest multiple of a supplied significance. The
  3199. // syntax of the function is:
  3200. //
  3201. // ISO.CEILING(number,[significance])
  3202. //
  3203. func (fn *formulaFuncs) ISOdotCEILING(argsList *list.List) formulaArg {
  3204. if argsList.Len() == 0 {
  3205. return newErrorFormulaArg(formulaErrorVALUE, "ISO.CEILING requires at least 1 argument")
  3206. }
  3207. if argsList.Len() > 2 {
  3208. return newErrorFormulaArg(formulaErrorVALUE, "ISO.CEILING allows at most 2 arguments")
  3209. }
  3210. var significance float64
  3211. number := argsList.Front().Value.(formulaArg).ToNumber()
  3212. if number.Type == ArgError {
  3213. return number
  3214. }
  3215. if number.Number < 0 {
  3216. significance = -1
  3217. }
  3218. if argsList.Len() == 1 {
  3219. return newNumberFormulaArg(math.Ceil(number.Number))
  3220. }
  3221. if argsList.Len() > 1 {
  3222. s := argsList.Back().Value.(formulaArg).ToNumber()
  3223. if s.Type == ArgError {
  3224. return s
  3225. }
  3226. significance = s.Number
  3227. significance = math.Abs(significance)
  3228. if significance == 0 {
  3229. return newNumberFormulaArg(significance)
  3230. }
  3231. }
  3232. val, res := math.Modf(number.Number / significance)
  3233. if res != 0 {
  3234. if number.Number > 0 {
  3235. val++
  3236. }
  3237. }
  3238. return newNumberFormulaArg(val * significance)
  3239. }
  3240. // lcm returns the least common multiple of two supplied integers.
  3241. func lcm(a, b float64) float64 {
  3242. a = math.Trunc(a)
  3243. b = math.Trunc(b)
  3244. if a == 0 && b == 0 {
  3245. return 0
  3246. }
  3247. return a * b / gcd(a, b)
  3248. }
  3249. // LCM function returns the least common multiple of two or more supplied
  3250. // integers. The syntax of the function is:
  3251. //
  3252. // LCM(number1,[number2],...)
  3253. //
  3254. func (fn *formulaFuncs) LCM(argsList *list.List) formulaArg {
  3255. if argsList.Len() == 0 {
  3256. return newErrorFormulaArg(formulaErrorVALUE, "LCM requires at least 1 argument")
  3257. }
  3258. var (
  3259. val float64
  3260. nums = []float64{}
  3261. err error
  3262. )
  3263. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3264. token := arg.Value.(formulaArg)
  3265. switch token.Type {
  3266. case ArgString:
  3267. if token.String == "" {
  3268. continue
  3269. }
  3270. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  3271. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3272. }
  3273. case ArgNumber:
  3274. val = token.Number
  3275. }
  3276. nums = append(nums, val)
  3277. }
  3278. if nums[0] < 0 {
  3279. return newErrorFormulaArg(formulaErrorVALUE, "LCM only accepts positive arguments")
  3280. }
  3281. if len(nums) == 1 {
  3282. return newNumberFormulaArg(nums[0])
  3283. }
  3284. cm := nums[0]
  3285. for i := 1; i < len(nums); i++ {
  3286. if nums[i] < 0 {
  3287. return newErrorFormulaArg(formulaErrorVALUE, "LCM only accepts positive arguments")
  3288. }
  3289. cm = lcm(cm, nums[i])
  3290. }
  3291. return newNumberFormulaArg(cm)
  3292. }
  3293. // LN function calculates the natural logarithm of a given number. The syntax
  3294. // of the function is:
  3295. //
  3296. // LN(number)
  3297. //
  3298. func (fn *formulaFuncs) LN(argsList *list.List) formulaArg {
  3299. if argsList.Len() != 1 {
  3300. return newErrorFormulaArg(formulaErrorVALUE, "LN requires 1 numeric argument")
  3301. }
  3302. number := argsList.Front().Value.(formulaArg).ToNumber()
  3303. if number.Type == ArgError {
  3304. return number
  3305. }
  3306. return newNumberFormulaArg(math.Log(number.Number))
  3307. }
  3308. // LOG function calculates the logarithm of a given number, to a supplied
  3309. // base. The syntax of the function is:
  3310. //
  3311. // LOG(number,[base])
  3312. //
  3313. func (fn *formulaFuncs) LOG(argsList *list.List) formulaArg {
  3314. if argsList.Len() == 0 {
  3315. return newErrorFormulaArg(formulaErrorVALUE, "LOG requires at least 1 argument")
  3316. }
  3317. if argsList.Len() > 2 {
  3318. return newErrorFormulaArg(formulaErrorVALUE, "LOG allows at most 2 arguments")
  3319. }
  3320. base := 10.0
  3321. number := argsList.Front().Value.(formulaArg).ToNumber()
  3322. if number.Type == ArgError {
  3323. return number
  3324. }
  3325. if argsList.Len() > 1 {
  3326. b := argsList.Back().Value.(formulaArg).ToNumber()
  3327. if b.Type == ArgError {
  3328. return b
  3329. }
  3330. base = b.Number
  3331. }
  3332. if number.Number == 0 {
  3333. return newErrorFormulaArg(formulaErrorNUM, formulaErrorDIV)
  3334. }
  3335. if base == 0 {
  3336. return newErrorFormulaArg(formulaErrorNUM, formulaErrorDIV)
  3337. }
  3338. if base == 1 {
  3339. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  3340. }
  3341. return newNumberFormulaArg(math.Log(number.Number) / math.Log(base))
  3342. }
  3343. // LOG10 function calculates the base 10 logarithm of a given number. The
  3344. // syntax of the function is:
  3345. //
  3346. // LOG10(number)
  3347. //
  3348. func (fn *formulaFuncs) LOG10(argsList *list.List) formulaArg {
  3349. if argsList.Len() != 1 {
  3350. return newErrorFormulaArg(formulaErrorVALUE, "LOG10 requires 1 numeric argument")
  3351. }
  3352. number := argsList.Front().Value.(formulaArg).ToNumber()
  3353. if number.Type == ArgError {
  3354. return number
  3355. }
  3356. return newNumberFormulaArg(math.Log10(number.Number))
  3357. }
  3358. // minor function implement a minor of a matrix A is the determinant of some
  3359. // smaller square matrix.
  3360. func minor(sqMtx [][]float64, idx int) [][]float64 {
  3361. ret := [][]float64{}
  3362. for i := range sqMtx {
  3363. if i == 0 {
  3364. continue
  3365. }
  3366. row := []float64{}
  3367. for j := range sqMtx {
  3368. if j == idx {
  3369. continue
  3370. }
  3371. row = append(row, sqMtx[i][j])
  3372. }
  3373. ret = append(ret, row)
  3374. }
  3375. return ret
  3376. }
  3377. // det determinant of the 2x2 matrix.
  3378. func det(sqMtx [][]float64) float64 {
  3379. if len(sqMtx) == 2 {
  3380. m00 := sqMtx[0][0]
  3381. m01 := sqMtx[0][1]
  3382. m10 := sqMtx[1][0]
  3383. m11 := sqMtx[1][1]
  3384. return m00*m11 - m10*m01
  3385. }
  3386. var res, sgn float64 = 0, 1
  3387. for j := range sqMtx {
  3388. res += sgn * sqMtx[0][j] * det(minor(sqMtx, j))
  3389. sgn *= -1
  3390. }
  3391. return res
  3392. }
  3393. // MDETERM calculates the determinant of a square matrix. The
  3394. // syntax of the function is:
  3395. //
  3396. // MDETERM(array)
  3397. //
  3398. func (fn *formulaFuncs) MDETERM(argsList *list.List) (result formulaArg) {
  3399. var (
  3400. num float64
  3401. numMtx = [][]float64{}
  3402. err error
  3403. strMtx [][]formulaArg
  3404. )
  3405. if argsList.Len() < 1 {
  3406. return newErrorFormulaArg(formulaErrorVALUE, "MDETERM requires at least 1 argument")
  3407. }
  3408. strMtx = argsList.Front().Value.(formulaArg).Matrix
  3409. var rows = len(strMtx)
  3410. for _, row := range argsList.Front().Value.(formulaArg).Matrix {
  3411. if len(row) != rows {
  3412. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  3413. }
  3414. numRow := []float64{}
  3415. for _, ele := range row {
  3416. if num, err = strconv.ParseFloat(ele.String, 64); err != nil {
  3417. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3418. }
  3419. numRow = append(numRow, num)
  3420. }
  3421. numMtx = append(numMtx, numRow)
  3422. }
  3423. return newNumberFormulaArg(det(numMtx))
  3424. }
  3425. // MOD function returns the remainder of a division between two supplied
  3426. // numbers. The syntax of the function is:
  3427. //
  3428. // MOD(number,divisor)
  3429. //
  3430. func (fn *formulaFuncs) MOD(argsList *list.List) formulaArg {
  3431. if argsList.Len() != 2 {
  3432. return newErrorFormulaArg(formulaErrorVALUE, "MOD requires 2 numeric arguments")
  3433. }
  3434. number := argsList.Front().Value.(formulaArg).ToNumber()
  3435. if number.Type == ArgError {
  3436. return number
  3437. }
  3438. divisor := argsList.Back().Value.(formulaArg).ToNumber()
  3439. if divisor.Type == ArgError {
  3440. return divisor
  3441. }
  3442. if divisor.Number == 0 {
  3443. return newErrorFormulaArg(formulaErrorDIV, "MOD divide by zero")
  3444. }
  3445. trunc, rem := math.Modf(number.Number / divisor.Number)
  3446. if rem < 0 {
  3447. trunc--
  3448. }
  3449. return newNumberFormulaArg(number.Number - divisor.Number*trunc)
  3450. }
  3451. // MROUND function rounds a supplied number up or down to the nearest multiple
  3452. // of a given number. The syntax of the function is:
  3453. //
  3454. // MROUND(number,multiple)
  3455. //
  3456. func (fn *formulaFuncs) MROUND(argsList *list.List) formulaArg {
  3457. if argsList.Len() != 2 {
  3458. return newErrorFormulaArg(formulaErrorVALUE, "MROUND requires 2 numeric arguments")
  3459. }
  3460. n := argsList.Front().Value.(formulaArg).ToNumber()
  3461. if n.Type == ArgError {
  3462. return n
  3463. }
  3464. multiple := argsList.Back().Value.(formulaArg).ToNumber()
  3465. if multiple.Type == ArgError {
  3466. return multiple
  3467. }
  3468. if multiple.Number == 0 {
  3469. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3470. }
  3471. if multiple.Number < 0 && n.Number > 0 ||
  3472. multiple.Number > 0 && n.Number < 0 {
  3473. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3474. }
  3475. number, res := math.Modf(n.Number / multiple.Number)
  3476. if math.Trunc(res+0.5) > 0 {
  3477. number++
  3478. }
  3479. return newNumberFormulaArg(number * multiple.Number)
  3480. }
  3481. // MULTINOMIAL function calculates the ratio of the factorial of a sum of
  3482. // supplied values to the product of factorials of those values. The syntax of
  3483. // the function is:
  3484. //
  3485. // MULTINOMIAL(number1,[number2],...)
  3486. //
  3487. func (fn *formulaFuncs) MULTINOMIAL(argsList *list.List) formulaArg {
  3488. val, num, denom := 0.0, 0.0, 1.0
  3489. var err error
  3490. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3491. token := arg.Value.(formulaArg)
  3492. switch token.Type {
  3493. case ArgString:
  3494. if token.String == "" {
  3495. continue
  3496. }
  3497. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  3498. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3499. }
  3500. case ArgNumber:
  3501. val = token.Number
  3502. }
  3503. num += val
  3504. denom *= fact(val)
  3505. }
  3506. return newNumberFormulaArg(fact(num) / denom)
  3507. }
  3508. // MUNIT function returns the unit matrix for a specified dimension. The
  3509. // syntax of the function is:
  3510. //
  3511. // MUNIT(dimension)
  3512. //
  3513. func (fn *formulaFuncs) MUNIT(argsList *list.List) (result formulaArg) {
  3514. if argsList.Len() != 1 {
  3515. return newErrorFormulaArg(formulaErrorVALUE, "MUNIT requires 1 numeric argument")
  3516. }
  3517. dimension := argsList.Back().Value.(formulaArg).ToNumber()
  3518. if dimension.Type == ArgError || dimension.Number < 0 {
  3519. return newErrorFormulaArg(formulaErrorVALUE, dimension.Error)
  3520. }
  3521. matrix := make([][]formulaArg, 0, int(dimension.Number))
  3522. for i := 0; i < int(dimension.Number); i++ {
  3523. row := make([]formulaArg, int(dimension.Number))
  3524. for j := 0; j < int(dimension.Number); j++ {
  3525. if i == j {
  3526. row[j] = newNumberFormulaArg(1.0)
  3527. } else {
  3528. row[j] = newNumberFormulaArg(0.0)
  3529. }
  3530. }
  3531. matrix = append(matrix, row)
  3532. }
  3533. return newMatrixFormulaArg(matrix)
  3534. }
  3535. // ODD function ounds a supplied number away from zero (i.e. rounds a positive
  3536. // number up and a negative number down), to the next odd number. The syntax
  3537. // of the function is:
  3538. //
  3539. // ODD(number)
  3540. //
  3541. func (fn *formulaFuncs) ODD(argsList *list.List) formulaArg {
  3542. if argsList.Len() != 1 {
  3543. return newErrorFormulaArg(formulaErrorVALUE, "ODD requires 1 numeric argument")
  3544. }
  3545. number := argsList.Back().Value.(formulaArg).ToNumber()
  3546. if number.Type == ArgError {
  3547. return number
  3548. }
  3549. if number.Number == 0 {
  3550. return newNumberFormulaArg(1)
  3551. }
  3552. sign := math.Signbit(number.Number)
  3553. m, frac := math.Modf((number.Number - 1) / 2)
  3554. val := m*2 + 1
  3555. if frac != 0 {
  3556. if !sign {
  3557. val += 2
  3558. } else {
  3559. val -= 2
  3560. }
  3561. }
  3562. return newNumberFormulaArg(val)
  3563. }
  3564. // PI function returns the value of the mathematical constant π (pi), accurate
  3565. // to 15 digits (14 decimal places). The syntax of the function is:
  3566. //
  3567. // PI()
  3568. //
  3569. func (fn *formulaFuncs) PI(argsList *list.List) formulaArg {
  3570. if argsList.Len() != 0 {
  3571. return newErrorFormulaArg(formulaErrorVALUE, "PI accepts no arguments")
  3572. }
  3573. return newNumberFormulaArg(math.Pi)
  3574. }
  3575. // POWER function calculates a given number, raised to a supplied power.
  3576. // The syntax of the function is:
  3577. //
  3578. // POWER(number,power)
  3579. //
  3580. func (fn *formulaFuncs) POWER(argsList *list.List) formulaArg {
  3581. if argsList.Len() != 2 {
  3582. return newErrorFormulaArg(formulaErrorVALUE, "POWER requires 2 numeric arguments")
  3583. }
  3584. x := argsList.Front().Value.(formulaArg).ToNumber()
  3585. if x.Type == ArgError {
  3586. return x
  3587. }
  3588. y := argsList.Back().Value.(formulaArg).ToNumber()
  3589. if y.Type == ArgError {
  3590. return y
  3591. }
  3592. if x.Number == 0 && y.Number == 0 {
  3593. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3594. }
  3595. if x.Number == 0 && y.Number < 0 {
  3596. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  3597. }
  3598. return newNumberFormulaArg(math.Pow(x.Number, y.Number))
  3599. }
  3600. // PRODUCT function returns the product (multiplication) of a supplied set of
  3601. // numerical values. The syntax of the function is:
  3602. //
  3603. // PRODUCT(number1,[number2],...)
  3604. //
  3605. func (fn *formulaFuncs) PRODUCT(argsList *list.List) formulaArg {
  3606. val, product := 0.0, 1.0
  3607. var err error
  3608. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3609. token := arg.Value.(formulaArg)
  3610. switch token.Type {
  3611. case ArgUnknown:
  3612. continue
  3613. case ArgString:
  3614. if token.String == "" {
  3615. continue
  3616. }
  3617. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  3618. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3619. }
  3620. product = product * val
  3621. case ArgNumber:
  3622. product = product * token.Number
  3623. case ArgMatrix:
  3624. for _, row := range token.Matrix {
  3625. for _, value := range row {
  3626. if value.String == "" {
  3627. continue
  3628. }
  3629. if val, err = strconv.ParseFloat(value.String, 64); err != nil {
  3630. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  3631. }
  3632. product = product * val
  3633. }
  3634. }
  3635. }
  3636. }
  3637. return newNumberFormulaArg(product)
  3638. }
  3639. // QUOTIENT function returns the integer portion of a division between two
  3640. // supplied numbers. The syntax of the function is:
  3641. //
  3642. // QUOTIENT(numerator,denominator)
  3643. //
  3644. func (fn *formulaFuncs) QUOTIENT(argsList *list.List) formulaArg {
  3645. if argsList.Len() != 2 {
  3646. return newErrorFormulaArg(formulaErrorVALUE, "QUOTIENT requires 2 numeric arguments")
  3647. }
  3648. x := argsList.Front().Value.(formulaArg).ToNumber()
  3649. if x.Type == ArgError {
  3650. return x
  3651. }
  3652. y := argsList.Back().Value.(formulaArg).ToNumber()
  3653. if y.Type == ArgError {
  3654. return y
  3655. }
  3656. if y.Number == 0 {
  3657. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  3658. }
  3659. return newNumberFormulaArg(math.Trunc(x.Number / y.Number))
  3660. }
  3661. // RADIANS function converts radians into degrees. The syntax of the function is:
  3662. //
  3663. // RADIANS(angle)
  3664. //
  3665. func (fn *formulaFuncs) RADIANS(argsList *list.List) formulaArg {
  3666. if argsList.Len() != 1 {
  3667. return newErrorFormulaArg(formulaErrorVALUE, "RADIANS requires 1 numeric argument")
  3668. }
  3669. angle := argsList.Front().Value.(formulaArg).ToNumber()
  3670. if angle.Type == ArgError {
  3671. return angle
  3672. }
  3673. return newNumberFormulaArg(math.Pi / 180.0 * angle.Number)
  3674. }
  3675. // RAND function generates a random real number between 0 and 1. The syntax of
  3676. // the function is:
  3677. //
  3678. // RAND()
  3679. //
  3680. func (fn *formulaFuncs) RAND(argsList *list.List) formulaArg {
  3681. if argsList.Len() != 0 {
  3682. return newErrorFormulaArg(formulaErrorVALUE, "RAND accepts no arguments")
  3683. }
  3684. return newNumberFormulaArg(rand.New(rand.NewSource(time.Now().UnixNano())).Float64())
  3685. }
  3686. // RANDBETWEEN function generates a random integer between two supplied
  3687. // integers. The syntax of the function is:
  3688. //
  3689. // RANDBETWEEN(bottom,top)
  3690. //
  3691. func (fn *formulaFuncs) RANDBETWEEN(argsList *list.List) formulaArg {
  3692. if argsList.Len() != 2 {
  3693. return newErrorFormulaArg(formulaErrorVALUE, "RANDBETWEEN requires 2 numeric arguments")
  3694. }
  3695. bottom := argsList.Front().Value.(formulaArg).ToNumber()
  3696. if bottom.Type == ArgError {
  3697. return bottom
  3698. }
  3699. top := argsList.Back().Value.(formulaArg).ToNumber()
  3700. if top.Type == ArgError {
  3701. return top
  3702. }
  3703. if top.Number < bottom.Number {
  3704. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3705. }
  3706. num := rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(int64(top.Number - bottom.Number + 1))
  3707. return newNumberFormulaArg(float64(num + int64(bottom.Number)))
  3708. }
  3709. // romanNumerals defined a numeral system that originated in ancient Rome and
  3710. // remained the usual way of writing numbers throughout Europe well into the
  3711. // Late Middle Ages.
  3712. type romanNumerals struct {
  3713. n float64
  3714. s string
  3715. }
  3716. var romanTable = [][]romanNumerals{
  3717. {
  3718. {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"},
  3719. {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"},
  3720. },
  3721. {
  3722. {1000, "M"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {450, "LD"}, {400, "CD"},
  3723. {100, "C"}, {95, "VC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"},
  3724. {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"},
  3725. },
  3726. {
  3727. {1000, "M"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {490, "XD"},
  3728. {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"},
  3729. {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"},
  3730. },
  3731. {
  3732. {1000, "M"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"},
  3733. {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"},
  3734. {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"},
  3735. {5, "V"}, {4, "IV"}, {1, "I"},
  3736. },
  3737. {
  3738. {1000, "M"}, {999, "IM"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"},
  3739. {500, "D"}, {499, "ID"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"},
  3740. {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"},
  3741. {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"},
  3742. },
  3743. }
  3744. // ROMAN function converts an arabic number to Roman. I.e. for a supplied
  3745. // integer, the function returns a text string depicting the roman numeral
  3746. // form of the number. The syntax of the function is:
  3747. //
  3748. // ROMAN(number,[form])
  3749. //
  3750. func (fn *formulaFuncs) ROMAN(argsList *list.List) formulaArg {
  3751. if argsList.Len() == 0 {
  3752. return newErrorFormulaArg(formulaErrorVALUE, "ROMAN requires at least 1 argument")
  3753. }
  3754. if argsList.Len() > 2 {
  3755. return newErrorFormulaArg(formulaErrorVALUE, "ROMAN allows at most 2 arguments")
  3756. }
  3757. var form int
  3758. number := argsList.Front().Value.(formulaArg).ToNumber()
  3759. if number.Type == ArgError {
  3760. return number
  3761. }
  3762. if argsList.Len() > 1 {
  3763. f := argsList.Back().Value.(formulaArg).ToNumber()
  3764. if f.Type == ArgError {
  3765. return f
  3766. }
  3767. form = int(f.Number)
  3768. if form < 0 {
  3769. form = 0
  3770. } else if form > 4 {
  3771. form = 4
  3772. }
  3773. }
  3774. decimalTable := romanTable[0]
  3775. switch form {
  3776. case 1:
  3777. decimalTable = romanTable[1]
  3778. case 2:
  3779. decimalTable = romanTable[2]
  3780. case 3:
  3781. decimalTable = romanTable[3]
  3782. case 4:
  3783. decimalTable = romanTable[4]
  3784. }
  3785. val := math.Trunc(number.Number)
  3786. buf := bytes.Buffer{}
  3787. for _, r := range decimalTable {
  3788. for val >= r.n {
  3789. buf.WriteString(r.s)
  3790. val -= r.n
  3791. }
  3792. }
  3793. return newStringFormulaArg(buf.String())
  3794. }
  3795. type roundMode byte
  3796. const (
  3797. closest roundMode = iota
  3798. down
  3799. up
  3800. )
  3801. // round rounds a supplied number up or down.
  3802. func (fn *formulaFuncs) round(number, digits float64, mode roundMode) float64 {
  3803. var significance float64
  3804. if digits > 0 {
  3805. significance = math.Pow(1/10.0, digits)
  3806. } else {
  3807. significance = math.Pow(10.0, -digits)
  3808. }
  3809. val, res := math.Modf(number / significance)
  3810. switch mode {
  3811. case closest:
  3812. const eps = 0.499999999
  3813. if res >= eps {
  3814. val++
  3815. } else if res <= -eps {
  3816. val--
  3817. }
  3818. case down:
  3819. case up:
  3820. if res > 0 {
  3821. val++
  3822. } else if res < 0 {
  3823. val--
  3824. }
  3825. }
  3826. return val * significance
  3827. }
  3828. // ROUND function rounds a supplied number up or down, to a specified number
  3829. // of decimal places. The syntax of the function is:
  3830. //
  3831. // ROUND(number,num_digits)
  3832. //
  3833. func (fn *formulaFuncs) ROUND(argsList *list.List) formulaArg {
  3834. if argsList.Len() != 2 {
  3835. return newErrorFormulaArg(formulaErrorVALUE, "ROUND requires 2 numeric arguments")
  3836. }
  3837. number := argsList.Front().Value.(formulaArg).ToNumber()
  3838. if number.Type == ArgError {
  3839. return number
  3840. }
  3841. digits := argsList.Back().Value.(formulaArg).ToNumber()
  3842. if digits.Type == ArgError {
  3843. return digits
  3844. }
  3845. return newNumberFormulaArg(fn.round(number.Number, digits.Number, closest))
  3846. }
  3847. // ROUNDDOWN function rounds a supplied number down towards zero, to a
  3848. // specified number of decimal places. The syntax of the function is:
  3849. //
  3850. // ROUNDDOWN(number,num_digits)
  3851. //
  3852. func (fn *formulaFuncs) ROUNDDOWN(argsList *list.List) formulaArg {
  3853. if argsList.Len() != 2 {
  3854. return newErrorFormulaArg(formulaErrorVALUE, "ROUNDDOWN requires 2 numeric arguments")
  3855. }
  3856. number := argsList.Front().Value.(formulaArg).ToNumber()
  3857. if number.Type == ArgError {
  3858. return number
  3859. }
  3860. digits := argsList.Back().Value.(formulaArg).ToNumber()
  3861. if digits.Type == ArgError {
  3862. return digits
  3863. }
  3864. return newNumberFormulaArg(fn.round(number.Number, digits.Number, down))
  3865. }
  3866. // ROUNDUP function rounds a supplied number up, away from zero, to a
  3867. // specified number of decimal places. The syntax of the function is:
  3868. //
  3869. // ROUNDUP(number,num_digits)
  3870. //
  3871. func (fn *formulaFuncs) ROUNDUP(argsList *list.List) formulaArg {
  3872. if argsList.Len() != 2 {
  3873. return newErrorFormulaArg(formulaErrorVALUE, "ROUNDUP requires 2 numeric arguments")
  3874. }
  3875. number := argsList.Front().Value.(formulaArg).ToNumber()
  3876. if number.Type == ArgError {
  3877. return number
  3878. }
  3879. digits := argsList.Back().Value.(formulaArg).ToNumber()
  3880. if digits.Type == ArgError {
  3881. return digits
  3882. }
  3883. return newNumberFormulaArg(fn.round(number.Number, digits.Number, up))
  3884. }
  3885. // SEC function calculates the secant of a given angle. The syntax of the
  3886. // function is:
  3887. //
  3888. // SEC(number)
  3889. //
  3890. func (fn *formulaFuncs) SEC(argsList *list.List) formulaArg {
  3891. if argsList.Len() != 1 {
  3892. return newErrorFormulaArg(formulaErrorVALUE, "SEC requires 1 numeric argument")
  3893. }
  3894. number := argsList.Front().Value.(formulaArg).ToNumber()
  3895. if number.Type == ArgError {
  3896. return number
  3897. }
  3898. return newNumberFormulaArg(math.Cos(number.Number))
  3899. }
  3900. // SECH function calculates the hyperbolic secant (sech) of a supplied angle.
  3901. // The syntax of the function is:
  3902. //
  3903. // SECH(number)
  3904. //
  3905. func (fn *formulaFuncs) SECH(argsList *list.List) formulaArg {
  3906. if argsList.Len() != 1 {
  3907. return newErrorFormulaArg(formulaErrorVALUE, "SECH requires 1 numeric argument")
  3908. }
  3909. number := argsList.Front().Value.(formulaArg).ToNumber()
  3910. if number.Type == ArgError {
  3911. return number
  3912. }
  3913. return newNumberFormulaArg(1 / math.Cosh(number.Number))
  3914. }
  3915. // SIGN function returns the arithmetic sign (+1, -1 or 0) of a supplied
  3916. // number. I.e. if the number is positive, the Sign function returns +1, if
  3917. // the number is negative, the function returns -1 and if the number is 0
  3918. // (zero), the function returns 0. The syntax of the function is:
  3919. //
  3920. // SIGN(number)
  3921. //
  3922. func (fn *formulaFuncs) SIGN(argsList *list.List) formulaArg {
  3923. if argsList.Len() != 1 {
  3924. return newErrorFormulaArg(formulaErrorVALUE, "SIGN requires 1 numeric argument")
  3925. }
  3926. val := argsList.Front().Value.(formulaArg).ToNumber()
  3927. if val.Type == ArgError {
  3928. return val
  3929. }
  3930. if val.Number < 0 {
  3931. return newNumberFormulaArg(-1)
  3932. }
  3933. if val.Number > 0 {
  3934. return newNumberFormulaArg(1)
  3935. }
  3936. return newNumberFormulaArg(0)
  3937. }
  3938. // SIN function calculates the sine of a given angle. The syntax of the
  3939. // function is:
  3940. //
  3941. // SIN(number)
  3942. //
  3943. func (fn *formulaFuncs) SIN(argsList *list.List) formulaArg {
  3944. if argsList.Len() != 1 {
  3945. return newErrorFormulaArg(formulaErrorVALUE, "SIN requires 1 numeric argument")
  3946. }
  3947. number := argsList.Front().Value.(formulaArg).ToNumber()
  3948. if number.Type == ArgError {
  3949. return number
  3950. }
  3951. return newNumberFormulaArg(math.Sin(number.Number))
  3952. }
  3953. // SINH function calculates the hyperbolic sine (sinh) of a supplied number.
  3954. // The syntax of the function is:
  3955. //
  3956. // SINH(number)
  3957. //
  3958. func (fn *formulaFuncs) SINH(argsList *list.List) formulaArg {
  3959. if argsList.Len() != 1 {
  3960. return newErrorFormulaArg(formulaErrorVALUE, "SINH requires 1 numeric argument")
  3961. }
  3962. number := argsList.Front().Value.(formulaArg).ToNumber()
  3963. if number.Type == ArgError {
  3964. return number
  3965. }
  3966. return newNumberFormulaArg(math.Sinh(number.Number))
  3967. }
  3968. // SQRT function calculates the positive square root of a supplied number. The
  3969. // syntax of the function is:
  3970. //
  3971. // SQRT(number)
  3972. //
  3973. func (fn *formulaFuncs) SQRT(argsList *list.List) formulaArg {
  3974. if argsList.Len() != 1 {
  3975. return newErrorFormulaArg(formulaErrorVALUE, "SQRT requires 1 numeric argument")
  3976. }
  3977. value := argsList.Front().Value.(formulaArg).ToNumber()
  3978. if value.Type == ArgError {
  3979. return value
  3980. }
  3981. if value.Number < 0 {
  3982. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  3983. }
  3984. return newNumberFormulaArg(math.Sqrt(value.Number))
  3985. }
  3986. // SQRTPI function returns the square root of a supplied number multiplied by
  3987. // the mathematical constant, π. The syntax of the function is:
  3988. //
  3989. // SQRTPI(number)
  3990. //
  3991. func (fn *formulaFuncs) SQRTPI(argsList *list.List) formulaArg {
  3992. if argsList.Len() != 1 {
  3993. return newErrorFormulaArg(formulaErrorVALUE, "SQRTPI requires 1 numeric argument")
  3994. }
  3995. number := argsList.Front().Value.(formulaArg).ToNumber()
  3996. if number.Type == ArgError {
  3997. return number
  3998. }
  3999. return newNumberFormulaArg(math.Sqrt(number.Number * math.Pi))
  4000. }
  4001. // STDEV function calculates the sample standard deviation of a supplied set
  4002. // of values. The syntax of the function is:
  4003. //
  4004. // STDEV(number1,[number2],...)
  4005. //
  4006. func (fn *formulaFuncs) STDEV(argsList *list.List) formulaArg {
  4007. if argsList.Len() < 1 {
  4008. return newErrorFormulaArg(formulaErrorVALUE, "STDEV requires at least 1 argument")
  4009. }
  4010. return fn.stdev(false, argsList)
  4011. }
  4012. // STDEVdotS function calculates the sample standard deviation of a supplied
  4013. // set of values. The syntax of the function is:
  4014. //
  4015. // STDEV.S(number1,[number2],...)
  4016. //
  4017. func (fn *formulaFuncs) STDEVdotS(argsList *list.List) formulaArg {
  4018. if argsList.Len() < 1 {
  4019. return newErrorFormulaArg(formulaErrorVALUE, "STDEV.S requires at least 1 argument")
  4020. }
  4021. return fn.stdev(false, argsList)
  4022. }
  4023. // STDEVA function estimates standard deviation based on a sample. The
  4024. // standard deviation is a measure of how widely values are dispersed from
  4025. // the average value (the mean). The syntax of the function is:
  4026. //
  4027. // STDEVA(number1,[number2],...)
  4028. //
  4029. func (fn *formulaFuncs) STDEVA(argsList *list.List) formulaArg {
  4030. if argsList.Len() < 1 {
  4031. return newErrorFormulaArg(formulaErrorVALUE, "STDEVA requires at least 1 argument")
  4032. }
  4033. return fn.stdev(true, argsList)
  4034. }
  4035. // stdev is an implementation of the formula function STDEV and STDEVA.
  4036. func (fn *formulaFuncs) stdev(stdeva bool, argsList *list.List) formulaArg {
  4037. pow := func(result, count float64, n, m formulaArg) (float64, float64) {
  4038. if result == -1 {
  4039. result = math.Pow((n.Number - m.Number), 2)
  4040. } else {
  4041. result += math.Pow((n.Number - m.Number), 2)
  4042. }
  4043. count++
  4044. return result, count
  4045. }
  4046. count, result := -1.0, -1.0
  4047. var mean formulaArg
  4048. if stdeva {
  4049. mean = fn.AVERAGEA(argsList)
  4050. } else {
  4051. mean = fn.AVERAGE(argsList)
  4052. }
  4053. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4054. token := arg.Value.(formulaArg)
  4055. switch token.Type {
  4056. case ArgString, ArgNumber:
  4057. if !stdeva && (token.Value() == "TRUE" || token.Value() == "FALSE") {
  4058. continue
  4059. } else if stdeva && (token.Value() == "TRUE" || token.Value() == "FALSE") {
  4060. num := token.ToBool()
  4061. if num.Type == ArgNumber {
  4062. result, count = pow(result, count, num, mean)
  4063. continue
  4064. }
  4065. } else {
  4066. num := token.ToNumber()
  4067. if num.Type == ArgNumber {
  4068. result, count = pow(result, count, num, mean)
  4069. }
  4070. }
  4071. case ArgList, ArgMatrix:
  4072. for _, row := range token.ToList() {
  4073. if row.Type == ArgNumber || row.Type == ArgString {
  4074. if !stdeva && (row.Value() == "TRUE" || row.Value() == "FALSE") {
  4075. continue
  4076. } else if stdeva && (row.Value() == "TRUE" || row.Value() == "FALSE") {
  4077. num := row.ToBool()
  4078. if num.Type == ArgNumber {
  4079. result, count = pow(result, count, num, mean)
  4080. continue
  4081. }
  4082. } else {
  4083. num := row.ToNumber()
  4084. if num.Type == ArgNumber {
  4085. result, count = pow(result, count, num, mean)
  4086. }
  4087. }
  4088. }
  4089. }
  4090. }
  4091. }
  4092. if count > 0 && result >= 0 {
  4093. return newNumberFormulaArg(math.Sqrt(result / count))
  4094. }
  4095. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  4096. }
  4097. // POISSONdotDIST function calculates the Poisson Probability Mass Function or
  4098. // the Cumulative Poisson Probability Function for a supplied set of
  4099. // parameters. The syntax of the function is:
  4100. //
  4101. // POISSON.DIST(x,mean,cumulative)
  4102. //
  4103. func (fn *formulaFuncs) POISSONdotDIST(argsList *list.List) formulaArg {
  4104. if argsList.Len() != 3 {
  4105. return newErrorFormulaArg(formulaErrorVALUE, "POISSON.DIST requires 3 arguments")
  4106. }
  4107. return fn.POISSON(argsList)
  4108. }
  4109. // POISSON function calculates the Poisson Probability Mass Function or the
  4110. // Cumulative Poisson Probability Function for a supplied set of parameters.
  4111. // The syntax of the function is:
  4112. //
  4113. // POISSON(x,mean,cumulative)
  4114. //
  4115. func (fn *formulaFuncs) POISSON(argsList *list.List) formulaArg {
  4116. if argsList.Len() != 3 {
  4117. return newErrorFormulaArg(formulaErrorVALUE, "POISSON requires 3 arguments")
  4118. }
  4119. var x, mean, cumulative formulaArg
  4120. if x = argsList.Front().Value.(formulaArg).ToNumber(); x.Type != ArgNumber {
  4121. return x
  4122. }
  4123. if mean = argsList.Front().Next().Value.(formulaArg).ToNumber(); mean.Type != ArgNumber {
  4124. return mean
  4125. }
  4126. if cumulative = argsList.Back().Value.(formulaArg).ToBool(); cumulative.Type == ArgError {
  4127. return cumulative
  4128. }
  4129. if x.Number < 0 || mean.Number <= 0 {
  4130. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4131. }
  4132. if cumulative.Number == 1 {
  4133. summer := 0.0
  4134. floor := math.Floor(x.Number)
  4135. for i := 0; i <= int(floor); i++ {
  4136. summer += math.Pow(mean.Number, float64(i)) / fact(float64(i))
  4137. }
  4138. return newNumberFormulaArg(math.Exp(0-mean.Number) * summer)
  4139. }
  4140. return newNumberFormulaArg(math.Exp(0-mean.Number) * math.Pow(mean.Number, x.Number) / fact(x.Number))
  4141. }
  4142. // SUM function adds together a supplied set of numbers and returns the sum of
  4143. // these values. The syntax of the function is:
  4144. //
  4145. // SUM(number1,[number2],...)
  4146. //
  4147. func (fn *formulaFuncs) SUM(argsList *list.List) formulaArg {
  4148. var sum float64
  4149. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4150. token := arg.Value.(formulaArg)
  4151. switch token.Type {
  4152. case ArgUnknown:
  4153. continue
  4154. case ArgString:
  4155. if num := token.ToNumber(); num.Type == ArgNumber {
  4156. sum += num.Number
  4157. }
  4158. case ArgNumber:
  4159. sum += token.Number
  4160. case ArgMatrix:
  4161. for _, row := range token.Matrix {
  4162. for _, value := range row {
  4163. if num := value.ToNumber(); num.Type == ArgNumber {
  4164. sum += num.Number
  4165. }
  4166. }
  4167. }
  4168. }
  4169. }
  4170. return newNumberFormulaArg(sum)
  4171. }
  4172. // SUMIF function finds the values in a supplied array, that satisfy a given
  4173. // criteria, and returns the sum of the corresponding values in a second
  4174. // supplied array. The syntax of the function is:
  4175. //
  4176. // SUMIF(range,criteria,[sum_range])
  4177. //
  4178. func (fn *formulaFuncs) SUMIF(argsList *list.List) formulaArg {
  4179. if argsList.Len() < 2 {
  4180. return newErrorFormulaArg(formulaErrorVALUE, "SUMIF requires at least 2 argument")
  4181. }
  4182. var criteria = formulaCriteriaParser(argsList.Front().Next().Value.(formulaArg).String)
  4183. var rangeMtx = argsList.Front().Value.(formulaArg).Matrix
  4184. var sumRange [][]formulaArg
  4185. if argsList.Len() == 3 {
  4186. sumRange = argsList.Back().Value.(formulaArg).Matrix
  4187. }
  4188. var sum, val float64
  4189. var err error
  4190. for rowIdx, row := range rangeMtx {
  4191. for colIdx, col := range row {
  4192. var ok bool
  4193. fromVal := col.String
  4194. if col.String == "" {
  4195. continue
  4196. }
  4197. if ok, err = formulaCriteriaEval(fromVal, criteria); err != nil {
  4198. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4199. }
  4200. if ok {
  4201. if argsList.Len() == 3 {
  4202. if len(sumRange) <= rowIdx || len(sumRange[rowIdx]) <= colIdx {
  4203. continue
  4204. }
  4205. fromVal = sumRange[rowIdx][colIdx].String
  4206. }
  4207. if val, err = strconv.ParseFloat(fromVal, 64); err != nil {
  4208. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4209. }
  4210. sum += val
  4211. }
  4212. }
  4213. }
  4214. return newNumberFormulaArg(sum)
  4215. }
  4216. // SUMSQ function returns the sum of squares of a supplied set of values. The
  4217. // syntax of the function is:
  4218. //
  4219. // SUMSQ(number1,[number2],...)
  4220. //
  4221. func (fn *formulaFuncs) SUMSQ(argsList *list.List) formulaArg {
  4222. var val, sq float64
  4223. var err error
  4224. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4225. token := arg.Value.(formulaArg)
  4226. switch token.Type {
  4227. case ArgString:
  4228. if token.String == "" {
  4229. continue
  4230. }
  4231. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  4232. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4233. }
  4234. sq += val * val
  4235. case ArgNumber:
  4236. sq += token.Number
  4237. case ArgMatrix:
  4238. for _, row := range token.Matrix {
  4239. for _, value := range row {
  4240. if value.String == "" {
  4241. continue
  4242. }
  4243. if val, err = strconv.ParseFloat(value.String, 64); err != nil {
  4244. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4245. }
  4246. sq += val * val
  4247. }
  4248. }
  4249. }
  4250. }
  4251. return newNumberFormulaArg(sq)
  4252. }
  4253. // TAN function calculates the tangent of a given angle. The syntax of the
  4254. // function is:
  4255. //
  4256. // TAN(number)
  4257. //
  4258. func (fn *formulaFuncs) TAN(argsList *list.List) formulaArg {
  4259. if argsList.Len() != 1 {
  4260. return newErrorFormulaArg(formulaErrorVALUE, "TAN requires 1 numeric argument")
  4261. }
  4262. number := argsList.Front().Value.(formulaArg).ToNumber()
  4263. if number.Type == ArgError {
  4264. return number
  4265. }
  4266. return newNumberFormulaArg(math.Tan(number.Number))
  4267. }
  4268. // TANH function calculates the hyperbolic tangent (tanh) of a supplied
  4269. // number. The syntax of the function is:
  4270. //
  4271. // TANH(number)
  4272. //
  4273. func (fn *formulaFuncs) TANH(argsList *list.List) formulaArg {
  4274. if argsList.Len() != 1 {
  4275. return newErrorFormulaArg(formulaErrorVALUE, "TANH requires 1 numeric argument")
  4276. }
  4277. number := argsList.Front().Value.(formulaArg).ToNumber()
  4278. if number.Type == ArgError {
  4279. return number
  4280. }
  4281. return newNumberFormulaArg(math.Tanh(number.Number))
  4282. }
  4283. // TRUNC function truncates a supplied number to a specified number of decimal
  4284. // places. The syntax of the function is:
  4285. //
  4286. // TRUNC(number,[number_digits])
  4287. //
  4288. func (fn *formulaFuncs) TRUNC(argsList *list.List) formulaArg {
  4289. if argsList.Len() == 0 {
  4290. return newErrorFormulaArg(formulaErrorVALUE, "TRUNC requires at least 1 argument")
  4291. }
  4292. var digits, adjust, rtrim float64
  4293. var err error
  4294. number := argsList.Front().Value.(formulaArg).ToNumber()
  4295. if number.Type == ArgError {
  4296. return number
  4297. }
  4298. if argsList.Len() > 1 {
  4299. d := argsList.Back().Value.(formulaArg).ToNumber()
  4300. if d.Type == ArgError {
  4301. return d
  4302. }
  4303. digits = d.Number
  4304. digits = math.Floor(digits)
  4305. }
  4306. adjust = math.Pow(10, digits)
  4307. x := int((math.Abs(number.Number) - math.Abs(float64(int(number.Number)))) * adjust)
  4308. if x != 0 {
  4309. if rtrim, err = strconv.ParseFloat(strings.TrimRight(strconv.Itoa(x), "0"), 64); err != nil {
  4310. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4311. }
  4312. }
  4313. if (digits > 0) && (rtrim < adjust/10) {
  4314. return newNumberFormulaArg(number.Number)
  4315. }
  4316. return newNumberFormulaArg(float64(int(number.Number*adjust)) / adjust)
  4317. }
  4318. // Statistical Functions
  4319. // AVERAGE function returns the arithmetic mean of a list of supplied numbers.
  4320. // The syntax of the function is:
  4321. //
  4322. // AVERAGE(number1,[number2],...)
  4323. //
  4324. func (fn *formulaFuncs) AVERAGE(argsList *list.List) formulaArg {
  4325. args := []formulaArg{}
  4326. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4327. args = append(args, arg.Value.(formulaArg))
  4328. }
  4329. count, sum := fn.countSum(false, args)
  4330. if count == 0 {
  4331. return newErrorFormulaArg(formulaErrorDIV, "AVERAGE divide by zero")
  4332. }
  4333. return newNumberFormulaArg(sum / count)
  4334. }
  4335. // AVERAGEA function returns the arithmetic mean of a list of supplied numbers
  4336. // with text cell and zero values. The syntax of the function is:
  4337. //
  4338. // AVERAGEA(number1,[number2],...)
  4339. //
  4340. func (fn *formulaFuncs) AVERAGEA(argsList *list.List) formulaArg {
  4341. args := []formulaArg{}
  4342. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4343. args = append(args, arg.Value.(formulaArg))
  4344. }
  4345. count, sum := fn.countSum(true, args)
  4346. if count == 0 {
  4347. return newErrorFormulaArg(formulaErrorDIV, "AVERAGEA divide by zero")
  4348. }
  4349. return newNumberFormulaArg(sum / count)
  4350. }
  4351. // countSum get count and sum for a formula arguments array.
  4352. func (fn *formulaFuncs) countSum(countText bool, args []formulaArg) (count, sum float64) {
  4353. for _, arg := range args {
  4354. switch arg.Type {
  4355. case ArgNumber:
  4356. if countText || !arg.Boolean {
  4357. sum += arg.Number
  4358. count++
  4359. }
  4360. case ArgString:
  4361. if !countText && (arg.Value() == "TRUE" || arg.Value() == "FALSE") {
  4362. continue
  4363. } else if countText && (arg.Value() == "TRUE" || arg.Value() == "FALSE") {
  4364. num := arg.ToBool()
  4365. if num.Type == ArgNumber {
  4366. count++
  4367. sum += num.Number
  4368. continue
  4369. }
  4370. }
  4371. num := arg.ToNumber()
  4372. if countText && num.Type == ArgError && arg.String != "" {
  4373. count++
  4374. }
  4375. if num.Type == ArgNumber {
  4376. sum += num.Number
  4377. count++
  4378. }
  4379. case ArgList, ArgMatrix:
  4380. cnt, summary := fn.countSum(countText, arg.ToList())
  4381. sum += summary
  4382. count += cnt
  4383. }
  4384. }
  4385. return
  4386. }
  4387. // COUNT function returns the count of numeric values in a supplied set of
  4388. // cells or values. This count includes both numbers and dates. The syntax of
  4389. // the function is:
  4390. //
  4391. // COUNT(value1,[value2],...)
  4392. //
  4393. func (fn *formulaFuncs) COUNT(argsList *list.List) formulaArg {
  4394. var count int
  4395. for token := argsList.Front(); token != nil; token = token.Next() {
  4396. arg := token.Value.(formulaArg)
  4397. switch arg.Type {
  4398. case ArgString:
  4399. if arg.ToNumber().Type != ArgError {
  4400. count++
  4401. }
  4402. case ArgNumber:
  4403. count++
  4404. case ArgMatrix:
  4405. for _, row := range arg.Matrix {
  4406. for _, value := range row {
  4407. if value.ToNumber().Type != ArgError {
  4408. count++
  4409. }
  4410. }
  4411. }
  4412. }
  4413. }
  4414. return newNumberFormulaArg(float64(count))
  4415. }
  4416. // COUNTA function returns the number of non-blanks within a supplied set of
  4417. // cells or values. The syntax of the function is:
  4418. //
  4419. // COUNTA(value1,[value2],...)
  4420. //
  4421. func (fn *formulaFuncs) COUNTA(argsList *list.List) formulaArg {
  4422. var count int
  4423. for token := argsList.Front(); token != nil; token = token.Next() {
  4424. arg := token.Value.(formulaArg)
  4425. switch arg.Type {
  4426. case ArgString:
  4427. if arg.String != "" {
  4428. count++
  4429. }
  4430. case ArgNumber:
  4431. count++
  4432. case ArgMatrix:
  4433. for _, row := range arg.ToList() {
  4434. switch row.Type {
  4435. case ArgString:
  4436. if row.String != "" {
  4437. count++
  4438. }
  4439. case ArgNumber:
  4440. count++
  4441. }
  4442. }
  4443. }
  4444. }
  4445. return newNumberFormulaArg(float64(count))
  4446. }
  4447. // COUNTBLANK function returns the number of blank cells in a supplied range.
  4448. // The syntax of the function is:
  4449. //
  4450. // COUNTBLANK(range)
  4451. //
  4452. func (fn *formulaFuncs) COUNTBLANK(argsList *list.List) formulaArg {
  4453. if argsList.Len() != 1 {
  4454. return newErrorFormulaArg(formulaErrorVALUE, "COUNTBLANK requires 1 argument")
  4455. }
  4456. var count int
  4457. token := argsList.Front().Value.(formulaArg)
  4458. switch token.Type {
  4459. case ArgString:
  4460. if token.String == "" {
  4461. count++
  4462. }
  4463. case ArgList, ArgMatrix:
  4464. for _, row := range token.ToList() {
  4465. switch row.Type {
  4466. case ArgString:
  4467. if row.String == "" {
  4468. count++
  4469. }
  4470. case ArgEmpty:
  4471. count++
  4472. }
  4473. }
  4474. case ArgEmpty:
  4475. count++
  4476. }
  4477. return newNumberFormulaArg(float64(count))
  4478. }
  4479. // FISHER function calculates the Fisher Transformation for a supplied value.
  4480. // The syntax of the function is:
  4481. //
  4482. // FISHER(x)
  4483. //
  4484. func (fn *formulaFuncs) FISHER(argsList *list.List) formulaArg {
  4485. if argsList.Len() != 1 {
  4486. return newErrorFormulaArg(formulaErrorVALUE, "FISHER requires 1 numeric argument")
  4487. }
  4488. token := argsList.Front().Value.(formulaArg)
  4489. switch token.Type {
  4490. case ArgString:
  4491. arg := token.ToNumber()
  4492. if arg.Type == ArgNumber {
  4493. if arg.Number <= -1 || arg.Number >= 1 {
  4494. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4495. }
  4496. return newNumberFormulaArg(0.5 * math.Log((1+arg.Number)/(1-arg.Number)))
  4497. }
  4498. case ArgNumber:
  4499. if token.Number <= -1 || token.Number >= 1 {
  4500. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4501. }
  4502. return newNumberFormulaArg(0.5 * math.Log((1+token.Number)/(1-token.Number)))
  4503. }
  4504. return newErrorFormulaArg(formulaErrorVALUE, "FISHER requires 1 numeric argument")
  4505. }
  4506. // FISHERINV function calculates the inverse of the Fisher Transformation and
  4507. // returns a value between -1 and +1. The syntax of the function is:
  4508. //
  4509. // FISHERINV(y)
  4510. //
  4511. func (fn *formulaFuncs) FISHERINV(argsList *list.List) formulaArg {
  4512. if argsList.Len() != 1 {
  4513. return newErrorFormulaArg(formulaErrorVALUE, "FISHERINV requires 1 numeric argument")
  4514. }
  4515. token := argsList.Front().Value.(formulaArg)
  4516. switch token.Type {
  4517. case ArgString:
  4518. arg := token.ToNumber()
  4519. if arg.Type == ArgNumber {
  4520. return newNumberFormulaArg((math.Exp(2*arg.Number) - 1) / (math.Exp(2*arg.Number) + 1))
  4521. }
  4522. case ArgNumber:
  4523. return newNumberFormulaArg((math.Exp(2*token.Number) - 1) / (math.Exp(2*token.Number) + 1))
  4524. }
  4525. return newErrorFormulaArg(formulaErrorVALUE, "FISHERINV requires 1 numeric argument")
  4526. }
  4527. // GAMMA function returns the value of the Gamma Function, Γ(n), for a
  4528. // specified number, n. The syntax of the function is:
  4529. //
  4530. // GAMMA(number)
  4531. //
  4532. func (fn *formulaFuncs) GAMMA(argsList *list.List) formulaArg {
  4533. if argsList.Len() != 1 {
  4534. return newErrorFormulaArg(formulaErrorVALUE, "GAMMA requires 1 numeric argument")
  4535. }
  4536. token := argsList.Front().Value.(formulaArg)
  4537. switch token.Type {
  4538. case ArgString:
  4539. arg := token.ToNumber()
  4540. if arg.Type == ArgNumber {
  4541. if arg.Number <= 0 {
  4542. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4543. }
  4544. return newNumberFormulaArg(math.Gamma(arg.Number))
  4545. }
  4546. case ArgNumber:
  4547. if token.Number <= 0 {
  4548. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4549. }
  4550. return newNumberFormulaArg(math.Gamma(token.Number))
  4551. }
  4552. return newErrorFormulaArg(formulaErrorVALUE, "GAMMA requires 1 numeric argument")
  4553. }
  4554. // GAMMALN function returns the natural logarithm of the Gamma Function, Γ
  4555. // (n). The syntax of the function is:
  4556. //
  4557. // GAMMALN(x)
  4558. //
  4559. func (fn *formulaFuncs) GAMMALN(argsList *list.List) formulaArg {
  4560. if argsList.Len() != 1 {
  4561. return newErrorFormulaArg(formulaErrorVALUE, "GAMMALN requires 1 numeric argument")
  4562. }
  4563. token := argsList.Front().Value.(formulaArg)
  4564. switch token.Type {
  4565. case ArgString:
  4566. arg := token.ToNumber()
  4567. if arg.Type == ArgNumber {
  4568. if arg.Number <= 0 {
  4569. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4570. }
  4571. return newNumberFormulaArg(math.Log(math.Gamma(arg.Number)))
  4572. }
  4573. case ArgNumber:
  4574. if token.Number <= 0 {
  4575. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4576. }
  4577. return newNumberFormulaArg(math.Log(math.Gamma(token.Number)))
  4578. }
  4579. return newErrorFormulaArg(formulaErrorVALUE, "GAMMALN requires 1 numeric argument")
  4580. }
  4581. // HARMEAN function calculates the harmonic mean of a supplied set of values.
  4582. // The syntax of the function is:
  4583. //
  4584. // HARMEAN(number1,[number2],...)
  4585. //
  4586. func (fn *formulaFuncs) HARMEAN(argsList *list.List) formulaArg {
  4587. if argsList.Len() < 1 {
  4588. return newErrorFormulaArg(formulaErrorVALUE, "HARMEAN requires at least 1 argument")
  4589. }
  4590. if min := fn.MIN(argsList); min.Number < 0 {
  4591. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4592. }
  4593. number, val, cnt := 0.0, 0.0, 0.0
  4594. for token := argsList.Front(); token != nil; token = token.Next() {
  4595. arg := token.Value.(formulaArg)
  4596. switch arg.Type {
  4597. case ArgString:
  4598. num := arg.ToNumber()
  4599. if num.Type != ArgNumber {
  4600. continue
  4601. }
  4602. number = num.Number
  4603. case ArgNumber:
  4604. number = arg.Number
  4605. }
  4606. if number <= 0 {
  4607. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4608. }
  4609. val += (1 / number)
  4610. cnt++
  4611. }
  4612. return newNumberFormulaArg(1 / (val / cnt))
  4613. }
  4614. // KURT function calculates the kurtosis of a supplied set of values. The
  4615. // syntax of the function is:
  4616. //
  4617. // KURT(number1,[number2],...)
  4618. //
  4619. func (fn *formulaFuncs) KURT(argsList *list.List) formulaArg {
  4620. if argsList.Len() < 1 {
  4621. return newErrorFormulaArg(formulaErrorVALUE, "KURT requires at least 1 argument")
  4622. }
  4623. mean, stdev := fn.AVERAGE(argsList), fn.STDEV(argsList)
  4624. if stdev.Number > 0 {
  4625. count, summer := 0.0, 0.0
  4626. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  4627. token := arg.Value.(formulaArg)
  4628. switch token.Type {
  4629. case ArgString, ArgNumber:
  4630. num := token.ToNumber()
  4631. if num.Type == ArgError {
  4632. continue
  4633. }
  4634. summer += math.Pow((num.Number-mean.Number)/stdev.Number, 4)
  4635. count++
  4636. case ArgList, ArgMatrix:
  4637. for _, row := range token.ToList() {
  4638. if row.Type == ArgNumber || row.Type == ArgString {
  4639. num := row.ToNumber()
  4640. if num.Type == ArgError {
  4641. continue
  4642. }
  4643. summer += math.Pow((num.Number-mean.Number)/stdev.Number, 4)
  4644. count++
  4645. }
  4646. }
  4647. }
  4648. }
  4649. if count > 3 {
  4650. return newNumberFormulaArg(summer*(count*(count+1)/((count-1)*(count-2)*(count-3))) - (3 * math.Pow(count-1, 2) / ((count - 2) * (count - 3))))
  4651. }
  4652. }
  4653. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  4654. }
  4655. // NORMdotDIST function calculates the Normal Probability Density Function or
  4656. // the Cumulative Normal Distribution. Function for a supplied set of
  4657. // parameters. The syntax of the function is:
  4658. //
  4659. // NORM.DIST(x,mean,standard_dev,cumulative)
  4660. //
  4661. func (fn *formulaFuncs) NORMdotDIST(argsList *list.List) formulaArg {
  4662. if argsList.Len() != 4 {
  4663. return newErrorFormulaArg(formulaErrorVALUE, "NORM.DIST requires 4 arguments")
  4664. }
  4665. return fn.NORMDIST(argsList)
  4666. }
  4667. // NORMDIST function calculates the Normal Probability Density Function or the
  4668. // Cumulative Normal Distribution. Function for a supplied set of parameters.
  4669. // The syntax of the function is:
  4670. //
  4671. // NORMDIST(x,mean,standard_dev,cumulative)
  4672. //
  4673. func (fn *formulaFuncs) NORMDIST(argsList *list.List) formulaArg {
  4674. if argsList.Len() != 4 {
  4675. return newErrorFormulaArg(formulaErrorVALUE, "NORMDIST requires 4 arguments")
  4676. }
  4677. var x, mean, stdDev, cumulative formulaArg
  4678. if x = argsList.Front().Value.(formulaArg).ToNumber(); x.Type != ArgNumber {
  4679. return x
  4680. }
  4681. if mean = argsList.Front().Next().Value.(formulaArg).ToNumber(); mean.Type != ArgNumber {
  4682. return mean
  4683. }
  4684. if stdDev = argsList.Back().Prev().Value.(formulaArg).ToNumber(); stdDev.Type != ArgNumber {
  4685. return stdDev
  4686. }
  4687. if cumulative = argsList.Back().Value.(formulaArg).ToBool(); cumulative.Type == ArgError {
  4688. return cumulative
  4689. }
  4690. if stdDev.Number < 0 {
  4691. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4692. }
  4693. if cumulative.Number == 1 {
  4694. return newNumberFormulaArg(0.5 * (1 + math.Erf((x.Number-mean.Number)/(stdDev.Number*math.Sqrt(2)))))
  4695. }
  4696. return newNumberFormulaArg((1 / (math.Sqrt(2*math.Pi) * stdDev.Number)) * math.Exp(0-(math.Pow(x.Number-mean.Number, 2)/(2*(stdDev.Number*stdDev.Number)))))
  4697. }
  4698. // NORMdotINV function calculates the inverse of the Cumulative Normal
  4699. // Distribution Function for a supplied value of x, and a supplied
  4700. // distribution mean & standard deviation. The syntax of the function is:
  4701. //
  4702. // NORM.INV(probability,mean,standard_dev)
  4703. //
  4704. func (fn *formulaFuncs) NORMdotINV(argsList *list.List) formulaArg {
  4705. if argsList.Len() != 3 {
  4706. return newErrorFormulaArg(formulaErrorVALUE, "NORM.INV requires 3 arguments")
  4707. }
  4708. return fn.NORMINV(argsList)
  4709. }
  4710. // NORMINV function calculates the inverse of the Cumulative Normal
  4711. // Distribution Function for a supplied value of x, and a supplied
  4712. // distribution mean & standard deviation. The syntax of the function is:
  4713. //
  4714. // NORMINV(probability,mean,standard_dev)
  4715. //
  4716. func (fn *formulaFuncs) NORMINV(argsList *list.List) formulaArg {
  4717. if argsList.Len() != 3 {
  4718. return newErrorFormulaArg(formulaErrorVALUE, "NORMINV requires 3 arguments")
  4719. }
  4720. var prob, mean, stdDev formulaArg
  4721. if prob = argsList.Front().Value.(formulaArg).ToNumber(); prob.Type != ArgNumber {
  4722. return prob
  4723. }
  4724. if mean = argsList.Front().Next().Value.(formulaArg).ToNumber(); mean.Type != ArgNumber {
  4725. return mean
  4726. }
  4727. if stdDev = argsList.Back().Value.(formulaArg).ToNumber(); stdDev.Type != ArgNumber {
  4728. return stdDev
  4729. }
  4730. if prob.Number < 0 || prob.Number > 1 {
  4731. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4732. }
  4733. if stdDev.Number < 0 {
  4734. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  4735. }
  4736. inv, err := norminv(prob.Number)
  4737. if err != nil {
  4738. return newErrorFormulaArg(err.Error(), err.Error())
  4739. }
  4740. return newNumberFormulaArg(inv*stdDev.Number + mean.Number)
  4741. }
  4742. // NORMdotSdotDIST function calculates the Standard Normal Cumulative
  4743. // Distribution Function for a supplied value. The syntax of the function
  4744. // is:
  4745. //
  4746. // NORM.S.DIST(z)
  4747. //
  4748. func (fn *formulaFuncs) NORMdotSdotDIST(argsList *list.List) formulaArg {
  4749. if argsList.Len() != 2 {
  4750. return newErrorFormulaArg(formulaErrorVALUE, "NORM.S.DIST requires 2 numeric arguments")
  4751. }
  4752. args := list.New().Init()
  4753. args.PushBack(argsList.Front().Value.(formulaArg))
  4754. args.PushBack(formulaArg{Type: ArgNumber, Number: 0})
  4755. args.PushBack(formulaArg{Type: ArgNumber, Number: 1})
  4756. args.PushBack(argsList.Back().Value.(formulaArg))
  4757. return fn.NORMDIST(args)
  4758. }
  4759. // NORMSDIST function calculates the Standard Normal Cumulative Distribution
  4760. // Function for a supplied value. The syntax of the function is:
  4761. //
  4762. // NORMSDIST(z)
  4763. //
  4764. func (fn *formulaFuncs) NORMSDIST(argsList *list.List) formulaArg {
  4765. if argsList.Len() != 1 {
  4766. return newErrorFormulaArg(formulaErrorVALUE, "NORMSDIST requires 1 numeric argument")
  4767. }
  4768. args := list.New().Init()
  4769. args.PushBack(argsList.Front().Value.(formulaArg))
  4770. args.PushBack(formulaArg{Type: ArgNumber, Number: 0})
  4771. args.PushBack(formulaArg{Type: ArgNumber, Number: 1})
  4772. args.PushBack(formulaArg{Type: ArgNumber, Number: 1, Boolean: true})
  4773. return fn.NORMDIST(args)
  4774. }
  4775. // NORMSINV function calculates the inverse of the Standard Normal Cumulative
  4776. // Distribution Function for a supplied probability value. The syntax of the
  4777. // function is:
  4778. //
  4779. // NORMSINV(probability)
  4780. //
  4781. func (fn *formulaFuncs) NORMSINV(argsList *list.List) formulaArg {
  4782. if argsList.Len() != 1 {
  4783. return newErrorFormulaArg(formulaErrorVALUE, "NORMSINV requires 1 numeric argument")
  4784. }
  4785. args := list.New().Init()
  4786. args.PushBack(argsList.Front().Value.(formulaArg))
  4787. args.PushBack(formulaArg{Type: ArgNumber, Number: 0})
  4788. args.PushBack(formulaArg{Type: ArgNumber, Number: 1})
  4789. return fn.NORMINV(args)
  4790. }
  4791. // NORMdotSdotINV function calculates the inverse of the Standard Normal
  4792. // Cumulative Distribution Function for a supplied probability value. The
  4793. // syntax of the function is:
  4794. //
  4795. // NORM.S.INV(probability)
  4796. //
  4797. func (fn *formulaFuncs) NORMdotSdotINV(argsList *list.List) formulaArg {
  4798. if argsList.Len() != 1 {
  4799. return newErrorFormulaArg(formulaErrorVALUE, "NORM.S.INV requires 1 numeric argument")
  4800. }
  4801. args := list.New().Init()
  4802. args.PushBack(argsList.Front().Value.(formulaArg))
  4803. args.PushBack(formulaArg{Type: ArgNumber, Number: 0})
  4804. args.PushBack(formulaArg{Type: ArgNumber, Number: 1})
  4805. return fn.NORMINV(args)
  4806. }
  4807. // norminv returns the inverse of the normal cumulative distribution for the
  4808. // specified value.
  4809. func norminv(p float64) (float64, error) {
  4810. a := map[int]float64{
  4811. 1: -3.969683028665376e+01, 2: 2.209460984245205e+02, 3: -2.759285104469687e+02,
  4812. 4: 1.383577518672690e+02, 5: -3.066479806614716e+01, 6: 2.506628277459239e+00,
  4813. }
  4814. b := map[int]float64{
  4815. 1: -5.447609879822406e+01, 2: 1.615858368580409e+02, 3: -1.556989798598866e+02,
  4816. 4: 6.680131188771972e+01, 5: -1.328068155288572e+01,
  4817. }
  4818. c := map[int]float64{
  4819. 1: -7.784894002430293e-03, 2: -3.223964580411365e-01, 3: -2.400758277161838e+00,
  4820. 4: -2.549732539343734e+00, 5: 4.374664141464968e+00, 6: 2.938163982698783e+00,
  4821. }
  4822. d := map[int]float64{
  4823. 1: 7.784695709041462e-03, 2: 3.224671290700398e-01, 3: 2.445134137142996e+00,
  4824. 4: 3.754408661907416e+00,
  4825. }
  4826. pLow := 0.02425 // Use lower region approx. below this
  4827. pHigh := 1 - pLow // Use upper region approx. above this
  4828. if 0 < p && p < pLow {
  4829. // Rational approximation for lower region.
  4830. q := math.Sqrt(-2 * math.Log(p))
  4831. return (((((c[1]*q+c[2])*q+c[3])*q+c[4])*q+c[5])*q + c[6]) /
  4832. ((((d[1]*q+d[2])*q+d[3])*q+d[4])*q + 1), nil
  4833. } else if pLow <= p && p <= pHigh {
  4834. // Rational approximation for central region.
  4835. q := p - 0.5
  4836. r := q * q
  4837. return (((((a[1]*r+a[2])*r+a[3])*r+a[4])*r+a[5])*r + a[6]) * q /
  4838. (((((b[1]*r+b[2])*r+b[3])*r+b[4])*r+b[5])*r + 1), nil
  4839. } else if pHigh < p && p < 1 {
  4840. // Rational approximation for upper region.
  4841. q := math.Sqrt(-2 * math.Log(1-p))
  4842. return -(((((c[1]*q+c[2])*q+c[3])*q+c[4])*q+c[5])*q + c[6]) /
  4843. ((((d[1]*q+d[2])*q+d[3])*q+d[4])*q + 1), nil
  4844. }
  4845. return 0, errors.New(formulaErrorNUM)
  4846. }
  4847. // kth is an implementation of the formula function LARGE and SMALL.
  4848. func (fn *formulaFuncs) kth(name string, argsList *list.List) formulaArg {
  4849. if argsList.Len() != 2 {
  4850. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 2 arguments", name))
  4851. }
  4852. array := argsList.Front().Value.(formulaArg).ToList()
  4853. kArg := argsList.Back().Value.(formulaArg).ToNumber()
  4854. if kArg.Type != ArgNumber {
  4855. return kArg
  4856. }
  4857. k := int(kArg.Number)
  4858. if k < 1 {
  4859. return newErrorFormulaArg(formulaErrorNUM, "k should be > 0")
  4860. }
  4861. data := []float64{}
  4862. for _, arg := range array {
  4863. if numArg := arg.ToNumber(); numArg.Type == ArgNumber {
  4864. data = append(data, numArg.Number)
  4865. }
  4866. }
  4867. if len(data) < k {
  4868. return newErrorFormulaArg(formulaErrorNUM, "k should be <= length of array")
  4869. }
  4870. sort.Float64s(data)
  4871. if name == "LARGE" {
  4872. return newNumberFormulaArg(data[len(data)-k])
  4873. }
  4874. return newNumberFormulaArg(data[k-1])
  4875. }
  4876. // LARGE function returns the k'th largest value from an array of numeric
  4877. // values. The syntax of the function is:
  4878. //
  4879. // LARGE(array,k)
  4880. //
  4881. func (fn *formulaFuncs) LARGE(argsList *list.List) formulaArg {
  4882. return fn.kth("LARGE", argsList)
  4883. }
  4884. // MAX function returns the largest value from a supplied set of numeric
  4885. // values. The syntax of the function is:
  4886. //
  4887. // MAX(number1,[number2],...)
  4888. //
  4889. func (fn *formulaFuncs) MAX(argsList *list.List) formulaArg {
  4890. if argsList.Len() == 0 {
  4891. return newErrorFormulaArg(formulaErrorVALUE, "MAX requires at least 1 argument")
  4892. }
  4893. return fn.max(false, argsList)
  4894. }
  4895. // MAXA function returns the largest value from a supplied set of numeric
  4896. // values, while counting text and the logical value FALSE as the value 0 and
  4897. // counting the logical value TRUE as the value 1. The syntax of the function
  4898. // is:
  4899. //
  4900. // MAXA(number1,[number2],...)
  4901. //
  4902. func (fn *formulaFuncs) MAXA(argsList *list.List) formulaArg {
  4903. if argsList.Len() == 0 {
  4904. return newErrorFormulaArg(formulaErrorVALUE, "MAXA requires at least 1 argument")
  4905. }
  4906. return fn.max(true, argsList)
  4907. }
  4908. // max is an implementation of the formula function MAX and MAXA.
  4909. func (fn *formulaFuncs) max(maxa bool, argsList *list.List) formulaArg {
  4910. max := -math.MaxFloat64
  4911. for token := argsList.Front(); token != nil; token = token.Next() {
  4912. arg := token.Value.(formulaArg)
  4913. switch arg.Type {
  4914. case ArgString:
  4915. if !maxa && (arg.Value() == "TRUE" || arg.Value() == "FALSE") {
  4916. continue
  4917. } else {
  4918. num := arg.ToBool()
  4919. if num.Type == ArgNumber && num.Number > max {
  4920. max = num.Number
  4921. continue
  4922. }
  4923. }
  4924. num := arg.ToNumber()
  4925. if num.Type != ArgError && num.Number > max {
  4926. max = num.Number
  4927. }
  4928. case ArgNumber:
  4929. if arg.Number > max {
  4930. max = arg.Number
  4931. }
  4932. case ArgList, ArgMatrix:
  4933. for _, row := range arg.ToList() {
  4934. switch row.Type {
  4935. case ArgString:
  4936. if !maxa && (row.Value() == "TRUE" || row.Value() == "FALSE") {
  4937. continue
  4938. } else {
  4939. num := row.ToBool()
  4940. if num.Type == ArgNumber && num.Number > max {
  4941. max = num.Number
  4942. continue
  4943. }
  4944. }
  4945. num := row.ToNumber()
  4946. if num.Type != ArgError && num.Number > max {
  4947. max = num.Number
  4948. }
  4949. case ArgNumber:
  4950. if row.Number > max {
  4951. max = row.Number
  4952. }
  4953. }
  4954. }
  4955. case ArgError:
  4956. return arg
  4957. }
  4958. }
  4959. if max == -math.MaxFloat64 {
  4960. max = 0
  4961. }
  4962. return newNumberFormulaArg(max)
  4963. }
  4964. // MEDIAN function returns the statistical median (the middle value) of a list
  4965. // of supplied numbers. The syntax of the function is:
  4966. //
  4967. // MEDIAN(number1,[number2],...)
  4968. //
  4969. func (fn *formulaFuncs) MEDIAN(argsList *list.List) formulaArg {
  4970. if argsList.Len() == 0 {
  4971. return newErrorFormulaArg(formulaErrorVALUE, "MEDIAN requires at least 1 argument")
  4972. }
  4973. var values = []float64{}
  4974. var median, digits float64
  4975. var err error
  4976. for token := argsList.Front(); token != nil; token = token.Next() {
  4977. arg := token.Value.(formulaArg)
  4978. switch arg.Type {
  4979. case ArgString:
  4980. num := arg.ToNumber()
  4981. if num.Type == ArgError {
  4982. return newErrorFormulaArg(formulaErrorVALUE, num.Error)
  4983. }
  4984. values = append(values, num.Number)
  4985. case ArgNumber:
  4986. values = append(values, arg.Number)
  4987. case ArgMatrix:
  4988. for _, row := range arg.Matrix {
  4989. for _, value := range row {
  4990. if value.String == "" {
  4991. continue
  4992. }
  4993. if digits, err = strconv.ParseFloat(value.String, 64); err != nil {
  4994. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  4995. }
  4996. values = append(values, digits)
  4997. }
  4998. }
  4999. }
  5000. }
  5001. sort.Float64s(values)
  5002. if len(values)%2 == 0 {
  5003. median = (values[len(values)/2-1] + values[len(values)/2]) / 2
  5004. } else {
  5005. median = values[len(values)/2]
  5006. }
  5007. return newNumberFormulaArg(median)
  5008. }
  5009. // MIN function returns the smallest value from a supplied set of numeric
  5010. // values. The syntax of the function is:
  5011. //
  5012. // MIN(number1,[number2],...)
  5013. //
  5014. func (fn *formulaFuncs) MIN(argsList *list.List) formulaArg {
  5015. if argsList.Len() == 0 {
  5016. return newErrorFormulaArg(formulaErrorVALUE, "MIN requires at least 1 argument")
  5017. }
  5018. return fn.min(false, argsList)
  5019. }
  5020. // MINA function returns the smallest value from a supplied set of numeric
  5021. // values, while counting text and the logical value FALSE as the value 0 and
  5022. // counting the logical value TRUE as the value 1. The syntax of the function
  5023. // is:
  5024. //
  5025. // MINA(number1,[number2],...)
  5026. //
  5027. func (fn *formulaFuncs) MINA(argsList *list.List) formulaArg {
  5028. if argsList.Len() == 0 {
  5029. return newErrorFormulaArg(formulaErrorVALUE, "MINA requires at least 1 argument")
  5030. }
  5031. return fn.min(true, argsList)
  5032. }
  5033. // min is an implementation of the formula function MIN and MINA.
  5034. func (fn *formulaFuncs) min(mina bool, argsList *list.List) formulaArg {
  5035. min := math.MaxFloat64
  5036. for token := argsList.Front(); token != nil; token = token.Next() {
  5037. arg := token.Value.(formulaArg)
  5038. switch arg.Type {
  5039. case ArgString:
  5040. if !mina && (arg.Value() == "TRUE" || arg.Value() == "FALSE") {
  5041. continue
  5042. } else {
  5043. num := arg.ToBool()
  5044. if num.Type == ArgNumber && num.Number < min {
  5045. min = num.Number
  5046. continue
  5047. }
  5048. }
  5049. num := arg.ToNumber()
  5050. if num.Type != ArgError && num.Number < min {
  5051. min = num.Number
  5052. }
  5053. case ArgNumber:
  5054. if arg.Number < min {
  5055. min = arg.Number
  5056. }
  5057. case ArgList, ArgMatrix:
  5058. for _, row := range arg.ToList() {
  5059. switch row.Type {
  5060. case ArgString:
  5061. if !mina && (row.Value() == "TRUE" || row.Value() == "FALSE") {
  5062. continue
  5063. } else {
  5064. num := row.ToBool()
  5065. if num.Type == ArgNumber && num.Number < min {
  5066. min = num.Number
  5067. continue
  5068. }
  5069. }
  5070. num := row.ToNumber()
  5071. if num.Type != ArgError && num.Number < min {
  5072. min = num.Number
  5073. }
  5074. case ArgNumber:
  5075. if row.Number < min {
  5076. min = row.Number
  5077. }
  5078. }
  5079. }
  5080. case ArgError:
  5081. return arg
  5082. }
  5083. }
  5084. if min == math.MaxFloat64 {
  5085. min = 0
  5086. }
  5087. return newNumberFormulaArg(min)
  5088. }
  5089. // PERCENTILEdotINC function returns the k'th percentile (i.e. the value below
  5090. // which k% of the data values fall) for a supplied range of values and a
  5091. // supplied k. The syntax of the function is:
  5092. //
  5093. // PERCENTILE.INC(array,k)
  5094. //
  5095. func (fn *formulaFuncs) PERCENTILEdotINC(argsList *list.List) formulaArg {
  5096. if argsList.Len() != 2 {
  5097. return newErrorFormulaArg(formulaErrorVALUE, "PERCENTILE.INC requires 2 arguments")
  5098. }
  5099. return fn.PERCENTILE(argsList)
  5100. }
  5101. // PERCENTILE function returns the k'th percentile (i.e. the value below which
  5102. // k% of the data values fall) for a supplied range of values and a supplied
  5103. // k. The syntax of the function is:
  5104. //
  5105. // PERCENTILE(array,k)
  5106. //
  5107. func (fn *formulaFuncs) PERCENTILE(argsList *list.List) formulaArg {
  5108. if argsList.Len() != 2 {
  5109. return newErrorFormulaArg(formulaErrorVALUE, "PERCENTILE requires 2 arguments")
  5110. }
  5111. array := argsList.Front().Value.(formulaArg).ToList()
  5112. k := argsList.Back().Value.(formulaArg).ToNumber()
  5113. if k.Type != ArgNumber {
  5114. return k
  5115. }
  5116. if k.Number < 0 || k.Number > 1 {
  5117. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  5118. }
  5119. numbers := []float64{}
  5120. for _, arg := range array {
  5121. if arg.Type == ArgError {
  5122. return arg
  5123. }
  5124. num := arg.ToNumber()
  5125. if num.Type == ArgNumber {
  5126. numbers = append(numbers, num.Number)
  5127. }
  5128. }
  5129. cnt := len(numbers)
  5130. sort.Float64s(numbers)
  5131. idx := k.Number * (float64(cnt) - 1)
  5132. base := math.Floor(idx)
  5133. if idx == base {
  5134. return newNumberFormulaArg(numbers[int(idx)])
  5135. }
  5136. next := base + 1
  5137. proportion := idx - base
  5138. return newNumberFormulaArg(numbers[int(base)] + ((numbers[int(next)] - numbers[int(base)]) * proportion))
  5139. }
  5140. // PERMUT function calculates the number of permutations of a specified number
  5141. // of objects from a set of objects. The syntax of the function is:
  5142. //
  5143. // PERMUT(number,number_chosen)
  5144. //
  5145. func (fn *formulaFuncs) PERMUT(argsList *list.List) formulaArg {
  5146. if argsList.Len() != 2 {
  5147. return newErrorFormulaArg(formulaErrorVALUE, "PERMUT requires 2 numeric arguments")
  5148. }
  5149. number := argsList.Front().Value.(formulaArg).ToNumber()
  5150. chosen := argsList.Back().Value.(formulaArg).ToNumber()
  5151. if number.Type != ArgNumber {
  5152. return number
  5153. }
  5154. if chosen.Type != ArgNumber {
  5155. return chosen
  5156. }
  5157. if number.Number < chosen.Number {
  5158. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  5159. }
  5160. return newNumberFormulaArg(math.Round(fact(number.Number) / fact(number.Number-chosen.Number)))
  5161. }
  5162. // PERMUTATIONA function calculates the number of permutations, with
  5163. // repetitions, of a specified number of objects from a set. The syntax of
  5164. // the function is:
  5165. //
  5166. // PERMUTATIONA(number,number_chosen)
  5167. //
  5168. func (fn *formulaFuncs) PERMUTATIONA(argsList *list.List) formulaArg {
  5169. if argsList.Len() < 1 {
  5170. return newErrorFormulaArg(formulaErrorVALUE, "PERMUTATIONA requires 2 numeric arguments")
  5171. }
  5172. number := argsList.Front().Value.(formulaArg).ToNumber()
  5173. chosen := argsList.Back().Value.(formulaArg).ToNumber()
  5174. if number.Type != ArgNumber {
  5175. return number
  5176. }
  5177. if chosen.Type != ArgNumber {
  5178. return chosen
  5179. }
  5180. num, numChosen := math.Floor(number.Number), math.Floor(chosen.Number)
  5181. if num < 0 || numChosen < 0 {
  5182. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  5183. }
  5184. return newNumberFormulaArg(math.Pow(num, numChosen))
  5185. }
  5186. // QUARTILE function returns a requested quartile of a supplied range of
  5187. // values. The syntax of the function is:
  5188. //
  5189. // QUARTILE(array,quart)
  5190. //
  5191. func (fn *formulaFuncs) QUARTILE(argsList *list.List) formulaArg {
  5192. if argsList.Len() != 2 {
  5193. return newErrorFormulaArg(formulaErrorVALUE, "QUARTILE requires 2 arguments")
  5194. }
  5195. quart := argsList.Back().Value.(formulaArg).ToNumber()
  5196. if quart.Type != ArgNumber {
  5197. return quart
  5198. }
  5199. if quart.Number < 0 || quart.Number > 4 {
  5200. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  5201. }
  5202. args := list.New().Init()
  5203. args.PushBack(argsList.Front().Value.(formulaArg))
  5204. args.PushBack(newNumberFormulaArg(quart.Number / 4))
  5205. return fn.PERCENTILE(args)
  5206. }
  5207. // QUARTILEdotINC function returns a requested quartile of a supplied range of
  5208. // values. The syntax of the function is:
  5209. //
  5210. // QUARTILE.INC(array,quart)
  5211. //
  5212. func (fn *formulaFuncs) QUARTILEdotINC(argsList *list.List) formulaArg {
  5213. if argsList.Len() != 2 {
  5214. return newErrorFormulaArg(formulaErrorVALUE, "QUARTILE.INC requires 2 arguments")
  5215. }
  5216. return fn.QUARTILE(argsList)
  5217. }
  5218. // SKEW function calculates the skewness of the distribution of a supplied set
  5219. // of values. The syntax of the function is:
  5220. //
  5221. // SKEW(number1,[number2],...)
  5222. //
  5223. func (fn *formulaFuncs) SKEW(argsList *list.List) formulaArg {
  5224. if argsList.Len() < 1 {
  5225. return newErrorFormulaArg(formulaErrorVALUE, "SKEW requires at least 1 argument")
  5226. }
  5227. mean, stdDev, count, summer := fn.AVERAGE(argsList), fn.STDEV(argsList), 0.0, 0.0
  5228. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5229. token := arg.Value.(formulaArg)
  5230. switch token.Type {
  5231. case ArgNumber, ArgString:
  5232. num := token.ToNumber()
  5233. if num.Type == ArgError {
  5234. return num
  5235. }
  5236. summer += math.Pow((num.Number-mean.Number)/stdDev.Number, 3)
  5237. count++
  5238. case ArgList, ArgMatrix:
  5239. for _, row := range token.ToList() {
  5240. numArg := row.ToNumber()
  5241. if numArg.Type != ArgNumber {
  5242. continue
  5243. }
  5244. summer += math.Pow((numArg.Number-mean.Number)/stdDev.Number, 3)
  5245. count++
  5246. }
  5247. }
  5248. }
  5249. if count > 2 {
  5250. return newNumberFormulaArg(summer * (count / ((count - 1) * (count - 2))))
  5251. }
  5252. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  5253. }
  5254. // SMALL function returns the k'th smallest value from an array of numeric
  5255. // values. The syntax of the function is:
  5256. //
  5257. // SMALL(array,k)
  5258. //
  5259. func (fn *formulaFuncs) SMALL(argsList *list.List) formulaArg {
  5260. return fn.kth("SMALL", argsList)
  5261. }
  5262. // VARP function returns the Variance of a given set of values. The syntax of
  5263. // the function is:
  5264. //
  5265. // VARP(number1,[number2],...)
  5266. //
  5267. func (fn *formulaFuncs) VARP(argsList *list.List) formulaArg {
  5268. if argsList.Len() < 1 {
  5269. return newErrorFormulaArg(formulaErrorVALUE, "VARP requires at least 1 argument")
  5270. }
  5271. summerA, summerB, count := 0.0, 0.0, 0.0
  5272. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5273. for _, token := range arg.Value.(formulaArg).ToList() {
  5274. if num := token.ToNumber(); num.Type == ArgNumber {
  5275. summerA += (num.Number * num.Number)
  5276. summerB += num.Number
  5277. count++
  5278. }
  5279. }
  5280. }
  5281. if count > 0 {
  5282. summerA *= count
  5283. summerB *= summerB
  5284. return newNumberFormulaArg((summerA - summerB) / (count * count))
  5285. }
  5286. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  5287. }
  5288. // VARdotP function returns the Variance of a given set of values. The syntax
  5289. // of the function is:
  5290. //
  5291. // VAR.P(number1,[number2],...)
  5292. //
  5293. func (fn *formulaFuncs) VARdotP(argsList *list.List) formulaArg {
  5294. if argsList.Len() < 1 {
  5295. return newErrorFormulaArg(formulaErrorVALUE, "VAR.P requires at least 1 argument")
  5296. }
  5297. return fn.VARP(argsList)
  5298. }
  5299. // Information Functions
  5300. // ISBLANK function tests if a specified cell is blank (empty) and if so,
  5301. // returns TRUE; Otherwise the function returns FALSE. The syntax of the
  5302. // function is:
  5303. //
  5304. // ISBLANK(value)
  5305. //
  5306. func (fn *formulaFuncs) ISBLANK(argsList *list.List) formulaArg {
  5307. if argsList.Len() != 1 {
  5308. return newErrorFormulaArg(formulaErrorVALUE, "ISBLANK requires 1 argument")
  5309. }
  5310. token := argsList.Front().Value.(formulaArg)
  5311. result := "FALSE"
  5312. switch token.Type {
  5313. case ArgUnknown:
  5314. result = "TRUE"
  5315. case ArgString:
  5316. if token.String == "" {
  5317. result = "TRUE"
  5318. }
  5319. }
  5320. return newStringFormulaArg(result)
  5321. }
  5322. // ISERR function tests if an initial supplied expression (or value) returns
  5323. // any Excel Error, except the #N/A error. If so, the function returns the
  5324. // logical value TRUE; If the supplied value is not an error or is the #N/A
  5325. // error, the ISERR function returns FALSE. The syntax of the function is:
  5326. //
  5327. // ISERR(value)
  5328. //
  5329. func (fn *formulaFuncs) ISERR(argsList *list.List) formulaArg {
  5330. if argsList.Len() != 1 {
  5331. return newErrorFormulaArg(formulaErrorVALUE, "ISERR requires 1 argument")
  5332. }
  5333. token := argsList.Front().Value.(formulaArg)
  5334. result := "FALSE"
  5335. if token.Type == ArgError {
  5336. for _, errType := range []string{
  5337. formulaErrorDIV, formulaErrorNAME, formulaErrorNUM,
  5338. formulaErrorVALUE, formulaErrorREF, formulaErrorNULL,
  5339. formulaErrorSPILL, formulaErrorCALC, formulaErrorGETTINGDATA,
  5340. } {
  5341. if errType == token.String {
  5342. result = "TRUE"
  5343. }
  5344. }
  5345. }
  5346. return newStringFormulaArg(result)
  5347. }
  5348. // ISERROR function tests if an initial supplied expression (or value) returns
  5349. // an Excel Error, and if so, returns the logical value TRUE; Otherwise the
  5350. // function returns FALSE. The syntax of the function is:
  5351. //
  5352. // ISERROR(value)
  5353. //
  5354. func (fn *formulaFuncs) ISERROR(argsList *list.List) formulaArg {
  5355. if argsList.Len() != 1 {
  5356. return newErrorFormulaArg(formulaErrorVALUE, "ISERROR requires 1 argument")
  5357. }
  5358. token := argsList.Front().Value.(formulaArg)
  5359. result := "FALSE"
  5360. if token.Type == ArgError {
  5361. for _, errType := range []string{
  5362. formulaErrorDIV, formulaErrorNAME, formulaErrorNA, formulaErrorNUM,
  5363. formulaErrorVALUE, formulaErrorREF, formulaErrorNULL, formulaErrorSPILL,
  5364. formulaErrorCALC, formulaErrorGETTINGDATA,
  5365. } {
  5366. if errType == token.String {
  5367. result = "TRUE"
  5368. }
  5369. }
  5370. }
  5371. return newStringFormulaArg(result)
  5372. }
  5373. // ISEVEN function tests if a supplied number (or numeric expression)
  5374. // evaluates to an even number, and if so, returns TRUE; Otherwise, the
  5375. // function returns FALSE. The syntax of the function is:
  5376. //
  5377. // ISEVEN(value)
  5378. //
  5379. func (fn *formulaFuncs) ISEVEN(argsList *list.List) formulaArg {
  5380. if argsList.Len() != 1 {
  5381. return newErrorFormulaArg(formulaErrorVALUE, "ISEVEN requires 1 argument")
  5382. }
  5383. var (
  5384. token = argsList.Front().Value.(formulaArg)
  5385. result = "FALSE"
  5386. numeric int
  5387. err error
  5388. )
  5389. if token.Type == ArgString {
  5390. if numeric, err = strconv.Atoi(token.String); err != nil {
  5391. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  5392. }
  5393. if numeric == numeric/2*2 {
  5394. return newStringFormulaArg("TRUE")
  5395. }
  5396. }
  5397. return newStringFormulaArg(result)
  5398. }
  5399. // ISNA function tests if an initial supplied expression (or value) returns
  5400. // the Excel #N/A Error, and if so, returns TRUE; Otherwise the function
  5401. // returns FALSE. The syntax of the function is:
  5402. //
  5403. // ISNA(value)
  5404. //
  5405. func (fn *formulaFuncs) ISNA(argsList *list.List) formulaArg {
  5406. if argsList.Len() != 1 {
  5407. return newErrorFormulaArg(formulaErrorVALUE, "ISNA requires 1 argument")
  5408. }
  5409. token := argsList.Front().Value.(formulaArg)
  5410. result := "FALSE"
  5411. if token.Type == ArgError && token.String == formulaErrorNA {
  5412. result = "TRUE"
  5413. }
  5414. return newStringFormulaArg(result)
  5415. }
  5416. // ISNONTEXT function function tests if a supplied value is text. If not, the
  5417. // function returns TRUE; If the supplied value is text, the function returns
  5418. // FALSE. The syntax of the function is:
  5419. //
  5420. // ISNONTEXT(value)
  5421. //
  5422. func (fn *formulaFuncs) ISNONTEXT(argsList *list.List) formulaArg {
  5423. if argsList.Len() != 1 {
  5424. return newErrorFormulaArg(formulaErrorVALUE, "ISNONTEXT requires 1 argument")
  5425. }
  5426. token := argsList.Front().Value.(formulaArg)
  5427. result := "TRUE"
  5428. if token.Type == ArgString && token.String != "" {
  5429. result = "FALSE"
  5430. }
  5431. return newStringFormulaArg(result)
  5432. }
  5433. // ISNUMBER function function tests if a supplied value is a number. If so,
  5434. // the function returns TRUE; Otherwise it returns FALSE. The syntax of the
  5435. // function is:
  5436. //
  5437. // ISNUMBER(value)
  5438. //
  5439. func (fn *formulaFuncs) ISNUMBER(argsList *list.List) formulaArg {
  5440. if argsList.Len() != 1 {
  5441. return newErrorFormulaArg(formulaErrorVALUE, "ISNUMBER requires 1 argument")
  5442. }
  5443. token, result := argsList.Front().Value.(formulaArg), false
  5444. if token.Type == ArgString && token.String != "" {
  5445. if _, err := strconv.Atoi(token.String); err == nil {
  5446. result = true
  5447. }
  5448. }
  5449. return newBoolFormulaArg(result)
  5450. }
  5451. // ISODD function tests if a supplied number (or numeric expression) evaluates
  5452. // to an odd number, and if so, returns TRUE; Otherwise, the function returns
  5453. // FALSE. The syntax of the function is:
  5454. //
  5455. // ISODD(value)
  5456. //
  5457. func (fn *formulaFuncs) ISODD(argsList *list.List) formulaArg {
  5458. if argsList.Len() != 1 {
  5459. return newErrorFormulaArg(formulaErrorVALUE, "ISODD requires 1 argument")
  5460. }
  5461. var (
  5462. token = argsList.Front().Value.(formulaArg)
  5463. result = "FALSE"
  5464. numeric int
  5465. err error
  5466. )
  5467. if token.Type == ArgString {
  5468. if numeric, err = strconv.Atoi(token.String); err != nil {
  5469. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  5470. }
  5471. if numeric != numeric/2*2 {
  5472. return newStringFormulaArg("TRUE")
  5473. }
  5474. }
  5475. return newStringFormulaArg(result)
  5476. }
  5477. // ISTEXT function tests if a supplied value is text, and if so, returns TRUE;
  5478. // Otherwise, the function returns FALSE. The syntax of the function is:
  5479. //
  5480. // ISTEXT(value)
  5481. //
  5482. func (fn *formulaFuncs) ISTEXT(argsList *list.List) formulaArg {
  5483. if argsList.Len() != 1 {
  5484. return newErrorFormulaArg(formulaErrorVALUE, "ISTEXT requires 1 argument")
  5485. }
  5486. token := argsList.Front().Value.(formulaArg)
  5487. if token.ToNumber().Type != ArgError {
  5488. return newBoolFormulaArg(false)
  5489. }
  5490. return newBoolFormulaArg(token.Type == ArgString)
  5491. }
  5492. // N function converts data into a numeric value. The syntax of the function
  5493. // is:
  5494. //
  5495. // N(value)
  5496. //
  5497. func (fn *formulaFuncs) N(argsList *list.List) formulaArg {
  5498. if argsList.Len() != 1 {
  5499. return newErrorFormulaArg(formulaErrorVALUE, "N requires 1 argument")
  5500. }
  5501. token, num := argsList.Front().Value.(formulaArg), 0.0
  5502. if token.Type == ArgError {
  5503. return token
  5504. }
  5505. if arg := token.ToNumber(); arg.Type == ArgNumber {
  5506. num = arg.Number
  5507. }
  5508. if token.Value() == "TRUE" {
  5509. num = 1
  5510. }
  5511. return newNumberFormulaArg(num)
  5512. }
  5513. // NA function returns the Excel #N/A error. This error message has the
  5514. // meaning 'value not available' and is produced when an Excel Formula is
  5515. // unable to find a value that it needs. The syntax of the function is:
  5516. //
  5517. // NA()
  5518. //
  5519. func (fn *formulaFuncs) NA(argsList *list.List) formulaArg {
  5520. if argsList.Len() != 0 {
  5521. return newErrorFormulaArg(formulaErrorVALUE, "NA accepts no arguments")
  5522. }
  5523. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  5524. }
  5525. // SHEET function returns the Sheet number for a specified reference. The
  5526. // syntax of the function is:
  5527. //
  5528. // SHEET()
  5529. //
  5530. func (fn *formulaFuncs) SHEET(argsList *list.List) formulaArg {
  5531. if argsList.Len() != 0 {
  5532. return newErrorFormulaArg(formulaErrorVALUE, "SHEET accepts no arguments")
  5533. }
  5534. return newNumberFormulaArg(float64(fn.f.GetSheetIndex(fn.sheet) + 1))
  5535. }
  5536. // T function tests if a supplied value is text and if so, returns the
  5537. // supplied text; Otherwise, the function returns an empty text string. The
  5538. // syntax of the function is:
  5539. //
  5540. // T(value)
  5541. //
  5542. func (fn *formulaFuncs) T(argsList *list.List) formulaArg {
  5543. if argsList.Len() != 1 {
  5544. return newErrorFormulaArg(formulaErrorVALUE, "T requires 1 argument")
  5545. }
  5546. token := argsList.Front().Value.(formulaArg)
  5547. if token.Type == ArgError {
  5548. return token
  5549. }
  5550. if token.Type == ArgNumber {
  5551. return newStringFormulaArg("")
  5552. }
  5553. return newStringFormulaArg(token.Value())
  5554. }
  5555. // Logical Functions
  5556. // AND function tests a number of supplied conditions and returns TRUE or
  5557. // FALSE. The syntax of the function is:
  5558. //
  5559. // AND(logical_test1,[logical_test2],...)
  5560. //
  5561. func (fn *formulaFuncs) AND(argsList *list.List) formulaArg {
  5562. if argsList.Len() == 0 {
  5563. return newErrorFormulaArg(formulaErrorVALUE, "AND requires at least 1 argument")
  5564. }
  5565. if argsList.Len() > 30 {
  5566. return newErrorFormulaArg(formulaErrorVALUE, "AND accepts at most 30 arguments")
  5567. }
  5568. var (
  5569. and = true
  5570. val float64
  5571. err error
  5572. )
  5573. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5574. token := arg.Value.(formulaArg)
  5575. switch token.Type {
  5576. case ArgUnknown:
  5577. continue
  5578. case ArgString:
  5579. if token.String == "TRUE" {
  5580. continue
  5581. }
  5582. if token.String == "FALSE" {
  5583. return newStringFormulaArg(token.String)
  5584. }
  5585. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  5586. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  5587. }
  5588. and = and && (val != 0)
  5589. case ArgMatrix:
  5590. // TODO
  5591. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5592. }
  5593. }
  5594. return newBoolFormulaArg(and)
  5595. }
  5596. // FALSE function function returns the logical value FALSE. The syntax of the
  5597. // function is:
  5598. //
  5599. // FALSE()
  5600. //
  5601. func (fn *formulaFuncs) FALSE(argsList *list.List) formulaArg {
  5602. if argsList.Len() != 0 {
  5603. return newErrorFormulaArg(formulaErrorVALUE, "FALSE takes no arguments")
  5604. }
  5605. return newBoolFormulaArg(false)
  5606. }
  5607. // IFERROR function receives two values (or expressions) and tests if the
  5608. // first of these evaluates to an error. The syntax of the function is:
  5609. //
  5610. // IFERROR(value,value_if_error)
  5611. //
  5612. func (fn *formulaFuncs) IFERROR(argsList *list.List) formulaArg {
  5613. if argsList.Len() != 2 {
  5614. return newErrorFormulaArg(formulaErrorVALUE, "IFERROR requires 2 arguments")
  5615. }
  5616. value := argsList.Front().Value.(formulaArg)
  5617. if value.Type != ArgError {
  5618. if value.Type == ArgEmpty {
  5619. return newNumberFormulaArg(0)
  5620. }
  5621. return value
  5622. }
  5623. return argsList.Back().Value.(formulaArg)
  5624. }
  5625. // NOT function returns the opposite to a supplied logical value. The syntax
  5626. // of the function is:
  5627. //
  5628. // NOT(logical)
  5629. //
  5630. func (fn *formulaFuncs) NOT(argsList *list.List) formulaArg {
  5631. if argsList.Len() != 1 {
  5632. return newErrorFormulaArg(formulaErrorVALUE, "NOT requires 1 argument")
  5633. }
  5634. token := argsList.Front().Value.(formulaArg)
  5635. switch token.Type {
  5636. case ArgString, ArgList:
  5637. if strings.ToUpper(token.String) == "TRUE" {
  5638. return newBoolFormulaArg(false)
  5639. }
  5640. if strings.ToUpper(token.String) == "FALSE" {
  5641. return newBoolFormulaArg(true)
  5642. }
  5643. case ArgNumber:
  5644. return newBoolFormulaArg(!(token.Number != 0))
  5645. case ArgError:
  5646. return token
  5647. }
  5648. return newErrorFormulaArg(formulaErrorVALUE, "NOT expects 1 boolean or numeric argument")
  5649. }
  5650. // OR function tests a number of supplied conditions and returns either TRUE
  5651. // or FALSE. The syntax of the function is:
  5652. //
  5653. // OR(logical_test1,[logical_test2],...)
  5654. //
  5655. func (fn *formulaFuncs) OR(argsList *list.List) formulaArg {
  5656. if argsList.Len() == 0 {
  5657. return newErrorFormulaArg(formulaErrorVALUE, "OR requires at least 1 argument")
  5658. }
  5659. if argsList.Len() > 30 {
  5660. return newErrorFormulaArg(formulaErrorVALUE, "OR accepts at most 30 arguments")
  5661. }
  5662. var (
  5663. or bool
  5664. val float64
  5665. err error
  5666. )
  5667. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5668. token := arg.Value.(formulaArg)
  5669. switch token.Type {
  5670. case ArgUnknown:
  5671. continue
  5672. case ArgString:
  5673. if token.String == "FALSE" {
  5674. continue
  5675. }
  5676. if token.String == "TRUE" {
  5677. or = true
  5678. continue
  5679. }
  5680. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  5681. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  5682. }
  5683. or = val != 0
  5684. case ArgMatrix:
  5685. // TODO
  5686. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5687. }
  5688. }
  5689. return newStringFormulaArg(strings.ToUpper(strconv.FormatBool(or)))
  5690. }
  5691. // TRUE function returns the logical value TRUE. The syntax of the function
  5692. // is:
  5693. //
  5694. // TRUE()
  5695. //
  5696. func (fn *formulaFuncs) TRUE(argsList *list.List) formulaArg {
  5697. if argsList.Len() != 0 {
  5698. return newErrorFormulaArg(formulaErrorVALUE, "TRUE takes no arguments")
  5699. }
  5700. return newBoolFormulaArg(true)
  5701. }
  5702. // Date and Time Functions
  5703. // DATE returns a date, from a user-supplied year, month and day. The syntax
  5704. // of the function is:
  5705. //
  5706. // DATE(year,month,day)
  5707. //
  5708. func (fn *formulaFuncs) DATE(argsList *list.List) formulaArg {
  5709. if argsList.Len() != 3 {
  5710. return newErrorFormulaArg(formulaErrorVALUE, "DATE requires 3 number arguments")
  5711. }
  5712. year := argsList.Front().Value.(formulaArg).ToNumber()
  5713. month := argsList.Front().Next().Value.(formulaArg).ToNumber()
  5714. day := argsList.Back().Value.(formulaArg).ToNumber()
  5715. if year.Type != ArgNumber || month.Type != ArgNumber || day.Type != ArgNumber {
  5716. return newErrorFormulaArg(formulaErrorVALUE, "DATE requires 3 number arguments")
  5717. }
  5718. d := makeDate(int(year.Number), time.Month(month.Number), int(day.Number))
  5719. return newStringFormulaArg(timeFromExcelTime(daysBetween(excelMinTime1900.Unix(), d)+1, false).String())
  5720. }
  5721. // DATEDIF function calculates the number of days, months, or years between
  5722. // two dates. The syntax of the function is:
  5723. //
  5724. // DATEDIF(start_date,end_date,unit)
  5725. //
  5726. func (fn *formulaFuncs) DATEDIF(argsList *list.List) formulaArg {
  5727. if argsList.Len() != 3 {
  5728. return newErrorFormulaArg(formulaErrorVALUE, "DATEDIF requires 3 number arguments")
  5729. }
  5730. startArg, endArg := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Front().Next().Value.(formulaArg).ToNumber()
  5731. if startArg.Type != ArgNumber || endArg.Type != ArgNumber {
  5732. return startArg
  5733. }
  5734. if startArg.Number > endArg.Number {
  5735. return newErrorFormulaArg(formulaErrorNUM, "start_date > end_date")
  5736. }
  5737. if startArg.Number == endArg.Number {
  5738. return newNumberFormulaArg(0)
  5739. }
  5740. unit := strings.ToLower(argsList.Back().Value.(formulaArg).Value())
  5741. startDate, endDate := timeFromExcelTime(startArg.Number, false), timeFromExcelTime(endArg.Number, false)
  5742. sy, smm, sd := startDate.Date()
  5743. ey, emm, ed := endDate.Date()
  5744. sm, em, diff := int(smm), int(emm), 0.0
  5745. switch unit {
  5746. case "d":
  5747. return newNumberFormulaArg(endArg.Number - startArg.Number)
  5748. case "y":
  5749. diff = float64(ey - sy)
  5750. if em < sm || (em == sm && ed < sd) {
  5751. diff--
  5752. }
  5753. case "m":
  5754. ydiff := ey - sy
  5755. mdiff := em - sm
  5756. if ed < sd {
  5757. mdiff--
  5758. }
  5759. if mdiff < 0 {
  5760. ydiff--
  5761. mdiff += 12
  5762. }
  5763. diff = float64(ydiff*12 + mdiff)
  5764. case "md":
  5765. smMD := em
  5766. if ed < sd {
  5767. smMD--
  5768. }
  5769. diff = endArg.Number - daysBetween(excelMinTime1900.Unix(), makeDate(ey, time.Month(smMD), sd)) - 1
  5770. case "ym":
  5771. diff = float64(em - sm)
  5772. if ed < sd {
  5773. diff--
  5774. }
  5775. if diff < 0 {
  5776. diff += 12
  5777. }
  5778. case "yd":
  5779. syYD := sy
  5780. if em < sm || (em == sm && ed < sd) {
  5781. syYD++
  5782. }
  5783. s := daysBetween(excelMinTime1900.Unix(), makeDate(syYD, time.Month(em), ed))
  5784. e := daysBetween(excelMinTime1900.Unix(), makeDate(sy, time.Month(sm), sd))
  5785. diff = s - e
  5786. default:
  5787. return newErrorFormulaArg(formulaErrorVALUE, "DATEDIF has invalid unit")
  5788. }
  5789. return newNumberFormulaArg(diff)
  5790. }
  5791. // NOW function returns the current date and time. The function receives no
  5792. // arguments and therefore. The syntax of the function is:
  5793. //
  5794. // NOW()
  5795. //
  5796. func (fn *formulaFuncs) NOW(argsList *list.List) formulaArg {
  5797. if argsList.Len() != 0 {
  5798. return newErrorFormulaArg(formulaErrorVALUE, "NOW accepts no arguments")
  5799. }
  5800. now := time.Now()
  5801. _, offset := now.Zone()
  5802. return newNumberFormulaArg(25569.0 + float64(now.Unix()+int64(offset))/86400)
  5803. }
  5804. // TODAY function returns the current date. The function has no arguments and
  5805. // therefore. The syntax of the function is:
  5806. //
  5807. // TODAY()
  5808. //
  5809. func (fn *formulaFuncs) TODAY(argsList *list.List) formulaArg {
  5810. if argsList.Len() != 0 {
  5811. return newErrorFormulaArg(formulaErrorVALUE, "TODAY accepts no arguments")
  5812. }
  5813. now := time.Now()
  5814. _, offset := now.Zone()
  5815. return newNumberFormulaArg(daysBetween(excelMinTime1900.Unix(), now.Unix()+int64(offset)) + 1)
  5816. }
  5817. // makeDate return date as a Unix time, the number of seconds elapsed since
  5818. // January 1, 1970 UTC.
  5819. func makeDate(y int, m time.Month, d int) int64 {
  5820. if y == 1900 && int(m) <= 2 {
  5821. d--
  5822. }
  5823. date := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
  5824. return date.Unix()
  5825. }
  5826. // daysBetween return time interval of the given start timestamp and end
  5827. // timestamp.
  5828. func daysBetween(startDate, endDate int64) float64 {
  5829. return float64(int(0.5 + float64((endDate-startDate)/86400)))
  5830. }
  5831. // Text Functions
  5832. // CHAR function returns the character relating to a supplied character set
  5833. // number (from 1 to 255). syntax of the function is:
  5834. //
  5835. // CHAR(number)
  5836. //
  5837. func (fn *formulaFuncs) CHAR(argsList *list.List) formulaArg {
  5838. if argsList.Len() != 1 {
  5839. return newErrorFormulaArg(formulaErrorVALUE, "CHAR requires 1 argument")
  5840. }
  5841. arg := argsList.Front().Value.(formulaArg).ToNumber()
  5842. if arg.Type != ArgNumber {
  5843. return arg
  5844. }
  5845. num := int(arg.Number)
  5846. if num < 0 || num > 255 {
  5847. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5848. }
  5849. return newStringFormulaArg(fmt.Sprintf("%c", num))
  5850. }
  5851. // CLEAN removes all non-printable characters from a supplied text string. The
  5852. // syntax of the function is:
  5853. //
  5854. // CLEAN(text)
  5855. //
  5856. func (fn *formulaFuncs) CLEAN(argsList *list.List) formulaArg {
  5857. if argsList.Len() != 1 {
  5858. return newErrorFormulaArg(formulaErrorVALUE, "CLEAN requires 1 argument")
  5859. }
  5860. b := bytes.Buffer{}
  5861. for _, c := range argsList.Front().Value.(formulaArg).String {
  5862. if c > 31 {
  5863. b.WriteRune(c)
  5864. }
  5865. }
  5866. return newStringFormulaArg(b.String())
  5867. }
  5868. // CODE function converts the first character of a supplied text string into
  5869. // the associated numeric character set code used by your computer. The
  5870. // syntax of the function is:
  5871. //
  5872. // CODE(text)
  5873. //
  5874. func (fn *formulaFuncs) CODE(argsList *list.List) formulaArg {
  5875. return fn.code("CODE", argsList)
  5876. }
  5877. // code is an implementation of the formula function CODE and UNICODE.
  5878. func (fn *formulaFuncs) code(name string, argsList *list.List) formulaArg {
  5879. if argsList.Len() != 1 {
  5880. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 1 argument", name))
  5881. }
  5882. text := argsList.Front().Value.(formulaArg).Value()
  5883. if len(text) == 0 {
  5884. if name == "CODE" {
  5885. return newNumberFormulaArg(0)
  5886. }
  5887. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  5888. }
  5889. return newNumberFormulaArg(float64(text[0]))
  5890. }
  5891. // CONCAT function joins together a series of supplied text strings into one
  5892. // combined text string.
  5893. //
  5894. // CONCAT(text1,[text2],...)
  5895. //
  5896. func (fn *formulaFuncs) CONCAT(argsList *list.List) formulaArg {
  5897. return fn.concat("CONCAT", argsList)
  5898. }
  5899. // CONCATENATE function joins together a series of supplied text strings into
  5900. // one combined text string.
  5901. //
  5902. // CONCATENATE(text1,[text2],...)
  5903. //
  5904. func (fn *formulaFuncs) CONCATENATE(argsList *list.List) formulaArg {
  5905. return fn.concat("CONCATENATE", argsList)
  5906. }
  5907. // concat is an implementation of the formula function CONCAT and CONCATENATE.
  5908. func (fn *formulaFuncs) concat(name string, argsList *list.List) formulaArg {
  5909. buf := bytes.Buffer{}
  5910. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  5911. token := arg.Value.(formulaArg)
  5912. switch token.Type {
  5913. case ArgString:
  5914. buf.WriteString(token.String)
  5915. case ArgNumber:
  5916. if token.Boolean {
  5917. if token.Number == 0 {
  5918. buf.WriteString("FALSE")
  5919. } else {
  5920. buf.WriteString("TRUE")
  5921. }
  5922. } else {
  5923. buf.WriteString(token.Value())
  5924. }
  5925. default:
  5926. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires arguments to be strings", name))
  5927. }
  5928. }
  5929. return newStringFormulaArg(buf.String())
  5930. }
  5931. // EXACT function tests if two supplied text strings or values are exactly
  5932. // equal and if so, returns TRUE; Otherwise, the function returns FALSE. The
  5933. // function is case-sensitive. The syntax of the function is:
  5934. //
  5935. // EXACT(text1,text2)
  5936. //
  5937. func (fn *formulaFuncs) EXACT(argsList *list.List) formulaArg {
  5938. if argsList.Len() != 2 {
  5939. return newErrorFormulaArg(formulaErrorVALUE, "EXACT requires 2 arguments")
  5940. }
  5941. text1 := argsList.Front().Value.(formulaArg).Value()
  5942. text2 := argsList.Back().Value.(formulaArg).Value()
  5943. return newBoolFormulaArg(text1 == text2)
  5944. }
  5945. // FIXED function rounds a supplied number to a specified number of decimal
  5946. // places and then converts this into text. The syntax of the function is:
  5947. //
  5948. // FIXED(number,[decimals],[no_commas])
  5949. //
  5950. func (fn *formulaFuncs) FIXED(argsList *list.List) formulaArg {
  5951. if argsList.Len() < 1 {
  5952. return newErrorFormulaArg(formulaErrorVALUE, "FIXED requires at least 1 argument")
  5953. }
  5954. if argsList.Len() > 3 {
  5955. return newErrorFormulaArg(formulaErrorVALUE, "FIXED allows at most 3 arguments")
  5956. }
  5957. numArg := argsList.Front().Value.(formulaArg).ToNumber()
  5958. if numArg.Type != ArgNumber {
  5959. return numArg
  5960. }
  5961. precision, decimals, noCommas := 0, 0, false
  5962. s := strings.Split(argsList.Front().Value.(formulaArg).Value(), ".")
  5963. if argsList.Len() == 1 && len(s) == 2 {
  5964. precision = len(s[1])
  5965. decimals = len(s[1])
  5966. }
  5967. if argsList.Len() >= 2 {
  5968. decimalsArg := argsList.Front().Next().Value.(formulaArg).ToNumber()
  5969. if decimalsArg.Type != ArgNumber {
  5970. return decimalsArg
  5971. }
  5972. decimals = int(decimalsArg.Number)
  5973. }
  5974. if argsList.Len() == 3 {
  5975. noCommasArg := argsList.Back().Value.(formulaArg).ToBool()
  5976. if noCommasArg.Type == ArgError {
  5977. return noCommasArg
  5978. }
  5979. noCommas = noCommasArg.Boolean
  5980. }
  5981. n := math.Pow(10, float64(decimals))
  5982. r := numArg.Number * n
  5983. fixed := float64(int(r+math.Copysign(0.5, r))) / n
  5984. if decimals > 0 {
  5985. precision = decimals
  5986. }
  5987. if noCommas {
  5988. return newStringFormulaArg(fmt.Sprintf(fmt.Sprintf("%%.%df", precision), fixed))
  5989. }
  5990. p := message.NewPrinter(language.English)
  5991. return newStringFormulaArg(p.Sprintf(fmt.Sprintf("%%.%df", precision), fixed))
  5992. }
  5993. // FIND function returns the position of a specified character or sub-string
  5994. // within a supplied text string. The function is case-sensitive. The syntax
  5995. // of the function is:
  5996. //
  5997. // FIND(find_text,within_text,[start_num])
  5998. //
  5999. func (fn *formulaFuncs) FIND(argsList *list.List) formulaArg {
  6000. return fn.find("FIND", argsList)
  6001. }
  6002. // FINDB counts each double-byte character as 2 when you have enabled the
  6003. // editing of a language that supports DBCS and then set it as the default
  6004. // language. Otherwise, FINDB counts each character as 1. The syntax of the
  6005. // function is:
  6006. //
  6007. // FINDB(find_text,within_text,[start_num])
  6008. //
  6009. func (fn *formulaFuncs) FINDB(argsList *list.List) formulaArg {
  6010. return fn.find("FINDB", argsList)
  6011. }
  6012. // find is an implementation of the formula function FIND and FINDB.
  6013. func (fn *formulaFuncs) find(name string, argsList *list.List) formulaArg {
  6014. if argsList.Len() < 2 {
  6015. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires at least 2 arguments", name))
  6016. }
  6017. if argsList.Len() > 3 {
  6018. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s allows at most 3 arguments", name))
  6019. }
  6020. findText := argsList.Front().Value.(formulaArg).Value()
  6021. withinText := argsList.Front().Next().Value.(formulaArg).Value()
  6022. startNum, result := 1, 1
  6023. if argsList.Len() == 3 {
  6024. numArg := argsList.Back().Value.(formulaArg).ToNumber()
  6025. if numArg.Type != ArgNumber {
  6026. return numArg
  6027. }
  6028. if numArg.Number < 0 {
  6029. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  6030. }
  6031. startNum = int(numArg.Number)
  6032. }
  6033. if findText == "" {
  6034. return newNumberFormulaArg(float64(startNum))
  6035. }
  6036. for idx := range withinText {
  6037. if result < startNum {
  6038. result++
  6039. }
  6040. if strings.Index(withinText[idx:], findText) == 0 {
  6041. return newNumberFormulaArg(float64(result))
  6042. }
  6043. result++
  6044. }
  6045. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  6046. }
  6047. // LEFT function returns a specified number of characters from the start of a
  6048. // supplied text string. The syntax of the function is:
  6049. //
  6050. // LEFT(text,[num_chars])
  6051. //
  6052. func (fn *formulaFuncs) LEFT(argsList *list.List) formulaArg {
  6053. return fn.leftRight("LEFT", argsList)
  6054. }
  6055. // LEFTB returns the first character or characters in a text string, based on
  6056. // the number of bytes you specify. The syntax of the function is:
  6057. //
  6058. // LEFTB(text,[num_bytes])
  6059. //
  6060. func (fn *formulaFuncs) LEFTB(argsList *list.List) formulaArg {
  6061. return fn.leftRight("LEFTB", argsList)
  6062. }
  6063. // leftRight is an implementation of the formula function LEFT, LEFTB, RIGHT,
  6064. // RIGHTB. TODO: support DBCS include Japanese, Chinese (Simplified), Chinese
  6065. // (Traditional), and Korean.
  6066. func (fn *formulaFuncs) leftRight(name string, argsList *list.List) formulaArg {
  6067. if argsList.Len() < 1 {
  6068. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires at least 1 argument", name))
  6069. }
  6070. if argsList.Len() > 2 {
  6071. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s allows at most 2 arguments", name))
  6072. }
  6073. text, numChars := argsList.Front().Value.(formulaArg).Value(), 1
  6074. if argsList.Len() == 2 {
  6075. numArg := argsList.Back().Value.(formulaArg).ToNumber()
  6076. if numArg.Type != ArgNumber {
  6077. return numArg
  6078. }
  6079. if numArg.Number < 0 {
  6080. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  6081. }
  6082. numChars = int(numArg.Number)
  6083. }
  6084. if len(text) > numChars {
  6085. if name == "LEFT" || name == "LEFTB" {
  6086. return newStringFormulaArg(text[:numChars])
  6087. }
  6088. return newStringFormulaArg(text[len(text)-numChars:])
  6089. }
  6090. return newStringFormulaArg(text)
  6091. }
  6092. // LEN returns the length of a supplied text string. The syntax of the
  6093. // function is:
  6094. //
  6095. // LEN(text)
  6096. //
  6097. func (fn *formulaFuncs) LEN(argsList *list.List) formulaArg {
  6098. if argsList.Len() != 1 {
  6099. return newErrorFormulaArg(formulaErrorVALUE, "LEN requires 1 string argument")
  6100. }
  6101. return newStringFormulaArg(strconv.Itoa(len(argsList.Front().Value.(formulaArg).String)))
  6102. }
  6103. // LENB returns the number of bytes used to represent the characters in a text
  6104. // string. LENB counts 2 bytes per character only when a DBCS language is set
  6105. // as the default language. Otherwise LENB behaves the same as LEN, counting
  6106. // 1 byte per character. The syntax of the function is:
  6107. //
  6108. // LENB(text)
  6109. //
  6110. // TODO: the languages that support DBCS include Japanese, Chinese
  6111. // (Simplified), Chinese (Traditional), and Korean.
  6112. func (fn *formulaFuncs) LENB(argsList *list.List) formulaArg {
  6113. if argsList.Len() != 1 {
  6114. return newErrorFormulaArg(formulaErrorVALUE, "LENB requires 1 string argument")
  6115. }
  6116. return newStringFormulaArg(strconv.Itoa(len(argsList.Front().Value.(formulaArg).String)))
  6117. }
  6118. // LOWER converts all characters in a supplied text string to lower case. The
  6119. // syntax of the function is:
  6120. //
  6121. // LOWER(text)
  6122. //
  6123. func (fn *formulaFuncs) LOWER(argsList *list.List) formulaArg {
  6124. if argsList.Len() != 1 {
  6125. return newErrorFormulaArg(formulaErrorVALUE, "LOWER requires 1 argument")
  6126. }
  6127. return newStringFormulaArg(strings.ToLower(argsList.Front().Value.(formulaArg).String))
  6128. }
  6129. // MID function returns a specified number of characters from the middle of a
  6130. // supplied text string. The syntax of the function is:
  6131. //
  6132. // MID(text,start_num,num_chars)
  6133. //
  6134. func (fn *formulaFuncs) MID(argsList *list.List) formulaArg {
  6135. return fn.mid("MID", argsList)
  6136. }
  6137. // MIDB returns a specific number of characters from a text string, starting
  6138. // at the position you specify, based on the number of bytes you specify. The
  6139. // syntax of the function is:
  6140. //
  6141. // MID(text,start_num,num_chars)
  6142. //
  6143. func (fn *formulaFuncs) MIDB(argsList *list.List) formulaArg {
  6144. return fn.mid("MIDB", argsList)
  6145. }
  6146. // mid is an implementation of the formula function MID and MIDB. TODO:
  6147. // support DBCS include Japanese, Chinese (Simplified), Chinese
  6148. // (Traditional), and Korean.
  6149. func (fn *formulaFuncs) mid(name string, argsList *list.List) formulaArg {
  6150. if argsList.Len() != 3 {
  6151. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 3 arguments", name))
  6152. }
  6153. text := argsList.Front().Value.(formulaArg).Value()
  6154. startNumArg, numCharsArg := argsList.Front().Next().Value.(formulaArg).ToNumber(), argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6155. if startNumArg.Type != ArgNumber {
  6156. return startNumArg
  6157. }
  6158. if numCharsArg.Type != ArgNumber {
  6159. return numCharsArg
  6160. }
  6161. startNum := int(startNumArg.Number)
  6162. if startNum < 0 {
  6163. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  6164. }
  6165. textLen := len(text)
  6166. if startNum > textLen {
  6167. return newStringFormulaArg("")
  6168. }
  6169. startNum--
  6170. endNum := startNum + int(numCharsArg.Number)
  6171. if endNum > textLen+1 {
  6172. return newStringFormulaArg(text[startNum:])
  6173. }
  6174. return newStringFormulaArg(text[startNum:endNum])
  6175. }
  6176. // PROPER converts all characters in a supplied text string to proper case
  6177. // (i.e. all letters that do not immediately follow another letter are set to
  6178. // upper case and all other characters are lower case). The syntax of the
  6179. // function is:
  6180. //
  6181. // PROPER(text)
  6182. //
  6183. func (fn *formulaFuncs) PROPER(argsList *list.List) formulaArg {
  6184. if argsList.Len() != 1 {
  6185. return newErrorFormulaArg(formulaErrorVALUE, "PROPER requires 1 argument")
  6186. }
  6187. buf := bytes.Buffer{}
  6188. isLetter := false
  6189. for _, char := range argsList.Front().Value.(formulaArg).String {
  6190. if !isLetter && unicode.IsLetter(char) {
  6191. buf.WriteRune(unicode.ToUpper(char))
  6192. } else {
  6193. buf.WriteRune(unicode.ToLower(char))
  6194. }
  6195. isLetter = unicode.IsLetter(char)
  6196. }
  6197. return newStringFormulaArg(buf.String())
  6198. }
  6199. // REPLACE function replaces all or part of a text string with another string.
  6200. // The syntax of the function is:
  6201. //
  6202. // REPLACE(old_text,start_num,num_chars,new_text)
  6203. //
  6204. func (fn *formulaFuncs) REPLACE(argsList *list.List) formulaArg {
  6205. return fn.replace("REPLACE", argsList)
  6206. }
  6207. // REPLACEB replaces part of a text string, based on the number of bytes you
  6208. // specify, with a different text string.
  6209. //
  6210. // REPLACEB(old_text,start_num,num_chars,new_text)
  6211. //
  6212. func (fn *formulaFuncs) REPLACEB(argsList *list.List) formulaArg {
  6213. return fn.replace("REPLACEB", argsList)
  6214. }
  6215. // replace is an implementation of the formula function REPLACE and REPLACEB.
  6216. // TODO: support DBCS include Japanese, Chinese (Simplified), Chinese
  6217. // (Traditional), and Korean.
  6218. func (fn *formulaFuncs) replace(name string, argsList *list.List) formulaArg {
  6219. if argsList.Len() != 4 {
  6220. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 4 arguments", name))
  6221. }
  6222. oldText, newText := argsList.Front().Value.(formulaArg).Value(), argsList.Back().Value.(formulaArg).Value()
  6223. startNumArg, numCharsArg := argsList.Front().Next().Value.(formulaArg).ToNumber(), argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6224. if startNumArg.Type != ArgNumber {
  6225. return startNumArg
  6226. }
  6227. if numCharsArg.Type != ArgNumber {
  6228. return numCharsArg
  6229. }
  6230. oldTextLen, startIdx := len(oldText), int(startNumArg.Number)
  6231. if startIdx > oldTextLen {
  6232. startIdx = oldTextLen + 1
  6233. }
  6234. endIdx := startIdx + int(numCharsArg.Number)
  6235. if endIdx > oldTextLen {
  6236. endIdx = oldTextLen + 1
  6237. }
  6238. if startIdx < 1 || endIdx < 1 {
  6239. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  6240. }
  6241. result := oldText[:startIdx-1] + newText + oldText[endIdx-1:]
  6242. return newStringFormulaArg(result)
  6243. }
  6244. // REPT function returns a supplied text string, repeated a specified number
  6245. // of times. The syntax of the function is:
  6246. //
  6247. // REPT(text,number_times)
  6248. //
  6249. func (fn *formulaFuncs) REPT(argsList *list.List) formulaArg {
  6250. if argsList.Len() != 2 {
  6251. return newErrorFormulaArg(formulaErrorVALUE, "REPT requires 2 arguments")
  6252. }
  6253. text := argsList.Front().Value.(formulaArg)
  6254. if text.Type != ArgString {
  6255. return newErrorFormulaArg(formulaErrorVALUE, "REPT requires first argument to be a string")
  6256. }
  6257. times := argsList.Back().Value.(formulaArg).ToNumber()
  6258. if times.Type != ArgNumber {
  6259. return newErrorFormulaArg(formulaErrorVALUE, "REPT requires second argument to be a number")
  6260. }
  6261. if times.Number < 0 {
  6262. return newErrorFormulaArg(formulaErrorVALUE, "REPT requires second argument to be >= 0")
  6263. }
  6264. if times.Number == 0 {
  6265. return newStringFormulaArg("")
  6266. }
  6267. buf := bytes.Buffer{}
  6268. for i := 0; i < int(times.Number); i++ {
  6269. buf.WriteString(text.String)
  6270. }
  6271. return newStringFormulaArg(buf.String())
  6272. }
  6273. // RIGHT function returns a specified number of characters from the end of a
  6274. // supplied text string. The syntax of the function is:
  6275. //
  6276. // RIGHT(text,[num_chars])
  6277. //
  6278. func (fn *formulaFuncs) RIGHT(argsList *list.List) formulaArg {
  6279. return fn.leftRight("RIGHT", argsList)
  6280. }
  6281. // RIGHTB returns the last character or characters in a text string, based on
  6282. // the number of bytes you specify. The syntax of the function is:
  6283. //
  6284. // RIGHTB(text,[num_bytes])
  6285. //
  6286. func (fn *formulaFuncs) RIGHTB(argsList *list.List) formulaArg {
  6287. return fn.leftRight("RIGHTB", argsList)
  6288. }
  6289. // SUBSTITUTE function replaces one or more instances of a given text string,
  6290. // within an original text string. The syntax of the function is:
  6291. //
  6292. // SUBSTITUTE(text,old_text,new_text,[instance_num])
  6293. //
  6294. func (fn *formulaFuncs) SUBSTITUTE(argsList *list.List) formulaArg {
  6295. if argsList.Len() != 3 && argsList.Len() != 4 {
  6296. return newErrorFormulaArg(formulaErrorVALUE, "SUBSTITUTE requires 3 or 4 arguments")
  6297. }
  6298. text, oldText := argsList.Front().Value.(formulaArg), argsList.Front().Next().Value.(formulaArg)
  6299. newText, instanceNum := argsList.Front().Next().Next().Value.(formulaArg), 0
  6300. if argsList.Len() == 3 {
  6301. return newStringFormulaArg(strings.Replace(text.Value(), oldText.Value(), newText.Value(), -1))
  6302. }
  6303. instanceNumArg := argsList.Back().Value.(formulaArg).ToNumber()
  6304. if instanceNumArg.Type != ArgNumber {
  6305. return instanceNumArg
  6306. }
  6307. instanceNum = int(instanceNumArg.Number)
  6308. if instanceNum < 1 {
  6309. return newErrorFormulaArg(formulaErrorVALUE, "instance_num should be > 0")
  6310. }
  6311. str, oldTextLen, count, chars, pos := text.Value(), len(oldText.Value()), instanceNum, 0, -1
  6312. for {
  6313. count--
  6314. index := strings.Index(str, oldText.Value())
  6315. if index == -1 {
  6316. pos = -1
  6317. break
  6318. } else {
  6319. pos = index + chars
  6320. if count == 0 {
  6321. break
  6322. }
  6323. idx := oldTextLen + index
  6324. chars += idx
  6325. str = str[idx:]
  6326. }
  6327. }
  6328. if pos == -1 {
  6329. return newStringFormulaArg(text.Value())
  6330. }
  6331. pre, post := text.Value()[:pos], text.Value()[pos+oldTextLen:]
  6332. return newStringFormulaArg(pre + newText.Value() + post)
  6333. }
  6334. // TRIM removes extra spaces (i.e. all spaces except for single spaces between
  6335. // words or characters) from a supplied text string. The syntax of the
  6336. // function is:
  6337. //
  6338. // TRIM(text)
  6339. //
  6340. func (fn *formulaFuncs) TRIM(argsList *list.List) formulaArg {
  6341. if argsList.Len() != 1 {
  6342. return newErrorFormulaArg(formulaErrorVALUE, "TRIM requires 1 argument")
  6343. }
  6344. return newStringFormulaArg(strings.TrimSpace(argsList.Front().Value.(formulaArg).String))
  6345. }
  6346. // UNICHAR returns the Unicode character that is referenced by the given
  6347. // numeric value. The syntax of the function is:
  6348. //
  6349. // UNICHAR(number)
  6350. //
  6351. func (fn *formulaFuncs) UNICHAR(argsList *list.List) formulaArg {
  6352. if argsList.Len() != 1 {
  6353. return newErrorFormulaArg(formulaErrorVALUE, "UNICHAR requires 1 argument")
  6354. }
  6355. numArg := argsList.Front().Value.(formulaArg).ToNumber()
  6356. if numArg.Type != ArgNumber {
  6357. return numArg
  6358. }
  6359. if numArg.Number <= 0 || numArg.Number > 55295 {
  6360. return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)
  6361. }
  6362. return newStringFormulaArg(string(rune(numArg.Number)))
  6363. }
  6364. // UNICODE function returns the code point for the first character of a
  6365. // supplied text string. The syntax of the function is:
  6366. //
  6367. // UNICODE(text)
  6368. //
  6369. func (fn *formulaFuncs) UNICODE(argsList *list.List) formulaArg {
  6370. return fn.code("UNICODE", argsList)
  6371. }
  6372. // UPPER converts all characters in a supplied text string to upper case. The
  6373. // syntax of the function is:
  6374. //
  6375. // UPPER(text)
  6376. //
  6377. func (fn *formulaFuncs) UPPER(argsList *list.List) formulaArg {
  6378. if argsList.Len() != 1 {
  6379. return newErrorFormulaArg(formulaErrorVALUE, "UPPER requires 1 argument")
  6380. }
  6381. return newStringFormulaArg(strings.ToUpper(argsList.Front().Value.(formulaArg).String))
  6382. }
  6383. // Conditional Functions
  6384. // IF function tests a supplied condition and returns one result if the
  6385. // condition evaluates to TRUE, and another result if the condition evaluates
  6386. // to FALSE. The syntax of the function is:
  6387. //
  6388. // IF(logical_test,value_if_true,value_if_false)
  6389. //
  6390. func (fn *formulaFuncs) IF(argsList *list.List) formulaArg {
  6391. if argsList.Len() == 0 {
  6392. return newErrorFormulaArg(formulaErrorVALUE, "IF requires at least 1 argument")
  6393. }
  6394. if argsList.Len() > 3 {
  6395. return newErrorFormulaArg(formulaErrorVALUE, "IF accepts at most 3 arguments")
  6396. }
  6397. token := argsList.Front().Value.(formulaArg)
  6398. var (
  6399. cond bool
  6400. err error
  6401. result string
  6402. )
  6403. switch token.Type {
  6404. case ArgString:
  6405. if cond, err = strconv.ParseBool(token.String); err != nil {
  6406. return newErrorFormulaArg(formulaErrorVALUE, err.Error())
  6407. }
  6408. if argsList.Len() == 1 {
  6409. return newBoolFormulaArg(cond)
  6410. }
  6411. if cond {
  6412. return newStringFormulaArg(argsList.Front().Next().Value.(formulaArg).String)
  6413. }
  6414. if argsList.Len() == 3 {
  6415. result = argsList.Back().Value.(formulaArg).String
  6416. }
  6417. }
  6418. return newStringFormulaArg(result)
  6419. }
  6420. // Lookup and Reference Functions
  6421. // CHOOSE function returns a value from an array, that corresponds to a
  6422. // supplied index number (position). The syntax of the function is:
  6423. //
  6424. // CHOOSE(index_num,value1,[value2],...)
  6425. //
  6426. func (fn *formulaFuncs) CHOOSE(argsList *list.List) formulaArg {
  6427. if argsList.Len() < 2 {
  6428. return newErrorFormulaArg(formulaErrorVALUE, "CHOOSE requires 2 arguments")
  6429. }
  6430. idx, err := strconv.Atoi(argsList.Front().Value.(formulaArg).String)
  6431. if err != nil {
  6432. return newErrorFormulaArg(formulaErrorVALUE, "CHOOSE requires first argument of type number")
  6433. }
  6434. if argsList.Len() <= idx {
  6435. return newErrorFormulaArg(formulaErrorVALUE, "index_num should be <= to the number of values")
  6436. }
  6437. arg := argsList.Front()
  6438. for i := 0; i < idx; i++ {
  6439. arg = arg.Next()
  6440. }
  6441. var result formulaArg
  6442. switch arg.Value.(formulaArg).Type {
  6443. case ArgString:
  6444. result = newStringFormulaArg(arg.Value.(formulaArg).String)
  6445. case ArgMatrix:
  6446. result = newMatrixFormulaArg(arg.Value.(formulaArg).Matrix)
  6447. }
  6448. return result
  6449. }
  6450. // deepMatchRune finds whether the text deep matches/satisfies the pattern
  6451. // string.
  6452. func deepMatchRune(str, pattern []rune, simple bool) bool {
  6453. for len(pattern) > 0 {
  6454. switch pattern[0] {
  6455. default:
  6456. if len(str) == 0 || str[0] != pattern[0] {
  6457. return false
  6458. }
  6459. case '?':
  6460. if len(str) == 0 && !simple {
  6461. return false
  6462. }
  6463. case '*':
  6464. return deepMatchRune(str, pattern[1:], simple) ||
  6465. (len(str) > 0 && deepMatchRune(str[1:], pattern, simple))
  6466. }
  6467. str = str[1:]
  6468. pattern = pattern[1:]
  6469. }
  6470. return len(str) == 0 && len(pattern) == 0
  6471. }
  6472. // matchPattern finds whether the text matches or satisfies the pattern
  6473. // string. The pattern supports '*' and '?' wildcards in the pattern string.
  6474. func matchPattern(pattern, name string) (matched bool) {
  6475. if pattern == "" {
  6476. return name == pattern
  6477. }
  6478. if pattern == "*" {
  6479. return true
  6480. }
  6481. rname, rpattern := make([]rune, 0, len(name)), make([]rune, 0, len(pattern))
  6482. for _, r := range name {
  6483. rname = append(rname, r)
  6484. }
  6485. for _, r := range pattern {
  6486. rpattern = append(rpattern, r)
  6487. }
  6488. simple := false // Does extended wildcard '*' and '?' match.
  6489. return deepMatchRune(rname, rpattern, simple)
  6490. }
  6491. // compareFormulaArg compares the left-hand sides and the right-hand sides
  6492. // formula arguments by given conditions such as case sensitive, if exact
  6493. // match, and make compare result as formula criteria condition type.
  6494. func compareFormulaArg(lhs, rhs formulaArg, caseSensitive, exactMatch bool) byte {
  6495. if lhs.Type != rhs.Type {
  6496. return criteriaErr
  6497. }
  6498. switch lhs.Type {
  6499. case ArgNumber:
  6500. if lhs.Number == rhs.Number {
  6501. return criteriaEq
  6502. }
  6503. if lhs.Number < rhs.Number {
  6504. return criteriaL
  6505. }
  6506. return criteriaG
  6507. case ArgString:
  6508. ls, rs := lhs.String, rhs.String
  6509. if !caseSensitive {
  6510. ls, rs = strings.ToLower(ls), strings.ToLower(rs)
  6511. }
  6512. if exactMatch {
  6513. match := matchPattern(rs, ls)
  6514. if match {
  6515. return criteriaEq
  6516. }
  6517. return criteriaG
  6518. }
  6519. switch strings.Compare(ls, rs) {
  6520. case 1:
  6521. return criteriaG
  6522. case -1:
  6523. return criteriaL
  6524. case 0:
  6525. return criteriaEq
  6526. }
  6527. return criteriaErr
  6528. case ArgEmpty:
  6529. return criteriaEq
  6530. case ArgList:
  6531. return compareFormulaArgList(lhs, rhs, caseSensitive, exactMatch)
  6532. case ArgMatrix:
  6533. return compareFormulaArgMatrix(lhs, rhs, caseSensitive, exactMatch)
  6534. }
  6535. return criteriaErr
  6536. }
  6537. // compareFormulaArgList compares the left-hand sides and the right-hand sides
  6538. // list type formula arguments.
  6539. func compareFormulaArgList(lhs, rhs formulaArg, caseSensitive, exactMatch bool) byte {
  6540. if len(lhs.List) < len(rhs.List) {
  6541. return criteriaL
  6542. }
  6543. if len(lhs.List) > len(rhs.List) {
  6544. return criteriaG
  6545. }
  6546. for arg := range lhs.List {
  6547. criteria := compareFormulaArg(lhs.List[arg], rhs.List[arg], caseSensitive, exactMatch)
  6548. if criteria != criteriaEq {
  6549. return criteria
  6550. }
  6551. }
  6552. return criteriaEq
  6553. }
  6554. // compareFormulaArgMatrix compares the left-hand sides and the right-hand sides
  6555. // matrix type formula arguments.
  6556. func compareFormulaArgMatrix(lhs, rhs formulaArg, caseSensitive, exactMatch bool) byte {
  6557. if len(lhs.Matrix) < len(rhs.Matrix) {
  6558. return criteriaL
  6559. }
  6560. if len(lhs.Matrix) > len(rhs.Matrix) {
  6561. return criteriaG
  6562. }
  6563. for i := range lhs.Matrix {
  6564. left := lhs.Matrix[i]
  6565. right := lhs.Matrix[i]
  6566. if len(left) < len(right) {
  6567. return criteriaL
  6568. }
  6569. if len(left) > len(right) {
  6570. return criteriaG
  6571. }
  6572. for arg := range left {
  6573. criteria := compareFormulaArg(left[arg], right[arg], caseSensitive, exactMatch)
  6574. if criteria != criteriaEq {
  6575. return criteria
  6576. }
  6577. }
  6578. }
  6579. return criteriaEq
  6580. }
  6581. // COLUMN function returns the first column number within a supplied reference
  6582. // or the number of the current column. The syntax of the function is:
  6583. //
  6584. // COLUMN([reference])
  6585. //
  6586. func (fn *formulaFuncs) COLUMN(argsList *list.List) formulaArg {
  6587. if argsList.Len() > 1 {
  6588. return newErrorFormulaArg(formulaErrorVALUE, "COLUMN requires at most 1 argument")
  6589. }
  6590. if argsList.Len() == 1 {
  6591. if argsList.Front().Value.(formulaArg).cellRanges != nil && argsList.Front().Value.(formulaArg).cellRanges.Len() > 0 {
  6592. return newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRanges.Front().Value.(cellRange).From.Col))
  6593. }
  6594. if argsList.Front().Value.(formulaArg).cellRefs != nil && argsList.Front().Value.(formulaArg).cellRefs.Len() > 0 {
  6595. return newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRefs.Front().Value.(cellRef).Col))
  6596. }
  6597. return newErrorFormulaArg(formulaErrorVALUE, "invalid reference")
  6598. }
  6599. col, _, _ := CellNameToCoordinates(fn.cell)
  6600. return newNumberFormulaArg(float64(col))
  6601. }
  6602. // COLUMNS function receives an Excel range and returns the number of columns
  6603. // that are contained within the range. The syntax of the function is:
  6604. //
  6605. // COLUMNS(array)
  6606. //
  6607. func (fn *formulaFuncs) COLUMNS(argsList *list.List) formulaArg {
  6608. if argsList.Len() != 1 {
  6609. return newErrorFormulaArg(formulaErrorVALUE, "COLUMNS requires 1 argument")
  6610. }
  6611. var min, max int
  6612. if argsList.Front().Value.(formulaArg).cellRanges != nil && argsList.Front().Value.(formulaArg).cellRanges.Len() > 0 {
  6613. crs := argsList.Front().Value.(formulaArg).cellRanges
  6614. for cr := crs.Front(); cr != nil; cr = cr.Next() {
  6615. if min == 0 {
  6616. min = cr.Value.(cellRange).From.Col
  6617. }
  6618. if min > cr.Value.(cellRange).From.Col {
  6619. min = cr.Value.(cellRange).From.Col
  6620. }
  6621. if min > cr.Value.(cellRange).To.Col {
  6622. min = cr.Value.(cellRange).To.Col
  6623. }
  6624. if max < cr.Value.(cellRange).To.Col {
  6625. max = cr.Value.(cellRange).To.Col
  6626. }
  6627. if max < cr.Value.(cellRange).From.Col {
  6628. max = cr.Value.(cellRange).From.Col
  6629. }
  6630. }
  6631. }
  6632. if argsList.Front().Value.(formulaArg).cellRefs != nil && argsList.Front().Value.(formulaArg).cellRefs.Len() > 0 {
  6633. cr := argsList.Front().Value.(formulaArg).cellRefs
  6634. for refs := cr.Front(); refs != nil; refs = refs.Next() {
  6635. if min == 0 {
  6636. min = refs.Value.(cellRef).Col
  6637. }
  6638. if min > refs.Value.(cellRef).Col {
  6639. min = refs.Value.(cellRef).Col
  6640. }
  6641. if max < refs.Value.(cellRef).Col {
  6642. max = refs.Value.(cellRef).Col
  6643. }
  6644. }
  6645. }
  6646. if max == TotalColumns {
  6647. return newNumberFormulaArg(float64(TotalColumns))
  6648. }
  6649. result := max - min + 1
  6650. if max == min {
  6651. if min == 0 {
  6652. return newErrorFormulaArg(formulaErrorVALUE, "invalid reference")
  6653. }
  6654. return newNumberFormulaArg(float64(1))
  6655. }
  6656. return newNumberFormulaArg(float64(result))
  6657. }
  6658. // HLOOKUP function 'looks up' a given value in the top row of a data array
  6659. // (or table), and returns the corresponding value from another row of the
  6660. // array. The syntax of the function is:
  6661. //
  6662. // HLOOKUP(lookup_value,table_array,row_index_num,[range_lookup])
  6663. //
  6664. func (fn *formulaFuncs) HLOOKUP(argsList *list.List) formulaArg {
  6665. if argsList.Len() < 3 {
  6666. return newErrorFormulaArg(formulaErrorVALUE, "HLOOKUP requires at least 3 arguments")
  6667. }
  6668. if argsList.Len() > 4 {
  6669. return newErrorFormulaArg(formulaErrorVALUE, "HLOOKUP requires at most 4 arguments")
  6670. }
  6671. lookupValue := argsList.Front().Value.(formulaArg)
  6672. tableArray := argsList.Front().Next().Value.(formulaArg)
  6673. if tableArray.Type != ArgMatrix {
  6674. return newErrorFormulaArg(formulaErrorVALUE, "HLOOKUP requires second argument of table array")
  6675. }
  6676. rowArg := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6677. if rowArg.Type != ArgNumber {
  6678. return newErrorFormulaArg(formulaErrorVALUE, "HLOOKUP requires numeric row argument")
  6679. }
  6680. rowIdx, matchIdx, wasExact, exactMatch := int(rowArg.Number)-1, -1, false, false
  6681. if argsList.Len() == 4 {
  6682. rangeLookup := argsList.Back().Value.(formulaArg).ToBool()
  6683. if rangeLookup.Type == ArgError {
  6684. return newErrorFormulaArg(formulaErrorVALUE, rangeLookup.Error)
  6685. }
  6686. if rangeLookup.Number == 0 {
  6687. exactMatch = true
  6688. }
  6689. }
  6690. row := tableArray.Matrix[0]
  6691. if exactMatch || len(tableArray.Matrix) == TotalRows {
  6692. start:
  6693. for idx, mtx := range row {
  6694. lhs := mtx
  6695. switch lookupValue.Type {
  6696. case ArgNumber:
  6697. if !lookupValue.Boolean {
  6698. lhs = mtx.ToNumber()
  6699. if lhs.Type == ArgError {
  6700. lhs = mtx
  6701. }
  6702. }
  6703. case ArgMatrix:
  6704. lhs = tableArray
  6705. }
  6706. if compareFormulaArg(lhs, lookupValue, false, exactMatch) == criteriaEq {
  6707. matchIdx = idx
  6708. wasExact = true
  6709. break start
  6710. }
  6711. }
  6712. } else {
  6713. matchIdx, wasExact = hlookupBinarySearch(row, lookupValue)
  6714. }
  6715. if matchIdx == -1 {
  6716. return newErrorFormulaArg(formulaErrorNA, "HLOOKUP no result found")
  6717. }
  6718. if rowIdx < 0 || rowIdx >= len(tableArray.Matrix) {
  6719. return newErrorFormulaArg(formulaErrorNA, "HLOOKUP has invalid row index")
  6720. }
  6721. row = tableArray.Matrix[rowIdx]
  6722. if wasExact || !exactMatch {
  6723. return row[matchIdx]
  6724. }
  6725. return newErrorFormulaArg(formulaErrorNA, "HLOOKUP no result found")
  6726. }
  6727. // VLOOKUP function 'looks up' a given value in the left-hand column of a
  6728. // data array (or table), and returns the corresponding value from another
  6729. // column of the array. The syntax of the function is:
  6730. //
  6731. // VLOOKUP(lookup_value,table_array,col_index_num,[range_lookup])
  6732. //
  6733. func (fn *formulaFuncs) VLOOKUP(argsList *list.List) formulaArg {
  6734. if argsList.Len() < 3 {
  6735. return newErrorFormulaArg(formulaErrorVALUE, "VLOOKUP requires at least 3 arguments")
  6736. }
  6737. if argsList.Len() > 4 {
  6738. return newErrorFormulaArg(formulaErrorVALUE, "VLOOKUP requires at most 4 arguments")
  6739. }
  6740. lookupValue := argsList.Front().Value.(formulaArg)
  6741. tableArray := argsList.Front().Next().Value.(formulaArg)
  6742. if tableArray.Type != ArgMatrix {
  6743. return newErrorFormulaArg(formulaErrorVALUE, "VLOOKUP requires second argument of table array")
  6744. }
  6745. colIdx := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  6746. if colIdx.Type != ArgNumber {
  6747. return newErrorFormulaArg(formulaErrorVALUE, "VLOOKUP requires numeric col argument")
  6748. }
  6749. col, matchIdx, wasExact, exactMatch := int(colIdx.Number)-1, -1, false, false
  6750. if argsList.Len() == 4 {
  6751. rangeLookup := argsList.Back().Value.(formulaArg).ToBool()
  6752. if rangeLookup.Type == ArgError {
  6753. return newErrorFormulaArg(formulaErrorVALUE, rangeLookup.Error)
  6754. }
  6755. if rangeLookup.Number == 0 {
  6756. exactMatch = true
  6757. }
  6758. }
  6759. if exactMatch || len(tableArray.Matrix) == TotalRows {
  6760. start:
  6761. for idx, mtx := range tableArray.Matrix {
  6762. lhs := mtx[0]
  6763. switch lookupValue.Type {
  6764. case ArgNumber:
  6765. if !lookupValue.Boolean {
  6766. lhs = mtx[0].ToNumber()
  6767. if lhs.Type == ArgError {
  6768. lhs = mtx[0]
  6769. }
  6770. }
  6771. case ArgMatrix:
  6772. lhs = tableArray
  6773. }
  6774. if compareFormulaArg(lhs, lookupValue, false, exactMatch) == criteriaEq {
  6775. matchIdx = idx
  6776. wasExact = true
  6777. break start
  6778. }
  6779. }
  6780. } else {
  6781. matchIdx, wasExact = vlookupBinarySearch(tableArray, lookupValue)
  6782. }
  6783. if matchIdx == -1 {
  6784. return newErrorFormulaArg(formulaErrorNA, "VLOOKUP no result found")
  6785. }
  6786. mtx := tableArray.Matrix[matchIdx]
  6787. if col < 0 || col >= len(mtx) {
  6788. return newErrorFormulaArg(formulaErrorNA, "VLOOKUP has invalid column index")
  6789. }
  6790. if wasExact || !exactMatch {
  6791. return mtx[col]
  6792. }
  6793. return newErrorFormulaArg(formulaErrorNA, "VLOOKUP no result found")
  6794. }
  6795. // vlookupBinarySearch finds the position of a target value when range lookup
  6796. // is TRUE, if the data of table array can't guarantee be sorted, it will
  6797. // return wrong result.
  6798. func vlookupBinarySearch(tableArray, lookupValue formulaArg) (matchIdx int, wasExact bool) {
  6799. var low, high, lastMatchIdx int = 0, len(tableArray.Matrix) - 1, -1
  6800. for low <= high {
  6801. var mid int = low + (high-low)/2
  6802. mtx := tableArray.Matrix[mid]
  6803. lhs := mtx[0]
  6804. switch lookupValue.Type {
  6805. case ArgNumber:
  6806. if !lookupValue.Boolean {
  6807. lhs = mtx[0].ToNumber()
  6808. if lhs.Type == ArgError {
  6809. lhs = mtx[0]
  6810. }
  6811. }
  6812. case ArgMatrix:
  6813. lhs = tableArray
  6814. }
  6815. result := compareFormulaArg(lhs, lookupValue, false, false)
  6816. if result == criteriaEq {
  6817. matchIdx, wasExact = mid, true
  6818. return
  6819. } else if result == criteriaG {
  6820. high = mid - 1
  6821. } else if result == criteriaL {
  6822. matchIdx, low = mid, mid+1
  6823. if lhs.Value() != "" {
  6824. lastMatchIdx = matchIdx
  6825. }
  6826. } else {
  6827. return -1, false
  6828. }
  6829. }
  6830. matchIdx, wasExact = lastMatchIdx, true
  6831. return
  6832. }
  6833. // vlookupBinarySearch finds the position of a target value when range lookup
  6834. // is TRUE, if the data of table array can't guarantee be sorted, it will
  6835. // return wrong result.
  6836. func hlookupBinarySearch(row []formulaArg, lookupValue formulaArg) (matchIdx int, wasExact bool) {
  6837. var low, high, lastMatchIdx int = 0, len(row) - 1, -1
  6838. for low <= high {
  6839. var mid int = low + (high-low)/2
  6840. mtx := row[mid]
  6841. result := compareFormulaArg(mtx, lookupValue, false, false)
  6842. if result == criteriaEq {
  6843. matchIdx, wasExact = mid, true
  6844. return
  6845. } else if result == criteriaG {
  6846. high = mid - 1
  6847. } else if result == criteriaL {
  6848. low, lastMatchIdx = mid+1, mid
  6849. } else {
  6850. return -1, false
  6851. }
  6852. }
  6853. matchIdx, wasExact = lastMatchIdx, true
  6854. return
  6855. }
  6856. // LOOKUP function performs an approximate match lookup in a one-column or
  6857. // one-row range, and returns the corresponding value from another one-column
  6858. // or one-row range. The syntax of the function is:
  6859. //
  6860. // LOOKUP(lookup_value,lookup_vector,[result_vector])
  6861. //
  6862. func (fn *formulaFuncs) LOOKUP(argsList *list.List) formulaArg {
  6863. if argsList.Len() < 2 {
  6864. return newErrorFormulaArg(formulaErrorVALUE, "LOOKUP requires at least 2 arguments")
  6865. }
  6866. if argsList.Len() > 3 {
  6867. return newErrorFormulaArg(formulaErrorVALUE, "LOOKUP requires at most 3 arguments")
  6868. }
  6869. lookupValue := argsList.Front().Value.(formulaArg)
  6870. lookupVector := argsList.Front().Next().Value.(formulaArg)
  6871. if lookupVector.Type != ArgMatrix && lookupVector.Type != ArgList {
  6872. return newErrorFormulaArg(formulaErrorVALUE, "LOOKUP requires second argument of table array")
  6873. }
  6874. cols, matchIdx := lookupCol(lookupVector), -1
  6875. for idx, col := range cols {
  6876. lhs := lookupValue
  6877. switch col.Type {
  6878. case ArgNumber:
  6879. lhs = lhs.ToNumber()
  6880. if !col.Boolean {
  6881. if lhs.Type == ArgError {
  6882. lhs = lookupValue
  6883. }
  6884. }
  6885. }
  6886. if compareFormulaArg(lhs, col, false, false) == criteriaEq {
  6887. matchIdx = idx
  6888. break
  6889. }
  6890. }
  6891. column := cols
  6892. if argsList.Len() == 3 {
  6893. column = lookupCol(argsList.Back().Value.(formulaArg))
  6894. }
  6895. if matchIdx < 0 || matchIdx >= len(column) {
  6896. return newErrorFormulaArg(formulaErrorNA, "LOOKUP no result found")
  6897. }
  6898. return column[matchIdx]
  6899. }
  6900. // lookupCol extract columns for LOOKUP.
  6901. func lookupCol(arr formulaArg) []formulaArg {
  6902. col := arr.List
  6903. if arr.Type == ArgMatrix {
  6904. col = nil
  6905. for _, r := range arr.Matrix {
  6906. if len(r) > 0 {
  6907. col = append(col, r[0])
  6908. continue
  6909. }
  6910. col = append(col, newEmptyFormulaArg())
  6911. }
  6912. }
  6913. return col
  6914. }
  6915. // ROW function returns the first row number within a supplied reference or
  6916. // the number of the current row. The syntax of the function is:
  6917. //
  6918. // ROW([reference])
  6919. //
  6920. func (fn *formulaFuncs) ROW(argsList *list.List) formulaArg {
  6921. if argsList.Len() > 1 {
  6922. return newErrorFormulaArg(formulaErrorVALUE, "ROW requires at most 1 argument")
  6923. }
  6924. if argsList.Len() == 1 {
  6925. if argsList.Front().Value.(formulaArg).cellRanges != nil && argsList.Front().Value.(formulaArg).cellRanges.Len() > 0 {
  6926. return newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRanges.Front().Value.(cellRange).From.Row))
  6927. }
  6928. if argsList.Front().Value.(formulaArg).cellRefs != nil && argsList.Front().Value.(formulaArg).cellRefs.Len() > 0 {
  6929. return newNumberFormulaArg(float64(argsList.Front().Value.(formulaArg).cellRefs.Front().Value.(cellRef).Row))
  6930. }
  6931. return newErrorFormulaArg(formulaErrorVALUE, "invalid reference")
  6932. }
  6933. _, row, _ := CellNameToCoordinates(fn.cell)
  6934. return newNumberFormulaArg(float64(row))
  6935. }
  6936. // ROWS function takes an Excel range and returns the number of rows that are
  6937. // contained within the range. The syntax of the function is:
  6938. //
  6939. // ROWS(array)
  6940. //
  6941. func (fn *formulaFuncs) ROWS(argsList *list.List) formulaArg {
  6942. if argsList.Len() != 1 {
  6943. return newErrorFormulaArg(formulaErrorVALUE, "ROWS requires 1 argument")
  6944. }
  6945. var min, max int
  6946. if argsList.Front().Value.(formulaArg).cellRanges != nil && argsList.Front().Value.(formulaArg).cellRanges.Len() > 0 {
  6947. crs := argsList.Front().Value.(formulaArg).cellRanges
  6948. for cr := crs.Front(); cr != nil; cr = cr.Next() {
  6949. if min == 0 {
  6950. min = cr.Value.(cellRange).From.Row
  6951. }
  6952. if min > cr.Value.(cellRange).From.Row {
  6953. min = cr.Value.(cellRange).From.Row
  6954. }
  6955. if min > cr.Value.(cellRange).To.Row {
  6956. min = cr.Value.(cellRange).To.Row
  6957. }
  6958. if max < cr.Value.(cellRange).To.Row {
  6959. max = cr.Value.(cellRange).To.Row
  6960. }
  6961. if max < cr.Value.(cellRange).From.Row {
  6962. max = cr.Value.(cellRange).From.Row
  6963. }
  6964. }
  6965. }
  6966. if argsList.Front().Value.(formulaArg).cellRefs != nil && argsList.Front().Value.(formulaArg).cellRefs.Len() > 0 {
  6967. cr := argsList.Front().Value.(formulaArg).cellRefs
  6968. for refs := cr.Front(); refs != nil; refs = refs.Next() {
  6969. if min == 0 {
  6970. min = refs.Value.(cellRef).Row
  6971. }
  6972. if min > refs.Value.(cellRef).Row {
  6973. min = refs.Value.(cellRef).Row
  6974. }
  6975. if max < refs.Value.(cellRef).Row {
  6976. max = refs.Value.(cellRef).Row
  6977. }
  6978. }
  6979. }
  6980. if max == TotalRows {
  6981. return newStringFormulaArg(strconv.Itoa(TotalRows))
  6982. }
  6983. result := max - min + 1
  6984. if max == min {
  6985. if min == 0 {
  6986. return newErrorFormulaArg(formulaErrorVALUE, "invalid reference")
  6987. }
  6988. return newNumberFormulaArg(float64(1))
  6989. }
  6990. return newStringFormulaArg(strconv.Itoa(result))
  6991. }
  6992. // Web Functions
  6993. // ENCODEURL function returns a URL-encoded string, replacing certain
  6994. // non-alphanumeric characters with the percentage symbol (%) and a
  6995. // hexadecimal number. The syntax of the function is:
  6996. //
  6997. // ENCODEURL(url)
  6998. //
  6999. func (fn *formulaFuncs) ENCODEURL(argsList *list.List) formulaArg {
  7000. if argsList.Len() != 1 {
  7001. return newErrorFormulaArg(formulaErrorVALUE, "ENCODEURL requires 1 argument")
  7002. }
  7003. token := argsList.Front().Value.(formulaArg).Value()
  7004. return newStringFormulaArg(strings.Replace(url.QueryEscape(token), "+", "%20", -1))
  7005. }
  7006. // Financial Functions
  7007. // CUMIPMT function calculates the cumulative interest paid on a loan or
  7008. // investment, between two specified periods. The syntax of the function is:
  7009. //
  7010. // CUMIPMT(rate,nper,pv,start_period,end_period,type)
  7011. //
  7012. func (fn *formulaFuncs) CUMIPMT(argsList *list.List) formulaArg {
  7013. return fn.cumip("CUMIPMT", argsList)
  7014. }
  7015. // CUMPRINC function calculates the cumulative payment on the principal of a
  7016. // loan or investment, between two specified periods. The syntax of the
  7017. // function is:
  7018. //
  7019. // CUMPRINC(rate,nper,pv,start_period,end_period,type)
  7020. //
  7021. func (fn *formulaFuncs) CUMPRINC(argsList *list.List) formulaArg {
  7022. return fn.cumip("CUMPRINC", argsList)
  7023. }
  7024. // cumip is an implementation of the formula function CUMIPMT and CUMPRINC.
  7025. func (fn *formulaFuncs) cumip(name string, argsList *list.List) formulaArg {
  7026. if argsList.Len() != 6 {
  7027. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 6 arguments", name))
  7028. }
  7029. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7030. if rate.Type != ArgNumber {
  7031. return rate
  7032. }
  7033. nper := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7034. if nper.Type != ArgNumber {
  7035. return nper
  7036. }
  7037. pv := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7038. if pv.Type != ArgNumber {
  7039. return pv
  7040. }
  7041. start := argsList.Back().Prev().Prev().Value.(formulaArg).ToNumber()
  7042. if start.Type != ArgNumber {
  7043. return start
  7044. }
  7045. end := argsList.Back().Prev().Value.(formulaArg).ToNumber()
  7046. if end.Type != ArgNumber {
  7047. return end
  7048. }
  7049. typ := argsList.Back().Value.(formulaArg).ToNumber()
  7050. if typ.Type != ArgNumber {
  7051. return typ
  7052. }
  7053. if typ.Number != 0 && typ.Number != 1 {
  7054. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7055. }
  7056. if start.Number < 1 || start.Number > end.Number {
  7057. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7058. }
  7059. num, ipmt := 0.0, newNumberFormulaArg(0)
  7060. for per := start.Number; per <= end.Number; per++ {
  7061. args := list.New().Init()
  7062. args.PushBack(rate)
  7063. args.PushBack(newNumberFormulaArg(per))
  7064. args.PushBack(nper)
  7065. args.PushBack(pv)
  7066. args.PushBack(newNumberFormulaArg(0))
  7067. args.PushBack(typ)
  7068. if name == "CUMIPMT" {
  7069. ipmt = fn.IPMT(args)
  7070. } else {
  7071. ipmt = fn.PPMT(args)
  7072. }
  7073. num += ipmt.Number
  7074. }
  7075. return newNumberFormulaArg(num)
  7076. }
  7077. // DB function calculates the depreciation of an asset, using the Fixed
  7078. // Declining Balance Method, for each period of the asset's lifetime. The
  7079. // syntax of the function is:
  7080. //
  7081. // DB(cost,salvage,life,period,[month])
  7082. //
  7083. func (fn *formulaFuncs) DB(argsList *list.List) formulaArg {
  7084. if argsList.Len() < 4 {
  7085. return newErrorFormulaArg(formulaErrorVALUE, "DB requires at least 4 arguments")
  7086. }
  7087. if argsList.Len() > 5 {
  7088. return newErrorFormulaArg(formulaErrorVALUE, "DB allows at most 5 arguments")
  7089. }
  7090. cost := argsList.Front().Value.(formulaArg).ToNumber()
  7091. if cost.Type != ArgNumber {
  7092. return cost
  7093. }
  7094. salvage := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7095. if salvage.Type != ArgNumber {
  7096. return salvage
  7097. }
  7098. life := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7099. if life.Type != ArgNumber {
  7100. return life
  7101. }
  7102. period := argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber()
  7103. if period.Type != ArgNumber {
  7104. return period
  7105. }
  7106. month := newNumberFormulaArg(12)
  7107. if argsList.Len() == 5 {
  7108. if month = argsList.Back().Value.(formulaArg).ToNumber(); month.Type != ArgNumber {
  7109. return month
  7110. }
  7111. }
  7112. if cost.Number == 0 {
  7113. return newNumberFormulaArg(0)
  7114. }
  7115. if (cost.Number <= 0) || ((salvage.Number / cost.Number) < 0) || (life.Number <= 0) || (period.Number < 1) || (month.Number < 1) {
  7116. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7117. }
  7118. dr := 1 - math.Pow(salvage.Number/cost.Number, 1/life.Number)
  7119. dr = math.Round(dr*1000) / 1000
  7120. pd, depreciation := 0.0, 0.0
  7121. for per := 1; per <= int(period.Number); per++ {
  7122. if per == 1 {
  7123. depreciation = cost.Number * dr * month.Number / 12
  7124. } else if per == int(life.Number+1) {
  7125. depreciation = (cost.Number - pd) * dr * (12 - month.Number) / 12
  7126. } else {
  7127. depreciation = (cost.Number - pd) * dr
  7128. }
  7129. pd += depreciation
  7130. }
  7131. return newNumberFormulaArg(depreciation)
  7132. }
  7133. // DDB function calculates the depreciation of an asset, using the Double
  7134. // Declining Balance Method, or another specified depreciation rate. The
  7135. // syntax of the function is:
  7136. //
  7137. // DDB(cost,salvage,life,period,[factor])
  7138. //
  7139. func (fn *formulaFuncs) DDB(argsList *list.List) formulaArg {
  7140. if argsList.Len() < 4 {
  7141. return newErrorFormulaArg(formulaErrorVALUE, "DDB requires at least 4 arguments")
  7142. }
  7143. if argsList.Len() > 5 {
  7144. return newErrorFormulaArg(formulaErrorVALUE, "DDB allows at most 5 arguments")
  7145. }
  7146. cost := argsList.Front().Value.(formulaArg).ToNumber()
  7147. if cost.Type != ArgNumber {
  7148. return cost
  7149. }
  7150. salvage := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7151. if salvage.Type != ArgNumber {
  7152. return salvage
  7153. }
  7154. life := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7155. if life.Type != ArgNumber {
  7156. return life
  7157. }
  7158. period := argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber()
  7159. if period.Type != ArgNumber {
  7160. return period
  7161. }
  7162. factor := newNumberFormulaArg(2)
  7163. if argsList.Len() == 5 {
  7164. if factor = argsList.Back().Value.(formulaArg).ToNumber(); factor.Type != ArgNumber {
  7165. return factor
  7166. }
  7167. }
  7168. if cost.Number == 0 {
  7169. return newNumberFormulaArg(0)
  7170. }
  7171. if (cost.Number <= 0) || ((salvage.Number / cost.Number) < 0) || (life.Number <= 0) || (period.Number < 1) || (factor.Number <= 0.0) || (period.Number > life.Number) {
  7172. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7173. }
  7174. pd, depreciation := 0.0, 0.0
  7175. for per := 1; per <= int(period.Number); per++ {
  7176. depreciation = math.Min((cost.Number-pd)*(factor.Number/life.Number), (cost.Number - salvage.Number - pd))
  7177. pd += depreciation
  7178. }
  7179. return newNumberFormulaArg(depreciation)
  7180. }
  7181. // DOLLARDE function converts a dollar value in fractional notation, into a
  7182. // dollar value expressed as a decimal. The syntax of the function is:
  7183. //
  7184. // DOLLARDE(fractional_dollar,fraction)
  7185. //
  7186. func (fn *formulaFuncs) DOLLARDE(argsList *list.List) formulaArg {
  7187. return fn.dollar("DOLLARDE", argsList)
  7188. }
  7189. // DOLLARFR function converts a dollar value in decimal notation, into a
  7190. // dollar value that is expressed in fractional notation. The syntax of the
  7191. // function is:
  7192. //
  7193. // DOLLARFR(decimal_dollar,fraction)
  7194. //
  7195. func (fn *formulaFuncs) DOLLARFR(argsList *list.List) formulaArg {
  7196. return fn.dollar("DOLLARFR", argsList)
  7197. }
  7198. // dollar is an implementation of the formula function DOLLARDE and DOLLARFR.
  7199. func (fn *formulaFuncs) dollar(name string, argsList *list.List) formulaArg {
  7200. if argsList.Len() != 2 {
  7201. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires 2 arguments", name))
  7202. }
  7203. dollar := argsList.Front().Value.(formulaArg).ToNumber()
  7204. if dollar.Type != ArgNumber {
  7205. return dollar
  7206. }
  7207. frac := argsList.Back().Value.(formulaArg).ToNumber()
  7208. if frac.Type != ArgNumber {
  7209. return frac
  7210. }
  7211. if frac.Number < 0 {
  7212. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7213. }
  7214. if frac.Number == 0 {
  7215. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  7216. }
  7217. cents := math.Mod(dollar.Number, 1)
  7218. if name == "DOLLARDE" {
  7219. cents /= frac.Number
  7220. cents *= math.Pow(10, math.Ceil(math.Log10(frac.Number)))
  7221. } else {
  7222. cents *= frac.Number
  7223. cents *= math.Pow(10, -math.Ceil(math.Log10(frac.Number)))
  7224. }
  7225. return newNumberFormulaArg(math.Floor(dollar.Number) + cents)
  7226. }
  7227. // EFFECT function returns the effective annual interest rate for a given
  7228. // nominal interest rate and number of compounding periods per year. The
  7229. // syntax of the function is:
  7230. //
  7231. // EFFECT(nominal_rate,npery)
  7232. //
  7233. func (fn *formulaFuncs) EFFECT(argsList *list.List) formulaArg {
  7234. if argsList.Len() != 2 {
  7235. return newErrorFormulaArg(formulaErrorVALUE, "EFFECT requires 2 arguments")
  7236. }
  7237. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7238. if rate.Type != ArgNumber {
  7239. return rate
  7240. }
  7241. npery := argsList.Back().Value.(formulaArg).ToNumber()
  7242. if npery.Type != ArgNumber {
  7243. return npery
  7244. }
  7245. if rate.Number <= 0 || npery.Number < 1 {
  7246. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7247. }
  7248. return newNumberFormulaArg(math.Pow((1+rate.Number/npery.Number), npery.Number) - 1)
  7249. }
  7250. // FV function calculates the Future Value of an investment with periodic
  7251. // constant payments and a constant interest rate. The syntax of the function
  7252. // is:
  7253. //
  7254. // FV(rate,nper,[pmt],[pv],[type])
  7255. //
  7256. func (fn *formulaFuncs) FV(argsList *list.List) formulaArg {
  7257. if argsList.Len() < 3 {
  7258. return newErrorFormulaArg(formulaErrorVALUE, "FV requires at least 3 arguments")
  7259. }
  7260. if argsList.Len() > 5 {
  7261. return newErrorFormulaArg(formulaErrorVALUE, "FV allows at most 5 arguments")
  7262. }
  7263. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7264. if rate.Type != ArgNumber {
  7265. return rate
  7266. }
  7267. nper := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7268. if nper.Type != ArgNumber {
  7269. return nper
  7270. }
  7271. pmt := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7272. if pmt.Type != ArgNumber {
  7273. return pmt
  7274. }
  7275. pv, typ := newNumberFormulaArg(0), newNumberFormulaArg(0)
  7276. if argsList.Len() >= 4 {
  7277. if pv = argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber(); pv.Type != ArgNumber {
  7278. return pv
  7279. }
  7280. }
  7281. if argsList.Len() == 5 {
  7282. if typ = argsList.Back().Value.(formulaArg).ToNumber(); typ.Type != ArgNumber {
  7283. return typ
  7284. }
  7285. }
  7286. if typ.Number != 0 && typ.Number != 1 {
  7287. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7288. }
  7289. if rate.Number != 0 {
  7290. return newNumberFormulaArg(-pv.Number*math.Pow(1+rate.Number, nper.Number) - pmt.Number*(1+rate.Number*typ.Number)*(math.Pow(1+rate.Number, nper.Number)-1)/rate.Number)
  7291. }
  7292. return newNumberFormulaArg(-pv.Number - pmt.Number*nper.Number)
  7293. }
  7294. // FVSCHEDULE function calculates the Future Value of an investment with a
  7295. // variable interest rate. The syntax of the function is:
  7296. //
  7297. // FVSCHEDULE(principal,schedule)
  7298. //
  7299. func (fn *formulaFuncs) FVSCHEDULE(argsList *list.List) formulaArg {
  7300. if argsList.Len() != 2 {
  7301. return newErrorFormulaArg(formulaErrorVALUE, "FVSCHEDULE requires 2 arguments")
  7302. }
  7303. pri := argsList.Front().Value.(formulaArg).ToNumber()
  7304. if pri.Type != ArgNumber {
  7305. return pri
  7306. }
  7307. principal := pri.Number
  7308. for _, arg := range argsList.Back().Value.(formulaArg).ToList() {
  7309. if arg.Value() == "" {
  7310. continue
  7311. }
  7312. rate := arg.ToNumber()
  7313. if rate.Type != ArgNumber {
  7314. return rate
  7315. }
  7316. principal *= (1 + rate.Number)
  7317. }
  7318. return newNumberFormulaArg(principal)
  7319. }
  7320. // IPMT function calculates the interest payment, during a specific period of a
  7321. // loan or investment that is paid in constant periodic payments, with a
  7322. // constant interest rate. The syntax of the function is:
  7323. //
  7324. // IPMT(rate,per,nper,pv,[fv],[type])
  7325. //
  7326. func (fn *formulaFuncs) IPMT(argsList *list.List) formulaArg {
  7327. return fn.ipmt("IPMT", argsList)
  7328. }
  7329. // ipmt is an implementation of the formula function IPMT and PPMT.
  7330. func (fn *formulaFuncs) ipmt(name string, argsList *list.List) formulaArg {
  7331. if argsList.Len() < 4 {
  7332. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s requires at least 4 arguments", name))
  7333. }
  7334. if argsList.Len() > 6 {
  7335. return newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf("%s allows at most 6 arguments", name))
  7336. }
  7337. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7338. if rate.Type != ArgNumber {
  7339. return rate
  7340. }
  7341. per := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7342. if per.Type != ArgNumber {
  7343. return per
  7344. }
  7345. nper := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7346. if nper.Type != ArgNumber {
  7347. return nper
  7348. }
  7349. pv := argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber()
  7350. if pv.Type != ArgNumber {
  7351. return pv
  7352. }
  7353. fv, typ := newNumberFormulaArg(0), newNumberFormulaArg(0)
  7354. if argsList.Len() >= 5 {
  7355. if fv = argsList.Front().Next().Next().Next().Next().Value.(formulaArg).ToNumber(); fv.Type != ArgNumber {
  7356. return fv
  7357. }
  7358. }
  7359. if argsList.Len() == 6 {
  7360. if typ = argsList.Back().Value.(formulaArg).ToNumber(); typ.Type != ArgNumber {
  7361. return typ
  7362. }
  7363. }
  7364. if typ.Number != 0 && typ.Number != 1 {
  7365. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7366. }
  7367. if per.Number <= 0 || per.Number > nper.Number {
  7368. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7369. }
  7370. args := list.New().Init()
  7371. args.PushBack(rate)
  7372. args.PushBack(nper)
  7373. args.PushBack(pv)
  7374. args.PushBack(fv)
  7375. args.PushBack(typ)
  7376. pmt, capital, interest, principal := fn.PMT(args), pv.Number, 0.0, 0.0
  7377. for i := 1; i <= int(per.Number); i++ {
  7378. if typ.Number != 0 && i == 1 {
  7379. interest = 0
  7380. } else {
  7381. interest = -capital * rate.Number
  7382. }
  7383. principal = pmt.Number - interest
  7384. capital += principal
  7385. }
  7386. if name == "IPMT" {
  7387. return newNumberFormulaArg(interest)
  7388. }
  7389. return newNumberFormulaArg(principal)
  7390. }
  7391. // IRR function returns the Internal Rate of Return for a supplied series of
  7392. // periodic cash flows (i.e. an initial investment value and a series of net
  7393. // income values). The syntax of the function is:
  7394. //
  7395. // IRR(values,[guess])
  7396. //
  7397. func (fn *formulaFuncs) IRR(argsList *list.List) formulaArg {
  7398. if argsList.Len() < 1 {
  7399. return newErrorFormulaArg(formulaErrorVALUE, "IRR requires at least 1 argument")
  7400. }
  7401. if argsList.Len() > 2 {
  7402. return newErrorFormulaArg(formulaErrorVALUE, "IRR allows at most 2 arguments")
  7403. }
  7404. values, guess := argsList.Front().Value.(formulaArg).ToList(), newNumberFormulaArg(0.1)
  7405. if argsList.Len() > 1 {
  7406. if guess = argsList.Back().Value.(formulaArg).ToNumber(); guess.Type != ArgNumber {
  7407. return guess
  7408. }
  7409. }
  7410. x1, x2 := newNumberFormulaArg(0), guess
  7411. args := list.New().Init()
  7412. args.PushBack(x1)
  7413. for _, v := range values {
  7414. args.PushBack(v)
  7415. }
  7416. f1 := fn.NPV(args)
  7417. args.Front().Value = x2
  7418. f2 := fn.NPV(args)
  7419. for i := 0; i < maxFinancialIterations; i++ {
  7420. if f1.Number*f2.Number < 0 {
  7421. break
  7422. }
  7423. if math.Abs(f1.Number) < math.Abs((f2.Number)) {
  7424. x1.Number += 1.6 * (x1.Number - x2.Number)
  7425. args.Front().Value = x1
  7426. f1 = fn.NPV(args)
  7427. continue
  7428. }
  7429. x2.Number += 1.6 * (x2.Number - x1.Number)
  7430. args.Front().Value = x2
  7431. f2 = fn.NPV(args)
  7432. }
  7433. if f1.Number*f2.Number > 0 {
  7434. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7435. }
  7436. args.Front().Value = x1
  7437. f := fn.NPV(args)
  7438. var rtb, dx, xMid, fMid float64
  7439. if f.Number < 0 {
  7440. rtb = x1.Number
  7441. dx = x2.Number - x1.Number
  7442. } else {
  7443. rtb = x2.Number
  7444. dx = x1.Number - x2.Number
  7445. }
  7446. for i := 0; i < maxFinancialIterations; i++ {
  7447. dx *= 0.5
  7448. xMid = rtb + dx
  7449. args.Front().Value = newNumberFormulaArg(xMid)
  7450. fMid = fn.NPV(args).Number
  7451. if fMid <= 0 {
  7452. rtb = xMid
  7453. }
  7454. if math.Abs(fMid) < financialPercision || math.Abs(dx) < financialPercision {
  7455. break
  7456. }
  7457. }
  7458. return newNumberFormulaArg(xMid)
  7459. }
  7460. // ISPMT function calculates the interest paid during a specific period of a
  7461. // loan or investment. The syntax of the function is:
  7462. //
  7463. // ISPMT(rate,per,nper,pv)
  7464. //
  7465. func (fn *formulaFuncs) ISPMT(argsList *list.List) formulaArg {
  7466. if argsList.Len() != 4 {
  7467. return newErrorFormulaArg(formulaErrorVALUE, "ISPMT requires 4 arguments")
  7468. }
  7469. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7470. if rate.Type != ArgNumber {
  7471. return rate
  7472. }
  7473. per := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7474. if per.Type != ArgNumber {
  7475. return per
  7476. }
  7477. nper := argsList.Back().Prev().Value.(formulaArg).ToNumber()
  7478. if nper.Type != ArgNumber {
  7479. return nper
  7480. }
  7481. pv := argsList.Back().Value.(formulaArg).ToNumber()
  7482. if pv.Type != ArgNumber {
  7483. return pv
  7484. }
  7485. pr, payment, num := pv.Number, pv.Number/nper.Number, 0.0
  7486. for i := 0; i <= int(per.Number); i++ {
  7487. num = rate.Number * pr * -1
  7488. pr -= payment
  7489. if i == int(nper.Number) {
  7490. num = 0
  7491. }
  7492. }
  7493. return newNumberFormulaArg(num)
  7494. }
  7495. // MIRR function returns the Modified Internal Rate of Return for a supplied
  7496. // series of periodic cash flows (i.e. a set of values, which includes an
  7497. // initial investment value and a series of net income values). The syntax of
  7498. // the function is:
  7499. //
  7500. // MIRR(values,finance_rate,reinvest_rate)
  7501. //
  7502. func (fn *formulaFuncs) MIRR(argsList *list.List) formulaArg {
  7503. if argsList.Len() != 3 {
  7504. return newErrorFormulaArg(formulaErrorVALUE, "MIRR requires 3 arguments")
  7505. }
  7506. values := argsList.Front().Value.(formulaArg).ToList()
  7507. financeRate := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7508. if financeRate.Type != ArgNumber {
  7509. return financeRate
  7510. }
  7511. reinvestRate := argsList.Back().Value.(formulaArg).ToNumber()
  7512. if reinvestRate.Type != ArgNumber {
  7513. return reinvestRate
  7514. }
  7515. n, fr, rr, npvPos, npvNeg := len(values), 1+financeRate.Number, 1+reinvestRate.Number, 0.0, 0.0
  7516. for i, v := range values {
  7517. val := v.ToNumber()
  7518. if val.Number >= 0 {
  7519. npvPos += val.Number / math.Pow(float64(rr), float64(i))
  7520. continue
  7521. }
  7522. npvNeg += val.Number / math.Pow(float64(fr), float64(i))
  7523. }
  7524. if npvNeg == 0 || npvPos == 0 || reinvestRate.Number <= -1 {
  7525. return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)
  7526. }
  7527. return newNumberFormulaArg(math.Pow(-npvPos*math.Pow(rr, float64(n))/(npvNeg*rr), 1/(float64(n)-1)) - 1)
  7528. }
  7529. // NOMINAL function returns the nominal interest rate for a given effective
  7530. // interest rate and number of compounding periods per year. The syntax of
  7531. // the function is:
  7532. //
  7533. // NOMINAL(effect_rate,npery)
  7534. //
  7535. func (fn *formulaFuncs) NOMINAL(argsList *list.List) formulaArg {
  7536. if argsList.Len() != 2 {
  7537. return newErrorFormulaArg(formulaErrorVALUE, "NOMINAL requires 2 arguments")
  7538. }
  7539. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7540. if rate.Type != ArgNumber {
  7541. return rate
  7542. }
  7543. npery := argsList.Back().Value.(formulaArg).ToNumber()
  7544. if npery.Type != ArgNumber {
  7545. return npery
  7546. }
  7547. if rate.Number <= 0 || npery.Number < 1 {
  7548. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7549. }
  7550. return newNumberFormulaArg(npery.Number * (math.Pow(rate.Number+1, 1/npery.Number) - 1))
  7551. }
  7552. // NPER function calculates the number of periods required to pay off a loan,
  7553. // for a constant periodic payment and a constant interest rate. The syntax
  7554. // of the function is:
  7555. //
  7556. // NPER(rate,pmt,pv,[fv],[type])
  7557. //
  7558. func (fn *formulaFuncs) NPER(argsList *list.List) formulaArg {
  7559. if argsList.Len() < 3 {
  7560. return newErrorFormulaArg(formulaErrorVALUE, "NPER requires at least 3 arguments")
  7561. }
  7562. if argsList.Len() > 5 {
  7563. return newErrorFormulaArg(formulaErrorVALUE, "NPER allows at most 5 arguments")
  7564. }
  7565. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7566. if rate.Type != ArgNumber {
  7567. return rate
  7568. }
  7569. pmt := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7570. if pmt.Type != ArgNumber {
  7571. return pmt
  7572. }
  7573. pv := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7574. if pv.Type != ArgNumber {
  7575. return pv
  7576. }
  7577. fv, typ := newNumberFormulaArg(0), newNumberFormulaArg(0)
  7578. if argsList.Len() >= 4 {
  7579. if fv = argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber(); fv.Type != ArgNumber {
  7580. return fv
  7581. }
  7582. }
  7583. if argsList.Len() == 5 {
  7584. if typ = argsList.Back().Value.(formulaArg).ToNumber(); typ.Type != ArgNumber {
  7585. return typ
  7586. }
  7587. }
  7588. if typ.Number != 0 && typ.Number != 1 {
  7589. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7590. }
  7591. if pmt.Number == 0 {
  7592. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7593. }
  7594. if rate.Number != 0 {
  7595. p := math.Log((pmt.Number*(1+rate.Number*typ.Number)/rate.Number-fv.Number)/(pv.Number+pmt.Number*(1+rate.Number*typ.Number)/rate.Number)) / math.Log(1+rate.Number)
  7596. return newNumberFormulaArg(p)
  7597. }
  7598. return newNumberFormulaArg((-pv.Number - fv.Number) / pmt.Number)
  7599. }
  7600. // NPV function calculates the Net Present Value of an investment, based on a
  7601. // supplied discount rate, and a series of future payments and income. The
  7602. // syntax of the function is:
  7603. //
  7604. // NPV(rate,value1,[value2],[value3],...)
  7605. //
  7606. func (fn *formulaFuncs) NPV(argsList *list.List) formulaArg {
  7607. if argsList.Len() < 2 {
  7608. return newErrorFormulaArg(formulaErrorVALUE, "NPV requires at least 2 arguments")
  7609. }
  7610. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7611. if rate.Type != ArgNumber {
  7612. return rate
  7613. }
  7614. val, i := 0.0, 1
  7615. for arg := argsList.Front().Next(); arg != nil; arg = arg.Next() {
  7616. num := arg.Value.(formulaArg).ToNumber()
  7617. if num.Type != ArgNumber {
  7618. continue
  7619. }
  7620. val += num.Number / math.Pow(1+rate.Number, float64(i))
  7621. i++
  7622. }
  7623. return newNumberFormulaArg(val)
  7624. }
  7625. // PDURATION function calculates the number of periods required for an
  7626. // investment to reach a specified future value. The syntax of the function
  7627. // is:
  7628. //
  7629. // PDURATION(rate,pv,fv)
  7630. //
  7631. func (fn *formulaFuncs) PDURATION(argsList *list.List) formulaArg {
  7632. if argsList.Len() != 3 {
  7633. return newErrorFormulaArg(formulaErrorVALUE, "PDURATION requires 3 arguments")
  7634. }
  7635. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7636. if rate.Type != ArgNumber {
  7637. return rate
  7638. }
  7639. pv := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7640. if pv.Type != ArgNumber {
  7641. return pv
  7642. }
  7643. fv := argsList.Back().Value.(formulaArg).ToNumber()
  7644. if fv.Type != ArgNumber {
  7645. return fv
  7646. }
  7647. if rate.Number <= 0 || pv.Number <= 0 || fv.Number <= 0 {
  7648. return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)
  7649. }
  7650. return newNumberFormulaArg((math.Log(fv.Number) - math.Log(pv.Number)) / math.Log(1+rate.Number))
  7651. }
  7652. // PMT function calculates the constant periodic payment required to pay off
  7653. // (or partially pay off) a loan or investment, with a constant interest
  7654. // rate, over a specified period. The syntax of the function is:
  7655. //
  7656. // PMT(rate,nper,pv,[fv],[type])
  7657. //
  7658. func (fn *formulaFuncs) PMT(argsList *list.List) formulaArg {
  7659. if argsList.Len() < 3 {
  7660. return newErrorFormulaArg(formulaErrorVALUE, "PMT requires at least 3 arguments")
  7661. }
  7662. if argsList.Len() > 5 {
  7663. return newErrorFormulaArg(formulaErrorVALUE, "PMT allows at most 5 arguments")
  7664. }
  7665. rate := argsList.Front().Value.(formulaArg).ToNumber()
  7666. if rate.Type != ArgNumber {
  7667. return rate
  7668. }
  7669. nper := argsList.Front().Next().Value.(formulaArg).ToNumber()
  7670. if nper.Type != ArgNumber {
  7671. return nper
  7672. }
  7673. pv := argsList.Front().Next().Next().Value.(formulaArg).ToNumber()
  7674. if pv.Type != ArgNumber {
  7675. return pv
  7676. }
  7677. fv, typ := newNumberFormulaArg(0), newNumberFormulaArg(0)
  7678. if argsList.Len() >= 4 {
  7679. if fv = argsList.Front().Next().Next().Next().Value.(formulaArg).ToNumber(); fv.Type != ArgNumber {
  7680. return fv
  7681. }
  7682. }
  7683. if argsList.Len() == 5 {
  7684. if typ = argsList.Back().Value.(formulaArg).ToNumber(); typ.Type != ArgNumber {
  7685. return typ
  7686. }
  7687. }
  7688. if typ.Number != 0 && typ.Number != 1 {
  7689. return newErrorFormulaArg(formulaErrorNA, formulaErrorNA)
  7690. }
  7691. if rate.Number != 0 {
  7692. p := (-fv.Number - pv.Number*math.Pow((1+rate.Number), nper.Number)) / (1 + rate.Number*typ.Number) / ((math.Pow((1+rate.Number), nper.Number) - 1) / rate.Number)
  7693. return newNumberFormulaArg(p)
  7694. }
  7695. return newNumberFormulaArg((-pv.Number - fv.Number) / nper.Number)
  7696. }
  7697. // PPMT function calculates the payment on the principal, during a specific
  7698. // period of a loan or investment that is paid in constant periodic payments,
  7699. // with a constant interest rate. The syntax of the function is:
  7700. //
  7701. // PPMT(rate,per,nper,pv,[fv],[type])
  7702. //
  7703. func (fn *formulaFuncs) PPMT(argsList *list.List) formulaArg {
  7704. return fn.ipmt("PPMT", argsList)
  7705. }