calc.go 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415
  1. // Copyright 2016 - 2020 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 Exce™ 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.10 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "container/list"
  15. "errors"
  16. "fmt"
  17. "math"
  18. "math/rand"
  19. "reflect"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/xuri/efp"
  24. )
  25. // Excel formula errors
  26. const (
  27. formulaErrorDIV = "#DIV/0!"
  28. formulaErrorNAME = "#NAME?"
  29. formulaErrorNA = "#N/A"
  30. formulaErrorNUM = "#NUM!"
  31. formulaErrorVALUE = "#VALUE!"
  32. formulaErrorREF = "#REF!"
  33. formulaErrorNULL = "#NULL"
  34. formulaErrorSPILL = "#SPILL!"
  35. formulaErrorCALC = "#CALC!"
  36. formulaErrorGETTINGDATA = "#GETTING_DATA"
  37. )
  38. // cellRef defines the structure of a cell reference.
  39. type cellRef struct {
  40. Col int
  41. Row int
  42. Sheet string
  43. }
  44. // cellRef defines the structure of a cell range.
  45. type cellRange struct {
  46. From cellRef
  47. To cellRef
  48. }
  49. // formulaArg is the argument of a formula or function.
  50. type formulaArg struct {
  51. Value string
  52. Matrix []string
  53. }
  54. // formulaFuncs is the type of the formula functions.
  55. type formulaFuncs struct{}
  56. // CalcCellValue provides a function to get calculated cell value. This
  57. // feature is currently in beta. Array formula, table formula and some other
  58. // formulas are not supported currently.
  59. func (f *File) CalcCellValue(sheet, cell string) (result string, err error) {
  60. var (
  61. formula string
  62. token efp.Token
  63. )
  64. if formula, err = f.GetCellFormula(sheet, cell); err != nil {
  65. return
  66. }
  67. ps := efp.ExcelParser()
  68. tokens := ps.Parse(formula)
  69. if tokens == nil {
  70. return
  71. }
  72. if token, err = f.evalInfixExp(sheet, tokens); err != nil {
  73. return
  74. }
  75. result = token.TValue
  76. return
  77. }
  78. // getPriority calculate arithmetic operator priority.
  79. func getPriority(token efp.Token) (pri int) {
  80. var priority = map[string]int{
  81. "*": 2,
  82. "/": 2,
  83. "+": 1,
  84. "-": 1,
  85. }
  86. pri, _ = priority[token.TValue]
  87. if token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix {
  88. pri = 3
  89. }
  90. if token.TSubType == efp.TokenSubTypeStart && token.TType == efp.TokenTypeSubexpression { // (
  91. pri = 0
  92. }
  93. return
  94. }
  95. // evalInfixExp evaluate syntax analysis by given infix expression after
  96. // lexical analysis. Evaluate an infix expression containing formulas by
  97. // stacks:
  98. //
  99. // opd - Operand
  100. // opt - Operator
  101. // opf - Operation formula
  102. // opfd - Operand of the operation formula
  103. // opft - Operator of the operation formula
  104. //
  105. // Evaluate arguments of the operation formula by list:
  106. //
  107. // args - Arguments of the operation formula
  108. //
  109. // TODO: handle subtypes: Nothing, Text, Logical, Error, Concatenation, Intersection, Union
  110. //
  111. func (f *File) evalInfixExp(sheet string, tokens []efp.Token) (efp.Token, error) {
  112. var err error
  113. opdStack, optStack, opfStack, opfdStack, opftStack := NewStack(), NewStack(), NewStack(), NewStack(), NewStack()
  114. argsList := list.New()
  115. for i := 0; i < len(tokens); i++ {
  116. token := tokens[i]
  117. // out of function stack
  118. if opfStack.Len() == 0 {
  119. if err = f.parseToken(sheet, token, opdStack, optStack); err != nil {
  120. return efp.Token{}, err
  121. }
  122. }
  123. // function start
  124. if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStart {
  125. opfStack.Push(token)
  126. continue
  127. }
  128. // in function stack, walk 2 token at once
  129. if opfStack.Len() > 0 {
  130. var nextToken efp.Token
  131. if i+1 < len(tokens) {
  132. nextToken = tokens[i+1]
  133. }
  134. // current token is args or range, skip next token, order required: parse reference first
  135. if token.TSubType == efp.TokenSubTypeRange {
  136. if !opftStack.Empty() {
  137. // parse reference: must reference at here
  138. result, _, err := f.parseReference(sheet, token.TValue)
  139. if err != nil {
  140. return efp.Token{TValue: formulaErrorNAME}, err
  141. }
  142. if len(result) != 1 {
  143. return efp.Token{}, errors.New(formulaErrorVALUE)
  144. }
  145. opfdStack.Push(efp.Token{
  146. TType: efp.TokenTypeOperand,
  147. TSubType: efp.TokenSubTypeNumber,
  148. TValue: result[0],
  149. })
  150. continue
  151. }
  152. if nextToken.TType == efp.TokenTypeArgument || nextToken.TType == efp.TokenTypeFunction {
  153. // parse reference: reference or range at here
  154. result, matrix, err := f.parseReference(sheet, token.TValue)
  155. if err != nil {
  156. return efp.Token{TValue: formulaErrorNAME}, err
  157. }
  158. for idx, val := range result {
  159. arg := formulaArg{Value: val}
  160. if idx < len(matrix) {
  161. arg.Matrix = matrix[idx]
  162. }
  163. argsList.PushBack(arg)
  164. }
  165. if len(result) == 0 {
  166. return efp.Token{}, errors.New(formulaErrorVALUE)
  167. }
  168. continue
  169. }
  170. }
  171. // check current token is opft
  172. if err = f.parseToken(sheet, token, opfdStack, opftStack); err != nil {
  173. return efp.Token{}, err
  174. }
  175. // current token is arg
  176. if token.TType == efp.TokenTypeArgument {
  177. for !opftStack.Empty() {
  178. // calculate trigger
  179. topOpt := opftStack.Peek().(efp.Token)
  180. if err := calculate(opfdStack, topOpt); err != nil {
  181. return efp.Token{}, err
  182. }
  183. opftStack.Pop()
  184. }
  185. if !opfdStack.Empty() {
  186. argsList.PushBack(formulaArg{
  187. Value: opfdStack.Pop().(efp.Token).TValue,
  188. })
  189. }
  190. continue
  191. }
  192. // current token is logical
  193. if token.TType == efp.OperatorsInfix && token.TSubType == efp.TokenSubTypeLogical {
  194. }
  195. // current token is text
  196. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeText {
  197. argsList.PushBack(formulaArg{
  198. Value: token.TValue,
  199. })
  200. }
  201. // current token is function stop
  202. if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStop {
  203. for !opftStack.Empty() {
  204. // calculate trigger
  205. topOpt := opftStack.Peek().(efp.Token)
  206. if err := calculate(opfdStack, topOpt); err != nil {
  207. return efp.Token{}, err
  208. }
  209. opftStack.Pop()
  210. }
  211. // push opfd to args
  212. if opfdStack.Len() > 0 {
  213. argsList.PushBack(formulaArg{
  214. Value: opfdStack.Pop().(efp.Token).TValue,
  215. })
  216. }
  217. // call formula function to evaluate
  218. result, err := callFuncByName(&formulaFuncs{}, strings.NewReplacer(
  219. "_xlfn", "", ".", "").Replace(opfStack.Peek().(efp.Token).TValue),
  220. []reflect.Value{reflect.ValueOf(argsList)})
  221. if err != nil {
  222. return efp.Token{}, err
  223. }
  224. argsList.Init()
  225. opfStack.Pop()
  226. if opfStack.Len() > 0 { // still in function stack
  227. opfdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  228. } else {
  229. opdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  230. }
  231. }
  232. }
  233. }
  234. for optStack.Len() != 0 {
  235. topOpt := optStack.Peek().(efp.Token)
  236. if err = calculate(opdStack, topOpt); err != nil {
  237. return efp.Token{}, err
  238. }
  239. optStack.Pop()
  240. }
  241. return opdStack.Peek().(efp.Token), err
  242. }
  243. // calculate evaluate basic arithmetic operations.
  244. func calculate(opdStack *Stack, opt efp.Token) error {
  245. if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorPrefix {
  246. opd := opdStack.Pop().(efp.Token)
  247. opdVal, err := strconv.ParseFloat(opd.TValue, 64)
  248. if err != nil {
  249. return err
  250. }
  251. result := 0 - opdVal
  252. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  253. }
  254. if opt.TValue == "+" {
  255. rOpd := opdStack.Pop().(efp.Token)
  256. lOpd := opdStack.Pop().(efp.Token)
  257. lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
  258. if err != nil {
  259. return err
  260. }
  261. rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
  262. if err != nil {
  263. return err
  264. }
  265. result := lOpdVal + rOpdVal
  266. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  267. }
  268. if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorInfix {
  269. rOpd := opdStack.Pop().(efp.Token)
  270. lOpd := opdStack.Pop().(efp.Token)
  271. lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
  272. if err != nil {
  273. return err
  274. }
  275. rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
  276. if err != nil {
  277. return err
  278. }
  279. result := lOpdVal - rOpdVal
  280. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  281. }
  282. if opt.TValue == "*" {
  283. rOpd := opdStack.Pop().(efp.Token)
  284. lOpd := opdStack.Pop().(efp.Token)
  285. lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
  286. if err != nil {
  287. return err
  288. }
  289. rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
  290. if err != nil {
  291. return err
  292. }
  293. result := lOpdVal * rOpdVal
  294. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  295. }
  296. if opt.TValue == "/" {
  297. rOpd := opdStack.Pop().(efp.Token)
  298. lOpd := opdStack.Pop().(efp.Token)
  299. lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
  300. if err != nil {
  301. return err
  302. }
  303. rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
  304. if err != nil {
  305. return err
  306. }
  307. result := lOpdVal / rOpdVal
  308. if rOpdVal == 0 {
  309. return errors.New(formulaErrorDIV)
  310. }
  311. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  312. }
  313. return nil
  314. }
  315. // parseToken parse basic arithmetic operator priority and evaluate based on
  316. // operators and operands.
  317. func (f *File) parseToken(sheet string, token efp.Token, opdStack, optStack *Stack) error {
  318. // parse reference: must reference at here
  319. if token.TSubType == efp.TokenSubTypeRange {
  320. result, _, err := f.parseReference(sheet, token.TValue)
  321. if err != nil {
  322. return errors.New(formulaErrorNAME)
  323. }
  324. if len(result) != 1 {
  325. return errors.New(formulaErrorVALUE)
  326. }
  327. token.TValue = result[0]
  328. token.TType = efp.TokenTypeOperand
  329. token.TSubType = efp.TokenSubTypeNumber
  330. }
  331. if (token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix) || token.TValue == "+" || token.TValue == "-" || token.TValue == "*" || token.TValue == "/" {
  332. if optStack.Len() == 0 {
  333. optStack.Push(token)
  334. } else {
  335. tokenPriority := getPriority(token)
  336. topOpt := optStack.Peek().(efp.Token)
  337. topOptPriority := getPriority(topOpt)
  338. if tokenPriority > topOptPriority {
  339. optStack.Push(token)
  340. } else {
  341. for tokenPriority <= topOptPriority {
  342. optStack.Pop()
  343. if err := calculate(opdStack, topOpt); err != nil {
  344. return err
  345. }
  346. if optStack.Len() > 0 {
  347. topOpt = optStack.Peek().(efp.Token)
  348. topOptPriority = getPriority(topOpt)
  349. continue
  350. }
  351. break
  352. }
  353. optStack.Push(token)
  354. }
  355. }
  356. }
  357. if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStart { // (
  358. optStack.Push(token)
  359. }
  360. if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStop { // )
  361. for optStack.Peek().(efp.Token).TSubType != efp.TokenSubTypeStart && optStack.Peek().(efp.Token).TType != efp.TokenTypeSubexpression { // != (
  362. topOpt := optStack.Peek().(efp.Token)
  363. if err := calculate(opdStack, topOpt); err != nil {
  364. return err
  365. }
  366. optStack.Pop()
  367. }
  368. optStack.Pop()
  369. }
  370. // opd
  371. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeNumber {
  372. opdStack.Push(token)
  373. }
  374. return nil
  375. }
  376. // parseReference parse reference and extract values by given reference
  377. // characters and default sheet name.
  378. func (f *File) parseReference(sheet, reference string) (result []string, matrix [][]string, err error) {
  379. reference = strings.Replace(reference, "$", "", -1)
  380. refs, cellRanges, cellRefs := list.New(), list.New(), list.New()
  381. for _, ref := range strings.Split(reference, ":") {
  382. tokens := strings.Split(ref, "!")
  383. cr := cellRef{}
  384. if len(tokens) == 2 { // have a worksheet name
  385. cr.Sheet = tokens[0]
  386. if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[1]); err != nil {
  387. return
  388. }
  389. if refs.Len() > 0 {
  390. e := refs.Back()
  391. cellRefs.PushBack(e.Value.(cellRef))
  392. refs.Remove(e)
  393. }
  394. refs.PushBack(cr)
  395. continue
  396. }
  397. if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[0]); err != nil {
  398. return
  399. }
  400. e := refs.Back()
  401. if e == nil {
  402. cr.Sheet = sheet
  403. refs.PushBack(cr)
  404. continue
  405. }
  406. cellRanges.PushBack(cellRange{
  407. From: e.Value.(cellRef),
  408. To: cr,
  409. })
  410. refs.Remove(e)
  411. }
  412. if refs.Len() > 0 {
  413. e := refs.Back()
  414. cellRefs.PushBack(e.Value.(cellRef))
  415. refs.Remove(e)
  416. }
  417. result, matrix, err = f.rangeResolver(cellRefs, cellRanges)
  418. return
  419. }
  420. // rangeResolver extract value as string from given reference and range list.
  421. // This function will not ignore the empty cell. Note that the result of 3D
  422. // range references may be different from Excel in some cases, for example,
  423. // A1:A2:A2:B3 in Excel will include B1, but we wont.
  424. func (f *File) rangeResolver(cellRefs, cellRanges *list.List) (result []string, matrix [][]string, err error) {
  425. filter := map[string]string{}
  426. // extract value from ranges
  427. for temp := cellRanges.Front(); temp != nil; temp = temp.Next() {
  428. cr := temp.Value.(cellRange)
  429. if cr.From.Sheet != cr.To.Sheet {
  430. err = errors.New(formulaErrorVALUE)
  431. }
  432. rng := []int{cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row}
  433. sortCoordinates(rng)
  434. matrix = [][]string{}
  435. for row := rng[1]; row <= rng[3]; row++ {
  436. var matrixRow = []string{}
  437. for col := rng[0]; col <= rng[2]; col++ {
  438. var cell, value string
  439. if cell, err = CoordinatesToCellName(col, row); err != nil {
  440. return
  441. }
  442. if value, err = f.GetCellValue(cr.From.Sheet, cell); err != nil {
  443. return
  444. }
  445. filter[cell] = value
  446. matrixRow = append(matrixRow, value)
  447. }
  448. matrix = append(matrix, matrixRow)
  449. }
  450. }
  451. // extract value from references
  452. for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
  453. cr := temp.Value.(cellRef)
  454. var cell string
  455. if cell, err = CoordinatesToCellName(cr.Col, cr.Row); err != nil {
  456. return
  457. }
  458. if filter[cell], err = f.GetCellValue(cr.Sheet, cell); err != nil {
  459. return
  460. }
  461. }
  462. for _, val := range filter {
  463. result = append(result, val)
  464. }
  465. return
  466. }
  467. // callFuncByName calls the no error or only error return function with
  468. // reflect by given receiver, name and parameters.
  469. func callFuncByName(receiver interface{}, name string, params []reflect.Value) (result string, err error) {
  470. function := reflect.ValueOf(receiver).MethodByName(name)
  471. if function.IsValid() {
  472. rt := function.Call(params)
  473. if len(rt) == 0 {
  474. return
  475. }
  476. if !rt[1].IsNil() {
  477. err = rt[1].Interface().(error)
  478. return
  479. }
  480. result = rt[0].Interface().(string)
  481. return
  482. }
  483. err = fmt.Errorf("not support %s function", name)
  484. return
  485. }
  486. // Math and Trigonometric functions
  487. // ABS function returns the absolute value of any supplied number. The syntax
  488. // of the function is:
  489. //
  490. // ABS(number)
  491. //
  492. func (fn *formulaFuncs) ABS(argsList *list.List) (result string, err error) {
  493. if argsList.Len() != 1 {
  494. err = errors.New("ABS requires 1 numeric argument")
  495. return
  496. }
  497. var val float64
  498. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  499. return
  500. }
  501. result = fmt.Sprintf("%g", math.Abs(val))
  502. return
  503. }
  504. // ACOS function calculates the arccosine (i.e. the inverse cosine) of a given
  505. // number, and returns an angle, in radians, between 0 and π. The syntax of
  506. // the function is:
  507. //
  508. // ACOS(number)
  509. //
  510. func (fn *formulaFuncs) ACOS(argsList *list.List) (result string, err error) {
  511. if argsList.Len() != 1 {
  512. err = errors.New("ACOS requires 1 numeric argument")
  513. return
  514. }
  515. var val float64
  516. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  517. return
  518. }
  519. result = fmt.Sprintf("%g", math.Acos(val))
  520. return
  521. }
  522. // ACOSH function calculates the inverse hyperbolic cosine of a supplied number.
  523. // of the function is:
  524. //
  525. // ACOSH(number)
  526. //
  527. func (fn *formulaFuncs) ACOSH(argsList *list.List) (result string, err error) {
  528. if argsList.Len() != 1 {
  529. err = errors.New("ACOSH requires 1 numeric argument")
  530. return
  531. }
  532. var val float64
  533. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  534. return
  535. }
  536. result = fmt.Sprintf("%g", math.Acosh(val))
  537. return
  538. }
  539. // ACOT function calculates the arccotangent (i.e. the inverse cotangent) of a
  540. // given number, and returns an angle, in radians, between 0 and π. The syntax
  541. // of the function is:
  542. //
  543. // ACOT(number)
  544. //
  545. func (fn *formulaFuncs) ACOT(argsList *list.List) (result string, err error) {
  546. if argsList.Len() != 1 {
  547. err = errors.New("ACOT requires 1 numeric argument")
  548. return
  549. }
  550. var val float64
  551. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  552. return
  553. }
  554. result = fmt.Sprintf("%g", math.Pi/2-math.Atan(val))
  555. return
  556. }
  557. // ACOTH function calculates the hyperbolic arccotangent (coth) of a supplied
  558. // value. The syntax of the function is:
  559. //
  560. // ACOTH(number)
  561. //
  562. func (fn *formulaFuncs) ACOTH(argsList *list.List) (result string, err error) {
  563. if argsList.Len() != 1 {
  564. err = errors.New("ACOTH requires 1 numeric argument")
  565. return
  566. }
  567. var val float64
  568. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  569. return
  570. }
  571. result = fmt.Sprintf("%g", math.Atanh(1/val))
  572. return
  573. }
  574. // ARABIC function converts a Roman numeral into an Arabic numeral. The syntax
  575. // of the function is:
  576. //
  577. // ARABIC(text)
  578. //
  579. func (fn *formulaFuncs) ARABIC(argsList *list.List) (result string, err error) {
  580. if argsList.Len() != 1 {
  581. err = errors.New("ARABIC requires 1 numeric argument")
  582. return
  583. }
  584. val, last, prefix := 0.0, 0.0, 1.0
  585. for _, char := range argsList.Front().Value.(formulaArg).Value {
  586. digit := 0.0
  587. switch char {
  588. case '-':
  589. prefix = -1
  590. continue
  591. case 'I':
  592. digit = 1
  593. case 'V':
  594. digit = 5
  595. case 'X':
  596. digit = 10
  597. case 'L':
  598. digit = 50
  599. case 'C':
  600. digit = 100
  601. case 'D':
  602. digit = 500
  603. case 'M':
  604. digit = 1000
  605. }
  606. val += digit
  607. switch {
  608. case last == digit && (last == 5 || last == 50 || last == 500):
  609. result = formulaErrorVALUE
  610. return
  611. case 2*last == digit:
  612. result = formulaErrorVALUE
  613. return
  614. }
  615. if last < digit {
  616. val -= 2 * last
  617. }
  618. last = digit
  619. }
  620. result = fmt.Sprintf("%g", prefix*val)
  621. return
  622. }
  623. // ASIN function calculates the arcsine (i.e. the inverse sine) of a given
  624. // number, and returns an angle, in radians, between -π/2 and π/2. The syntax
  625. // of the function is:
  626. //
  627. // ASIN(number)
  628. //
  629. func (fn *formulaFuncs) ASIN(argsList *list.List) (result string, err error) {
  630. if argsList.Len() != 1 {
  631. err = errors.New("ASIN requires 1 numeric argument")
  632. return
  633. }
  634. var val float64
  635. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  636. return
  637. }
  638. result = fmt.Sprintf("%g", math.Asin(val))
  639. return
  640. }
  641. // ASINH function calculates the inverse hyperbolic sine of a supplied number.
  642. // The syntax of the function is:
  643. //
  644. // ASINH(number)
  645. //
  646. func (fn *formulaFuncs) ASINH(argsList *list.List) (result string, err error) {
  647. if argsList.Len() != 1 {
  648. err = errors.New("ASINH requires 1 numeric argument")
  649. return
  650. }
  651. var val float64
  652. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  653. return
  654. }
  655. result = fmt.Sprintf("%g", math.Asinh(val))
  656. return
  657. }
  658. // ATAN function calculates the arctangent (i.e. the inverse tangent) of a
  659. // given number, and returns an angle, in radians, between -π/2 and +π/2. The
  660. // syntax of the function is:
  661. //
  662. // ATAN(number)
  663. //
  664. func (fn *formulaFuncs) ATAN(argsList *list.List) (result string, err error) {
  665. if argsList.Len() != 1 {
  666. err = errors.New("ATAN requires 1 numeric argument")
  667. return
  668. }
  669. var val float64
  670. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  671. return
  672. }
  673. result = fmt.Sprintf("%g", math.Atan(val))
  674. return
  675. }
  676. // ATANH function calculates the inverse hyperbolic tangent of a supplied
  677. // number. The syntax of the function is:
  678. //
  679. // ATANH(number)
  680. //
  681. func (fn *formulaFuncs) ATANH(argsList *list.List) (result string, err error) {
  682. if argsList.Len() != 1 {
  683. err = errors.New("ATANH requires 1 numeric argument")
  684. return
  685. }
  686. var val float64
  687. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  688. return
  689. }
  690. result = fmt.Sprintf("%g", math.Atanh(val))
  691. return
  692. }
  693. // ATAN2 function calculates the arctangent (i.e. the inverse tangent) of a
  694. // given set of x and y coordinates, and returns an angle, in radians, between
  695. // -π/2 and +π/2. The syntax of the function is:
  696. //
  697. // ATAN2(x_num,y_num)
  698. //
  699. func (fn *formulaFuncs) ATAN2(argsList *list.List) (result string, err error) {
  700. if argsList.Len() != 2 {
  701. err = errors.New("ATAN2 requires 2 numeric arguments")
  702. return
  703. }
  704. var x, y float64
  705. if x, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  706. return
  707. }
  708. if y, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  709. return
  710. }
  711. result = fmt.Sprintf("%g", math.Atan2(x, y))
  712. return
  713. }
  714. // gcd returns the greatest common divisor of two supplied integers.
  715. func gcd(x, y float64) float64 {
  716. x, y = math.Trunc(x), math.Trunc(y)
  717. if x == 0 {
  718. return y
  719. }
  720. if y == 0 {
  721. return x
  722. }
  723. for x != y {
  724. if x > y {
  725. x = x - y
  726. } else {
  727. y = y - x
  728. }
  729. }
  730. return x
  731. }
  732. // BASE function converts a number into a supplied base (radix), and returns a
  733. // text representation of the calculated value. The syntax of the function is:
  734. //
  735. // BASE(number,radix,[min_length])
  736. //
  737. func (fn *formulaFuncs) BASE(argsList *list.List) (result string, err error) {
  738. if argsList.Len() < 2 {
  739. err = errors.New("BASE requires at least 2 arguments")
  740. return
  741. }
  742. if argsList.Len() > 3 {
  743. err = errors.New("BASE allows at most 3 arguments")
  744. return
  745. }
  746. var number float64
  747. var radix, minLength int
  748. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  749. return
  750. }
  751. if radix, err = strconv.Atoi(argsList.Front().Next().Value.(formulaArg).Value); err != nil {
  752. return
  753. }
  754. if radix < 2 || radix > 36 {
  755. err = errors.New("radix must be an integer ≥ 2 and ≤ 36")
  756. return
  757. }
  758. if argsList.Len() > 2 {
  759. if minLength, err = strconv.Atoi(argsList.Back().Value.(formulaArg).Value); err != nil {
  760. return
  761. }
  762. }
  763. result = strconv.FormatInt(int64(number), radix)
  764. if len(result) < minLength {
  765. result = strings.Repeat("0", minLength-len(result)) + result
  766. }
  767. result = strings.ToUpper(result)
  768. return
  769. }
  770. // CEILING function rounds a supplied number away from zero, to the nearest
  771. // multiple of a given number. The syntax of the function is:
  772. //
  773. // CEILING(number,significance)
  774. //
  775. func (fn *formulaFuncs) CEILING(argsList *list.List) (result string, err error) {
  776. if argsList.Len() == 0 {
  777. err = errors.New("CEILING requires at least 1 argument")
  778. return
  779. }
  780. if argsList.Len() > 2 {
  781. err = errors.New("CEILING allows at most 2 arguments")
  782. return
  783. }
  784. var number, significance float64 = 0, 1
  785. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  786. return
  787. }
  788. if number < 0 {
  789. significance = -1
  790. }
  791. if argsList.Len() > 1 {
  792. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  793. return
  794. }
  795. }
  796. if significance < 0 && number > 0 {
  797. err = errors.New("negative sig to CEILING invalid")
  798. return
  799. }
  800. if argsList.Len() == 1 {
  801. result = fmt.Sprintf("%g", math.Ceil(number))
  802. return
  803. }
  804. number, res := math.Modf(number / significance)
  805. if res > 0 {
  806. number++
  807. }
  808. result = fmt.Sprintf("%g", number*significance)
  809. return
  810. }
  811. // CEILINGMATH function rounds a supplied number up to a supplied multiple of
  812. // significance. The syntax of the function is:
  813. //
  814. // CEILING.MATH(number,[significance],[mode])
  815. //
  816. func (fn *formulaFuncs) CEILINGMATH(argsList *list.List) (result string, err error) {
  817. if argsList.Len() == 0 {
  818. err = errors.New("CEILING.MATH requires at least 1 argument")
  819. return
  820. }
  821. if argsList.Len() > 3 {
  822. err = errors.New("CEILING.MATH allows at most 3 arguments")
  823. return
  824. }
  825. var number, significance, mode float64 = 0, 1, 1
  826. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  827. return
  828. }
  829. if number < 0 {
  830. significance = -1
  831. }
  832. if argsList.Len() > 1 {
  833. if significance, err = strconv.ParseFloat(argsList.Front().Next().Value.(formulaArg).Value, 64); err != nil {
  834. return
  835. }
  836. }
  837. if argsList.Len() == 1 {
  838. result = fmt.Sprintf("%g", math.Ceil(number))
  839. return
  840. }
  841. if argsList.Len() > 2 {
  842. if mode, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  843. return
  844. }
  845. }
  846. val, res := math.Modf(number / significance)
  847. if res != 0 {
  848. if number > 0 {
  849. val++
  850. } else if mode < 0 {
  851. val--
  852. }
  853. }
  854. result = fmt.Sprintf("%g", val*significance)
  855. return
  856. }
  857. // CEILINGPRECISE function rounds a supplied number up (regardless of the
  858. // number's sign), to the nearest multiple of a given number. The syntax of
  859. // the function is:
  860. //
  861. // CEILING.PRECISE(number,[significance])
  862. //
  863. func (fn *formulaFuncs) CEILINGPRECISE(argsList *list.List) (result string, err error) {
  864. if argsList.Len() == 0 {
  865. err = errors.New("CEILING.PRECISE requires at least 1 argument")
  866. return
  867. }
  868. if argsList.Len() > 2 {
  869. err = errors.New("CEILING.PRECISE allows at most 2 arguments")
  870. return
  871. }
  872. var number, significance float64 = 0, 1
  873. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  874. return
  875. }
  876. if number < 0 {
  877. significance = -1
  878. }
  879. if argsList.Len() == 1 {
  880. result = fmt.Sprintf("%g", math.Ceil(number))
  881. return
  882. }
  883. if argsList.Len() > 1 {
  884. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  885. return
  886. }
  887. significance = math.Abs(significance)
  888. if significance == 0 {
  889. result = "0"
  890. return
  891. }
  892. }
  893. val, res := math.Modf(number / significance)
  894. if res != 0 {
  895. if number > 0 {
  896. val++
  897. }
  898. }
  899. result = fmt.Sprintf("%g", val*significance)
  900. return
  901. }
  902. // COMBIN function calculates the number of combinations (in any order) of a
  903. // given number objects from a set. The syntax of the function is:
  904. //
  905. // COMBIN(number,number_chosen)
  906. //
  907. func (fn *formulaFuncs) COMBIN(argsList *list.List) (result string, err error) {
  908. if argsList.Len() != 2 {
  909. err = errors.New("COMBIN requires 2 argument")
  910. return
  911. }
  912. var number, chosen, val float64 = 0, 0, 1
  913. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  914. return
  915. }
  916. if chosen, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  917. return
  918. }
  919. number, chosen = math.Trunc(number), math.Trunc(chosen)
  920. if chosen > number {
  921. err = errors.New("COMBIN requires number >= number_chosen")
  922. return
  923. }
  924. if chosen == number || chosen == 0 {
  925. result = "1"
  926. return
  927. }
  928. for c := float64(1); c <= chosen; c++ {
  929. val *= (number + 1 - c) / c
  930. }
  931. result = fmt.Sprintf("%g", math.Ceil(val))
  932. return
  933. }
  934. // COMBINA function calculates the number of combinations, with repetitions,
  935. // of a given number objects from a set. The syntax of the function is:
  936. //
  937. // COMBINA(number,number_chosen)
  938. //
  939. func (fn *formulaFuncs) COMBINA(argsList *list.List) (result string, err error) {
  940. if argsList.Len() != 2 {
  941. err = errors.New("COMBINA requires 2 argument")
  942. return
  943. }
  944. var number, chosen float64
  945. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  946. return
  947. }
  948. if chosen, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  949. return
  950. }
  951. number, chosen = math.Trunc(number), math.Trunc(chosen)
  952. if number < chosen {
  953. err = errors.New("COMBINA requires number > number_chosen")
  954. return
  955. }
  956. if number == 0 {
  957. result = "0"
  958. return
  959. }
  960. args := list.New()
  961. args.PushBack(formulaArg{
  962. Value: fmt.Sprintf("%g", number+chosen-1),
  963. })
  964. args.PushBack(formulaArg{
  965. Value: fmt.Sprintf("%g", number-1),
  966. })
  967. return fn.COMBIN(args)
  968. }
  969. // COS function calculates the cosine of a given angle. The syntax of the
  970. // function is:
  971. //
  972. // COS(number)
  973. //
  974. func (fn *formulaFuncs) COS(argsList *list.List) (result string, err error) {
  975. if argsList.Len() != 1 {
  976. err = errors.New("COS requires 1 numeric argument")
  977. return
  978. }
  979. var val float64
  980. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  981. return
  982. }
  983. result = fmt.Sprintf("%g", math.Cos(val))
  984. return
  985. }
  986. // COSH function calculates the hyperbolic cosine (cosh) of a supplied number.
  987. // The syntax of the function is:
  988. //
  989. // COSH(number)
  990. //
  991. func (fn *formulaFuncs) COSH(argsList *list.List) (result string, err error) {
  992. if argsList.Len() != 1 {
  993. err = errors.New("COSH requires 1 numeric argument")
  994. return
  995. }
  996. var val float64
  997. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  998. return
  999. }
  1000. result = fmt.Sprintf("%g", math.Cosh(val))
  1001. return
  1002. }
  1003. // COT function calculates the cotangent of a given angle. The syntax of the
  1004. // function is:
  1005. //
  1006. // COT(number)
  1007. //
  1008. func (fn *formulaFuncs) COT(argsList *list.List) (result string, err error) {
  1009. if argsList.Len() != 1 {
  1010. err = errors.New("COT requires 1 numeric argument")
  1011. return
  1012. }
  1013. var val float64
  1014. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1015. return
  1016. }
  1017. if val == 0 {
  1018. err = errors.New(formulaErrorNAME)
  1019. return
  1020. }
  1021. result = fmt.Sprintf("%g", math.Tan(val))
  1022. return
  1023. }
  1024. // COTH function calculates the hyperbolic cotangent (coth) of a supplied
  1025. // angle. The syntax of the function is:
  1026. //
  1027. // COTH(number)
  1028. //
  1029. func (fn *formulaFuncs) COTH(argsList *list.List) (result string, err error) {
  1030. if argsList.Len() != 1 {
  1031. err = errors.New("COTH requires 1 numeric argument")
  1032. return
  1033. }
  1034. var val float64
  1035. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1036. return
  1037. }
  1038. if val == 0 {
  1039. err = errors.New(formulaErrorNAME)
  1040. return
  1041. }
  1042. result = fmt.Sprintf("%g", math.Tanh(val))
  1043. return
  1044. }
  1045. // CSC function calculates the cosecant of a given angle. The syntax of the
  1046. // function is:
  1047. //
  1048. // CSC(number)
  1049. //
  1050. func (fn *formulaFuncs) CSC(argsList *list.List) (result string, err error) {
  1051. if argsList.Len() != 1 {
  1052. err = errors.New("CSC requires 1 numeric argument")
  1053. return
  1054. }
  1055. var val float64
  1056. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1057. return
  1058. }
  1059. if val == 0 {
  1060. err = errors.New(formulaErrorNAME)
  1061. return
  1062. }
  1063. result = fmt.Sprintf("%g", 1/math.Sin(val))
  1064. return
  1065. }
  1066. // CSCH function calculates the hyperbolic cosecant (csch) of a supplied
  1067. // angle. The syntax of the function is:
  1068. //
  1069. // CSCH(number)
  1070. //
  1071. func (fn *formulaFuncs) CSCH(argsList *list.List) (result string, err error) {
  1072. if argsList.Len() != 1 {
  1073. err = errors.New("CSCH requires 1 numeric argument")
  1074. return
  1075. }
  1076. var val float64
  1077. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1078. return
  1079. }
  1080. if val == 0 {
  1081. err = errors.New(formulaErrorNAME)
  1082. return
  1083. }
  1084. result = fmt.Sprintf("%g", 1/math.Sinh(val))
  1085. return
  1086. }
  1087. // DECIMAL function converts a text representation of a number in a specified
  1088. // base, into a decimal value. The syntax of the function is:
  1089. //
  1090. // DECIMAL(text,radix)
  1091. //
  1092. func (fn *formulaFuncs) DECIMAL(argsList *list.List) (result string, err error) {
  1093. if argsList.Len() != 2 {
  1094. err = errors.New("DECIMAL requires 2 numeric arguments")
  1095. return
  1096. }
  1097. var text = argsList.Front().Value.(formulaArg).Value
  1098. var radix int
  1099. if radix, err = strconv.Atoi(argsList.Back().Value.(formulaArg).Value); err != nil {
  1100. return
  1101. }
  1102. if len(text) > 2 && (strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X")) {
  1103. text = text[2:]
  1104. }
  1105. val, err := strconv.ParseInt(text, radix, 64)
  1106. if err != nil {
  1107. err = errors.New(formulaErrorNUM)
  1108. return
  1109. }
  1110. result = fmt.Sprintf("%g", float64(val))
  1111. return
  1112. }
  1113. // DEGREES function converts radians into degrees. The syntax of the function
  1114. // is:
  1115. //
  1116. // DEGREES(angle)
  1117. //
  1118. func (fn *formulaFuncs) DEGREES(argsList *list.List) (result string, err error) {
  1119. if argsList.Len() != 1 {
  1120. err = errors.New("DEGREES requires 1 numeric argument")
  1121. return
  1122. }
  1123. var val float64
  1124. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1125. return
  1126. }
  1127. if val == 0 {
  1128. err = errors.New(formulaErrorNAME)
  1129. return
  1130. }
  1131. result = fmt.Sprintf("%g", 180.0/math.Pi*val)
  1132. return
  1133. }
  1134. // EVEN function rounds a supplied number away from zero (i.e. rounds a
  1135. // positive number up and a negative number down), to the next even number.
  1136. // The syntax of the function is:
  1137. //
  1138. // EVEN(number)
  1139. //
  1140. func (fn *formulaFuncs) EVEN(argsList *list.List) (result string, err error) {
  1141. if argsList.Len() != 1 {
  1142. err = errors.New("EVEN requires 1 numeric argument")
  1143. return
  1144. }
  1145. var number float64
  1146. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1147. return
  1148. }
  1149. sign := math.Signbit(number)
  1150. m, frac := math.Modf(number / 2)
  1151. val := m * 2
  1152. if frac != 0 {
  1153. if !sign {
  1154. val += 2
  1155. } else {
  1156. val -= 2
  1157. }
  1158. }
  1159. result = fmt.Sprintf("%g", val)
  1160. return
  1161. }
  1162. // EXP function calculates the value of the mathematical constant e, raised to
  1163. // the power of a given number. The syntax of the function is:
  1164. //
  1165. // EXP(number)
  1166. //
  1167. func (fn *formulaFuncs) EXP(argsList *list.List) (result string, err error) {
  1168. if argsList.Len() != 1 {
  1169. err = errors.New("EXP requires 1 numeric argument")
  1170. return
  1171. }
  1172. var number float64
  1173. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1174. return
  1175. }
  1176. result = strings.ToUpper(fmt.Sprintf("%g", math.Exp(number)))
  1177. return
  1178. }
  1179. // fact returns the factorial of a supplied number.
  1180. func fact(number float64) float64 {
  1181. val := float64(1)
  1182. for i := float64(2); i <= number; i++ {
  1183. val *= i
  1184. }
  1185. return val
  1186. }
  1187. // FACT function returns the factorial of a supplied number. The syntax of the
  1188. // function is:
  1189. //
  1190. // FACT(number)
  1191. //
  1192. func (fn *formulaFuncs) FACT(argsList *list.List) (result string, err error) {
  1193. if argsList.Len() != 1 {
  1194. err = errors.New("FACT requires 1 numeric argument")
  1195. return
  1196. }
  1197. var number float64
  1198. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1199. return
  1200. }
  1201. if number < 0 {
  1202. err = errors.New(formulaErrorNUM)
  1203. }
  1204. result = strings.ToUpper(fmt.Sprintf("%g", fact(number)))
  1205. return
  1206. }
  1207. // FACTDOUBLE function returns the double factorial of a supplied number. The
  1208. // syntax of the function is:
  1209. //
  1210. // FACTDOUBLE(number)
  1211. //
  1212. func (fn *formulaFuncs) FACTDOUBLE(argsList *list.List) (result string, err error) {
  1213. if argsList.Len() != 1 {
  1214. err = errors.New("FACTDOUBLE requires 1 numeric argument")
  1215. return
  1216. }
  1217. var number, val float64 = 0, 1
  1218. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1219. return
  1220. }
  1221. if number < 0 {
  1222. err = errors.New(formulaErrorNUM)
  1223. }
  1224. for i := math.Trunc(number); i > 1; i -= 2 {
  1225. val *= i
  1226. }
  1227. result = strings.ToUpper(fmt.Sprintf("%g", val))
  1228. return
  1229. }
  1230. // FLOOR function rounds a supplied number towards zero to the nearest
  1231. // multiple of a specified significance. The syntax of the function is:
  1232. //
  1233. // FLOOR(number,significance)
  1234. //
  1235. func (fn *formulaFuncs) FLOOR(argsList *list.List) (result string, err error) {
  1236. if argsList.Len() != 2 {
  1237. err = errors.New("FLOOR requires 2 numeric arguments")
  1238. return
  1239. }
  1240. var number, significance float64 = 0, 1
  1241. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1242. return
  1243. }
  1244. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  1245. return
  1246. }
  1247. if significance < 0 && number >= 0 {
  1248. err = errors.New(formulaErrorNUM)
  1249. }
  1250. val := number
  1251. val, res := math.Modf(val / significance)
  1252. if res != 0 {
  1253. if number < 0 && res < 0 {
  1254. val--
  1255. }
  1256. }
  1257. result = strings.ToUpper(fmt.Sprintf("%g", val*significance))
  1258. return
  1259. }
  1260. // FLOORMATH function rounds a supplied number down to a supplied multiple of
  1261. // significance. The syntax of the function is:
  1262. //
  1263. // FLOOR.MATH(number,[significance],[mode])
  1264. //
  1265. func (fn *formulaFuncs) FLOORMATH(argsList *list.List) (result string, err error) {
  1266. if argsList.Len() == 0 {
  1267. err = errors.New("FLOOR.MATH requires at least 1 argument")
  1268. return
  1269. }
  1270. if argsList.Len() > 3 {
  1271. err = errors.New("FLOOR.MATH allows at most 3 arguments")
  1272. return
  1273. }
  1274. var number, significance, mode float64 = 0, 1, 1
  1275. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1276. return
  1277. }
  1278. if number < 0 {
  1279. significance = -1
  1280. }
  1281. if argsList.Len() > 1 {
  1282. if significance, err = strconv.ParseFloat(argsList.Front().Next().Value.(formulaArg).Value, 64); err != nil {
  1283. return
  1284. }
  1285. }
  1286. if argsList.Len() == 1 {
  1287. result = fmt.Sprintf("%g", math.Floor(number))
  1288. return
  1289. }
  1290. if argsList.Len() > 2 {
  1291. if mode, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  1292. return
  1293. }
  1294. }
  1295. val, res := math.Modf(number / significance)
  1296. if res != 0 && number < 0 && mode > 0 {
  1297. val--
  1298. }
  1299. result = fmt.Sprintf("%g", val*significance)
  1300. return
  1301. }
  1302. // FLOORPRECISE function rounds a supplied number down to a supplied multiple
  1303. // of significance. The syntax of the function is:
  1304. //
  1305. // FLOOR.PRECISE(number,[significance])
  1306. //
  1307. func (fn *formulaFuncs) FLOORPRECISE(argsList *list.List) (result string, err error) {
  1308. if argsList.Len() == 0 {
  1309. err = errors.New("FLOOR.PRECISE requires at least 1 argument")
  1310. return
  1311. }
  1312. if argsList.Len() > 2 {
  1313. err = errors.New("FLOOR.PRECISE allows at most 2 arguments")
  1314. return
  1315. }
  1316. var number, significance float64 = 0, 1
  1317. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1318. return
  1319. }
  1320. if number < 0 {
  1321. significance = -1
  1322. }
  1323. if argsList.Len() == 1 {
  1324. result = fmt.Sprintf("%g", math.Floor(number))
  1325. return
  1326. }
  1327. if argsList.Len() > 1 {
  1328. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  1329. return
  1330. }
  1331. significance = math.Abs(significance)
  1332. if significance == 0 {
  1333. result = "0"
  1334. return
  1335. }
  1336. }
  1337. val, res := math.Modf(number / significance)
  1338. if res != 0 {
  1339. if number < 0 {
  1340. val--
  1341. }
  1342. }
  1343. result = fmt.Sprintf("%g", val*significance)
  1344. return
  1345. }
  1346. // GCD function returns the greatest common divisor of two or more supplied
  1347. // integers. The syntax of the function is:
  1348. //
  1349. // GCD(number1,[number2],...)
  1350. //
  1351. func (fn *formulaFuncs) GCD(argsList *list.List) (result string, err error) {
  1352. if argsList.Len() == 0 {
  1353. err = errors.New("GCD requires at least 1 argument")
  1354. return
  1355. }
  1356. var (
  1357. val float64
  1358. nums = []float64{}
  1359. )
  1360. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  1361. token := arg.Value.(formulaArg).Value
  1362. if token == "" {
  1363. continue
  1364. }
  1365. if val, err = strconv.ParseFloat(token, 64); err != nil {
  1366. return
  1367. }
  1368. nums = append(nums, val)
  1369. }
  1370. if nums[0] < 0 {
  1371. err = errors.New("GCD only accepts positive arguments")
  1372. return
  1373. }
  1374. if len(nums) == 1 {
  1375. result = fmt.Sprintf("%g", nums[0])
  1376. return
  1377. }
  1378. cd := nums[0]
  1379. for i := 1; i < len(nums); i++ {
  1380. if nums[i] < 0 {
  1381. err = errors.New("GCD only accepts positive arguments")
  1382. return
  1383. }
  1384. cd = gcd(cd, nums[i])
  1385. }
  1386. result = fmt.Sprintf("%g", cd)
  1387. return
  1388. }
  1389. // INT function truncates a supplied number down to the closest integer. The
  1390. // syntax of the function is:
  1391. //
  1392. // INT(number)
  1393. //
  1394. func (fn *formulaFuncs) INT(argsList *list.List) (result string, err error) {
  1395. if argsList.Len() != 1 {
  1396. err = errors.New("INT requires 1 numeric argument")
  1397. return
  1398. }
  1399. var number float64
  1400. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1401. return
  1402. }
  1403. val, frac := math.Modf(number)
  1404. if frac < 0 {
  1405. val--
  1406. }
  1407. result = fmt.Sprintf("%g", val)
  1408. return
  1409. }
  1410. // ISOCEILING function rounds a supplied number up (regardless of the number's
  1411. // sign), to the nearest multiple of a supplied significance. The syntax of
  1412. // the function is:
  1413. //
  1414. // ISO.CEILING(number,[significance])
  1415. //
  1416. func (fn *formulaFuncs) ISOCEILING(argsList *list.List) (result string, err error) {
  1417. if argsList.Len() == 0 {
  1418. err = errors.New("ISO.CEILING requires at least 1 argument")
  1419. return
  1420. }
  1421. if argsList.Len() > 2 {
  1422. err = errors.New("ISO.CEILING allows at most 2 arguments")
  1423. return
  1424. }
  1425. var number, significance float64 = 0, 1
  1426. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1427. return
  1428. }
  1429. if number < 0 {
  1430. significance = -1
  1431. }
  1432. if argsList.Len() == 1 {
  1433. result = fmt.Sprintf("%g", math.Ceil(number))
  1434. return
  1435. }
  1436. if argsList.Len() > 1 {
  1437. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  1438. return
  1439. }
  1440. significance = math.Abs(significance)
  1441. if significance == 0 {
  1442. result = "0"
  1443. return
  1444. }
  1445. }
  1446. val, res := math.Modf(number / significance)
  1447. if res != 0 {
  1448. if number > 0 {
  1449. val++
  1450. }
  1451. }
  1452. result = fmt.Sprintf("%g", val*significance)
  1453. return
  1454. }
  1455. // lcm returns the least common multiple of two supplied integers.
  1456. func lcm(a, b float64) float64 {
  1457. a = math.Trunc(a)
  1458. b = math.Trunc(b)
  1459. if a == 0 && b == 0 {
  1460. return 0
  1461. }
  1462. return a * b / gcd(a, b)
  1463. }
  1464. // LCM function returns the least common multiple of two or more supplied
  1465. // integers. The syntax of the function is:
  1466. //
  1467. // LCM(number1,[number2],...)
  1468. //
  1469. func (fn *formulaFuncs) LCM(argsList *list.List) (result string, err error) {
  1470. if argsList.Len() == 0 {
  1471. err = errors.New("LCM requires at least 1 argument")
  1472. return
  1473. }
  1474. var (
  1475. val float64
  1476. nums = []float64{}
  1477. )
  1478. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  1479. token := arg.Value.(formulaArg).Value
  1480. if token == "" {
  1481. continue
  1482. }
  1483. if val, err = strconv.ParseFloat(token, 64); err != nil {
  1484. return
  1485. }
  1486. nums = append(nums, val)
  1487. }
  1488. if nums[0] < 0 {
  1489. err = errors.New("LCM only accepts positive arguments")
  1490. return
  1491. }
  1492. if len(nums) == 1 {
  1493. result = fmt.Sprintf("%g", nums[0])
  1494. return
  1495. }
  1496. cm := nums[0]
  1497. for i := 1; i < len(nums); i++ {
  1498. if nums[i] < 0 {
  1499. err = errors.New("LCM only accepts positive arguments")
  1500. return
  1501. }
  1502. cm = lcm(cm, nums[i])
  1503. }
  1504. result = fmt.Sprintf("%g", cm)
  1505. return
  1506. }
  1507. // LN function calculates the natural logarithm of a given number. The syntax
  1508. // of the function is:
  1509. //
  1510. // LN(number)
  1511. //
  1512. func (fn *formulaFuncs) LN(argsList *list.List) (result string, err error) {
  1513. if argsList.Len() != 1 {
  1514. err = errors.New("LN requires 1 numeric argument")
  1515. return
  1516. }
  1517. var number float64
  1518. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1519. return
  1520. }
  1521. result = fmt.Sprintf("%g", math.Log(number))
  1522. return
  1523. }
  1524. // LOG function calculates the logarithm of a given number, to a supplied
  1525. // base. The syntax of the function is:
  1526. //
  1527. // LOG(number,[base])
  1528. //
  1529. func (fn *formulaFuncs) LOG(argsList *list.List) (result string, err error) {
  1530. if argsList.Len() == 0 {
  1531. err = errors.New("LOG requires at least 1 argument")
  1532. return
  1533. }
  1534. if argsList.Len() > 2 {
  1535. err = errors.New("LOG allows at most 2 arguments")
  1536. return
  1537. }
  1538. var number, base float64 = 0, 10
  1539. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1540. return
  1541. }
  1542. if argsList.Len() > 1 {
  1543. if base, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  1544. return
  1545. }
  1546. }
  1547. if number == 0 {
  1548. err = errors.New(formulaErrorNUM)
  1549. return
  1550. }
  1551. if base == 0 {
  1552. err = errors.New(formulaErrorNUM)
  1553. return
  1554. }
  1555. if base == 1 {
  1556. err = errors.New(formulaErrorDIV)
  1557. return
  1558. }
  1559. result = fmt.Sprintf("%g", math.Log(number)/math.Log(base))
  1560. return
  1561. }
  1562. // LOG10 function calculates the base 10 logarithm of a given number. The
  1563. // syntax of the function is:
  1564. //
  1565. // LOG10(number)
  1566. //
  1567. func (fn *formulaFuncs) LOG10(argsList *list.List) (result string, err error) {
  1568. if argsList.Len() != 1 {
  1569. err = errors.New("LOG10 requires 1 numeric argument")
  1570. return
  1571. }
  1572. var number float64
  1573. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1574. return
  1575. }
  1576. result = fmt.Sprintf("%g", math.Log10(number))
  1577. return
  1578. }
  1579. func minor(sqMtx [][]float64, idx int) [][]float64 {
  1580. ret := [][]float64{}
  1581. for i := range sqMtx {
  1582. if i == 0 {
  1583. continue
  1584. }
  1585. row := []float64{}
  1586. for j := range sqMtx {
  1587. if j == idx {
  1588. continue
  1589. }
  1590. row = append(row, sqMtx[i][j])
  1591. }
  1592. ret = append(ret, row)
  1593. }
  1594. return ret
  1595. }
  1596. // det determinant of the 2x2 matrix.
  1597. func det(sqMtx [][]float64) float64 {
  1598. if len(sqMtx) == 2 {
  1599. m00 := sqMtx[0][0]
  1600. m01 := sqMtx[0][1]
  1601. m10 := sqMtx[1][0]
  1602. m11 := sqMtx[1][1]
  1603. return m00*m11 - m10*m01
  1604. }
  1605. var res, sgn float64 = 0, 1
  1606. for j := range sqMtx {
  1607. res += sgn * sqMtx[0][j] * det(minor(sqMtx, j))
  1608. sgn *= -1
  1609. }
  1610. return res
  1611. }
  1612. // MDETERM calculates the determinant of a square matrix. The
  1613. // syntax of the function is:
  1614. //
  1615. // MDETERM(array)
  1616. //
  1617. func (fn *formulaFuncs) MDETERM(argsList *list.List) (result string, err error) {
  1618. var num float64
  1619. var rows int
  1620. var numMtx = [][]float64{}
  1621. var strMtx = [][]string{}
  1622. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  1623. if len(arg.Value.(formulaArg).Matrix) == 0 {
  1624. break
  1625. }
  1626. strMtx = append(strMtx, arg.Value.(formulaArg).Matrix)
  1627. rows++
  1628. }
  1629. for _, row := range strMtx {
  1630. if len(row) != rows {
  1631. err = errors.New(formulaErrorVALUE)
  1632. return
  1633. }
  1634. numRow := []float64{}
  1635. for _, ele := range row {
  1636. if num, err = strconv.ParseFloat(ele, 64); err != nil {
  1637. return
  1638. }
  1639. numRow = append(numRow, num)
  1640. }
  1641. numMtx = append(numMtx, numRow)
  1642. }
  1643. result = fmt.Sprintf("%g", det(numMtx))
  1644. return
  1645. }
  1646. // MOD function returns the remainder of a division between two supplied
  1647. // numbers. The syntax of the function is:
  1648. //
  1649. // MOD(number,divisor)
  1650. //
  1651. func (fn *formulaFuncs) MOD(argsList *list.List) (result string, err error) {
  1652. if argsList.Len() != 2 {
  1653. err = errors.New("MOD requires 2 numeric arguments")
  1654. return
  1655. }
  1656. var number, divisor float64
  1657. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1658. return
  1659. }
  1660. if divisor, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  1661. return
  1662. }
  1663. if divisor == 0 {
  1664. err = errors.New(formulaErrorDIV)
  1665. return
  1666. }
  1667. trunc, rem := math.Modf(number / divisor)
  1668. if rem < 0 {
  1669. trunc--
  1670. }
  1671. result = fmt.Sprintf("%g", number-divisor*trunc)
  1672. return
  1673. }
  1674. // MROUND function rounds a supplied number up or down to the nearest multiple
  1675. // of a given number. The syntax of the function is:
  1676. //
  1677. // MOD(number,multiple)
  1678. //
  1679. func (fn *formulaFuncs) MROUND(argsList *list.List) (result string, err error) {
  1680. if argsList.Len() != 2 {
  1681. err = errors.New("MROUND requires 2 numeric arguments")
  1682. return
  1683. }
  1684. var number, multiple float64 = 0, 1
  1685. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1686. return
  1687. }
  1688. if multiple, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  1689. return
  1690. }
  1691. if multiple == 0 {
  1692. err = errors.New(formulaErrorNUM)
  1693. return
  1694. }
  1695. if multiple < 0 && number > 0 ||
  1696. multiple > 0 && number < 0 {
  1697. err = errors.New(formulaErrorNUM)
  1698. return
  1699. }
  1700. number, res := math.Modf(number / multiple)
  1701. if math.Trunc(res+0.5) > 0 {
  1702. number++
  1703. }
  1704. result = fmt.Sprintf("%g", number*multiple)
  1705. return
  1706. }
  1707. // MULTINOMIAL function calculates the ratio of the factorial of a sum of
  1708. // supplied values to the product of factorials of those values. The syntax of
  1709. // the function is:
  1710. //
  1711. // MULTINOMIAL(number1,[number2],...)
  1712. //
  1713. func (fn *formulaFuncs) MULTINOMIAL(argsList *list.List) (result string, err error) {
  1714. var val, num, denom float64 = 0, 0, 1
  1715. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  1716. token := arg.Value.(formulaArg)
  1717. if token.Value == "" {
  1718. continue
  1719. }
  1720. if val, err = strconv.ParseFloat(token.Value, 64); err != nil {
  1721. return
  1722. }
  1723. num += val
  1724. denom *= fact(val)
  1725. }
  1726. result = fmt.Sprintf("%g", fact(num)/denom)
  1727. return
  1728. }
  1729. // MUNIT function returns the unit matrix for a specified dimension. The
  1730. // syntax of the function is:
  1731. //
  1732. // MUNIT(dimension)
  1733. //
  1734. func (fn *formulaFuncs) MUNIT(argsList *list.List) (result string, err error) {
  1735. if argsList.Len() != 1 {
  1736. err = errors.New("MUNIT requires 1 numeric argument")
  1737. return
  1738. }
  1739. var dimension int
  1740. if dimension, err = strconv.Atoi(argsList.Front().Value.(formulaArg).Value); err != nil {
  1741. return
  1742. }
  1743. matrix := make([][]float64, 0, dimension)
  1744. for i := 0; i < dimension; i++ {
  1745. row := make([]float64, dimension)
  1746. for j := 0; j < dimension; j++ {
  1747. if i == j {
  1748. row[j] = float64(1.0)
  1749. } else {
  1750. row[j] = float64(0.0)
  1751. }
  1752. }
  1753. matrix = append(matrix, row)
  1754. }
  1755. return
  1756. }
  1757. // ODD function ounds a supplied number away from zero (i.e. rounds a positive
  1758. // number up and a negative number down), to the next odd number. The syntax
  1759. // of the function is:
  1760. //
  1761. // ODD(number)
  1762. //
  1763. func (fn *formulaFuncs) ODD(argsList *list.List) (result string, err error) {
  1764. if argsList.Len() != 1 {
  1765. err = errors.New("ODD requires 1 numeric argument")
  1766. return
  1767. }
  1768. var number float64
  1769. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1770. return
  1771. }
  1772. if number == 0 {
  1773. result = "1"
  1774. return
  1775. }
  1776. sign := math.Signbit(number)
  1777. m, frac := math.Modf((number - 1) / 2)
  1778. val := m*2 + 1
  1779. if frac != 0 {
  1780. if !sign {
  1781. val += 2
  1782. } else {
  1783. val -= 2
  1784. }
  1785. }
  1786. result = fmt.Sprintf("%g", val)
  1787. return
  1788. }
  1789. // PI function returns the value of the mathematical constant π (pi), accurate
  1790. // to 15 digits (14 decimal places). The syntax of the function is:
  1791. //
  1792. // PI()
  1793. //
  1794. func (fn *formulaFuncs) PI(argsList *list.List) (result string, err error) {
  1795. if argsList.Len() != 0 {
  1796. err = errors.New("PI accepts no arguments")
  1797. return
  1798. }
  1799. result = fmt.Sprintf("%g", math.Pi)
  1800. return
  1801. }
  1802. // POWER function calculates a given number, raised to a supplied power.
  1803. // The syntax of the function is:
  1804. //
  1805. // POWER(number,power)
  1806. //
  1807. func (fn *formulaFuncs) POWER(argsList *list.List) (result string, err error) {
  1808. if argsList.Len() != 2 {
  1809. err = errors.New("POWER requires 2 numeric arguments")
  1810. return
  1811. }
  1812. var x, y float64
  1813. if x, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1814. return
  1815. }
  1816. if y, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  1817. return
  1818. }
  1819. if x == 0 && y == 0 {
  1820. err = errors.New(formulaErrorNUM)
  1821. return
  1822. }
  1823. if x == 0 && y < 0 {
  1824. err = errors.New(formulaErrorDIV)
  1825. return
  1826. }
  1827. result = fmt.Sprintf("%g", math.Pow(x, y))
  1828. return
  1829. }
  1830. // PRODUCT function returns the product (multiplication) of a supplied set of
  1831. // numerical values. The syntax of the function is:
  1832. //
  1833. // PRODUCT(number1,[number2],...)
  1834. //
  1835. func (fn *formulaFuncs) PRODUCT(argsList *list.List) (result string, err error) {
  1836. var val, product float64 = 0, 1
  1837. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  1838. token := arg.Value.(formulaArg)
  1839. if token.Value == "" {
  1840. continue
  1841. }
  1842. if val, err = strconv.ParseFloat(token.Value, 64); err != nil {
  1843. return
  1844. }
  1845. product = product * val
  1846. }
  1847. result = fmt.Sprintf("%g", product)
  1848. return
  1849. }
  1850. // QUOTIENT function returns the integer portion of a division between two
  1851. // supplied numbers. The syntax of the function is:
  1852. //
  1853. // QUOTIENT(numerator,denominator)
  1854. //
  1855. func (fn *formulaFuncs) QUOTIENT(argsList *list.List) (result string, err error) {
  1856. if argsList.Len() != 2 {
  1857. err = errors.New("QUOTIENT requires 2 numeric arguments")
  1858. return
  1859. }
  1860. var x, y float64
  1861. if x, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1862. return
  1863. }
  1864. if y, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  1865. return
  1866. }
  1867. if y == 0 {
  1868. err = errors.New(formulaErrorDIV)
  1869. return
  1870. }
  1871. result = fmt.Sprintf("%g", math.Trunc(x/y))
  1872. return
  1873. }
  1874. // RADIANS function converts radians into degrees. The syntax of the function is:
  1875. //
  1876. // RADIANS(angle)
  1877. //
  1878. func (fn *formulaFuncs) RADIANS(argsList *list.List) (result string, err error) {
  1879. if argsList.Len() != 1 {
  1880. err = errors.New("RADIANS requires 1 numeric argument")
  1881. return
  1882. }
  1883. var angle float64
  1884. if angle, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1885. return
  1886. }
  1887. result = fmt.Sprintf("%g", math.Pi/180.0*angle)
  1888. return
  1889. }
  1890. // RAND function generates a random real number between 0 and 1. The syntax of
  1891. // the function is:
  1892. //
  1893. // RAND()
  1894. //
  1895. func (fn *formulaFuncs) RAND(argsList *list.List) (result string, err error) {
  1896. if argsList.Len() != 0 {
  1897. err = errors.New("RAND accepts no arguments")
  1898. return
  1899. }
  1900. result = fmt.Sprintf("%g", rand.New(rand.NewSource(time.Now().UnixNano())).Float64())
  1901. return
  1902. }
  1903. // RANDBETWEEN function generates a random integer between two supplied
  1904. // integers. The syntax of the function is:
  1905. //
  1906. // RANDBETWEEN(bottom,top)
  1907. //
  1908. func (fn *formulaFuncs) RANDBETWEEN(argsList *list.List) (result string, err error) {
  1909. if argsList.Len() != 2 {
  1910. err = errors.New("RANDBETWEEN requires 2 numeric arguments")
  1911. return
  1912. }
  1913. var bottom, top int64
  1914. if bottom, err = strconv.ParseInt(argsList.Front().Value.(formulaArg).Value, 10, 64); err != nil {
  1915. return
  1916. }
  1917. if top, err = strconv.ParseInt(argsList.Back().Value.(formulaArg).Value, 10, 64); err != nil {
  1918. return
  1919. }
  1920. if top < bottom {
  1921. err = errors.New(formulaErrorNUM)
  1922. return
  1923. }
  1924. result = fmt.Sprintf("%g", float64(rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(top-bottom+1)+bottom))
  1925. return
  1926. }
  1927. // romanNumerals defined a numeral system that originated in ancient Rome and
  1928. // remained the usual way of writing numbers throughout Europe well into the
  1929. // Late Middle Ages.
  1930. type romanNumerals struct {
  1931. n float64
  1932. s string
  1933. }
  1934. var romanTable = [][]romanNumerals{{{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
  1935. {{1000, "M"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {95, "VC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
  1936. {{1000, "M"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
  1937. {{1000, "M"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
  1938. {{1000, "M"}, {999, "IM"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {499, "ID"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}}}
  1939. // ROMAN function converts an arabic number to Roman. I.e. for a supplied
  1940. // integer, the function returns a text string depicting the roman numeral
  1941. // form of the number. The syntax of the function is:
  1942. //
  1943. // ROMAN(number,[form])
  1944. //
  1945. func (fn *formulaFuncs) ROMAN(argsList *list.List) (result string, err error) {
  1946. if argsList.Len() == 0 {
  1947. err = errors.New("ROMAN requires at least 1 argument")
  1948. return
  1949. }
  1950. if argsList.Len() > 2 {
  1951. err = errors.New("ROMAN allows at most 2 arguments")
  1952. return
  1953. }
  1954. var number float64
  1955. var form int
  1956. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  1957. return
  1958. }
  1959. if argsList.Len() > 1 {
  1960. if form, err = strconv.Atoi(argsList.Back().Value.(formulaArg).Value); err != nil {
  1961. return
  1962. }
  1963. if form < 0 {
  1964. form = 0
  1965. } else if form > 4 {
  1966. form = 4
  1967. }
  1968. }
  1969. decimalTable := romanTable[0]
  1970. switch form {
  1971. case 1:
  1972. decimalTable = romanTable[1]
  1973. case 2:
  1974. decimalTable = romanTable[2]
  1975. case 3:
  1976. decimalTable = romanTable[3]
  1977. case 4:
  1978. decimalTable = romanTable[4]
  1979. }
  1980. val := math.Trunc(number)
  1981. buf := bytes.Buffer{}
  1982. for _, r := range decimalTable {
  1983. for val >= r.n {
  1984. buf.WriteString(r.s)
  1985. val -= r.n
  1986. }
  1987. }
  1988. result = buf.String()
  1989. return
  1990. }
  1991. type roundMode byte
  1992. const (
  1993. closest roundMode = iota
  1994. down
  1995. up
  1996. )
  1997. // round rounds a supplied number up or down.
  1998. func (fn *formulaFuncs) round(number, digits float64, mode roundMode) float64 {
  1999. significance := 1.0
  2000. if digits > 0 {
  2001. significance = math.Pow(1/10.0, digits)
  2002. } else {
  2003. significance = math.Pow(10.0, -digits)
  2004. }
  2005. val, res := math.Modf(number / significance)
  2006. switch mode {
  2007. case closest:
  2008. const eps = 0.499999999
  2009. if res >= eps {
  2010. val++
  2011. } else if res <= -eps {
  2012. val--
  2013. }
  2014. case down:
  2015. case up:
  2016. if res > 0 {
  2017. val++
  2018. } else if res < 0 {
  2019. val--
  2020. }
  2021. }
  2022. return val * significance
  2023. }
  2024. // ROUND function rounds a supplied number up or down, to a specified number
  2025. // of decimal places. The syntax of the function is:
  2026. //
  2027. // ROUND(number,num_digits)
  2028. //
  2029. func (fn *formulaFuncs) ROUND(argsList *list.List) (result string, err error) {
  2030. if argsList.Len() != 2 {
  2031. err = errors.New("ROUND requires 2 numeric arguments")
  2032. return
  2033. }
  2034. var number, digits float64
  2035. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2036. return
  2037. }
  2038. if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  2039. return
  2040. }
  2041. result = fmt.Sprintf("%g", fn.round(number, digits, closest))
  2042. return
  2043. }
  2044. // ROUNDDOWN function rounds a supplied number down towards zero, to a
  2045. // specified number of decimal places. The syntax of the function is:
  2046. //
  2047. // ROUNDDOWN(number,num_digits)
  2048. //
  2049. func (fn *formulaFuncs) ROUNDDOWN(argsList *list.List) (result string, err error) {
  2050. if argsList.Len() != 2 {
  2051. err = errors.New("ROUNDDOWN requires 2 numeric arguments")
  2052. return
  2053. }
  2054. var number, digits float64
  2055. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2056. return
  2057. }
  2058. if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  2059. return
  2060. }
  2061. result = fmt.Sprintf("%g", fn.round(number, digits, down))
  2062. return
  2063. }
  2064. // ROUNDUP function rounds a supplied number up, away from zero, to a
  2065. // specified number of decimal places. The syntax of the function is:
  2066. //
  2067. // ROUNDUP(number,num_digits)
  2068. //
  2069. func (fn *formulaFuncs) ROUNDUP(argsList *list.List) (result string, err error) {
  2070. if argsList.Len() != 2 {
  2071. err = errors.New("ROUNDUP requires 2 numeric arguments")
  2072. return
  2073. }
  2074. var number, digits float64
  2075. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2076. return
  2077. }
  2078. if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  2079. return
  2080. }
  2081. result = fmt.Sprintf("%g", fn.round(number, digits, up))
  2082. return
  2083. }
  2084. // SEC function calculates the secant of a given angle. The syntax of the
  2085. // function is:
  2086. //
  2087. // SEC(number)
  2088. //
  2089. func (fn *formulaFuncs) SEC(argsList *list.List) (result string, err error) {
  2090. if argsList.Len() != 1 {
  2091. err = errors.New("SEC requires 1 numeric argument")
  2092. return
  2093. }
  2094. var number float64
  2095. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2096. return
  2097. }
  2098. result = fmt.Sprintf("%g", math.Cos(number))
  2099. return
  2100. }
  2101. // SECH function calculates the hyperbolic secant (sech) of a supplied angle.
  2102. // The syntax of the function is:
  2103. //
  2104. // SECH(number)
  2105. //
  2106. func (fn *formulaFuncs) SECH(argsList *list.List) (result string, err error) {
  2107. if argsList.Len() != 1 {
  2108. err = errors.New("SECH requires 1 numeric argument")
  2109. return
  2110. }
  2111. var number float64
  2112. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2113. return
  2114. }
  2115. result = fmt.Sprintf("%g", 1/math.Cosh(number))
  2116. return
  2117. }
  2118. // SIGN function returns the arithmetic sign (+1, -1 or 0) of a supplied
  2119. // number. I.e. if the number is positive, the Sign function returns +1, if
  2120. // the number is negative, the function returns -1 and if the number is 0
  2121. // (zero), the function returns 0. The syntax of the function is:
  2122. //
  2123. // SIGN(number)
  2124. //
  2125. func (fn *formulaFuncs) SIGN(argsList *list.List) (result string, err error) {
  2126. if argsList.Len() != 1 {
  2127. err = errors.New("SIGN requires 1 numeric argument")
  2128. return
  2129. }
  2130. var val float64
  2131. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2132. return
  2133. }
  2134. if val < 0 {
  2135. result = "-1"
  2136. return
  2137. }
  2138. if val > 0 {
  2139. result = "1"
  2140. return
  2141. }
  2142. result = "0"
  2143. return
  2144. }
  2145. // SIN function calculates the sine of a given angle. The syntax of the
  2146. // function is:
  2147. //
  2148. // SIN(number)
  2149. //
  2150. func (fn *formulaFuncs) SIN(argsList *list.List) (result string, err error) {
  2151. if argsList.Len() != 1 {
  2152. err = errors.New("SIN requires 1 numeric argument")
  2153. return
  2154. }
  2155. var number float64
  2156. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2157. return
  2158. }
  2159. result = fmt.Sprintf("%g", math.Sin(number))
  2160. return
  2161. }
  2162. // SINH function calculates the hyperbolic sine (sinh) of a supplied number.
  2163. // The syntax of the function is:
  2164. //
  2165. // SINH(number)
  2166. //
  2167. func (fn *formulaFuncs) SINH(argsList *list.List) (result string, err error) {
  2168. if argsList.Len() != 1 {
  2169. err = errors.New("SINH requires 1 numeric argument")
  2170. return
  2171. }
  2172. var number float64
  2173. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2174. return
  2175. }
  2176. result = fmt.Sprintf("%g", math.Sinh(number))
  2177. return
  2178. }
  2179. // SQRT function calculates the positive square root of a supplied number. The
  2180. // syntax of the function is:
  2181. //
  2182. // SQRT(number)
  2183. //
  2184. func (fn *formulaFuncs) SQRT(argsList *list.List) (result string, err error) {
  2185. if argsList.Len() != 1 {
  2186. err = errors.New("SQRT requires 1 numeric argument")
  2187. return
  2188. }
  2189. var res float64
  2190. var value = argsList.Front().Value.(formulaArg).Value
  2191. if value == "" {
  2192. result = "0"
  2193. return
  2194. }
  2195. if res, err = strconv.ParseFloat(value, 64); err != nil {
  2196. return
  2197. }
  2198. if res < 0 {
  2199. err = errors.New(formulaErrorNUM)
  2200. return
  2201. }
  2202. result = fmt.Sprintf("%g", math.Sqrt(res))
  2203. return
  2204. }
  2205. // SQRTPI function returns the square root of a supplied number multiplied by
  2206. // the mathematical constant, π. The syntax of the function is:
  2207. //
  2208. // SQRTPI(number)
  2209. //
  2210. func (fn *formulaFuncs) SQRTPI(argsList *list.List) (result string, err error) {
  2211. if argsList.Len() != 1 {
  2212. err = errors.New("SQRTPI requires 1 numeric argument")
  2213. return
  2214. }
  2215. var number float64
  2216. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2217. return
  2218. }
  2219. result = fmt.Sprintf("%g", math.Sqrt(number*math.Pi))
  2220. return
  2221. }
  2222. // SUM function adds together a supplied set of numbers and returns the sum of
  2223. // these values. The syntax of the function is:
  2224. //
  2225. // SUM(number1,[number2],...)
  2226. //
  2227. func (fn *formulaFuncs) SUM(argsList *list.List) (result string, err error) {
  2228. var val, sum float64
  2229. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  2230. token := arg.Value.(formulaArg)
  2231. if token.Value == "" {
  2232. continue
  2233. }
  2234. if val, err = strconv.ParseFloat(token.Value, 64); err != nil {
  2235. return
  2236. }
  2237. sum += val
  2238. }
  2239. result = fmt.Sprintf("%g", sum)
  2240. return
  2241. }
  2242. // TAN function calculates the tangent of a given angle. The syntax of the
  2243. // function is:
  2244. //
  2245. // TAN(number)
  2246. //
  2247. func (fn *formulaFuncs) TAN(argsList *list.List) (result string, err error) {
  2248. if argsList.Len() != 1 {
  2249. err = errors.New("TAN requires 1 numeric argument")
  2250. return
  2251. }
  2252. var number float64
  2253. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2254. return
  2255. }
  2256. result = fmt.Sprintf("%g", math.Tan(number))
  2257. return
  2258. }
  2259. // TANH function calculates the hyperbolic tangent (tanh) of a supplied
  2260. // number. The syntax of the function is:
  2261. //
  2262. // TANH(number)
  2263. //
  2264. func (fn *formulaFuncs) TANH(argsList *list.List) (result string, err error) {
  2265. if argsList.Len() != 1 {
  2266. err = errors.New("TANH requires 1 numeric argument")
  2267. return
  2268. }
  2269. var number float64
  2270. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2271. return
  2272. }
  2273. result = fmt.Sprintf("%g", math.Tanh(number))
  2274. return
  2275. }
  2276. // TRUNC function truncates a supplied number to a specified number of decimal
  2277. // places. The syntax of the function is:
  2278. //
  2279. // TRUNC(number,[number_digits])
  2280. //
  2281. func (fn *formulaFuncs) TRUNC(argsList *list.List) (result string, err error) {
  2282. if argsList.Len() == 0 {
  2283. err = errors.New("TRUNC requires at least 1 argument")
  2284. return
  2285. }
  2286. var number, digits, adjust, rtrim float64
  2287. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).Value, 64); err != nil {
  2288. return
  2289. }
  2290. if argsList.Len() > 1 {
  2291. if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).Value, 64); err != nil {
  2292. return
  2293. }
  2294. digits = math.Floor(digits)
  2295. }
  2296. adjust = math.Pow(10, digits)
  2297. x := int((math.Abs(number) - math.Abs(float64(int(number)))) * adjust)
  2298. if x != 0 {
  2299. if rtrim, err = strconv.ParseFloat(strings.TrimRight(strconv.Itoa(x), "0"), 64); err != nil {
  2300. return
  2301. }
  2302. }
  2303. if (digits > 0) && (rtrim < adjust/10) {
  2304. result = fmt.Sprintf("%g", number)
  2305. return
  2306. }
  2307. result = fmt.Sprintf("%g", float64(int(number*adjust))/adjust)
  2308. return
  2309. }