Phantom Documentation

[Help Home] [Phantom Home]
Math Operations

Mathematical operations can be performed in Phantom.

Var1 = Var2 MATH Var3;

Where,

Var1 - The variable that takes the result of the operation
MATH - A mathematical operation performed between Var2 and Var3
Var2 - The second variable in the operation
Var3 - The third variable in the operation

MATH can be any one of the following:

+ - addition
- - subtraction
* - multiplication
\ - division
^ - power


Each variable type can also override the functionality of an operator. For example, a + operator between two strings will concatenate them. Refer to the documentation for a variable if unsure of an operator's purpose. Additionally, not all variable types support all operators. To see if an operator is supported by a variable type, see Variables.

Example Code

int i = 10;
i = i + 6; #i=16
i = i - 5; #i=11
i = i * 4; #i=44
i = i / 5; #i=8
i = i ^ 2; #i=64;

real r = 32.0;
r = r / 6; #r=5.333333
r = r ^ 0.5; #r=2.3094

# Concatenate two strings
string s = "Hello ";
s = s + "Phantom User";
disp(s);



Additionally, the following math operations are supported:


++ - Increment: increments the variable by one
-- - Decrement: decrements the variable by one

If the increment or decrement operator is placed before the variable, the operation is performed before the variable is used. If it is placed after the variable, the operation is performed after the variable is used.



Example Code

int i = 10;

disp(--i); # Will display 9
disp(i--); # Will display 9, then decrement
disp(i); # Will display 8


Order of Precedence
Math operators follow an order of precedence if they are applied consecutively. The order of precedence is as follows, with the first operators being performed first.


1. ^
2. */
3. +-
4. =


If two operators have the same priority, the precedence is from left to right. Additionally, any statement in parentheses is automatically moved to the top of the precedence order.


Example Code

int i = 9/3+4^2*2-1; #i=34
i = (9/3+4)^2-1; #i=48


Compatibility Between real and int
Note that most operators can be used between real and int data types. If the result type is an integer, the operation is truncated to an integer. This can cause strange results in math calculations, so it is best to type-cast the variables to the desired type using either the int or real functions. In the below example, the first statement (1/3) is truncated to 0 because both are integers. Therefore the result is 0. Typecasting the parameters fixes this issue.


Example Code

real r = 1/3*4; #r=0.0
r = real(1)/real(3)*real(4); #r=1.33333
r = 1.0/3.0*4; #r=1.33333



There are also many mathematical functions. For a list, see the standard functions. For more information on various operators, see the Operators section.

See Also:
Variables


Copyright 2000-2011 Phantom Automated Solutions