calc.go 236 KB

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