Julia Modules
A module is a ready-made collection of names that a program loads before use. Loading a module makes its tools available by name.
Statistics gives the mean
The using line loads Statistics first. The mean of the four numbers is 2.5.
using Statistics
println(mean([1, 2, 3, 4]))Statistics also gives the median
The middle value of 1, 2 and 9 is 2. It prints as a decimal number.
using Statistics
println(median([1, 2, 9]))Printf formats a decimal number
The format text asks for two digits after the point. A plain println line ends the output line.
using Printf
@printf("%.2f", 3.14159)
println()Example
using Statistics
using Printf
println(mean([2, 4, 6]))
println(median([2, 4, 6]))
@printf("%.2f", 2.567)
println()Key points
- using: a keyword that loads a module at the top of a script.
- Standard library: a set of modules that ships with Julia and needs no extra install.
- Statistics: a standard library module that brings tools such as mean and median.
- mean: a function that gives the average of the numbers in an array.
- median: a function that gives the middle value of the numbers in an array.
- Printf: a standard library module that brings formatted printing with @printf.
In this example, Statistics is loaded first, so mean and median both work on the same array. Printf is loaded next for the formatted print. The @printf line rounds 2.567 to 2.57, and the final println ends that line.
Note
@printf prints with no newline, so these blocks add a plain println line after it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does using Statistics make available?