Debian Codegraph @

texmf-dist/tex/lualatex/luacas/algebra/luacas-factorialexpression.lua

raw
1 --- @class FactorialExpression
2 --- The factorial of an expression.
3 --- @field expression Expression
4 FactorialExpression = {}
5 local __FactorialExpression = {}
6
7 ----------------------------
8 -- Instance functionality --
9 ----------------------------
10
11 --- Creates a new factorial expression with the given expression.
12 --- @param expression Expression
13 --- @return FactorialExpression
14 function FactorialExpression:new(expression)
15 local o = {}
16 local __o = Copy(__ExpressionOperations)
17
18 o.expression = expression
19
20 __o.__index = FactorialExpression
21 __o.__tostring = function(a)
22 return '(' .. tostring(a.expression) .. ')!'
23 end
24
25 o = setmetatable(o, __o)
26 return o
27 end
28
29 --- @return Expression
30 function FactorialExpression:evaluate()
31 if self.expression:type() == Integer then
32 if self.expression < Integer.zero() then
33 error("Aritmetic Error: Factorials of negative integers are not defined.")
34 end
35
36 if not FactorialExpression.LIMIT then
37 FactorialExpression.LIMIT = Integer(5000)
38 end
39
40 if self.expression > FactorialExpression.LIMIT then
41 return self
42 end
43 -- TODO: More efficient factorial computations.
44 local out = Integer.one()
45 local i = Integer.zero()
46 while i < self.expression do
47 i = i + Integer.one()
48 out = out * i
49 end
50 return out
51 end
52 return self
53 end
54
55 --- @return Expression
56 function FactorialExpression:autosimplify()
57 return FactorialExpression(self.expression:autosimplify()):evaluate()
58 end
59
60 --- @return table<number, Expression>
61 function FactorialExpression:subexpressions()
62 return {self.expression}
63 end
64
65 --- @param subexpressions table<number, Expression>
66 --- @return AbsExpression
67 function FactorialExpression:setsubexpressions(subexpressions)
68 return FactorialExpression(subexpressions[1])
69 end
70
71 --- @param other Expression
72 --- @return boolean
73 function FactorialExpression:order(other)
74 return FunctionExpression("fact", self.expression):order(other)
75 end
76
77 --- @return string
78 function FactorialExpression:tolatex()
79 if self.expression:isatomic() then
80 return self.expression:tolatex() .. "!"
81 end
82 return "(" .. self.expression:tolatex() .. ")!"
83 end
84
85 -----------------
86 -- Inheritance --
87 -----------------
88
89 __FactorialExpression.__index = CompoundExpression
90 __FactorialExpression.__call = FactorialExpression.new
91 FactorialExpression = setmetatable(FactorialExpression, __FactorialExpression)
92
93 ----------------------
94 -- Static constants --
95 ----------------------
96
97 -- Do not attempt to compute factorials larger than this.
98 FactorialExpression.LIMIT = Integer(5000)
99
100 FACT = function (a)
101 return FactorialExpression(a)
102 end