Help:Calculation

From Includipedia, the inclusionist encyclopedia

Jump to: navigation, search
Image:Wikimedia-logo.svg This is a copy of the master help page at Meta. Do not edit this copy.
Edits will be lost in the next update from the master page. See below for more information.
  1. REDIRECT Template:Phh:Reader  

This is a redirect that would not belong in print.

However, it may be a valid navigational aid for computer searches.

For more information, follow the category link.


Editing
Start new pages
Page name

Referencing
Links
Piped links
Interwiki linking
Footnotes (References)

Formatting
Wikitext
Lists & Tables
Image & file uploads
Formulae

Organising
Sections
Categories
Redirects (forward)
Namespaces
Moving a page
Page size

Fixing mistakes
Reverting edits
Show preview

Saving effort
Editing shortcuts
Edit toolbar
Magic words
Templates
Variables
Calculation

Communicating
Edit summary
Talk page
Edit conflict
Minor edit

Other
Characters
Sandbox


The accuracy and format of numeric results varies with the operating system of the server.

The MediaWiki extension ParserFunctions enables users to perform simple mathematical computations.

The expr function evaluates numerical expressions, and also boolean expressions involving numbers and booleans (not strings). The syntax is:

{{ #expr: expression }}

The spaces are not needed. Inside numbers no spaces are allowed.

The supported operators (roughly in order of precedence) are not, *, /, div, mod, +, -, round, =, <>, !=, <=, >=, and, and or.

Contents

Operators

Operator Operation Example
none Template:Evaldemo
Template:Evaldemo
+ Unary + sign Template:Evaldemo
- Unary - sign (negation) Template:Evaldemo
not Unary NOT, logical NOT Template:Evaldemo
Template:Evaldemo
* Multiplication Template:Evaldemo
/ Division, same as div Template:Evaldemo
div Division, same as /,
no integer division
Template:Evaldemo (should be 4)
Template:Evaldemo (should be 5)
mod "Modulo", remainder of division after truncating both operands to an integer (PHP operator %).

Caveat, div and mod are different from all programming languages. This has been fixed (but needs to be committed), see bugzilla:6068.
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo (should be 2.6)
Template:Evaldemo (should be 1.6)
Template:Evaldemo (should be 2.9)
+ Addition Template:Evaldemo
- Subtraction Template:Evaldemo
round Rounds off the number on the left to the power of 1/10 given on the right (PHP function round) Template:Evaldemo
Template:Evaldemo
{{ #expr: 3456 round -2}} = 3500
= Equality (numerical incl. logical) Template:Evaldemo
<> Inequality, same as != Template:Evaldemo
 != Inequality, same as <>, logical xor Template:Evaldemo
< Less than Template:Evaldemo
> Greater than Template:Evaldemo
<= Less than or equal to Template:Evaldemo
>= Greater than or equal to Template:Evaldemo
and Logical AND Template:Evaldemo
or Logical OR Template:Evaldemo

The boolean operators consider 0 to be false and any other number to be true. An intermediate or final result "true" is identified with 1. Thus Template:Evaldemo.

Precedence:

(+ and - have equal precedence, * and / also, both higher than the former two).

(first +, then =, then <).

(first additions, then round)

(mod and multiplication have equal precedence, evaluation from left to right)

Parentheses can force a different precedence: Template:Evaldemo

Blank spaces are good for readability but not needed for working properly, except between not and an adjacent and/div/mod/not/or/round operator, and within numbers not allowed:

  • {{ #expr:7mod3}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:7.5round0}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:0and1}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:0or not0}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:0ornot0}} gives "Expression error: Unrecognised word "ornot""
  • {{ #expr:123 456}} gives "Expression error: Unexpected number"
  • {{ #expr:not not3}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:notnot3}} gives "Expression error: Unrecognised word "notnot""
  • {{ #expr:---2}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:-+-2}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:2*-3}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:-not-not-not0}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:2*/3}} gives "Expression error: Unexpected / operator"

Numbers as input

Leading zeros are allowed, as well as a trailing decimal point (for an integer) and trailing zeros in a number with a decimal point.

These equivalences are also relevant for #ifeq and #switch, see below.

In [1] we have

define( 'EXPR_NUMBER_CLASS', '0123456789.' );
...
elseif ( false !== strpos( EXPR_NUMBER_CLASS, $char ) ) { 
// Number
if ( $expecting != 'expression' ) {throw new ExprError('unexpected_number');}
// Find the rest of it
$length = strspn( $expr, EXPR_NUMBER_CLASS, $p );
// Convert it to float, silently removing double decimal points
$operands[] = floatval( substr( $expr, $p, $length ) );
$p += $length;$expecting = 'operator';continue;}

Thus the part of the expression representing a number is a sequence of digits and points; due to floatval a second point and any digits and points immediately after it are ignored, and do not give an error message. Scientific notation and group separators are not allowed: an e or E is considered an unrecognized word after the number, a comma is considered an unrecognised punctuation character:

Thus a number can only consist of one or more digits, or zero or more digits, a point, and zero or more digits. (For the purpose of evaluating an expression a plus or minus sign is considered a unary operator instead of part of the number.)

Canonical form:

Accepted, although in some cases more or less odd:

Wrong:

Due to the specifier R ("raw"), {{ NUMBEROFARTICLES:R}} = "1035986" etc. produce numbers without group separators, which can be used in computations.

Numbers as output

A non-integer result has a decimal point in it. Scientific notation is produced for numbers with small absolute value (for Wikimedia: less than 1E-4) and for numbers with large absolute value (for Wikimedia: greater than or equal to 1E+12). Thus numbers produced include (depending on the operating system of the server):

For negative numbers simply a minus sign is prefixed:

Since scientific notation is not accepted as input, nested use of #expr may fail in cases where the same composite computation with a single #expr works.

Thus:
Template:Evaldemo,
{{ #expr:{{ #expr: 1/10000}} *2}} = 0.0002,
Template:Evaldemo, but
{{ #expr:{{ #expr: 1/100000}} *2}} = Expression error: Unrecognised word "e".
Long YYYYMMDDhhmmss timestamps can run into the same problem:
Template:Evaldemo,
{{ #expr:{{ CURRENTTIMESTAMP}}}} gives 20090109093700.
Timestamps without seconds are 12 digits, just short enough:
Template:Evaldemo

To allow the output of an expression to be used as input, the expression can be replaced by e.g.

  • {{#ifexpr: ''expression''/10000000000 >1 | {{#expr:''expression''/10000000000}} * 10000000000 | ''expression'' }}

Examples:

  • {{#ifexpr: 123456789012345/10000000000 >1 | {{#expr:123456789012345/10000000000}} * 10000000000 | 123456789012345 }} gives 12345.6789012 * 10000000000
  • {{#ifexpr: 12345.6789012345/10000000000 >1 | {{#expr:12345.6789012345/10000000000}} * 10000000000 | 12345.6789012345 }} gives 12345.6789012345

This increases the upper limit by a factor 1e10.

See Template:Tim for producing output of large integers in non-scientific notation, suitable as input in another computation. For producing numbers with commas as group separators, see Template:Tim.

If the result of rounding a negative number is zero, the result is "-0". To avoid that, an expression x can be replaced by 0 + ( x ):

Accuracy

The accuracy and format of numeric results varies with the operating system of the server. Some remarks in his section are specific for Wikimedia.

Accuracy of the result of #expr is less than internally used within the computation of an expression:

The macheps or smallest x such that 1+x != 1 appears to be near 0.5^53 + 0.5^106 or 1.1102230246251566636831481088739149080825883E-16 (see above):
Template:Evaldemo
Template:Evaldemo
That's the normal behaviour for 64=1+52+11 bits (52 mantissa, 11 exponent). As explained above it is unrelated to the smallest expression result greater than 1:
Template:Evaldemo
Template:Evaldemo below about 1 + 5E-12.

Branching depending on an expression

The function #ifexpr produces one of two specified results, depending on the value of a boolean expression involving numbers and booleans (not strings). Example:

{{#ifexpr: {{CURRENTDOW}} = 0 or {{CURRENTDOW}} = 6 | weekend | Mo-Fr}} yields Mo-Fr because today is Friday with {{ CURRENTDOW}} = "{{CURRENTDOWTemplate:Void}}".

Comparisons

  1. The function #ifeq: compares numbers and strings for equality (equal if both represent the same number or both are equal strings).
  2. The function #switch: compares one string with multiple others, and correspondingly produces one of multiple specified results.
  • {{ #switch:FR|UK=London|FR=Paris|NL=Amsterdam}} gives "{{{{{1Template:Void}}}|UK=London|FR=Paris|NL=Amsterdam}}"
  • {{ #switch:UK|UK|GB=London|FR=Paris}} gives "{{{{{1Template:Void}}}|UK|GB=London|FR=Paris}}"
  • {{ #switch:ZZ|UK=London|FR=Paris|no match}} gives "{{{{{1Template:Void}}}|UK=London|FR=Paris|no match}}"
  • {{ #ifeq:3|3.0|1|0}} gives "{{{{{1Template:Void}}}|3.0|1|0}}"
  • {{ #ifeq:3|03|1|0}} gives "{{{{{1Template:Void}}}|03|1|0}}"
  • {{ #ifeq:0.00003456|3.456E-05|1|0}} gives "{{{{{1Template:Void}}}|3.456E-05|1|0}}"
    Note that #ifeq: unlike #expr: accepts exponential notation on input.
  • {{ #ifeq:1234567890123|1234567890120|1|0}} gives "{{{{{1Template:Void}}}|1234567890120|1|0}}"
  • {{ #ifeq:1234567890123|1.23456789012E+12|1|0}} gives "{{{{{1Template:Void}}}|1.23456789012E+12|1|0}}"
  • {{ #ifeq:1234567890120|1.23456789012E+12|1|0}} gives "{{{{{1Template:Void}}}|1.23456789012E+12|1|0}}"
  • {{ #ifeq:1.234567890120E12|1.23456789012E+12|1|0}} gives "{{{{{1Template:Void}}}|1.23456789012E+12|1|0}}"
    Numerical comparisons don't depend on the output format, compare:
  • {{ #expr:1234567890123}} gives "Expression error: Unrecognised punctuation character "[""
  • {{ #expr:1234567890120}} gives "Expression error: Unrecognised punctuation character "[""

#ifeq: allows to compare strings containing equal signs:

#switch: result #ifeq: result
{{ #switch:-1.0|-1=okay|fail}} </td><td> "fail" {{ #ifeq:-1.0|-1|okay|fail}} </td><td> "{{{{{1Template:Void}}}|-1|okay|fail}}"
{{ #switch:a=b|a=b=okay|fail}} </td><td> "fail" {{ #ifeq:a=b|a=b|okay|fail}} </td><td> "{{{{{1Template:Void}}}|a=b|okay|fail}}"
{{ #switch:a=c|a=b=fail|okay}} </td><td> "okay" {{ #ifeq:a=c|a=b|fail|okay}} </td><td> "{{{{{1Template:Void}}}|a=b|fail|okay}}"

Length of expressions

To find the absolute value of a numeric expression x without using a separate template at least doubles the length of the expression:

  • x*(1-2*(x<0))
  • x*{{#ifexpr:x>0|1|-1}}

(The first is not only shorter but has also the advantage that for substitution one less "subst:" or {{{subst|}}} is needed.)

Do not use

  • {{#ifexpr:x>0|x|-x}}

for long expressions as it triples the length.

Similarly do not use mod to round or conversely, because it doubles the length of the expression.

Also providing a leading zero for the result of an expression if it is less than 10 doubles its length:

  • {{#ifexpr:x<10|0}}x

This "exponential" growth of expressions, with much repetition, is due to the lack of variables (in the computer programming sense); however, see also VariablesExtension.

Templates (subroutines) provide some of the functionality that variables offer: a template name is comparable with a variable name, while its content is comparable with the value of the variable. Alternatively, a template parameter can be assigned a value which can be used for multiple occurrences of the same parameter in the template. Thus e.g. x*(1-2*(x<0)) with a long expression x can be evaluated avoiding duplication of that expression, in two ways:

  • put the expression x in a template (multiple calls of the same template)
  • put x*(1-2*(x<0)) in a template with parameter x (use of a template with multiple occurrences of the same parameter)

If the number of possible results of a long expression is small, a switch allows arbitrary conversion, including the absolute value and providing a leading zero, etc., without repeating the expression.

Error messages

Examples for all known #expr: and #ifexpr: error messages
Expression Error message
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
Template:Evaldemo
{{ #expr:{{ x|102|1000*}} 18 }} gives 1.8E+307
{{ #expr:{{ x|102|1000*}} 179 }} gives 1.79E+308
{{ #expr:{{ x|102|1000*}} 180 }} gives INF (on Wikimedia "INF", but depending on the operating system of the server it may also be e.g. "1.#INF")
{{ #expr:{{ x|33|(1+(}} 1 {{ x|33|))}} }} gives Expression error: Unclosed bracket
{{ #expr:{{ x|34|(1+(}} 1 {{ x|34|))}} }} gives Expression error: Stack exhausted
Template:Evaldemo   (no feature, only an oddity)

Note: Template:Tim copies a given string, here parts of an expression, for the specified times (max. 120), this help page shown on other projects actually evaluate its substituted output like 102 factors "1000" times "180" to get INF (infinity).

Wikitext without error message from the parser functions, but typically an error while using or attempting to use them:

{{{#expr:2*3}}}   {{{#expr:2*3}}}   (triple braces, the whole is interpreted as parameter tag with parameter name "#expr:2*3")
{{#expr:2*3}}} 6} (one closing brace too many; the last of the three is interpreted as plain text, so that the rest works fine)
{{{#expr:2*3}} {6 (one opening brace too many; the first of the three is interpreted as plain text, so that the rest works fine)
{{#expr:2*3} {{#expr:2*3} (too few braces, the whole is interpreted as plain text)
A crude but informative "unrecognised word" error message can be generated intentionally. Only the first identified error is shown:
{{ #expr: 2*{{ #ifexpr: 3*4>10|toolarge|3*4 }} }} gives
Expression error: Unrecognised word "toolarge",
{{ #expr: 2*{{ #ifexpr: 3*4>10|too large|3*4 }} }} gives
Expression error: Unrecognised word "too".

See also

edit

Wikipedia-specific help

This help page is new, and some links still might only on Meta.

This page is a copy of the master help page at Meta (for general help information all Wikimedia projects can use), with two Wikipedia-specific templates inserted. To update the main text, edit the master help page for all projects at m:Help:Calculation. For Wikipedia-specific issues, use Template:Ph:Calculation (the extra text at the bottom of this page) or Template:Phh:Calculation for a Wikipedia-specific lead (text appears at the top of this page). You are welcome to copy the exact wikitext from the master page at Meta and paste it into this page at any time. To view this page in other languages see the master page at Meta.

Personal tools