Julia Math Functions
Math functions are ready-made functions that compute common number results. They cover roots, powers of ten, rounding, and limits.
Roots give floats
sqrt and cbrt return float results. The decimal part shows in the printed output.
println(sqrt(16))
println(cbrt(27))
println(abs(-3))Compare and combine whole numbers
max and min pick one of two values. gcd and lcm combine two whole numbers.
println(max(2, 7))
println(min(2, 7))
println(gcd(12, 18))
println(lcm(4, 6))Powers of ten and rounding down or up
log10 and exp work with powers. floor and ceil move a float to a whole float.
println(log10(1000))
println(exp(0))
println(floor(2.9))
println(ceil(2.1))Example
score = 15
println(clamp(score, 0, 10))
println(sqrt(81))
println(max(4, 9))
println(floor(7.8))Key points
- sqrt: a function that gives the square root of a number as a float.
- cbrt: a function that gives the cube root of a number as a float.
- Use abs to drop the sign of a number.
- Use gcd for the greatest common divisor and lcm for the least common multiple.
- Use floor to round a float down and ceil to round it up.
- Use clamp to keep a value inside a low and high limit.
In this example, clamp keeps 15 inside the limit of 10. The sqrt call gives 9.0 as a float. The max call picks 9 and floor moves 7.8 down to 7.0.
Note
log10(1000) is 3.0 because 10 to the power 3 is 1000.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does clamp(15, 0, 10) return?