Numbers
Numbers can be written as normal:
- Integers: For example
16to denote the integer (base 10) number 16. - Floats: For example,
3.14to denote the decimal number 3.14. - In a local declaration such as
x = 2.3;, hovering overxshows a tooltip indicating its type isFloat, whereas hovering overxinx = 2;showsNumber.- In the future, the name
Numberwill be deprecated in favour ofInteger.
- In the future, the name
Range of Numeric Values
Numbers (both integer and floating point) range from -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807.
⚠️ The closer to the boundaries, the greater the likelihood for rounding
errors; the small floating-point number -9223372036854771.5 rounds to -9223372036854772.
Likewise 9223372036854775 results in the approximate number 9223372036854776.
Arithmetic Operators
The following operators work on both integers and floats.
-x: Negationx + y: Additionx - y: Subtractionx * y: Multiplicationx / y: Divisionx % y: Modulox ^ y: Exponentiationsum(list): The sum of a list of integer numbers or a list of floating-point numbers.- For example, on integers,
sum([1, 2, 3])equals6. - Likewise, on floats,
sum([1.1, 2.1, 3.1])equals6.300000000000001.- Keep in mind that floating-point arithmetic is generally not precise!
- You can define a list in various ways, not just as a list of literal numbers. See Lists for more
detail on working with lists.
- Importantly, a list's elements must all be of the same type.
As such,
sum([1.1, 2, 3.1])has a type-error since the list is not well-formed. The fix is to replace integer2with2.0or2.to have it be treated as a float.
- Importantly, a list's elements must all be of the same type.
As such,
- For example, on integers,
Coercion Operators
To turn a literal integer such as 2 into a float we simply write 2. or 2.0.
- However, if we have any integer-valued expression, such as
xorx + 10, wherexis assigned an integer, then we can convert it to a float by writingfloat(x)orfloat(x + 10), respectively. - Conversely, if we have a float-valued expression
E, then we can convert it to an integer by writingint(E).- Note that
int(E)just truncates any decimal points; e.g.,int(2.9)results in2.
- Note that
The following table lists the functions that convert an integer to a float:
| Method | Description |
|---|---|
int(x) | Truncates decimal points |
floor(x) | Rounds down to the nearest smaller integer |
ceil(x) | Rounds up to the nearest larger integer |
round(x) | Rounds to the nearest integer |
Note that int(x) and floor(x) have the same behavior.