Numerical Variables

by Martin D. Maas, Ph.D

Numerical Type Hierarchy

One characteristic feature of Julia is the existence of a type hierarchy. Instead of discussing the full theory behind this (which you can check here in the Julia official documenation) let’s go over an example, the Hierarchy of Numerical Types:

Number
│ 
├── Complex
│
├── Real
│
├── AbstractFloat
│  │
│  ├── BigFloat
│  │
│  ├── Float16
│  │
│  ├── Float32
│  │
│  └── Float64
│
├── AbstractIrrational
│  │
│  └── Irrational
│
├── Integer
│  │
│  ├── Bool
│  │
│  ├── Signed
│  │  │
│  │  ├── BigInt
│  │  │
│  │  ├── Int128
│  │  │
│  │  ├── Int16
│  │  │
│  │  ├── Int32
│  │  │
│  │  ├── Int64
│  │  │
│  │  └── Int8
│  │
│  └── Unsigned
│     │
│     ├── UInt128
│     │
│     ├── UInt16
│     │
│     ├── UInt32
│     │
│     ├── UInt64
│     │
│     └── UInt8     
│     
└── Rational

Conversion of Integer to Float

Conversion of integer variables to floating-point numbers is straightforward. We can convert an integers to floats with different kinds of precisions, using functions like Float64, Float32 and Float16 which correspond to double, single, and half precision numbers.

Float64(2)    # 2.0  (double-precision)
Float32(2)    # 2.0f0 (single-precision)
Float16(2)    # Float16(2.0) (half-precision)

Conversion of Float to Integer

Some care must be taken when converting float to integer variables in Julia, as the conversion is not always valid (as the float must coincide with an integer exaclty). It is preferable to use functions like floor,ceil and round, as opposed to the direct use of functions like Int64,Int32.

For example:

Int64(2.0)          # 2
Int64(2.4)          # Error!
floor(Int64,2.4)    # 2
ceil(Int64,2.4)     # 3
round(Int64,2.4)    # 2

Integer Division

By default, dividing two integers could return a float. If we are interested in the integer (or Euclidean) division, the div function (or ÷, whose Unicode symbol can be obtained with \div) returns the quotient, while for the remainder we have the rem function, or %.

For example:

a = 1/2             # 0.5 (Float64)

div(x,y) computes x/y, truncated to an integer.

div(10,3)           # 3
÷(10,3)             # 3

rem(x,y) computes the remainder of x/y

rem(10,3)           # 1
10%3                # 1

Gotcha! Integer vs Float

In Julia, if you input a number like

a = 2

you’ll be getting an Int64 by default. This can lead to errors if we are not careful. For example, consider the following operation

a = 1/2^64
Inf

Now, that’s unexpected. Two things just happened. In the first place, an Int64 will overflow past 2^{64}, and the default overflow value is 0.

2^64                # returns 0

In the second place, in Julia 1 divided by 0 returns Inf. We just computed 1/0.

We have some alternatives:

1/2.0^64            # 5.421010862427522e-20
(1/2)^64            # 5.421010862427522e-20
1.0/2^64            # Inf