Jump to content

Module talk:Math/Archive 1

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia
Archive 1

average

It could be useful to add the average function:

--[[
average 
 
Finds the average
 
Usage:
    {{#invoke:Math| average | value1 | value2 | ... }}
OR
    {{#invoke:Math| average }}
 
When used with no arguments, it takes its input from the parent
frame.  Note, any values that do not evaluate to numbers are ignored.
]]
function z.average( frame )
    local args = frame.args;
    if args[1] == nil then
        local parent = frame:getParent();
        args = parent.args;
    end
    local sum = 0;
    local count = 0;
 
    local i = 1;
    while args[i] ~= nil do
        local val = z._cleanNumber( frame, args[i] );
        if val ~= nil then
            sum = sum + val
            count = count + 1
        end        
        i = i + 1;
    end
 
    return (count == 0 and 0 or sum/count)
end

--DixonD (talk) 23:17, 23 March 2013 (UTC)

I added it in. Dragons flight (talk) 14:37, 18 April 2013 (UTC)

random

Random invoked only with one argument returns a script error. I have tried to fix it in my sandbox including also a seed argument. --Vriullop (talk) 12:37, 31 March 2013 (UTC)

What are the parameters to call for a random number? I'm guessing {{#invoke:Math|random|count|seed}} but it doesn't seem to give me a random number. Technical 13 (talk) 15:59, 3 July 2013 (UTC)

: What parameters have been tested? WT101 (ChatCount) 18:23, 6 July 2013 (UTC)

GCD

A GCD function would be a nice replacement for {{gcd}}, which is pretty limited at the moment. For vi:Mô đun:Math, I ported the pseudocode at Extended Euclidean algorithm#Pseudocode to Lua, accounting for the edge case mentioned in that section:

--[=[
gcd
 
Calculates [[greatest common divisor]] according to the [[extended Euclidean algorithm]].
]=]
function z.gcd(frame)
    local args = frame.args
 
    if args[1] == nil then
        local parent = frame:getParent()
        args = parent.args
    end
 
    local a = z._cleanNumber(frame, args[1])
    local b = z._cleanNumber(frame, args[2])
    if not a or not b then return end
 
    local s = 0
    local olds = 1
    local t = 1
    local oldt = 0
    local r = b
    local oldr = a
    while r ~= 0 do
        local quotient = math.floor(oldr / r)
        oldr, r = r, oldr - quotient * r
        olds, s = s, olds - quotient * s
        oldt, t = t, oldt - quotient * t
    end
    mw.log("Bézout coefficients:", olds, oldt)
    mw.log("Greatest common divisor:", oldr)
    mw.log("Quotients by the GCD:", t, s)
 
    if a == 0 and b < 0 or b == 0 and a < 0 then oldr = oldr * -1 end
 
    return oldr
end

I'm not particularly well-versed in this area, but I tested the function against a few sample inputs, like the ones at Template:Gcd, and it seems to yield the right results. If anyone knows a better way to write this function, I'm all ears.

 – Minh Nguyễn (talk, contribs) 23:00, 26 November 2013 (UTC)

Thanks for the suggested code. :) I noticed a couple of things - first, if you're just interested in the greatest common denominator then you can get rid of s, olds, t, and oldt, as they are not used in calculating it. Second, if you use {{#invoke|math|gcd|-8|0}} you get the answer 8. This seems counterintuitive to me, but then I am not really sure what the conventions are here.

In addition to this update, I think the module needs a bit of TLC to make it work nicely when it is called from other templates and other Lua modules. I did start working on the sandbox, but then I lost all of my changes due to a bug in Vim relating to Japanese input methods. Bah. :( I'll try again tomorrow, I think. Given that this module has more than a million transclusions, we should probably take our time testing it to make sure it works, so I've marked this request as answered for now. — Mr. Stradivarius ♪ talk ♪ 13:24, 2 December 2013 (UTC)

Testcases

I added Module:Math/testcases and Module_talk:Math/testcases and there are some bugs in the current version of the Module:Math. Please copy corrected version from commons:Module:Math. --Jarekt (talk) 18:38, 3 December 2013 (UTC)

Perhaps Mr. Stradivarius would be able to review this request? — Martin (MSGJ · talk) 12:59, 4 December 2013 (UTC)
Sure, I'll take a look at it tomorrow. It should probably be done at the same time as the above request, and I'd prefer my enhancements went in as well, so it will take an hour or two to code up. — Mr. Stradivarius ♪ talk ♪ 14:26, 4 December 2013 (UTC)
Update: The code in the sandbox should be done, and it is passing all the unit tests. I haven't updated it just yet, though, as I have changed quite a few things and I want to write more unit tests to make sure that everything is working properly, not just the old stuff that was done through #invoke. — Mr. Stradivarius ♪ talk ♪ 14:04, 8 December 2013 (UTC)
Another update: I have made a couple of tweaks based on feedback from the new test cases for the pure Lua functions, and things look pretty much ready to go. Before we roll this out I think I will write some more test cases to test the ancillary functions as much as is possible. I also would like others to comment on the question of gcd with zero and negative values. What should the greatest common divisor of 0 and -8 be? 8, or -8? I'm really not sure. — Mr. Stradivarius ♪ talk ♪ 03:38, 12 December 2013 (UTC)
Personally, I don't think it matters. In the lattice of natural numbers (including 0) ordered by divisibility, gcd is the meet, and as far as I'm concerned, that's the most natural definition. If you throw in negative numbers, you don't have a lattice anymore, because (for example) 8 and −8 divide one another but are not equal (so divisibility is not a partial order but rather a preorder. But if you mod out by the obvious equivalence relation, you get the lattice back, except now 8 and −8 are the same node.
So if your application is sensitive to whether the answer is 8 or −8, you need to fix your application, rather than worrying about the definition of gcd. --Trovatore (talk) 04:08, 12 December 2013 (UTC)
I agree with Trovatore that the natural thing to do is to work in the setting of positive integers rather than integers. But the next most natural thing is to define gcd(0, -8) = 8 (and similarly gcd(-4, -8) = 4, etc.), so that applying the gcd always gives a positive value (except for gcd(0, 0), which is undefined). --JBL (talk) 04:38, 12 December 2013 (UTC)
Actually I said the natural numbers (nonnegative integers). --Trovatore (talk) 05:12, 12 December 2013 (UTC)
Oh, and I disagree about gcd(0,0) being undefined; see below. --Trovatore (talk) 05:48, 12 December 2013 (UTC)
The problem is that the gcd of integers is only defined up to a sign. You could take gcd(0, x) = x always, or gcd(0, x) = −x always, or gcd(0, x) = |x| always, or you could even assign signs at random. Mathematically, they're equivalent. That said, forcing the gcd to be positive regardless of the input is probably the right thing to do, but for computational reasons, not mathematical ones: To test that two numbers are coprime, for example, it's easiest to test that the gcd is 1, not that it's 1 or −1. Having to do the latter strikes me as error-prone. Ozob (talk) 05:01, 12 December 2013 (UTC)
(edit conflict) (written before I saw Ozob's reply) Thank you both for the replies - that helps a lot. If it is meaningless to deal with anything apart from positive integers, then there are two basic approaches we could take. Number one, we could simply raise an error if the user tries to input anything other than a positive integer. This has the advantage that any errors would be picked up straight away, and wouldn't be compounded by being passed over to other Lua functions that depend on gcd; it would also mean we wouldn't have to worry about exactly how to handle the edge cases involving zeroes, fractional numbers and negative numbers.

Number two, we could make a best guess as to what the user means when inputting negatives, zeroes and fractions - this would involve rounding the input number to the nearest integer, and then converting the sign to positive if the function outputs a negative number. This would have the advantage of reducing the possibility of big red text visible in articles, and it would also allow other Lua functions to use the gcd function without having to worry about checking the type of its output. However, we would still have to decide what to do with gcd(0, 0). (Perhaps we could output a nil value to other Lua modules and a blank string to #invoke.)

I'd be fine with implementing either of these approaches, so please let me know if you would prefer one over the other. — Mr. Stradivarius ♪ talk ♪ 05:09, 12 December 2013 (UTC)

There is really no problem with zero. In my opinion it's perfectly fine to set gcd(0,0)=0 — it is the meet of 0 and 0 in the lattice I described. There are some authors who don't like saying that 0 divides 0, because 0/0 is undefined. In my opinion that's kind of silly, because "k divides n" doesn't mean so much "n/k is an integer" as it does "n is an integer times k", and certainly 0 is an integer times 0. So if you set it up to return gcd(0,0)=0, you'll be at variance with the usage of some authors, but I can't imagine a practical problem that it will cause. --Trovatore (talk) 05:41, 12 December 2013 (UTC)
I agree. gcd(0,0) is defined, is not a special case (mathematically) and is equal to zero. Ozob (talk) 14:15, 12 December 2013 (UTC)
I don't personally care what happens with gcds of negative numbers, but please please please (if you don't already do this) make sure that x mod y (for positive y) always returns an integer in the interval [0,y–1] regardless of whether x is negative. C/C++/Java get this wrong, Python gets it right, and Python is the one you should emulate. —David Eppstein (talk) 06:18, 12 December 2013 (UTC)
That would be very nice, yes. --Trovatore (talk) 06:27, 12 December 2013 (UTC)
There isn't a mod function in Module:Math, because Lua already has the % operator and the math library, and normal wiki pages have the mod operator for the #expr parser function (see Help:Calculation). I don't know if those have the behaviour you want, though. — Mr. Stradivarius ♪ talk ♪ 06:39, 12 December 2013 (UTC)
Ok, thanks. Lua appears to be one of the languages that gets modulo correct. —David Eppstein (talk) 08:45, 12 December 2013 (UTC)
Actually, looking at the later posts in bugzilla:6068, it looks like we do need a sane modulo function for wikitext, so I have added a mod function to the module. You can use it with {{#invoke:math/sandbox|mod|x|y}} - could you test it and verify that it works as expected? — Mr. Stradivarius ♪ talk ♪ 09:28, 12 December 2013 (UTC)

I come here because of the question raised at Wikipedia talk:WikiProject Mathematics. As said above, it seems that the best choice for modulo operation is to choose a mod b in the interval [0, |b|-1]. This implies that gcd(a,b) is nonnegative except if (b=0, a<0) or (b<0, b divides a). If one desires to simplify fractions, one needs the final value of r and s, because r and s are coprime and a/b = ±t/s for these final values. If a and b are positive one has more precisely a/b = -t/s, because as +bt = 0. However to know if it is s or t which is negative, one has to test their signs (or keep track of the parity of the number of iterations. If a or b is negative, then there are several cases to consider, and I consider as safer (and not very costly) to begin by testing the signs of the input, to start the computation with |a| and |b| and to adjust the signs at the end. D.Lazard (talk) 13:28, 12 December 2013 (UTC)

Not to sidetrack the discussion, but I'm reminded of another good point. Sometimes what one wants from a gcd algorithm is not the greatest common divisor, but Bézout's identity: One wants to solve ax + by = g. Such algorithms are usually called extended GCD algorithms. They're useful (for example) if you want to compute an inverse in modular arithmetic. Coding an extended GCD algorithm is virtually identical to coding a regular GCD algorithm, but you need to track some additional output (the two coefficients). Ozob (talk) 14:15, 12 December 2013 (UTC)
Looking closer, it seems that this is what the originally suggested code is computing. It might be a good idea to have two functions, an ordinary gcd (which only returns the gcd) and an extended gcd (which returns the Bézout's identity coefficients). Ozob (talk) 14:19, 12 December 2013 (UTC)
I recently had need of these functions in Python. The Python standard library gcd does not check for sign and can return a negative if one of the inputs is negative. Some number theory texts define the gcd as the positive value (except gcd(0, 0)), and imo carrying this over is good programming practice even at the cost of a executing a few extra lines of code; programs should return uniquely defined results. (To be fair, the Python documentation does uniquely define the output though the definition is rather complicated.) In computing Bézout's identity coefficients, aka the extended Euclidean algorithm, most versions compute a solution but make no statement about which, of many possible, solution is returned. The solution is uniquely defined if additional inequalities are imposed, but again at the cost of executing a few more lines of code. --RDBury (talk) 16:31, 12 December 2013 (UTC)
This is discussed in Extended Euclidean algorithm: With positive inputs, the Extended Euclidean algorithm produces a positive GCD and one of the two pairs of Bézout's coefficients such that as + bt = gcd (a,b) ≥ 0, s < b/gcd(a,b) and t < a/gcd(a,b). If one want s > 0, as recommended for the modular inverse, one further line of code is needed, as in the pseudocode given in Extended Euclidean algorithm for the modular inverse. If the input are not necessary positive, the result is probably the same, but (when writing this part of Extended Euclidean algorithm), I was too lazy to check it and to verify if Knuth discussed this in his book (he probably did, at least in the exercises). D.Lazard (talk) 17:49, 12 December 2013 (UTC)
By the way, I follow the Osob's suggestion of two different versions: one for the gcd alone (which does not compute s and t, nor the successive quotients) and one for Bézout's identity (computing also the last values of olds and oldt) . But, I would add a third one for simplifying fractions (it uses the last values of s and t, and some tuning at the end for having a positive denominator) D.Lazard (talk) 18:04, 12 December 2013 (UTC)
I have added to Extended Euclidean algorithm a section "Simplification of fractions". D.Lazard (talk) 19:26, 12 December 2013 (UTC)
@D.Lazard: Would it make any sense to return the Bézout coefficients and the quotients in the case of more than two numbers? I know that we can compute the gcd of more than two numbers by doing gcd(a, b, c) = gcd(gcd(a, b), c); I'm not sure how this would work with the Bézout coefficients and quotients though. — Mr. Stradivarius ♪ talk ♪ 02:35, 13 December 2013 (UTC)
It does make sense. It proceeds recursively, just like gcd(a, b, c) = gcd(gcd(a, b), c). First one finds s and t such that sa + tb = g, where g = gcd(a, b). Then one finds u and v such that ug + vc = h, where h = gcd(g, c). Substituting reveals u(sa + tb) + vc = h, whence (us)a + (ut)b + vc = h, so us, ut, and v are the Bézout coefficients. Ozob (talk) 14:36, 13 December 2013 (UTC)
You certainly obtain some Bézout coefficients by this method. But, if you change the order of the polynomials (for example by computing gcd(gcd(a, c), b) ), you will get different Bézout coefficients without any information on the relations between these two series of Bézout coefficients, nor on the relations between these series and the "minimal" (in some sense) Bézout coefficients. I do not know any application of these generalized Bézout coefficients. I'll try to explain where is the problem. Bézout coefficients are the solutions of the equation a1x1 + ... +akxk =gcd. As in the case of equations over a field, the solutions of this equation are the sum of a particular solution and the general solution of the equation without right-hand side member. If k=2, the solutions of the equation without right-hand side member ax+by=0 is (ub/gcd(a,b), ua/gcd(a,b)), where u is an arbitrary integer. That is they form a free abelian group of dimension one. If k>2, the solutions form also a free abelian group, but its dimension is k-1. The interesting problem is thus to find a basis of this group. This can certainly be done with a Smith normal form algorithm, but this is not the subject of this thread. D.Lazard (talk) 16:02, 13 December 2013 (UTC)
I agree, but I'm not sure that this is relevant to this code. The correct logical setup is: Arrange the integers a1, ..., ak and −1 into an element v of the free group Zk+1. Then the sublattice of Zk+1 perpendicular to v is the set of all possible Bézout coefficients. It is an interesting problem both to find a basis (any basis) for this sublattice and to find a "good" basis (i.e., computationally convenient). The first, as you say, can be solved using Smith normal form, and the second using LLL. Both of these are outside the scope of this module. However, finding a single choice of Bézout coefficients is straightforward using the construction I gave above. I don't know what application it might have, but at least it's easy to compute.
@Mr. Stradivarius: I think the right answer to your question might be "yes, but it's not a good idea". Ozob (talk) 03:11, 14 December 2013 (UTC)
Ok, thanks for the replies. I'll go ahead and implement just the gcd without the ability to return any Bézout coefficients. If anyone needs them, we can always add them in later, or maybe better would be to make a more specialised module tailored to the problem. — Mr. Stradivarius ♪ talk ♪ 23:49, 17 December 2013 (UTC)

I noticed the mention of mod (%) above earlier, and having just found the reason for some weirdness in a module I'm working on, I thought I would share it. I was testing with very large inputs to see that nothing broke, and got a bug which was due to the following. Lua evaluates 525000000000000120000000000 % 3 as 68719476736! That is because it calculates

a % b == a - math.floor(a/b)*b

and that ends up calculating

525000000000000120000000000 - 525000000000000060000000000

with 68719476736 as the result—junk from exceeding floating point resolution limits. Johnuniq (talk) 23:37, 17 December 2013 (UTC)

Hmm, we had similar problems with Module:Random - see here for how we worked around it. I'm not sure if there's a good workaround for the problem you describe, or how we would go about implementing it, however. — Mr. Stradivarius ♪ talk ♪ 23:49, 17 December 2013 (UTC)
No good way, but what I did is this:
x = value % scale
if not (0 <= x and x < scale) then x = 0 end
Johnuniq (talk) 00:23, 18 December 2013 (UTC)
That figures. I've heard that things start to get very tricky when we are dealing with integers over 2^53. I've implemented your hack, and I've updated the module from the sandbox. That means that we now have a mod function available, and Minh Nguyễn, it means that you can now finally access the gcd function. :) I've also added some much-needed documentation - if you spot anything that I've got wrong or missed out, please go ahead and fix it. — Mr. Stradivarius ♪ talk ♪ 02:18, 18 December 2013 (UTC)
Both the solutions discussed for generating large random numbers and the kind of solution that would be necessary here share the common feature that they require big integer arithmetic. All that means is that large numbers are represented by arrays of machine words. Addition is done word by word, with carries propagating appropriately. Multiplication is similar. There should also be a sign bit. Arithmetic with big integers is less convenient than ordinary arithmetic because it's usually not built into the programming language, but otherwise it's the same. In particular, with a big integer library it would be possible to accurately perform the mod operation, compute large random numbers, and so on. Ozob (talk) 02:34, 18 December 2013 (UTC)

Big integers

Now that the module is updated and we are talking about possible new features or updates, I thought it would be nice to start a new section. Dealing with very big numbers is a problem for all of the arithmetical operations in Lua, not just in this module, so I think it would be best to implement this as a separate module. Also, I have found some BigNum, which is Lua code that already does this same thing. However, I'm not yet sure how easy it will be to port it to Scribunto, and I can't find a licence anywhere, so we may not be able to use it at all. There may be other libraries out there that have this functionality, though - let me know if you find any. — Mr. Stradivarius ♪ talk ♪ 02:45, 18 December 2013 (UTC)

Protected edit request on 8 April 2014

Please change "frame:preprocess('{{#expr: ' .. number_string .. '}}')" to "frame:callParserFunction('#expr', number_string)". Jackmcbarn (talk) 23:08, 8 April 2014 (UTC)

DoneMr. Stradivarius ♪ talk ♪ 03:32, 11 April 2014 (UTC)

Protected edit request on 20 June 2014

Please make these changes. Jackmcbarn (talk) 02:21, 20 June 2014 (UTC)

DoneMr. Stradivarius ♪ talk ♪ 02:47, 20 June 2014 (UTC)

_mod documentation

Could it be that the Module:Math#mod documentation has a mistake, mentioning mm._round? I could expect the function mm._mod to be used (which is not documented elsewhere, while being public). I did not check or compare calculations, mm._round could be right in there. -DePiep (talk) 11:43, 2 July 2014 (UTC)

Oh dear, it must have been like that since I edited the /doc page last - and that was a long time ago. Fixed. — Mr. Stradivarius ♪ talk ♪ 13:29, 2 July 2014 (UTC)
No big deal. My fun is that I proved I did RTFM :-). -DePiep (talk) 21:50, 2 July 2014 (UTC)

Possible addition

No pun intended. I converted Template:Addition to a more efficient module, though after the fact I thought it might work to group it in with this module that handles all the other math functions. moluɐɯ 20:45, 2 July 2014 (UTC)

Not done: please make your requested changes to the module's sandbox first; see WP:TESTCASES. Jackmcbarn (talk) 20:47, 2 July 2014 (UTC)
It's weird to say I understand basic Lua without exactly understanding how this template works exactly. I was kinda hoping an admin proficient in Lua would convert the simple function, but I guess I'll try to integrate it into the module first. moluɐɯ 20:53, 2 July 2014 (UTC)

mod error

I use mod this way:

{{#invoke:math|mod|123.6|1}} → 0.59999999999999
{{#invoke:math|mod|345.6|1}} → 0.60000000000002
(hardcoded: is, returns 0.60000000000002, expected 0.6). -DePiep (talk) 15:13, 22 May 2015 (UTC)
This is related to the fact that Lua uses floating point to represent numbers, and unfortunately there is no way of fixing it in the module. See Floating point#Accuracy problems for an explanation. — Mr. Stradivarius ♪ talk ♪ 23:05, 22 May 2015 (UTC)
Makes this function untrustworthy and useless. How many editors use it unchecked before this? -DePiep (talk) 23:48, 22 May 2015 (UTC)
(edit conflict)It looks like a FP precision error, amplified by the way it’s calculated, by doing a division then a subtraction. See e.g. the manual section 2.5.1. You could use round to eliminate it, e.g.
{{#invoke:math|round|{{#invoke:math|mod|123.6|1}}|5}} → 0.6
Although this only works in this case as the expected result is a terminating decimal.--JohnBlackburnewordsdeeds 23:12, 22 May 2015 (UTC)
You want me to research and use a round sub? (How do I know that one does have such an error?). Sure it is FP caused. My cause is that I can not trust mod, so it is useless. I'd expect someone would add a mod_correct. -DePiep (talk) 23:38, 22 May 2015 (UTC)
Hard to imagine how it could work otherwise. Mod, i.e. %, is often defined for integers to give an integer result which in theory would be exact. But Lua's version doesn't work like that and it would not work in your example which has non-integer inputs. So it's got to use FP math (actually double precision) which is inexact. Inexact in well understood ways, so there are easy workarounds such as to use round, provided your expected output is a terminating decimal. Which means it's not possible to provide a 'correct' version of mod which works for all possible inputs.--JohnBlackburnewordsdeeds 23:51, 22 May 2015 (UTC)
I can understand FP issues, but I'm not interested. I'm not here to learn that. mod is useless. And actually you are talking self-nonsense: one post earlier you said how it could be solved by rounding, now you say it cannot be solved. -DePiep (talk) 00:21, 23 May 2015 (UTC)
your examples can be fixed by rounding, but not the general case – basically any case where the second argument to mod is a fraction.--JohnBlackburnewordsdeeds 00:41, 23 May 2015 (UTC)
Blaming me for the bug. -DePiep (talk) 01:26, 23 May 2015 (UTC)

No, that was not my intent. I was merely pointing out that my 'fix', which does 'fix' your examples, cannot be used more generally with arbitrary input. No-one is at fault for this, it’s just how the maths works.--JohnBlackburnewordsdeeds 01:43, 23 May 2015 (UTC)

OK, way too rough. I struck. -DePiep (talk) 21:30, 23 May 2015 (UTC)
DePiep, what is your use case? Floating point arithmetic follows certain rules and has certain limitations that make sense from the computer point of view, but often seem odd from a human point of view. As others have said, there is no completely general solution (aside from abandoning floating point arithmetic entirely), but in many specific uses it is possible to find solutions. For example, rounding can usually restore human display expectations if the inputs are known in advance to be terminating decimals. So what is your use case? Dragons flight (talk) 01:52, 23 May 2015 (UTC)
I think there is a well-defined mathematical operation here: The elements of the group RZ are represented by the real numbers in [0,α). However, in general, determining that representation is computationally impossible; it's not hard, but it may require infinite memory. I don't see anything wrong with the examples above; floating point numbers have finite precision, and computations with them naturally have some error. Ozob (talk) 03:59, 23 May 2015 (UTC)
My cause is that an FP error is not needed. Even stronger: FP is not needed at all. Anyone just looking at the mod task can see the outcome. What if I had not checked this? re Ozob: "in general, determining that representation is computationally impossible" - I refuse to accept, that's only because you assume 'computational' to be limited to the ~1980 status. Donald Knuth by then had noted that computers should be able to handle 7/9 correctly. (My new thought, & to coin the idea: mod_better should have a third parameter precision. etc.). -DePiep (talk) 21:30, 23 May 2015 (UTC)
Read about floating point here Christian75 (talk) 21:51, 23 May 2015 (UTC)
If one of your inputs is 123.6 then you need FP math. You could do it by repeatedly subtracting 1, an integer but as you are subtracting it from a FP number you are doing FP math. If you use integer math (an option Lua doesn't have) you have to convert all inputs to an integer, so 123 or 124, which will clearly give the wrong answer. As for looking at it and seeing the outcome for me at least that's as it it effectively does a 'frac' operation, so extracts the fractional part of a FP number, a common operation in computing. Once you realise that it’s obvious what the result should be.--JohnBlackburnewordsdeeds 21:59, 23 May 2015 (UTC)
If one of your inputs is 123.6 then you need FP math - No, no need. I can do it mentally by looking at the figures. I can do it by a string handling function, just cutting characters. My point-1 is that FP is introduced unneeded, and then FP itself produces the problem. Point-2 is that you people keep telling me that is can not be done otherwise. -DePiep (talk) 22:07, 23 May 2015 (UTC)
The Lua math functions use floating point math (as for that matter does the parser function #expr), and in many cases allow basic expressions as input. If you want to use some formulation of exact math, you are of course free to do so, though you'd presumably need to either do it by hand or write your own functions for that. If you want to use exact math you then get a different set of edge cases, for example how do you choose to represent fractions, constants, and other expressions, e.g. {{#invoke:math|mod|11/3|1}} = 0.6666666666667 or {{#invoke:math|mod|e^pi|1}} = 0.140692632779. Both of those are truncated decimals here but make for reasonable approximations. Personally, I think {{#invoke:math|mod|345.6|1}} → 0.60000000000002 is also a reasonable approximation, though obviously you disagree. In the latter case you can recover the exact answer by rounding, but either of the earlier two examples would become somewhat less accurate by further rounding. If you restrict the class of inputs that you allow (e.g. only finite decimals) then one could write a function that is more accurate on that class of expressions (e.g. by using string operations), but you will have a different set of capabilities and limitations than the current mod used here. Dragons flight (talk) 23:58, 23 May 2015 (UTC)
"Lua math functions use floating point math" - Oh. Why is this relevant to me? "If you want to use ..." -- No I don't want to. Where did I say so? I wanted something else. (Another Good Editor explaining to me that I am the one who doesn't understand. Reaching the dozen by now). Just Read the F OP. -DePiep (talk) 02:28, 27 May 2015 (UTC)
I'll say it again - it's not possible to fix this in the module. It sucks, I know, but there's nothing we can do about it. — Mr. Stradivarius ♪ talk ♪ 02:46, 27 May 2015 (UTC)
'couse not. I know. Just glad I found it out in time. -DePiep (talk) 02:55, 27 May 2015 (UTC)

@Mr. Stradivarius and DePiep: Actually, there may be a way to work around this that will make everyone happy. When being called from wikitext, we can round the return value to 15 significant figures. I already set up Module:Decimals to do just that a while ago. Jackmcbarn (talk) 16:11, 27 May 2015 (UTC)

I planned to unwatch this page, but kept it. I'll leave my bickering though. -DePiep (talk)

Protected edit request on 27 March 2016

I have simplified some things in Module:Math/sandbox by creating a new binary_fold() function for min and max that takes a function that returns true when the "dominant" value should be the next value and false otherwise, changed some of the local functions to anonymous functions, and changed "applyFuncToArgs" to "fold" as the former name is misleading: it implies that it "maps" a list according to a function instead of folding/reducing it to one value. Diff + Amendment (final diff is latter diff or current version), test cases. No functional change. Esquivalience t 01:48, 27 March 2016 (UTC)

Johnuniq (talk) 02:43, 27 March 2016 (UTC)

Done I always knew that "applyFuncToArgs" was a lousy function name, but I didn't know enough programming then to know anything better, or to realise that I could extend the functionality using a binary version. This is a great improvement. — Mr. Stradivarius ♪ talk ♪ 12:17, 28 March 2016 (UTC)

Protected edit request on 25 June 2018

Fix typo in comments: change {{#invoke:Math | log | x }} to {{#invoke:Math | log10 | x }} in the comments just above the wrap.log10 function, because the function is named "log10". {{3x|p}}ery (talk) 03:41, 25 June 2018 (UTC)

I would put that on the to do list rather than hit 1.6 million pages for a typo. Johnuniq (talk) 03:55, 25 June 2018 (UTC)
Disabled for now. If you leave this in the sandbox it can be deployed when a more substantial change is made at the same time — Martin (MSGJ · talk) 07:22, 26 June 2018 (UTC)
In about 2020, if past history shows anything? {{3x|p}}ery (talk) 21:46, 26 June 2018 (UTC)

Protected edit request on 30 September 2018

@Primefac: Replace the content of Module:Math with Module:Math/sandbox, these fixes allow for the median function to accept decimals number and not return an error message when there's no input. See User:BrandonXLF/sandbox/5 and Template:Median. – BrandonXLF (t@lk) 23:13, 30 September 2018 (UTC)

 Partly done: I implemented a better solution using existing subfunctions within the module. Primefac (talk) 23:21, 30 September 2018 (UTC)

Does round's precision= parameter work for values that round to the nearest whole number?

Per the documentation, I would expect {{#invoke:Math|precision_format|value=1.02|precision=1}} to result in "1.0". Currently, it results in "1". Using a value of "1.12" correctly returns "1.1". What am I missing?

Update: The precision_format function appears to work better, but I don't know if it does what I want. See Template:Inflation/testcases#Significant digits. – Jonesey95 (talk) 23:27, 21 October 2019 (UTC)

This is because the devels of this module wrote the function clumsily. Try to call formatnum.formatNum(number, lang, prec) instead. I am not sure that their {{#invoke}} wrapper is usable, but the function is certainly callable from Lua, namely from the module:Complex_date. Incnis Mrsi (talk) 10:12, 22 October 2019 (UTC)
There are comments in formatnum that say that it truncates instead of rounding, and I was unable to get an invoke statement to work. As far as I can tell, this module's precision_format= parameter works fine for rounding and precision, so I just used that. – Jonesey95 (talk) 16:06, 22 October 2019 (UTC)

precision_format

Is it possible to have a version of precision_format that doesn't use scientific notation for small numbers? for example have {{#invoke:Math|precision_format|1/30000|7|scinote=n}} return 0.0000333 instead of 0? I could probably hack something by post-processing the output, but it seems better to have a way to do this in the module since the module does this part at the very end. Frietjes (talk) 18:36, 7 December 2019 (UTC)

How to get difference of two number

How to write code to get difference of two numerical values.?-❙❚❚❙❙ JinOy ❚❙❚❙❙ 19:50, 8 April 2020 (UTC)

Gnoeee, you wouldn't use the module for that, you would use the #expr conditional expression to calculate the difference. For example, {{#expr: 2-1}}1. Primefac (talk) 20:13, 8 April 2020 (UTC)
@Primefac: - Thank you. I have just tried a test case {{#invoke:math|sum|10|-5}} and it works-❙❚❚❙❙ JinOy ❚❙❚❙❙ 20:22, 8 April 2020 (UTC)
I guess technically that works too. I guess I just find #expr a lot easier to use, and less process-intensive. Primefac (talk) 20:29, 8 April 2020 (UTC)
I have added it to the article 2020 coronavirus pandemic in Kerala to get the count of active cases. From Wikidata, I fetched total cases, death and recovery numbers. Active cases is not available from Wikidata. So added the code with #expr and its works. But in my native Wiki (Malayalam), #expr shows some error when i tried. So used 'math' over there.-❙❚❚❙❙ JinOy ❚❙❚❙❙ 20:58, 8 April 2020 (UTC)